Compare commits

..

98 Commits

Author SHA1 Message Date
Brady f7041022d0 Merge branch 'master' into 1.13.2 2020-01-10 20:13:57 -06:00
Leijurv dd76d2eabc v1.3.6 2020-01-04 21:58:21 -08:00
Brady e3d3407de5 Remove normalizations from BlockOptionalMeta 2019-12-31 19:44:44 -06:00
Brady f3d860e8fa Merge branch 'master' into 1.13.2 2019-12-31 19:40:14 -06:00
Leijurv 1edd7126fd Merge branch 'master' into 1.13.2 2019-12-31 15:44:03 -08:00
Leijurv a57668bd15 Merge pull request #1073 from 0-x-2-2/1.13.2
Merged master into 1.13.2 branch. 😎
2019-10-17 13:54:06 -07:00
0x22 a324b58f55 Merged master into 1.13.2 branch. 😎 2019-10-17 16:01:35 -04:00
Leijurv 105c7d438a v1.3.5 2019-10-11 17:29:27 -07:00
Leijurv 1c00e167ca Merge branch 'master' into 1.13.2 2019-10-11 16:56:04 -07:00
Leijurv 861ee5049a unscuff 2019-10-11 16:15:38 -07:00
Brady c1fe588de4 Leijurv is crying and shaking right now 2019-10-11 18:08:39 -05:00
Brady 8fa2dac261 This should fix tab complete scuff 2019-10-11 17:59:36 -05:00
Leijurv f0ae31f455 fake merge of master into 1.13.2 2019-10-09 20:45:55 -07:00
Leijurv dc7d64fb88 Merge commit 'ce2fc6f2514245987659b378687f795ab641cf1e' into 1.13.2 2019-10-09 20:44:22 -07:00
Brady 62df244db7 Initial Brigadier overriden tab completion 2019-10-09 21:19:58 -05:00
Leijurv 2b4d6f4aa0 Merge branch 'master' into 1.13.2 2019-10-06 17:32:35 -07:00
Leijurv 7e505fc68f fix dropped items scanning 2019-10-06 16:00:26 -07:00
Leijurv 9c323aba91 Merge branch 'master' into 1.13.2 2019-10-06 15:51:27 -07:00
Leijurv ae9671bff0 meme fix, things work now 2019-09-30 17:57:09 -07:00
Leijurv d256f05787 Merge branch 'master' into 1.13.2 2019-09-30 17:52:47 -07:00
Leijurv a9ba05bf5e Merge branch 'master' into 1.13.2 2019-08-20 14:28:59 -07:00
Leijurv 7c9b812a5b Merge branch 'master' into 1.13.2 2019-08-17 16:07:26 -07:00
Leijurv a8226ba4c8 v1.3.4 2019-07-24 15:43:37 -07:00
Leijurv e34b2d1392 Merge branch 'master' into 1.13.2 2019-07-24 15:36:20 -07:00
Leijurv de6e96b952 Merge branch 'master' into 1.13.2 2019-07-23 11:58:45 -07:00
Leijurv 9dd6856872 get called out 2019-07-21 14:36:02 -07:00
Leijurv ed4753e968 now that impact locks to specific baritone versions this hack can finally be removed yay 2019-07-19 22:33:08 -07:00
Leijurv 1a4635df16 v1.3.3 2019-07-11 12:47:44 -07:00
Leijurv 1390af20b6 fix parkour and multithread farm 2019-07-11 12:46:24 -07:00
Leijurv 1427cf57a8 randomlooking 2019-07-11 11:56:44 -07:00
Leijurv d70243b4c0 leijurv would never do this 2019-07-11 11:08:45 -07:00
Leijurv 8f63dd4ba6 Merge branch 'master' into 1.13.2 2019-07-11 10:51:29 -07:00
Brady c7e1c917c3 Fix Baritone thinking it can walk through wall-placed skulls
Fixes #485
2019-07-08 19:21:09 -05:00
Leijurv 125facfbb6 Merge branch 'master' into 1.13.2 2019-06-10 11:50:14 -07:00
Leijurv 16b74ff53c v1.3.2 2019-05-16 14:57:26 -07:00
Leijurv 9297e98ac3 Merge branch 'master' into 1.13.2 2019-05-16 14:55:37 -07:00
Leijurv b521d7bee1 fix dummy merge typo 2019-05-02 11:42:49 -07:00
Leijurv 4e96c5e5ee Merge branch 'master' into 1.13.2 2019-05-01 23:12:19 -07:00
Leijurv ec819220b7 Merge branch 'master' into 1.13.2 2019-05-01 12:15:31 -07:00
Brady 3d3a5f420e Fix unsafe creation of potentially invalid ResourceLocation 2019-04-16 20:15:51 -05:00
Leijurv 9c9c9d4387 fix region pruning 2019-04-14 10:06:37 -07:00
Leijurv 82d09a536d v1.3.1 2019-04-13 19:21:44 -07:00
Leijurv 6e49adea33 i WUV impact 2019-04-13 19:10:13 -07:00
Leijurv f85afdbc70 Merge branch 'master' into 1.13.2 2019-04-12 21:57:01 -07:00
Leijurv 563028a5b3 fix invalid player move packet, and a bunch of things in world scanner 2019-04-09 19:30:48 -07:00
Leijurv d5c317b88b Merge branch 'master' into 1.13.2 2019-04-09 18:17:53 -07:00
Leijurv c59ec9da10 blank space 2019-03-23 22:17:40 -08:00
Leijurv 3a675836da Merge pull request #370 from babbaj/patch-1
use runAutoTest
2019-03-23 13:03:19 -07:00
babbaj 7e0fc81246 use runAutoTest 2019-03-23 15:55:16 -04:00
Leijurv f970f932c7 great 2019-03-23 10:52:03 -07:00
Leijurv 52d2741f52 and lets try making it fail delibrately 2019-03-23 10:31:36 -07:00
Leijurv 7bc6765cac rart 2019-03-23 10:13:14 -07:00
Leijurv 85b2aea6e9 where is this writing??? 2019-03-23 09:52:49 -07:00
Leijurv c6ba5481d9 one final attempt 2019-03-22 22:33:40 -07:00
Leijurv 81f47d5632 forgot file name lollll 2019-03-22 22:19:13 -07:00
Leijurv 9b1440ed2c that needs to be allowed 2019-03-22 22:07:12 -07:00
Leijurv 2a8dcee028 write to a file to indicate success 2019-03-22 22:05:27 -07:00
Leijurv 277ba3643c Merge branch 'master' into 1.13.2 2019-03-22 21:24:43 -07:00
Leijurv e5fbaf60f3 shutdownminecraftapplet 2019-03-22 21:04:35 -07:00
Leijurv 0deb854e1b v1.3.0 2019-03-21 16:40:18 -07:00
Leijurv 8268e3ec1b Merge branch 'master' into 1.13.2 2019-03-21 15:51:36 -07:00
Leijurv af91da6a28 Merge branch 'master' into 1.13.2 2019-03-19 18:12:26 -07:00
Leijurv 9a15a65ad5 not needed anymore 2019-03-19 13:59:56 -07:00
Leijurv 0cbe9f81c8 Merge branch 'master' into 1.13.2 2019-03-15 16:58:23 -07:00
Leijurv 42afd2dd54 maybe proper exit code 2019-03-15 16:49:36 -07:00
Leijurv 315929f31c hey so what if we didnt do that 2019-03-15 16:39:59 -07:00
Leijurv 358aa80280 docker time 2019-03-15 16:22:51 -07:00
Leijurv 1dd9e11994 documentation resigned 2019-03-15 16:19:07 -07:00
Leijurv 5a8f02c944 unscuff everything 2019-03-15 16:11:14 -07:00
Leijurv f248a5b677 make runClient work 2019-03-15 15:32:51 -07:00
Leijurv e4a49c5529 fix launchtesting not found on runClient 2019-03-15 14:00:11 -07:00
Leijurv 449b44ba50 line 2019-03-14 16:32:14 -07:00
Leijurv a00eec402e i love retina wtf 2019-03-14 16:32:04 -07:00
Leijurv 717779f742 air is stupid 2019-03-14 16:06:32 -07:00
Leijurv 6f843bd24d Merge branch 'master' into 1.13.2 2019-03-13 20:09:08 -07:00
Leijurv d79fbea433 scuffed air 2019-03-13 18:08:15 -07:00
Leijurv 4d22c10ddb unscuff water, thanks wwe 2019-03-12 23:08:06 -07:00
Leijurv 1ea92a6092 😎 2019-03-12 22:49:23 -07:00
Leijurv 66eba84d06 consistent spacing 2019-03-12 18:54:36 -07:00
Leijurv 92e39b5d1d its over its done 2019-03-12 18:45:54 -07:00
Leijurv 0ddc47f473 i am rarted 2019-03-12 18:21:29 -07:00
Leijurv ddfeca6947 unproject click cursed 2019-03-12 18:00:30 -07:00
Leijurv 6bd2e90cfd crash when pathing near shulker boxes 2019-03-12 17:18:58 -07:00
Leijurv 82505ddb01 online mode via env 2019-03-12 17:18:52 -07:00
Leijurv 2790d1d308 Merge branch 'master' into 1.13.2 2019-03-12 16:19:06 -07:00
Leijurv 11e503a022 many fixes 2019-03-12 16:17:43 -07:00
Leijurv 6fe49380ba pwned 2019-03-12 15:42:25 -07:00
Leijurv 1f2e267e3d fix a bunch of scuff 2019-03-12 15:41:58 -07:00
Leijurv 4cf6783622 fix the tests 2019-03-12 09:38:05 -07:00
Brady 82d77a7bac Update MixinGradle to 0.6.2
Includes fix ensuring that the SRGs are generated prior to Mixin annotation processing
2019-03-12 01:43:03 -05:00
Brady 841a927033 Merge remote-tracking branch 'origin/master' into 1.13.2 2019-03-12 01:09:11 -05:00
Brady 5a16561954 Working 1.13.2 development environment
Including a couple bugfixes to bad 1.13.2 code!!!
2019-03-12 01:05:39 -05:00
Brady e2cc51908b Notch builds 2019-03-08 23:18:00 -06:00
Brady 1390e04435 Add versions in parenthesis for todos to fix stuff 2019-03-08 15:14:52 -06:00
Brady 84d961cbab Fix usages of Setting#get() 2019-03-08 15:12:55 -06:00
Brady 87b9d3915c Fix compiler errors
unproject needs to be resolved
2019-03-08 15:03:58 -06:00
Brady c38d17563d Resolve merge conflicts
oh my god I should've updated my local branch before doing this
2019-03-08 14:44:49 -06:00
Brady 0c2af85ac0 Update to 1.13.2
Still need to setup method of launching, and Mixin support for ModLauncher
2019-03-08 14:30:43 -06:00
96 changed files with 1185 additions and 1294 deletions
+1 -8
View File
@@ -14,19 +14,12 @@ Baritone version:
Forge mods (if used): Forge mods (if used):
## Exception, error or logs ## Exception, error or logs
Please find your `latest.log` or `debug.log` in this folder and attach it to the issue You can find your logs in `%appdata%/.minecraft/logs/` (Windows) or `/Library/Application\ Support/minecraft/logs` (Mac).
Linux: `~/.minecraft/logs/`
Windows: `%appdata%/.minecraft/logs/`
Mac: `/Library/Application\ Support/minecraft/logs/`
## How to reproduce ## How to reproduce
Add your steps to reproduce the issue/bug experienced here. Add your steps to reproduce the issue/bug experienced here.
## Final checklist ## Final checklist
- [x] I know how to properly use check boxes
- [ ] I have included the version of Minecraft I'm running, baritone's version and forge mods (if used). - [ ] I have included the version of Minecraft I'm running, baritone's version and forge mods (if used).
- [ ] I have included logs, exceptions and / or steps to reproduce the issue. - [ ] I have included logs, exceptions and / or steps to reproduce the issue.
- [ ] I have not used any OwO's or UwU's in this issue. - [ ] I have not used any OwO's or UwU's in this issue.
-1
View File
@@ -10,5 +10,4 @@ assignees: ''
With as much detail as possible, describe your question and what you may need help with. With as much detail as possible, describe your question and what you may need help with.
## Final checklist ## Final checklist
- [x] I know how to properly use check boxes
- [ ] I have not used any OwO's or UwU's in this issue. - [ ] I have not used any OwO's or UwU's in this issue.
-1
View File
@@ -16,5 +16,4 @@ If applicable, what settings/customizability should be offered to tweak the func
Describe how your suggestion would improve Baritone, or the reason behind it being added. Describe how your suggestion would improve Baritone, or the reason behind it being added.
## Final checklist ## Final checklist
- [x] I know how to properly use check boxes
- [ ] I have not used any OwO's or UwU's in this issue. - [ ] I have not used any OwO's or UwU's in this issue.
+2
View File
@@ -11,6 +11,8 @@ build/
classes/ classes/
*.class *.class
/out
# IntelliJ Files # IntelliJ Files
.idea/ .idea/
*.iml *.iml
+1 -1
View File
@@ -10,7 +10,7 @@ install:
script: script:
- docker run --rm cabaletta/baritone ./gradlew javadoc - docker run --rm cabaletta/baritone ./gradlew javadoc
- docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient" - docker run --name baritone cabaletta/baritone /bin/sh -c "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runAutoTest; cat /code/autotest/success"
- docker cp baritone:/code/dist dist - docker cp baritone:/code/dist dist
- ls dist - ls dist
- cat dist/checksums.txt - cat dist/checksums.txt
+86 -1
View File
@@ -1 +1,86 @@
[Release](https://github.com/hykilpikonna/baritone/releases/tag/sx-1) # Baritone
[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone/)
[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases/)
[![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade)
[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone/)
[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases/)
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/master/)
[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/)
[![Minecraft](https://img.shields.io/badge/MC-1.14.4-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.14.4/)
[![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md)
[![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle)
[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues/)
[![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/)
[![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed)
[![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/)
![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg)
![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg)
![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code)
[![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/)
[![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.10%20/%20v1.3.5%20/%20v1.4.3-brightgreen.svg)](https://impactclient.net/)
[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/)
[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
[![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/)
[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/)
[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com/)
A Minecraft pathfinder bot.
Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797).
This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 and 1.13.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Have committed at least once a day from Aug 1 2018 to Aug 1 2019.
1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2
# Getting Started
Here are some links to help to get started:
- [Features](FEATURES.md)
- [Installation & setup](SETUP.md)
- [API Javadocs](https://baritone.leijurv.com/)
- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail)
- [Usage (chat control)](USAGE.md)
# API
The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/).
Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release
jar.
Below is an example of basic usage for changing some settings, and then pathing to a X/Z goal.
```
BaritoneAPI.getSettings().allowSprint.value = true;
BaritoneAPI.getSettings().primaryTimeoutMS.value = 2000L;
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalXZ(10000, 20000));
```
# FAQ
## Can I use Baritone as a library in my custom utility client?
That's what it's for, sure! (As long as usage is in compliance with the LGPL 3.0 License)
## How is it so fast?
Magic. (Hours of [leijurv](https://github.com/leijurv/) enduring excruciating pain)
## Why is it called Baritone?
It's named for FitMC's deep sultry voice.
+69 -14
View File
@@ -16,7 +16,7 @@
*/ */
group 'baritone' group 'baritone'
version '1.2.11' version '1.3.6'
buildscript { buildscript {
repositories { repositories {
@@ -25,24 +25,24 @@ buildscript {
url = 'http://files.minecraftforge.net/maven' url = 'http://files.minecraftforge.net/maven'
} }
maven { maven {
name = 'SpongePowered' name = 'impactdevelopment-repo'
url = 'http://repo.spongepowered.org/maven' url = 'https://impactdevelopment.github.io/maven/'
} }
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' classpath group: 'com.github.ImpactDevelopment', name: 'ForgeGradle', version: '3.0.115'
classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' classpath group: 'com.github.ImpactDevelopment', name: 'MixinGradle', version: '0.6.2'
} }
} }
import baritone.gradle.task.CreateDistTask import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask import baritone.gradle.task.ProguardTask
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client' apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'org.spongepowered.mixin' apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = '1.8'
@@ -52,8 +52,19 @@ compileJava {
} }
sourceSets { sourceSets {
api {
compileClasspath += main.compileClasspath
}
main {
compileClasspath += api.output
}
test {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
launch { launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output
} }
schematica_api { schematica_api {
@@ -65,14 +76,51 @@ sourceSets {
} }
} }
minecraft { task sourceJar(type: Jar, dependsOn: classes) {
version = '1.12.2' classifier = 'sources'
mappings = 'stable_39' from sourceSets.api.allSource
tweakClass = 'baritone.launch.BaritoneTweaker' }
runDir = 'run'
// The sources jar should use SRG names not MCP to ensure compatibility with all mappings minecraft {
makeObfSourceJar = true mappings channel: 'snapshot', version: '20190307-1.13.1'
reobfMappings 'notch'
runs {
client {
workingDirectory project.file('run')
source sourceSets.launch
main 'baritone.launch.LaunchTesting'
environment 'assetIndex', '{asset_index}'
environment 'assetDirectory', downloadAssets.output
environment 'nativesDirectory', extractNatives.output
environment 'tweakClass', 'baritone.launch.BaritoneTweaker'
if (Os.isFamily(Os.FAMILY_MAC)) {
jvmArgs "-XstartOnFirstThread"
}
}
autoTest {
workingDirectory project.file('autotest')
source sourceSets.launch
main 'baritone.launch.LaunchTesting'
environment 'assetIndex', '{asset_index}'
environment 'assetDirectory', downloadAssets.output
environment 'nativesDirectory', extractNatives.output
environment 'tweakClass', 'baritone.launch.BaritoneTweaker'
environment 'BARITONE_AUTO_TEST', 'true'
if (Os.isFamily(Os.FAMILY_MAC)) {
jvmArgs "-XstartOnFirstThread"
}
}
}
} }
repositories { repositories {
@@ -90,6 +138,12 @@ repositories {
} }
dependencies { dependencies {
minecraft 'com.github.ImpactDevelopment:Vanilla:1.13.2'
runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl'
}
runtime launchCompile('org.ow2.asm:asm-debug-all:5.2')
runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2')
runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') {
// Mixin includes a lot of dependencies that are too up-to-date // Mixin includes a lot of dependencies that are too up-to-date
@@ -99,6 +153,7 @@ dependencies {
exclude module: 'commons-io' exclude module: 'commons-io'
exclude module: 'log4j-core' exclude module: 'log4j-core'
} }
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
} }
@@ -40,17 +40,13 @@ class BaritoneGradleTask extends DefaultTask {
PROGUARD_STANDALONE_CONFIG = "standalone.pro", PROGUARD_STANDALONE_CONFIG = "standalone.pro",
PROGUARD_EXPORT_PATH = "proguard_out.jar", PROGUARD_EXPORT_PATH = "proguard_out.jar",
TEMP_LIBRARY_DIR = "tempLibraries/",
ARTIFACT_STANDARD = "%s-%s.jar", ARTIFACT_STANDARD = "%s-%s.jar",
ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar",
ARTIFACT_API = "%s-api-%s.jar", ARTIFACT_API = "%s-api-%s.jar",
ARTIFACT_STANDALONE = "%s-standalone-%s.jar", ARTIFACT_STANDALONE = "%s-standalone-%s.jar";
ARTIFACT_FORGE_API = "%s-api-forge-%s.jar",
ARTIFACT_FORGE_STANDALONE = "%s-standalone-forge-%s.jar";
protected String artifactName, artifactVersion; protected String artifactName, artifactVersion;
protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgeApiPath, artifactForgeStandalonePath, proguardOut; protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut;
protected void verifyArtifacts() throws IllegalStateException { protected void verifyArtifacts() throws IllegalStateException {
this.artifactName = getProject().getName(); this.artifactName = getProject().getName();
@@ -60,8 +56,6 @@ class BaritoneGradleTask extends DefaultTask {
this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED));
this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API));
this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE));
this.artifactForgeApiPath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_API));
this.artifactForgeStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_STANDALONE));
this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH);
@@ -45,8 +45,6 @@ public class CreateDistTask extends BaritoneGradleTask {
Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API));
Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE));
Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED));
Path forgeApi = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_API));
Path forgeStandalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_STANDALONE));
// NIO will not automatically create directories // NIO will not automatically create directories
Path dir = getRelativeFile("dist/"); Path dir = getRelativeFile("dist/");
@@ -58,11 +56,9 @@ public class CreateDistTask extends BaritoneGradleTask {
Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); Files.copy(this.artifactApiPath, api, REPLACE_EXISTING);
Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING);
Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING);
Files.copy(this.artifactForgeApiPath, forgeApi, REPLACE_EXISTING);
Files.copy(this.artifactForgeStandalonePath, forgeStandalone, REPLACE_EXISTING);
// Calculate all checksums and format them like "shasum" // Calculate all checksums and format them like "shasum"
List<String> shasum = Stream.of(api, forgeApi, standalone, forgeStandalone, unoptimized) List<String> shasum = Stream.of(api, standalone, unoptimized)
.map(path -> sha1(path) + " " + path.getFileName().toString()) .map(path -> sha1(path) + " " + path.getFileName().toString())
.collect(Collectors.toList()); .collect(Collectors.toList());
@@ -18,26 +18,18 @@
package baritone.gradle.task; package baritone.gradle.task;
import baritone.gradle.util.Determinizer; import baritone.gradle.util.Determinizer;
import baritone.gradle.util.MappingType;
import baritone.gradle.util.ReobfWrapper;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.gradle.api.NamedDomainObjectContainer; import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.internal.plugins.DefaultConvention;
import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskAction;
import org.gradle.internal.Pair;
import java.io.*; import java.io.*;
import java.lang.reflect.Field;
import java.net.URL; import java.net.URL;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.ArrayList;
import java.util.regex.Matcher; import java.util.List;
import java.util.regex.Pattern; import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
@@ -49,18 +41,12 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
*/ */
public class ProguardTask extends BaritoneGradleTask { public class ProguardTask extends BaritoneGradleTask {
private static final Pattern TEMP_LIBRARY_PATTERN = Pattern.compile("-libraryjars 'tempLibraries\\/([a-zA-Z0-9/_\\-\\.]+)\\.jar'");
@Input @Input
private String url; private String url;
@Input @Input
private String extract; private String extract;
private List<String> requiredLibraries;
private File mixin;
@TaskAction @TaskAction
protected void exec() throws Exception { protected void exec() throws Exception {
super.verifyArtifacts(); super.verifyArtifacts();
@@ -70,7 +56,6 @@ public class ProguardTask extends BaritoneGradleTask {
downloadProguard(); downloadProguard();
extractProguard(); extractProguard();
generateConfigs(); generateConfigs();
acquireDependencies();
proguardApi(); proguardApi();
proguardStandalone(); proguardStandalone();
cleanup(); cleanup();
@@ -81,7 +66,7 @@ public class ProguardTask extends BaritoneGradleTask {
Files.delete(this.artifactUnoptimizedPath); Files.delete(this.artifactUnoptimizedPath);
} }
Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString(), Optional.empty()); Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString());
} }
private void downloadProguard() throws Exception { private void downloadProguard() throws Exception {
@@ -114,6 +99,19 @@ public class ProguardTask extends BaritoneGradleTask {
String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", ""); String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", "");
template.add(2, "-libraryjars '" + out + "'"); template.add(2, "-libraryjars '" + out + "'");
// Discover all of the libraries that we will need to acquire from gradle
acquireDependencies().forEach(f -> {
if (f.toString().endsWith("-recomp.jar")) {
// remove MCP mapped jar
return;
}
if (f.toString().endsWith("client-extra.jar")) {
// go from the extra to the original downloaded client
f = new File(f.getParentFile(), "client.jar");
}
template.add(2, "-libraryjars '" + f + "'");
});
// API config doesn't require any changes from the changes that we made to the template // API config doesn't require any changes from the changes that we made to the template
Files.write(getTemporaryFile(PROGUARD_API_CONFIG), template); Files.write(getTemporaryFile(PROGUARD_API_CONFIG), template);
@@ -121,165 +119,20 @@ public class ProguardTask extends BaritoneGradleTask {
List<String> standalone = new ArrayList<>(template); List<String> standalone = new ArrayList<>(template);
standalone.removeIf(s -> s.contains("# this is the keep api")); standalone.removeIf(s -> s.contains("# this is the keep api"));
Files.write(getTemporaryFile(PROGUARD_STANDALONE_CONFIG), standalone); Files.write(getTemporaryFile(PROGUARD_STANDALONE_CONFIG), standalone);
// Discover all of the libraries that we will need to acquire from gradle
this.requiredLibraries = new ArrayList<>();
template.forEach(line -> {
if (!line.startsWith("#")) {
Matcher m = TEMP_LIBRARY_PATTERN.matcher(line);
if (m.find()) {
this.requiredLibraries.add(m.group(1));
}
}
});
} }
private void acquireDependencies() throws Exception { private Stream<File> acquireDependencies() {
return getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().findByName("launch").getRuntimeClasspath().getFiles().stream().filter(File::isFile);
// Create a map of all of the dependencies that we are able to access in this project
// Likely a better way to do this, I just pair the dependency with the first valid configuration
Map<String, Pair<Configuration, Dependency>> dependencyLookupMap = new HashMap<>();
getProject().getConfigurations().stream().filter(Configuration::isCanBeResolved).forEach(config ->
config.getAllDependencies().forEach(dependency ->
dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), Pair.of(config, dependency))));
// Create the directory if it doesn't already exist
Path tempLibraries = getTemporaryFile(TEMP_LIBRARY_DIR);
if (!Files.exists(tempLibraries)) {
Files.createDirectory(tempLibraries);
}
// Iterate the required libraries to copy them to tempLibraries
for (String lib : this.requiredLibraries) {
// copy from the forgegradle cache
if (lib.equals("minecraft")) {
Path cachedJar = getMinecraftJar();
Path inTempDir = getTemporaryFile("tempLibraries/minecraft.jar");
// TODO: maybe try not to copy every time
Files.copy(cachedJar, inTempDir, REPLACE_EXISTING);
continue;
}
// Find a configuration/dependency pair that matches the desired library
Pair<Configuration, Dependency> pair = null;
for (Map.Entry<String, Pair<Configuration, Dependency>> entry : dependencyLookupMap.entrySet()) {
if (entry.getKey().startsWith(lib)) {
pair = entry.getValue();
}
}
// The pair must be non-null
Objects.requireNonNull(pair);
// Find the library jar file, and copy it to tempLibraries
for (File file : pair.getLeft().files(pair.getRight())) {
if (file.getName().startsWith(lib)) {
if (lib.contains("mixin")) {
mixin = file;
}
Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING);
}
}
}
if (mixin == null) {
throw new IllegalStateException("Unable to find mixin jar");
}
}
// a bunch of epic stuff to get the path to the cached jar
private Path getMinecraftJar() throws Exception {
MappingType mappingType;
try {
mappingType = getMappingType();
} catch (Exception e) {
System.err.println("Failed to get mapping type, assuming NOTCH.");
mappingType = MappingType.NOTCH;
}
String suffix;
switch (mappingType) {
case NOTCH:
suffix = "";
break;
case SEARGE:
suffix = "-srgBin";
break;
case CUSTOM:
throw new IllegalStateException("Custom mappings not supported!");
default:
throw new IllegalStateException("Unknown mapping type: " + mappingType);
}
DefaultConvention convention = (DefaultConvention) this.getProject().getConvention();
Object extension = convention.getAsMap().get("minecraft");
Objects.requireNonNull(extension);
// for some reason cant use Class.forName
Class<?> class_baseExtension = extension.getClass().getSuperclass().getSuperclass().getSuperclass(); // <-- cursed
Field f_replacer = class_baseExtension.getDeclaredField("replacer");
f_replacer.setAccessible(true);
Object replacer = f_replacer.get(extension);
Class<?> class_replacementProvider = replacer.getClass();
Field replacement_replaceMap = class_replacementProvider.getDeclaredField("replaceMap");
replacement_replaceMap.setAccessible(true);
Map<String, Object> replacements = (Map) replacement_replaceMap.get(replacer);
String cacheDir = replacements.get("CACHE_DIR").toString() + "/net/minecraft";
String mcVersion = replacements.get("MC_VERSION").toString();
String mcpInsert = replacements.get("MAPPING_CHANNEL").toString() + "/" + replacements.get("MAPPING_VERSION").toString();
String fullJarName = "minecraft-" + mcVersion + suffix + ".jar";
String baseDir = String.format("%s/minecraft/%s/", cacheDir, mcVersion);
String jarPath;
if (mappingType == MappingType.SEARGE) {
jarPath = String.format("%s/%s/%s", baseDir, mcpInsert, fullJarName);
} else {
jarPath = baseDir + fullJarName;
}
jarPath = jarPath
.replace("/", File.separator)
.replace("\\", File.separator); // hecking regex
return new File(jarPath).toPath();
}
// throws IllegalStateException if mapping type is ambiguous or it fails to find it
private MappingType getMappingType() {
// if it fails to find this then its probably a forgegradle version problem
Set<Object> reobf = (NamedDomainObjectContainer<Object>) this.getProject().getExtensions().getByName("reobf");
List<MappingType> mappingTypes = getUsedMappingTypes(reobf);
long mappingTypesUsed = mappingTypes.size();
if (mappingTypesUsed == 0) {
throw new IllegalStateException("Failed to find mapping type (no jar task?)");
}
if (mappingTypesUsed > 1) {
throw new IllegalStateException("Ambiguous mapping type (multiple jars with different mapping types?)");
}
return mappingTypes.get(0);
}
private List<MappingType> getUsedMappingTypes(Set<Object> reobf) {
return reobf.stream()
.map(ReobfWrapper::new)
.map(ReobfWrapper::getMappingType)
.distinct()
.collect(Collectors.toList());
} }
private void proguardApi() throws Exception { private void proguardApi() throws Exception {
runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); runProguard(getTemporaryFile(PROGUARD_API_CONFIG));
Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString(), Optional.empty()); Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString());
Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeApiPath.toString(), Optional.of(mixin));
} }
private void proguardStandalone() throws Exception { private void proguardStandalone() throws Exception {
runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG));
Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString(), Optional.empty()); Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString());
Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeStandalonePath.toString(), Optional.of(mixin));
} }
private void cleanup() { private void cleanup() {
@@ -22,7 +22,10 @@ import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import java.io.*; import java.io.*;
import java.util.*; import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.jar.JarOutputStream; import java.util.jar.JarOutputStream;
@@ -36,7 +39,7 @@ import java.util.stream.Collectors;
*/ */
public class Determinizer { public class Determinizer {
public static void determinize(String inputPath, String outputPath, Optional<File> toInclude) throws IOException { public static void determinize(String inputPath, String outputPath) throws IOException {
System.out.println("Running Determinizer"); System.out.println("Running Determinizer");
System.out.println(" Input path: " + inputPath); System.out.println(" Input path: " + inputPath);
System.out.println(" Output path: " + outputPath); System.out.println(" Output path: " + outputPath);
@@ -63,30 +66,10 @@ public class Determinizer {
if (entry.getName().endsWith(".refmap.json")) { if (entry.getName().endsWith(".refmap.json")) {
JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject(); JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject();
jos.write(writeSorted(object).getBytes()); jos.write(writeSorted(object).getBytes());
} else if (entry.getName().equals("META-INF/MANIFEST.MF") && toInclude.isPresent()) { // only replace for forge jar
ByteArrayOutputStream cancer = new ByteArrayOutputStream();
copy(jarFile.getInputStream(entry), cancer);
String manifest = new String(cancer.toByteArray());
if (!manifest.contains("baritone.launch.BaritoneTweaker")) {
throw new IllegalStateException("unable to replace");
}
manifest = manifest.replace("baritone.launch.BaritoneTweaker", "org.spongepowered.asm.launch.MixinTweaker");
jos.write(manifest.getBytes());
} else { } else {
copy(jarFile.getInputStream(entry), jos); copy(jarFile.getInputStream(entry), jos);
} }
} }
if (toInclude.isPresent()) {
try (JarFile mixin = new JarFile(toInclude.get())) {
for (JarEntry entry : mixin.stream().sorted(Comparator.comparing(JarEntry::getName)).collect(Collectors.toList())) {
if (entry.getName().startsWith("META-INF") && !entry.getName().startsWith("META-INF/services")) {
continue;
}
jos.putNextEntry(entry);
copy(mixin.getInputStream(entry), jos);
}
}
}
jos.finish(); jos.finish();
} }
} }
@@ -1,29 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.gradle.util;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/MappingType.java">Original Source</a>
*/
public enum MappingType {
SEARGE,
NOTCH,
CUSTOM // forgegradle
}
@@ -1,63 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.gradle.util;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/ReobfWrapper.java">Original Source</a>
*/
public class ReobfWrapper {
private final Object instance;
private final Class<?> type;
public ReobfWrapper(Object instance) {
this.instance = instance;
Objects.requireNonNull(instance);
this.type = instance.getClass();
}
public String getName() {
try {
Field nameField = type.getDeclaredField("name");
nameField.setAccessible(true);
return (String) nameField.get(this.instance);
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
public MappingType getMappingType() {
try {
Field enumField = type.getDeclaredField("mappingType");
enumField.setAccessible(true);
Enum<?> aEnum = (Enum<?>) enumField.get(this.instance);
MappingType mappingType = MappingType.values()[aEnum.ordinal()];
if (!aEnum.name().equals(mappingType.name())) {
throw new IllegalStateException("ForgeGradle ReobfMappingType is not equivalent to MappingType (version error?)");
}
return mappingType;
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
}
+2 -49
View File
@@ -14,6 +14,8 @@
# lwjgl is weird # lwjgl is weird
-dontwarn org.lwjgl.** -dontwarn org.lwjgl.**
# also lwjgl lol
-dontwarn module-info
-keep class baritone.api.** { *; } # this is the keep api -keep class baritone.api.** { *; } # this is the keep api
@@ -36,55 +38,6 @@
#proguard doesnt like it when it cant find our fake schematica classes #proguard doesnt like it when it cant find our fake schematica classes
-dontwarn baritone.utils.schematic.schematica.** -dontwarn baritone.utils.schematic.schematica.**
# copy all necessary libraries into tempLibraries to build
# The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with
-libraryjars 'tempLibraries/minecraft.jar'
-libraryjars 'tempLibraries/SimpleTweaker-1.2.jar'
-libraryjars 'tempLibraries/authlib-1.5.25.jar'
-libraryjars 'tempLibraries/codecjorbis-20101023.jar'
-libraryjars 'tempLibraries/codecwav-20101023.jar'
-libraryjars 'tempLibraries/commons-codec-1.10.jar'
-libraryjars 'tempLibraries/commons-compress-1.8.1.jar'
-libraryjars 'tempLibraries/commons-io-2.5.jar'
-libraryjars 'tempLibraries/commons-lang3-3.5.jar'
-libraryjars 'tempLibraries/commons-logging-1.1.3.jar'
-libraryjars 'tempLibraries/fastutil-7.1.0.jar'
-libraryjars 'tempLibraries/gson-2.8.0.jar'
-libraryjars 'tempLibraries/guava-21.0.jar'
-libraryjars 'tempLibraries/httpclient-4.3.3.jar'
-libraryjars 'tempLibraries/httpcore-4.3.2.jar'
-libraryjars 'tempLibraries/icu4j-core-mojang-51.2.jar'
-libraryjars 'tempLibraries/jinput-2.0.5.jar'
-libraryjars 'tempLibraries/jna-4.4.0.jar'
-libraryjars 'tempLibraries/jopt-simple-5.0.3.jar'
-libraryjars 'tempLibraries/jsr305-3.0.1.jar'
-libraryjars 'tempLibraries/jutils-1.0.0.jar'
-libraryjars 'tempLibraries/libraryjavasound-20101123.jar'
-libraryjars 'tempLibraries/librarylwjglopenal-20100824.jar'
-libraryjars 'tempLibraries/log4j-api-2.8.1.jar'
-libraryjars 'tempLibraries/log4j-core-2.8.1.jar'
# startsWith is used to check the library, and mac/linux differ in which version they use
# this is FINE
-libraryjars 'tempLibraries/lwjgl-.jar'
-libraryjars 'tempLibraries/lwjgl_util-.jar'
-libraryjars 'tempLibraries/netty-all-4.1.9.Final.jar'
-libraryjars 'tempLibraries/oshi-core-1.1.jar'
-libraryjars 'tempLibraries/patchy-1.1.jar'
-libraryjars 'tempLibraries/platform-3.4.0.jar'
-libraryjars 'tempLibraries/realms-1.10.22.jar'
-libraryjars 'tempLibraries/soundsystem-20120107.jar'
-libraryjars 'tempLibraries/text2speech-1.10.3.jar'
-libraryjars 'tempLibraries/mixin-0.7.11-SNAPSHOT.jar'
-libraryjars 'tempLibraries/launchwrapper-1.11.jar' # TODO why does only 1.11.jar exist?
# Keep - Applications. Keep all application classes, along with their 'main' # Keep - Applications. Keep all application classes, along with their 'main'
# methods. # methods.
+11 -7
View File
@@ -158,10 +158,10 @@ public final class Settings {
* Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.) * Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.)
*/ */
public final Setting<List<Item>> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList( public final Setting<List<Item>> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList(
Item.getItemFromBlock(Blocks.DIRT), Blocks.DIRT.asItem(),
Item.getItemFromBlock(Blocks.COBBLESTONE), Blocks.COBBLESTONE.asItem(),
Item.getItemFromBlock(Blocks.NETHERRACK), Blocks.NETHERRACK.asItem(),
Item.getItemFromBlock(Blocks.STONE) Blocks.STONE.asItem()
))); )));
/** /**
@@ -177,10 +177,9 @@ public final class Settings {
public final Setting<List<Block>> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( // TODO can this be a HashSet or ImmutableSet? public final Setting<List<Block>> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( // TODO can this be a HashSet or ImmutableSet?
Blocks.CRAFTING_TABLE, Blocks.CRAFTING_TABLE,
Blocks.FURNACE, Blocks.FURNACE,
Blocks.LIT_FURNACE,
Blocks.CHEST, Blocks.CHEST,
Blocks.TRAPPED_CHEST, Blocks.TRAPPED_CHEST,
Blocks.STANDING_SIGN, Blocks.SIGN,
Blocks.WALL_SIGN Blocks.WALL_SIGN
))); )));
@@ -262,6 +261,11 @@ public final class Settings {
*/ */
public final Setting<Integer> rightClickSpeed = new Setting<>(4); public final Setting<Integer> rightClickSpeed = new Setting<>(4);
/**
* How many degrees to randomize the yaw every tick. Set to 0 to disable
*/
public final Setting<Double> randomLooking113 = new Setting<>(2d);
/** /**
* Block reach distance * Block reach distance
*/ */
@@ -954,7 +958,7 @@ public final class Settings {
* via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting * via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting
* {@link Setting#value}; * {@link Setting#value};
*/ */
public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getMinecraft().ingameGUI.getChatGUI()::printChatMessage); public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getInstance().ingameGUI.getChatGUI()::printChatMessage);
/** /**
* The size of the box that is rendered when the current goal is a GoalYLevel * The size of the box that is rendered when the current goal is a GoalYLevel
@@ -22,6 +22,7 @@ import baritone.api.command.exception.CommandException;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -32,7 +33,7 @@ public enum BlockById implements IDatatypeFor<Block> {
public Block get(IDatatypeContext ctx) throws CommandException { public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Block block; Block block;
if ((block = Block.REGISTRY.getObject(id)) == Blocks.AIR) { if ((block = IRegistry.BLOCK.get(id)) == Blocks.AIR) {
throw new IllegalArgumentException("no block found by that id"); throw new IllegalArgumentException("no block found by that id");
} }
return block; return block;
@@ -42,7 +43,7 @@ public enum BlockById implements IDatatypeFor<Block> {
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append( .append(
Block.REGISTRY.getKeys() IRegistry.BLOCK.keySet()
.stream() .stream()
.map(Object::toString) .map(Object::toString)
) )
@@ -17,22 +17,22 @@
package baritone.api.command.datatypes; package baritone.api.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import net.minecraft.entity.Entity; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.stream.Stream; import java.util.stream.Stream;
public enum EntityClassById implements IDatatypeFor<Class<? extends Entity>> { public enum EntityClassById implements IDatatypeFor<EntityType> {
INSTANCE; INSTANCE;
@Override @Override
public Class<? extends Entity> get(IDatatypeContext ctx) throws CommandException { public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Class<? extends Entity> entity; EntityType entity;
if ((entity = EntityList.REGISTRY.getObject(id)) == null) { if ((entity = IRegistry.ENTITY_TYPE.get(id)) == null) {
throw new IllegalArgumentException("no entity found by that id"); throw new IllegalArgumentException("no entity found by that id");
} }
return entity; return entity;
@@ -41,7 +41,7 @@ public enum EntityClassById implements IDatatypeFor<Class<? extends Entity>> {
@Override @Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(EntityList.getEntityNameList().stream().map(Object::toString)) .append(IRegistry.ENTITY_TYPE.stream().map(Object::toString))
.filterPrefixNamespaced(ctx.getConsumer().getString()) .filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically() .sortAlphabetically()
.stream(); .stream();
@@ -18,9 +18,10 @@
package baritone.api.command.datatypes; package baritone.api.command.datatypes;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.ITextComponent;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -36,14 +37,14 @@ public enum NearbyPlayer implements IDatatypeFor<EntityPlayer> {
public EntityPlayer get(IDatatypeContext ctx) throws CommandException { public EntityPlayer get(IDatatypeContext ctx) throws CommandException {
final String username = ctx.getConsumer().getString(); final String username = ctx.getConsumer().getString();
return getPlayers(ctx).stream() return getPlayers(ctx).stream()
.filter(s -> s.getName().equalsIgnoreCase(username)) .filter(s -> s.getName().getString().equalsIgnoreCase(username))
.findFirst().orElse(null); .findFirst().orElse(null);
} }
@Override @Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(getPlayers(ctx).stream().map(EntityPlayer::getName)) .append(getPlayers(ctx).stream().map(EntityPlayer::getName).map(ITextComponent::getString))
.filterPrefix(ctx.getConsumer().getString()) .filterPrefix(ctx.getConsumer().getString())
.sortAlphabetically() .sortAlphabetically()
.stream(); .stream();
@@ -23,7 +23,7 @@ import baritone.api.event.events.type.Overrideable;
/** /**
* @author LoganDark * @author LoganDark
*/ */
public class TabCompleteEvent extends Cancellable { public final class TabCompleteEvent extends Cancellable {
public final String prefix; public final String prefix;
public String[] completions; public String[] completions;
@@ -18,12 +18,11 @@
package baritone.api.event.listener; package baritone.api.event.listener;
import baritone.api.event.events.*; import baritone.api.event.events.*;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.network.Packet; import net.minecraft.network.Packet;
@@ -45,7 +44,7 @@ public interface IGameEventListener {
* Run once per game tick from before and after the player rotation is sent to the server. * Run once per game tick from before and after the player rotation is sent to the server.
* *
* @param event The event * @param event The event
* @see EntityPlayerSP#onUpdate() * @see EntityPlayerSP#tick()
*/ */
void onPlayerUpdate(PlayerUpdateEvent event); void onPlayerUpdate(PlayerUpdateEvent event);
@@ -68,14 +67,11 @@ public interface IGameEventListener {
* Runs before and after whenever a chunk is either loaded, unloaded, or populated. * Runs before and after whenever a chunk is either loaded, unloaded, or populated.
* *
* @param event The event * @param event The event
* @see WorldClient#doPreChunk(int, int, boolean)
*/ */
void onChunkEvent(ChunkEvent event); void onChunkEvent(ChunkEvent event);
/** /**
* Runs once per world render pass. Two passes are made when {@link GameSettings#anaglyph} is on. * Runs once per world render pass.
* <p>
* <b>Note:</b> {@link GameSettings#anaglyph} has been removed in Minecraft 1.13
* *
* @param event The event * @param event The event
*/ */
@@ -85,7 +81,7 @@ public interface IGameEventListener {
* Runs before and after whenever a new world is loaded * Runs before and after whenever a new world is loaded
* *
* @param event The event * @param event The event
* @see Minecraft#loadWorld(WorldClient, String) * @see Minecraft#loadWorld(WorldClient, GuiScreen)
*/ */
void onWorldEvent(WorldEvent event); void onWorldEvent(WorldEvent event);
@@ -94,7 +90,6 @@ public interface IGameEventListener {
* *
* @param event The event * @param event The event
* @see Packet * @see Packet
* @see GenericFutureListener
*/ */
void onSendPacket(PacketEvent event); void onSendPacket(PacketEvent event);
@@ -103,7 +98,6 @@ public interface IGameEventListener {
* *
* @param event The event * @param event The event
* @see Packet * @see Packet
* @see GenericFutureListener
*/ */
void onReceivePacket(PacketEvent event); void onReceivePacket(PacketEvent event);
@@ -117,10 +111,10 @@ public interface IGameEventListener {
void onPlayerRotationMove(RotationMoveEvent event); void onPlayerRotationMove(RotationMoveEvent event);
/** /**
* Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#onLivingUpdate} * Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#livingTick}
* *
* @param event The event * @param event The event
* @see EntityPlayerSP#onLivingUpdate() * @see EntityPlayerSP#livingTick()
*/ */
void onPlayerSprintState(SprintStateEvent event); void onPlayerSprintState(SprintStateEvent event);
@@ -52,7 +52,7 @@ public interface IBuilderProcess extends IBaritoneProcess {
boolean build(String name, File schematic, Vec3i origin); boolean build(String name, File schematic, Vec3i origin);
default boolean build(String schematicFile, BlockPos origin) { default boolean build(String schematicFile, BlockPos origin) {
File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); File file = new File(new File(Minecraft.getInstance().gameDir, "schematics"), schematicFile);
return build(schematicFile, file, origin); return build(schematicFile, file, origin);
} }
@@ -33,7 +33,7 @@ public class FillSchematic extends AbstractSchematic {
} }
public FillSchematic(int x, int y, int z, IBlockState state) { public FillSchematic(int x, int y, int z, IBlockState state) {
this(x, y, z, new BlockOptionalMeta(state.getBlock(), state.getBlock().getMetaFromState(state))); this(x, y, z, new BlockOptionalMeta(state.getBlock()));
} }
public BlockOptionalMeta getBom() { public BlockOptionalMeta getBom() {
@@ -20,43 +20,34 @@ package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack; import baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.state.IProperty;
import net.minecraft.state.properties.*;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.regex.MatchResult; import java.util.regex.MatchResult;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class BlockOptionalMeta { public final class BlockOptionalMeta {
private final Block block; private final Block block;
private final int meta;
private final boolean noMeta;
private final Set<IBlockState> blockstates; private final Set<IBlockState> blockstates;
private final ImmutableSet<Integer> stateHashes; private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes; private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations;
public BlockOptionalMeta(@Nonnull Block block, @Nullable Integer meta) {
this.block = block;
this.noMeta = meta == null;
this.meta = noMeta ? 0 : meta;
this.blockstates = getStates(block, meta);
this.stateHashes = getStateHashes(blockstates);
this.stackHashes = getStackHashes(blockstates);
}
public BlockOptionalMeta(@Nonnull Block block) { public BlockOptionalMeta(@Nonnull Block block) {
this(block, null); this.block = block;
this.blockstates = getStates(block);
this.stateHashes = getStateHashes(blockstates);
this.stackHashes = getStackHashes(blockstates);
} }
public BlockOptionalMeta(@Nonnull String selector) { public BlockOptionalMeta(@Nonnull String selector) {
@@ -67,187 +58,21 @@ public final class BlockOptionalMeta {
} }
MatchResult matchResult = matcher.toMatchResult(); MatchResult matchResult = matcher.toMatchResult();
noMeta = matchResult.group(2) == null;
ResourceLocation id = new ResourceLocation(matchResult.group(1)); ResourceLocation id = new ResourceLocation(matchResult.group(1));
if (!Block.REGISTRY.containsKey(id)) { if (!IRegistry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID"); throw new IllegalArgumentException("Invalid block ID");
} }
block = Block.REGISTRY.getObject(id); block = IRegistry.BLOCK.get(id);
meta = noMeta ? 0 : Integer.parseInt(matchResult.group(2)); blockstates = getStates(block);
blockstates = getStates(block, getMeta());
stateHashes = getStateHashes(blockstates); stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates); stackHashes = getStackHashes(blockstates);
} }
static { private static Set<IBlockState> getStates(@Nonnull Block block) {
Map<Object, Object> _normalizations = new HashMap<>(); return new HashSet<>(block.getStateContainer().getValidStates());
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
put.accept(EnumFacing.NORTH);
put.accept(EnumFacing.Axis.Y);
put.accept(BlockLog.EnumAxis.Y);
put.accept(BlockStairs.EnumHalf.BOTTOM);
put.accept(BlockStairs.EnumShape.STRAIGHT);
put.accept(BlockLever.EnumOrientation.DOWN_X);
put.accept(BlockDoublePlant.EnumBlockHalf.LOWER);
put.accept(BlockSlab.EnumBlockHalf.BOTTOM);
put.accept(BlockDoor.EnumDoorHalf.LOWER);
put.accept(BlockDoor.EnumHingePosition.LEFT);
put.accept(BlockBed.EnumPartType.HEAD);
put.accept(BlockRailBase.EnumRailDirection.NORTH_SOUTH);
put.accept(BlockTrapDoor.DoorHalf.BOTTOM);
_normalizations.put(BlockBanner.ROTATION, 0);
_normalizations.put(BlockBed.OCCUPIED, false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[0], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[1], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[2], false);
_normalizations.put(BlockButton.POWERED, false);
// _normalizations.put(BlockCactus.AGE, 0);
// _normalizations.put(BlockCauldron.LEVEL, 0);
// _normalizations.put(BlockChorusFlower.AGE, 0);
_normalizations.put(BlockChorusPlant.NORTH, false);
_normalizations.put(BlockChorusPlant.EAST, false);
_normalizations.put(BlockChorusPlant.SOUTH, false);
_normalizations.put(BlockChorusPlant.WEST, false);
_normalizations.put(BlockChorusPlant.UP, false);
_normalizations.put(BlockChorusPlant.DOWN, false);
// _normalizations.put(BlockCocoa.AGE, 0);
// _normalizations.put(BlockCrops.AGE, 0);
_normalizations.put(BlockDirt.SNOWY, false);
_normalizations.put(BlockDoor.OPEN, false);
_normalizations.put(BlockDoor.POWERED, false);
// _normalizations.put(BlockFarmland.MOISTURE, 0);
_normalizations.put(BlockFence.NORTH, false);
_normalizations.put(BlockFence.EAST, false);
_normalizations.put(BlockFence.WEST, false);
_normalizations.put(BlockFence.SOUTH, false);
// _normalizations.put(BlockFenceGate.POWERED, false);
// _normalizations.put(BlockFenceGate.IN_WALL, false);
_normalizations.put(BlockFire.AGE, 0);
_normalizations.put(BlockFire.NORTH, false);
_normalizations.put(BlockFire.EAST, false);
_normalizations.put(BlockFire.SOUTH, false);
_normalizations.put(BlockFire.WEST, false);
_normalizations.put(BlockFire.UPPER, false);
// _normalizations.put(BlockFrostedIce.AGE, 0);
_normalizations.put(BlockGrass.SNOWY, false);
// _normalizations.put(BlockHopper.ENABLED, true);
// _normalizations.put(BlockLever.POWERED, false);
// _normalizations.put(BlockLiquid.LEVEL, 0);
// _normalizations.put(BlockMycelium.SNOWY, false);
// _normalizations.put(BlockNetherWart.AGE, false);
_normalizations.put(BlockLeaves.CHECK_DECAY, false);
// _normalizations.put(BlockLeaves.DECAYABLE, false);
// _normalizations.put(BlockObserver.POWERED, false);
_normalizations.put(BlockPane.NORTH, false);
_normalizations.put(BlockPane.EAST, false);
_normalizations.put(BlockPane.WEST, false);
_normalizations.put(BlockPane.SOUTH, false);
// _normalizations.put(BlockPistonBase.EXTENDED, false);
// _normalizations.put(BlockPressurePlate.POWERED, false);
// _normalizations.put(BlockPressurePlateWeighted.POWER, false);
_normalizations.put(BlockQuartz.EnumType.LINES_X, BlockQuartz.EnumType.LINES_Y);
_normalizations.put(BlockQuartz.EnumType.LINES_Z, BlockQuartz.EnumType.LINES_Y);
// _normalizations.put(BlockRailDetector.POWERED, false);
// _normalizations.put(BlockRailPowered.POWERED, false);
_normalizations.put(BlockRedstoneWire.NORTH, false);
_normalizations.put(BlockRedstoneWire.EAST, false);
_normalizations.put(BlockRedstoneWire.SOUTH, false);
_normalizations.put(BlockRedstoneWire.WEST, false);
// _normalizations.put(BlockReed.AGE, false);
_normalizations.put(BlockSapling.STAGE, 0);
_normalizations.put(BlockSkull.NODROP, false);
_normalizations.put(BlockStandingSign.ROTATION, 0);
_normalizations.put(BlockStem.AGE, 0);
_normalizations.put(BlockTripWire.NORTH, false);
_normalizations.put(BlockTripWire.EAST, false);
_normalizations.put(BlockTripWire.WEST, false);
_normalizations.put(BlockTripWire.SOUTH, false);
_normalizations.put(BlockVine.NORTH, false);
_normalizations.put(BlockVine.EAST, false);
_normalizations.put(BlockVine.SOUTH, false);
_normalizations.put(BlockVine.WEST, false);
_normalizations.put(BlockVine.UP, false);
_normalizations.put(BlockWall.UP, false);
_normalizations.put(BlockWall.NORTH, false);
_normalizations.put(BlockWall.EAST, false);
_normalizations.put(BlockWall.WEST, false);
_normalizations.put(BlockWall.SOUTH, false);
normalizations = Collections.unmodifiableMap(_normalizations);
}
public static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) {
//noinspection unchecked
return (P) value;
}
public static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) {
//noinspection unchecked
return (C) value;
}
/**
* Normalizes the specified blockstate by setting meta-affecting properties which
* are not being targeted by the meta parameter to their default values.
* <p>
* For example, block variant/color is the primary target for the meta value, so properties
* such as rotation/facing direction will be set to default values in order to nullify
* the effect that they have on the state's meta value.
*
* @param state The state to normalize
* @return The normalized block state
*/
public static IBlockState normalize(IBlockState state) {
IBlockState newState = state;
for (IProperty<?> property : state.getProperties().keySet()) {
Class<?> valueClass = property.getValueClass();
if (normalizations.containsKey(property)) {
try {
newState = newState.withProperty(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(property))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(state.getValue(property))) {
try {
newState = newState.withProperty(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(state.getValue(property)))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(valueClass)) {
try {
newState = newState.withProperty(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(valueClass))
);
} catch (IllegalArgumentException ignored) {}
}
}
return newState;
}
/**
* Evaluate the target meta value for the specified state. The target meta value is
* most often that which is influenced by the variant/color property of the block state.
*
* @see #normalize(IBlockState)
*
* @param state The state to check
* @return The target meta of the state
*/
public static int stateMeta(IBlockState state) {
return state.getBlock().getMetaFromState(normalize(state));
}
private static Set<IBlockState> getStates(@Nonnull Block block, @Nullable Integer meta) {
return block.getBlockState().getValidStates().stream()
.filter(blockstate -> meta == null || stateMeta(blockstate) == meta)
.collect(Collectors.toSet());
} }
private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) { private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) {
@@ -263,8 +88,8 @@ public final class BlockOptionalMeta {
return ImmutableSet.copyOf( return ImmutableSet.copyOf(
blockstates.stream() blockstates.stream()
.map(state -> new ItemStack( .map(state -> new ItemStack(
state.getBlock().getItemDropped(state, new Random(), 0), state.getBlock().getItemDropped(state, null, null, 0).asItem(),
state.getBlock().damageDropped(state) 1
)) ))
.map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash())
.toArray(Integer[]::new) .toArray(Integer[]::new)
@@ -275,10 +100,6 @@ public final class BlockOptionalMeta {
return block; return block;
} }
public Integer getMeta() {
return noMeta ? null : meta;
}
public boolean matches(@Nonnull Block block) { public boolean matches(@Nonnull Block block) {
return block == this.block; return block == this.block;
} }
@@ -292,21 +113,14 @@ public final class BlockOptionalMeta {
//noinspection ConstantConditions //noinspection ConstantConditions
int hash = ((IItemStack) (Object) stack).getBaritoneHash(); int hash = ((IItemStack) (Object) stack).getBaritoneHash();
if (noMeta) { hash -= stack.getDamage();
hash -= stack.getItemDamage();
}
return stackHashes.contains(hash); return stackHashes.contains(hash);
} }
@Override @Override
public String toString() { public String toString() {
return String.format("BlockOptionalMeta{block=%s,meta=%s}", block, getMeta()); return String.format("BlockOptionalMeta{block=%s}", block);
}
public static IBlockState blockStateFromStack(ItemStack stack) {
//noinspection deprecation
return Block.getBlockFromItem(stack.getItem()).getStateFromMeta(stack.getMetadata());
} }
public IBlockState getAnyBlockState() { public IBlockState getAnyBlockState() {
@@ -19,6 +19,7 @@ package baritone.api.utils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -28,7 +29,7 @@ public class BlockUtils {
private static transient Map<String, Block> resourceCache = new HashMap<>(); private static transient Map<String, Block> resourceCache = new HashMap<>();
public static String blockToString(Block block) { public static String blockToString(Block block) {
ResourceLocation loc = Block.REGISTRY.getNameForObject(block); ResourceLocation loc = IRegistry.BLOCK.getKey(block);
String name = loc.getPath(); // normally, only write the part after the minecraft: String name = loc.getPath(); // normally, only write the part after the minecraft:
if (!loc.getNamespace().equals("minecraft")) { if (!loc.getNamespace().equals("minecraft")) {
// Baritone is running on top of forge with mods installed, perhaps? // Baritone is running on top of forge with mods installed, perhaps?
@@ -56,7 +57,7 @@ public class BlockUtils {
if (resourceCache.containsKey(name)) { if (resourceCache.containsKey(name)) {
return null; // cached as null return null; // cached as null
} }
block = Block.getBlockFromName(name.contains(":") ? name : "minecraft:" + name); block = IRegistry.BLOCK.get(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name));
Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification
copy.put(name, block); copy.put(name, block);
resourceCache = copy; resourceCache = copy;
+2 -2
View File
@@ -43,7 +43,7 @@ public interface Helper {
/** /**
* Instance of the game * Instance of the game
*/ */
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getInstance();
static ITextComponent getPrefix() { static ITextComponent getPrefix() {
// Inner text component // Inner text component
@@ -84,7 +84,7 @@ public interface Helper {
component.appendSibling(getPrefix()); component.appendSibling(getPrefix());
component.appendSibling(new TextComponentString(" ")); component.appendSibling(new TextComponentString(" "));
Arrays.asList(components).forEach(component::appendSibling); Arrays.asList(components).forEach(component::appendSibling);
Minecraft.getMinecraft().addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); mc.addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component));
} }
/** /**
@@ -84,7 +84,7 @@ public interface IPlayerContext {
*/ */
default Optional<BlockPos> getSelectedBlock() { default Optional<BlockPos> getSelectedBlock() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result != null && result.type == RayTraceResult.Type.BLOCK) {
return Optional.of(result.getBlockPos()); return Optional.of(result.getBlockPos());
} }
return Optional.empty(); return Optional.empty();
@@ -101,8 +101,8 @@ public interface IPlayerContext {
*/ */
default Optional<Entity> getSelectedEntity() { default Optional<Entity> getSelectedEntity() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.typeOfHit == RayTraceResult.Type.ENTITY) { if (result != null && result.type == RayTraceResult.Type.ENTITY) {
return Optional.of(result.entityHit); return Optional.of(result.entity);
} }
return Optional.empty(); return Optional.empty();
} }
@@ -18,6 +18,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.RayTraceFluidMode;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -40,13 +41,13 @@ public final class RayTraceUtils {
* @return The calculated raytrace result * @return The calculated raytrace result
*/ */
public static RayTraceResult rayTraceTowards(Entity entity, Rotation rotation, double blockReachDistance) { public static RayTraceResult rayTraceTowards(Entity entity, Rotation rotation, double blockReachDistance) {
Vec3d start = entity.getPositionEyes(1.0F); Vec3d start = entity.getEyePosition(1.0F);
Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation); Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation);
Vec3d end = start.add( Vec3d end = start.add(
direction.x * blockReachDistance, direction.x * blockReachDistance,
direction.y * blockReachDistance, direction.y * blockReachDistance,
direction.z * blockReachDistance direction.z * blockReachDistance
); );
return entity.world.rayTraceBlocks(start, end, false, false, true); return entity.world.rayTraceBlocks(start, end, RayTraceFluidMode.NEVER, false, true);
} }
} }
@@ -36,6 +36,9 @@ public class Rotation {
public Rotation(float yaw, float pitch) { public Rotation(float yaw, float pitch) {
this.yaw = yaw; this.yaw = yaw;
this.pitch = pitch; this.pitch = pitch;
if (Float.isInfinite(yaw) || Float.isNaN(yaw) || Float.isInfinite(pitch) || Float.isNaN(pitch)) {
throw new IllegalStateException(yaw + " " + pitch);
}
} }
/** /**
@@ -23,7 +23,13 @@ import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.*; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import java.util.Optional; import java.util.Optional;
@@ -174,11 +180,14 @@ public final class RotationUtils {
} }
IBlockState state = entity.world.getBlockState(pos); IBlockState state = entity.world.getBlockState(pos);
AxisAlignedBB aabb = state.getBoundingBox(entity.world, pos); VoxelShape shape = state.getShape(entity.world, pos);
if (shape.isEmpty()) {
shape = VoxelShapes.fullCube();
}
for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) { for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) {
double xDiff = aabb.minX * sideOffset.x + aabb.maxX * (1 - sideOffset.x); double xDiff = shape.getStart(EnumFacing.Axis.X) * sideOffset.x + shape.getEnd(EnumFacing.Axis.X) * (1 - sideOffset.x);
double yDiff = aabb.minY * sideOffset.y + aabb.maxY * (1 - sideOffset.y); double yDiff = shape.getStart(EnumFacing.Axis.Y) * sideOffset.y + shape.getEnd(EnumFacing.Axis.Y) * (1 - sideOffset.y);
double zDiff = aabb.minZ * sideOffset.z + aabb.maxZ * (1 - sideOffset.z); double zDiff = shape.getStart(EnumFacing.Axis.Z) * sideOffset.z + shape.getEnd(EnumFacing.Axis.Z) * (1 - sideOffset.z);
possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance); possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance);
if (possibleRotation.isPresent()) { if (possibleRotation.isPresent()) {
return possibleRotation; return possibleRotation;
@@ -199,10 +208,10 @@ public final class RotationUtils {
* @return The optional rotation * @return The optional rotation
*/ */
public static Optional<Rotation> reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) { public static Optional<Rotation> reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) {
Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); Rotation rotation = calcRotationFromVec3d(entity.getEyePosition(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch));
RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance);
//System.out.println(result); //System.out.println(result);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result != null && result.type == RayTraceResult.Type.BLOCK) {
if (result.getBlockPos().equals(pos)) { if (result.getBlockPos().equals(pos)) {
return Optional.of(rotation); return Optional.of(rotation);
} }
@@ -20,9 +20,12 @@ package baritone.api.utils;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.Settings; import baritone.api.Settings;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
import net.minecraft.util.registry.IRegistry;
import java.awt.*; import java.awt.*;
import java.io.BufferedReader; import java.io.BufferedReader;
@@ -43,13 +46,13 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static net.minecraft.client.Minecraft.getMinecraft;
public class SettingsUtil { public class SettingsUtil {
private static final Path SETTINGS_PATH = getMinecraft().gameDir.toPath().resolve("baritone").resolve("settings.txt"); private static final Path SETTINGS_PATH = Minecraft.getInstance().gameDir.toPath().resolve("baritone").resolve("settings.txt");
private static final Pattern SETTING_PATTERN = Pattern.compile("^(?<setting>[^ ]+) +(?<value>.+)"); // key and value split by the first space private static final Pattern SETTING_PATTERN = Pattern.compile("^(?<setting>[^ ]+) +(?<value>.+)"); // key and value split by the first space
private static boolean isComment(String line) { private static boolean isComment(String line) {
return line.startsWith("#") || line.startsWith("//"); return line.startsWith("#") || line.startsWith("//");
} }
@@ -233,15 +236,14 @@ public class SettingsUtil {
), ),
ITEM( ITEM(
Item.class, Item.class,
str -> Item.getByNameOrId(str.trim()), str -> IRegistry.ITEM.get(new ResourceLocation(str.trim())),
item -> Item.REGISTRY.getNameForObject(item).toString() item -> IRegistry.ITEM.getKey(item).toString()
), ),
LIST() { LIST() {
@Override @Override
public Object parse(ParserContext context, String raw) { public Object parse(ParserContext context, String raw) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0]; Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type); Parser parser = Parser.getParser(type);
return Stream.of(raw.split(",")) return Stream.of(raw.split(","))
.map(s -> parser.parse(context, s)) .map(s -> parser.parse(context, s))
.collect(Collectors.toList()); .collect(Collectors.toList());
+12 -5
View File
@@ -20,9 +20,10 @@ package baritone.api.utils;
import net.minecraft.block.BlockFire; import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.World; import net.minecraft.world.World;
/** /**
@@ -43,10 +44,16 @@ public final class VecUtils {
*/ */
public static Vec3d calculateBlockCenter(World world, BlockPos pos) { public static Vec3d calculateBlockCenter(World world, BlockPos pos) {
IBlockState b = world.getBlockState(pos); IBlockState b = world.getBlockState(pos);
AxisAlignedBB bbox = b.getBoundingBox(world, pos); VoxelShape shape = b.getCollisionShape(world, pos);
double xDiff = (bbox.minX + bbox.maxX) / 2; if (shape.isEmpty()) {
double yDiff = (bbox.minY + bbox.maxY) / 2; return getBlockPosCenter(pos);
double zDiff = (bbox.minZ + bbox.maxZ) / 2; }
double xDiff = (shape.getStart(EnumFacing.Axis.X) + shape.getEnd(EnumFacing.Axis.X)) / 2;
double yDiff = (shape.getStart(EnumFacing.Axis.Y) + shape.getEnd(EnumFacing.Axis.Y)) / 2;
double zDiff = (shape.getStart(EnumFacing.Axis.Z) + shape.getEnd(EnumFacing.Axis.Z)) / 2;
if (Double.isNaN(xDiff) || Double.isNaN(yDiff) || Double.isNaN(zDiff)) {
throw new IllegalStateException(b + " " + pos + " " + shape);
}
if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out
yDiff = 0; yDiff = 0;
} }
@@ -0,0 +1,105 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
import com.google.common.base.Strings;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.Agent;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication;
import net.minecraft.launchwrapper.Launch;
import java.io.File;
import java.lang.reflect.Field;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Based on GradleStart from ForgeGradle 2.3
*
* @author Brady
* @since 3/11/2019
*/
public class LaunchTesting {
public static void main(String[] args) {
Map<String, String> arguments = new HashMap<>();
hackNatives();
arguments.put("version", "BaritownedDeveloperEnvironment");
arguments.put("assetIndex", System.getenv("assetIndex"));
arguments.put("assetsDir", System.getenv().getOrDefault("assetDirectory", "assets"));
arguments.put("accessToken", "FML");
arguments.put("userProperties", "{}");
arguments.put("tweakClass", System.getenv("tweakClass"));
String password = System.getenv("password");
if (password != null && !password.isEmpty()) {
attemptLogin(arguments, System.getenv("username"), System.getenv("password"));
}
List<String> argsArray = new ArrayList<>();
arguments.forEach((k, v) -> {
argsArray.add("--" + k);
argsArray.add(v);
});
Launch.main(argsArray.toArray(new String[0]));
}
private static void hackNatives() {
String paths = System.getProperty("java.library.path");
String nativesDir = System.getenv().get("nativesDirectory");
if (Strings.isNullOrEmpty(paths))
paths = nativesDir;
else
paths += File.pathSeparator + nativesDir;
System.setProperty("java.library.path", paths);
// hack the classloader now.
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Throwable ignored) {}
}
private static void attemptLogin(Map<String, String> argMap, String username, String password) {
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) (new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1")).createUserAuthentication(Agent.MINECRAFT);
auth.setUsername(username);
auth.setPassword(password);
try {
auth.logIn();
} catch (AuthenticationException var4) {
throw new RuntimeException(var4);
}
argMap.put("accessToken", auth.getAuthenticatedToken());
argMap.put("uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
argMap.put("username", auth.getSelectedProfile().getName());
argMap.put("userType", auth.getUserType().getName());
argMap.put("userProperties", (new GsonBuilder()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(auth.getUserProperties()));
}
}
@@ -33,11 +33,11 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer {
protected BitArray storage; protected BitArray storage;
@Shadow @Shadow
protected IBlockStatePalette palette; protected IBlockStatePalette<IBlockState> palette;
@Override @Override
public IBlockState getAtPalette(int index) { public IBlockState getAtPalette(int index) {
return palette.getBlockState(index); return palette.get(index);
} }
@Override @Override
@@ -28,7 +28,10 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.Redirect;
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.GL_ONE;
import static org.lwjgl.opengl.GL11.GL_ZERO;
import static org.lwjgl.opengl.GL14.GL_CONSTANT_ALPHA;
import static org.lwjgl.opengl.GL14.GL_ONE_MINUS_CONSTANT_ALPHA;
@Mixin(ChunkRenderContainer.class) @Mixin(ChunkRenderContainer.class)
public class MixinChunkRenderContainer { public class MixinChunkRenderContainer {
@@ -41,11 +44,11 @@ public class MixinChunkRenderContainer {
) )
) )
private BlockPos getPosition(RenderChunk renderChunkIn) { private BlockPos getPosition(RenderChunk renderChunkIn) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer() && Minecraft.getInstance().world.getChunk(renderChunkIn.getPosition()).isEmpty()) {
GlStateManager.enableAlpha(); GlStateManager.enableAlphaTest();
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value); GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value);
GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); GlStateManager.blendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO);
} }
return renderChunkIn.getPosition(); return renderChunkIn.getPosition();
} }
@@ -43,7 +43,7 @@ public abstract class MixinChunkRenderWorker {
) )
) )
private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -23,6 +23,7 @@ import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EntityType;
import net.minecraft.world.World; import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@@ -44,9 +45,8 @@ public abstract class MixinEntityLivingBase extends Entity {
*/ */
private RotationMoveEvent jumpRotationEvent; private RotationMoveEvent jumpRotationEvent;
public MixinEntityLivingBase(World worldIn, RotationMoveEvent jumpRotationEvent) { public MixinEntityLivingBase(EntityType<?> entityTypeIn, World worldIn) {
super(worldIn); super(entityTypeIn, worldIn);
this.jumpRotationEvent = jumpRotationEvent;
} }
@Inject( @Inject(
@@ -58,10 +58,10 @@ public class MixinEntityPlayerSP {
} }
@Inject( @Inject(
method = "onUpdate", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/EntityPlayerSP.isRiding()Z", target = "net/minecraft/client/entity/EntityPlayerSP.isPassenger()Z",
shift = At.Shift.BY, shift = At.Shift.BY,
by = -3 by = -3
) )
@@ -74,7 +74,7 @@ public class MixinEntityPlayerSP {
} }
@Inject( @Inject(
method = "onUpdate", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/EntityPlayerSP.onUpdateWalkingPlayer()V", target = "net/minecraft/client/entity/EntityPlayerSP.onUpdateWalkingPlayer()V",
@@ -90,7 +90,7 @@ public class MixinEntityPlayerSP {
} }
@Redirect( @Redirect(
method = "onLivingUpdate", method = "livingTick",
at = @At( at = @At(
value = "FIELD", value = "FIELD",
target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z" target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z"
@@ -105,7 +105,7 @@ public class MixinEntityPlayerSP {
} }
@Redirect( @Redirect(
method = "onLivingUpdate", method = "livingTick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/settings/KeyBinding.isKeyDown()Z" target = "net/minecraft/client/settings/KeyBinding.isKeyDown()Z"
@@ -20,24 +20,24 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.GameRenderer;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class) @Mixin(GameRenderer.class)
public class MixinEntityRenderer { public class MixinGameRenderer {
@Inject( @Inject(
method = "renderWorldPass", method = "updateCameraAndRender(FJ)V",
at = @At( at = @At(
value = "INVOKE_STRING", value = "INVOKE_STRING",
target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"} args = {"ldc=hand"}
) )
) )
private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) { private void renderWorldPass(float partialTicks, long finishTimeNano, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks));
} }
@@ -0,0 +1,99 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.event.events.TabCompleteEvent;
import com.mojang.brigadier.context.StringRange;
import com.mojang.brigadier.suggestion.Suggestion;
import com.mojang.brigadier.suggestion.Suggestions;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.GuiTextField;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author Brady
* @since 10/9/2019
*/
@Mixin(GuiChat.class)
public class MixinGuiChat {
@Shadow
protected GuiTextField inputField;
@Shadow
@Final
protected List<String> commandUsage;
@Shadow
private CompletableFuture<Suggestions> pendingSuggestions;
@Inject(
method = "updateSuggestion",
at = @At("HEAD"),
cancellable = true
)
private void preUpdateSuggestion(CallbackInfo ci) {
// Anything that is present in the input text before the cursor position
String prefix = this.inputField.getText().substring(0, Math.min(this.inputField.getText().length(), this.inputField.getCursorPosition()));
TabCompleteEvent event = new TabCompleteEvent(prefix);
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onPreTabComplete(event);
if (event.isCancelled()) {
ci.cancel();
return;
}
if (event.completions != null) {
ci.cancel();
// TODO: Support populating the command usage
this.commandUsage.clear();
if (event.completions.length == 0) {
this.pendingSuggestions = Suggestions.empty();
} else {
int offset = this.inputField.getText().endsWith(" ")
? this.inputField.getCursorPosition()
: this.inputField.getText().lastIndexOf(" ") + 1; // If there is no space this is still 0 haha yes
List<Suggestion> suggestionList = Stream.of(event.completions)
.map(s -> new Suggestion(StringRange.between(offset, offset + s.length()), s))
.collect(Collectors.toList());
Suggestions suggestions = new Suggestions(
StringRange.between(offset, offset + suggestionList.stream().mapToInt(s -> s.getText().length()).max().orElse(0)),
suggestionList);
this.pendingSuggestions = new CompletableFuture<>();
this.pendingSuggestions.complete(suggestions);
}
}
}
}
@@ -35,14 +35,14 @@ public abstract class MixinItemStack implements IItemStack {
@Final @Final
private Item item; private Item item;
@Shadow
private int itemDamage;
@Unique @Unique
private int baritoneHash; private int baritoneHash;
@Shadow
protected abstract int getDamage();
private void recalculateHash() { private void recalculateHash() {
baritoneHash = item == null ? -1 : item.hashCode() + itemDamage; baritoneHash = item == null ? -1 : item.hashCode() + getDamage();
} }
@Inject( @Inject(
@@ -54,7 +54,7 @@ public abstract class MixinItemStack implements IItemStack {
} }
@Inject( @Inject(
method = "setItemDamage", method = "setDamage",
at = @At("TAIL") at = @At("TAIL")
) )
private void onItemDamageSet(CallbackInfo ci) { private void onItemDamageSet(CallbackInfo ci) {
@@ -100,10 +100,10 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Ljava/lang/String;)V", method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V",
at = @At("HEAD") at = @At("HEAD")
) )
private void preLoadWorld(WorldClient world, String loadingMessage, CallbackInfo ci) { private void preLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) {
// If we're unloading the world but one doesn't exist, ignore it // If we're unloading the world but one doesn't exist, ignore it
if (this.world == null && world == null) { if (this.world == null && world == null) {
return; return;
@@ -120,10 +120,10 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Ljava/lang/String;)V", method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V",
at = @At("RETURN") at = @At("RETURN")
) )
private void postLoadWorld(WorldClient world, String loadingMessage, CallbackInfo ci) { private void postLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) {
// still fire event for both null, as that means we've just finished exiting a world // still fire event for both null, as that means we've just finished exiting a world
// mc.world changing is only the primary baritone // mc.world changing is only the primary baritone
@@ -24,6 +24,7 @@ import baritone.api.event.events.type.EventState;
import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.play.server.SPacketChunkData; import net.minecraft.network.play.server.SPacketChunkData;
import net.minecraft.network.play.server.SPacketCombatEvent; import net.minecraft.network.play.server.SPacketCombatEvent;
import net.minecraft.network.play.server.SPacketUnloadChunk;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@@ -40,7 +41,7 @@ public class MixinNetHandlerPlayClient {
method = "handleChunkData", method = "handleChunkData",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/world/chunk/Chunk.read(Lnet/minecraft/network/PacketBuffer;IZ)V" target = "net/minecraft/client/multiplayer/ChunkProviderClient.func_212474_a(IILnet/minecraft/network/PacketBuffer;IZ)Lnet/minecraft/world/chunk/Chunk;"
) )
) )
private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { private void preRead(SPacketChunkData packetIn, CallbackInfo ci) {
@@ -77,6 +78,34 @@ public class MixinNetHandlerPlayClient {
} }
} }
@Inject(
method = "processChunkUnload",
at = @At("HEAD")
)
private void preChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.PRE, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
);
}
}
}
@Inject(
method = "processChunkUnload",
at = @At("RETURN")
)
private void postChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.POST, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
);
}
}
}
@Inject( @Inject(
method = "handleCombatEvent", method = "handleCombatEvent",
at = @At( at = @At(
@@ -53,7 +53,7 @@ public class MixinNetworkManager {
method = "dispatchPacket", method = "dispatchPacket",
at = @At("HEAD") at = @At("HEAD")
) )
private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) { private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return; return;
} }
@@ -69,7 +69,7 @@ public class MixinNetworkManager {
method = "dispatchPacket", method = "dispatchPacket",
at = @At("RETURN") at = @At("RETURN")
) )
private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) { private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return; return;
} }
@@ -85,7 +85,7 @@ public class MixinNetworkManager {
method = "channelRead0", method = "channelRead0",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/network/Packet.processPacket(Lnet/minecraft/network/INetHandler;)V" target = "net/minecraft/network/NetworkManager.processPacket(Lnet/minecraft/network/Packet;Lnet/minecraft/network/INetHandler;)V"
) )
) )
private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) { private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
@@ -23,8 +23,8 @@ import baritone.api.utils.IPlayerContext;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.RenderChunk; import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.client.renderer.chunk.RenderChunkCache;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ChunkCache;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.Redirect;
@@ -40,43 +40,11 @@ public class MixinRenderChunk {
method = "rebuildChunk", method = "rebuildChunk",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/world/ChunkCache.isEmpty()Z" target = "net/minecraft/client/renderer/chunk/RenderChunkCache.getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/state/IBlockState;"
) )
) )
private boolean isEmpty(ChunkCache chunkCache) { private IBlockState getBlockState(RenderChunkCache chunkCache, BlockPos pos) {
if (!chunkCache.isEmpty()) { if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
return false;
}
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
BlockPos position = ((RenderChunk) (Object) this).getPosition();
// RenderChunk extends from -1,-1,-1 to +16,+16,+16
// then the constructor of ChunkCache extends it one more (presumably to get things like the connected status of fences? idk)
// so if ANY of the adjacent chunks are loaded, we are unempty
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
if (baritone.bsi.isLoaded(16 * dx + position.getX(), 16 * dz + position.getZ())) {
return false;
}
}
}
}
}
return true;
}
@Redirect(
method = "rebuildChunk",
at = @At(
value = "INVOKE",
target = "net/minecraft/world/ChunkCache.getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/state/IBlockState;"
)
)
private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -17,23 +17,31 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import net.minecraft.client.gui.GuiChat; import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.RenderChunkCache;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GuiChat.ChatTabCompleter.class) @Mixin(RenderChunkCache.class)
public abstract class MixinChatTabCompleter extends MixinTabCompleter { public class MixinRenderChunkCache {
@Inject( @Redirect(
method = "complete", method = "generateCache",
at = @At("HEAD"), at = @At(
cancellable = true value = "INVOKE",
target = "net/minecraft/world/chunk/Chunk.isEmptyBetween(II)Z"
)
) )
private void onComplete(CallbackInfo ci) { private static boolean isEmpty(Chunk chunk, int yStart, int yEnd) {
if (dontComplete) { if (!chunk.isEmptyBetween(yStart, yEnd)) {
ci.cancel(); return false;
} }
if (chunk.isEmpty() && Baritone.settings().renderCachedChunks.value && Minecraft.getInstance().getIntegratedServer() == null) {
return false;
}
return true;
} }
} }
@@ -38,9 +38,9 @@ public class MixinRenderList {
) )
) )
private void popMatrix() { private void popMatrix() {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
// reset the blend func to normal (not dependent on constant alpha) // reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
} }
GlStateManager.popMatrix(); GlStateManager.popMatrix();
} }
@@ -1,60 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.properties.IProperty;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(targets = "net.minecraft.block.state.BlockStateContainer$StateImplementation")
public abstract class MixinStateImplementation {
@Shadow
@Final
private ImmutableMap<IProperty<?>, Comparable<?>> properties;
/**
* Block states are fucking immutable
*/
@Unique
private int hashCode;
@Inject(
method = "<init>*",
at = @At("RETURN")
)
private void onInit(CallbackInfo ci) {
hashCode = properties.hashCode();
}
/**
* Cache this instead of using the fucking map every time
*
* @author LoganDark
* @reason Regular IBlockState generates a new hash every fucking time. This is not needed when scanning millions
* per second
*/
@Override
@Overwrite
public int hashCode() {
return hashCode;
}
}
@@ -1,83 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.TabCompleteEvent;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.util.TabCompleter;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(TabCompleter.class)
public abstract class MixinTabCompleter {
@Shadow
@Final
protected GuiTextField textField;
@Shadow
protected boolean requestedCompletions;
@Shadow
public abstract void setCompletions(String... newCompl);
@Unique
protected boolean dontComplete = false;
@Inject(
method = "requestCompletions",
at = @At("HEAD"),
cancellable = true
)
private void onRequestCompletions(String prefix, CallbackInfo ci) {
if (!((Object) this instanceof GuiChat.ChatTabCompleter)) {
return;
}
IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone();
TabCompleteEvent event = new TabCompleteEvent(prefix);
baritone.getGameEventHandler().onPreTabComplete(event);
if (event.isCancelled()) {
ci.cancel();
return;
}
if (event.completions != null) {
ci.cancel();
this.dontComplete = true;
try {
this.requestedCompletions = true;
setCompletions(event.completions);
} finally {
this.dontComplete = false;
}
}
}
}
@@ -38,9 +38,9 @@ public class MixinVboRenderList {
) )
) )
private void popMatrix() { private void popMatrix() {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getMinecraft().isSingleplayer()) { if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
// reset the blend func to normal (not dependent on constant alpha) // reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
} }
GlStateManager.popMatrix(); GlStateManager.popMatrix();
} }
@@ -1,75 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.ChunkEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.multiplayer.WorldClient;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/2/2018
*/
@Mixin(WorldClient.class)
public class MixinWorldClient {
@Inject(
method = "doPreChunk",
at = @At("HEAD")
)
private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.PRE,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
}
}
@Inject(
method = "doPreChunk",
at = @At("RETURN")
)
private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
}
}
}
+4 -6
View File
@@ -11,14 +11,14 @@
"MixinAnvilChunkLoader", "MixinAnvilChunkLoader",
"MixinBitArray", "MixinBitArray",
"MixinBlockStateContainer", "MixinBlockStateContainer",
"MixinChatTabCompleter",
"MixinChunkProviderClient", "MixinChunkProviderClient",
"MixinChunkProviderServer", "MixinChunkProviderServer",
"MixinChunkRenderContainer", "MixinChunkRenderContainer",
"MixinChunkRenderWorker", "MixinChunkRenderWorker",
"MixinEntityLivingBase", "MixinEntityLivingBase",
"MixinEntityPlayerSP", "MixinEntityPlayerSP",
"MixinEntityRenderer", "MixinGameRenderer",
"MixinGuiChat",
"MixinGuiScreen", "MixinGuiScreen",
"MixinItemStack", "MixinItemStack",
"MixinMinecraft", "MixinMinecraft",
@@ -26,10 +26,8 @@
"MixinNetworkManager", "MixinNetworkManager",
"MixinPlayerControllerMP", "MixinPlayerControllerMP",
"MixinRenderChunk", "MixinRenderChunk",
"MixinRenderChunkCache",
"MixinRenderList", "MixinRenderList",
"MixinStateImplementation", "MixinVboRenderList"
"MixinTabCompleter",
"MixinVboRenderList",
"MixinWorldClient"
] ]
} }
+1 -1
View File
@@ -53,7 +53,7 @@ public class Baritone implements IBaritone {
static { static {
threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); dir = new File(Minecraft.getInstance().gameDir, "baritone");
if (!Files.exists(dir.toPath())) { if (!Files.exists(dir.toPath())) {
try { try {
Files.createDirectories(dir.toPath()); Files.createDirectories(dir.toPath());
@@ -134,7 +134,7 @@ public final class InventoryBehavior extends Behavior {
public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z)); IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z));
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())))) { if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.player(), stack, ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ)))))) {
return true; // gotem return true; // gotem
} }
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) { if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) {
@@ -28,9 +28,6 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
/** /**
* Target's values are as follows: * Target's values are as follows:
* <p>
* getFirst() -> yaw
* getSecond() -> pitch
*/ */
private Rotation target; private Rotation target;
@@ -53,6 +50,13 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
@Override @Override
public void updateTarget(Rotation target, boolean force) { public void updateTarget(Rotation target, boolean force) {
this.target = target; this.target = target;
if (!force) {
double rand = Math.random() - 0.5;
if (Math.abs(rand) < 0.1) {
rand *= 4;
}
this.target = new Rotation(this.target.getYaw() + (float) (rand * Baritone.settings().randomLooking113.value), this.target.getPitch());
}
this.force = force || !Baritone.settings().freeLook.value; this.force = force || !Baritone.settings().freeLook.value;
} }
+37 -20
View File
@@ -38,23 +38,13 @@ import java.util.Map;
public final class CachedChunk { public final class CachedChunk {
public static final ImmutableSet<Block> BLOCKS_TO_KEEP_TRACK_OF = ImmutableSet.of( public static final ImmutableSet<Block> BLOCKS_TO_KEEP_TRACK_OF = ImmutableSet.of(
Blocks.DIAMOND_BLOCK,
//Blocks.COAL_ORE,
Blocks.COAL_BLOCK,
//Blocks.IRON_ORE,
Blocks.IRON_BLOCK,
//Blocks.GOLD_ORE,
Blocks.GOLD_BLOCK,
Blocks.EMERALD_ORE,
Blocks.EMERALD_BLOCK,
Blocks.ENDER_CHEST, Blocks.ENDER_CHEST,
Blocks.FURNACE, Blocks.FURNACE,
Blocks.CHEST, Blocks.CHEST,
Blocks.TRAPPED_CHEST, Blocks.TRAPPED_CHEST,
Blocks.END_PORTAL, Blocks.END_PORTAL,
Blocks.END_PORTAL_FRAME, Blocks.END_PORTAL_FRAME,
Blocks.MOB_SPAWNER, Blocks.SPAWNER,
Blocks.BARRIER, Blocks.BARRIER,
Blocks.OBSERVER, Blocks.OBSERVER,
Blocks.WHITE_SHULKER_BOX, Blocks.WHITE_SHULKER_BOX,
@@ -65,7 +55,7 @@ public final class CachedChunk {
Blocks.LIME_SHULKER_BOX, Blocks.LIME_SHULKER_BOX,
Blocks.PINK_SHULKER_BOX, Blocks.PINK_SHULKER_BOX,
Blocks.GRAY_SHULKER_BOX, Blocks.GRAY_SHULKER_BOX,
Blocks.SILVER_SHULKER_BOX, Blocks.LIGHT_GRAY_SHULKER_BOX,
Blocks.CYAN_SHULKER_BOX, Blocks.CYAN_SHULKER_BOX,
Blocks.PURPLE_SHULKER_BOX, Blocks.PURPLE_SHULKER_BOX,
Blocks.BLUE_SHULKER_BOX, Blocks.BLUE_SHULKER_BOX,
@@ -73,25 +63,52 @@ public final class CachedChunk {
Blocks.GREEN_SHULKER_BOX, Blocks.GREEN_SHULKER_BOX,
Blocks.RED_SHULKER_BOX, Blocks.RED_SHULKER_BOX,
Blocks.BLACK_SHULKER_BOX, Blocks.BLACK_SHULKER_BOX,
Blocks.PORTAL, Blocks.NETHER_PORTAL,
Blocks.HOPPER, Blocks.HOPPER,
Blocks.BEACON, Blocks.BEACON,
Blocks.BREWING_STAND, Blocks.BREWING_STAND,
Blocks.SKULL,
// TODO: Maybe add a predicate for blocks to keep track of?
// This should really not need to happen
Blocks.CREEPER_HEAD,
Blocks.CREEPER_WALL_HEAD,
Blocks.DRAGON_HEAD,
Blocks.DRAGON_WALL_HEAD,
Blocks.PLAYER_HEAD,
Blocks.PLAYER_WALL_HEAD,
Blocks.ZOMBIE_HEAD,
Blocks.ZOMBIE_WALL_HEAD,
Blocks.SKELETON_SKULL,
Blocks.SKELETON_WALL_SKULL,
Blocks.WITHER_SKELETON_SKULL,
Blocks.WITHER_SKELETON_WALL_SKULL,
Blocks.ENCHANTING_TABLE, Blocks.ENCHANTING_TABLE,
Blocks.ANVIL, Blocks.ANVIL,
Blocks.LIT_FURNACE, Blocks.WHITE_BED,
Blocks.BED, Blocks.ORANGE_BED,
Blocks.MAGENTA_BED,
Blocks.LIGHT_BLUE_BED,
Blocks.YELLOW_BED,
Blocks.LIME_BED,
Blocks.PINK_BED,
Blocks.GRAY_BED,
Blocks.LIGHT_GRAY_BED,
Blocks.CYAN_BED,
Blocks.PURPLE_BED,
Blocks.BLUE_BED,
Blocks.BROWN_BED,
Blocks.GREEN_BED,
Blocks.RED_BED,
Blocks.BLACK_BED,
Blocks.DRAGON_EGG, Blocks.DRAGON_EGG,
Blocks.JUKEBOX, Blocks.JUKEBOX,
Blocks.END_GATEWAY, Blocks.END_GATEWAY,
Blocks.WEB, Blocks.COBWEB,
Blocks.NETHER_WART, Blocks.NETHER_WART,
Blocks.LADDER, Blocks.LADDER,
Blocks.VINE Blocks.VINE
); );
/** /**
* The size of the chunk data in bits. Equal to 16 KiB. * The size of the chunk data in bits. Equal to 16 KiB.
* <p> * <p>
@@ -170,8 +187,8 @@ public final class CachedChunk {
// we have this exact block, it's a surface block // we have this exact block, it's a surface block
/*System.out.println("Saying that " + x + "," + y + "," + z + " is " + state); /*System.out.println("Saying that " + x + "," + y + "," + z + " is " + state);
if (!Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock().equals(state.getBlock())) { if (!Minecraft.getInstance().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock().equals(state.getBlock())) {
throw new IllegalStateException("failed " + Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock() + " " + state.getBlock() + " " + (x + this.x * 16) + " " + y + " " + (z + this.z * 16)); throw new IllegalStateException("failed " + Minecraft.getInstance().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock() + " " + state.getBlock() + " " + (x + this.x * 16) + " " + y + " " + (z + this.z * 16));
}*/ }*/
return overview[internalPos]; return overview[internalPos];
} }
+1 -3
View File
@@ -184,9 +184,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
int distZ = ((region.getZ() << 9) + 256) - pruneCenter.getZ(); int distZ = ((region.getZ() << 9) + 256) - pruneCenter.getZ();
double dist = Math.sqrt(distX * distX + distZ * distZ); double dist = Math.sqrt(distX * distX + distZ * distZ);
if (dist > 1024) { if (dist > 1024) {
if (!Baritone.settings().censorCoordinates.value) { logDebug("Deleting cached region " + region.getX() + "," + region.getZ() + " from ram");
logDebug("Deleting cached region " + region.getX() + "," + region.getZ() + " from ram");
}
cachedRegions.remove(getRegionID(region.getX(), region.getZ())); cachedRegions.remove(getRegionID(region.getX(), region.getZ()));
} }
} }
+10 -9
View File
@@ -24,9 +24,10 @@ import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraft.world.chunk.ChunkSection;
import java.util.*; import java.util.*;
@@ -44,9 +45,9 @@ public final class ChunkPacker {
Map<String, List<BlockPos>> specialBlocks = new HashMap<>(); Map<String, List<BlockPos>> specialBlocks = new HashMap<>();
BitSet bitSet = new BitSet(CachedChunk.SIZE); BitSet bitSet = new BitSet(CachedChunk.SIZE);
try { try {
ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); ChunkSection[] chunkInternalStorageArray = chunk.getSections();
for (int y0 = 0; y0 < 16; y0++) { for (int y0 = 0; y0 < 16; y0++) {
ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0]; ChunkSection extendedblockstorage = chunkInternalStorageArray[y0];
if (extendedblockstorage == null) { if (extendedblockstorage == null) {
// any 16x16x16 area that's all air will have null storage // any 16x16x16 area that's all air will have null storage
// for example, in an ocean biome, with air from y=64 to y=256 // for example, in an ocean biome, with air from y=64 to y=256
@@ -58,7 +59,7 @@ public final class ChunkPacker {
// since a bitset is initialized to all zero, and air is saved as zeros // since a bitset is initialized to all zero, and air is saved as zeros
continue; continue;
} }
BlockStateContainer bsc = extendedblockstorage.getData(); BlockStateContainer<IBlockState> bsc = extendedblockstorage.getData();
int yReal = y0 << 4; int yReal = y0 << 4;
// the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x;
// for better cache locality, iterate in that order // for better cache locality, iterate in that order
@@ -105,10 +106,9 @@ public final class ChunkPacker {
return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis());
} }
private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) { private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) { if (MovementHelper.isWater(state)) {
// only water source blocks are plausibly usable, flowing water should be avoid // only water source blocks are plausibly usable, flowing water should be avoid
// FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong // FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong
if (MovementHelper.possiblyFlowing(state)) { if (MovementHelper.possiblyFlowing(state)) {
@@ -123,7 +123,8 @@ public final class ChunkPacker {
return PathingBlockType.AVOID; return PathingBlockType.AVOID;
} }
if (x == 0 || x == 15 || z == 0 || z == 15) { if (x == 0 || x == 15 || z == 0 || z == 15) {
if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) == -1000.0F) { Vec3d flow = state.getFluidState().getFlow(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4));
if (flow.x != 0.0 || flow.z != 0.0) {
return PathingBlockType.WATER; return PathingBlockType.WATER;
} }
return PathingBlockType.AVOID; return PathingBlockType.AVOID;
@@ -131,14 +132,14 @@ public final class ChunkPacker {
return PathingBlockType.WATER; return PathingBlockType.WATER;
} }
if (MovementHelper.avoidWalkingInto(block) || MovementHelper.isBottomSlab(state)) { if (MovementHelper.avoidWalkingInto(state) || MovementHelper.isBottomSlab(state)) {
return PathingBlockType.AVOID; return PathingBlockType.AVOID;
} }
// We used to do an AABB check here // We used to do an AABB check here
// however, this failed in the nether when you were near a nether fortress // however, this failed in the nether when you were near a nether fortress
// because fences check their adjacent blocks in the world for their fence connection status to determine AABB shape // because fences check their adjacent blocks in the world for their fence connection status to determine AABB shape
// this caused a nullpointerexception when we saved chunks on unload, because they were unable to check their neighbors // this caused a nullpointerexception when we saved chunks on unload, because they were unable to check their neighbors
if (block == Blocks.AIR || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) { if (block instanceof BlockAir || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) {
return PathingBlockType.AIR; return PathingBlockType.AIR;
} }
+4 -3
View File
@@ -24,6 +24,7 @@ import baritone.utils.accessor.IAnvilChunkLoader;
import baritone.utils.accessor.IChunkProviderServer; import baritone.utils.accessor.IChunkProviderServer;
import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldServer; import net.minecraft.world.WorldServer;
import net.minecraft.world.dimension.DimensionType;
import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.SystemUtils;
import java.io.File; import java.io.File;
@@ -55,7 +56,7 @@ public class WorldProvider implements IWorldProvider, Helper {
* *
* @param dimension The ID of the world's dimension * @param dimension The ID of the world's dimension
*/ */
public final void initWorld(int dimension) { public final void initWorld(DimensionType dimension) {
File directory; File directory;
File readme; File readme;
@@ -92,7 +93,7 @@ public class WorldProvider implements IWorldProvider, Helper {
} catch (IOException ignored) {} } catch (IOException ignored) {}
// We will actually store the world data in a subfolder: "DIM<id>" // We will actually store the world data in a subfolder: "DIM<id>"
Path dir = new File(directory, "DIM" + dimension).toPath(); Path dir = new File(directory, "DIM" + dimension.getId()).toPath();
if (!Files.exists(dir)) { if (!Files.exists(dir)) {
try { try {
Files.createDirectories(dir); Files.createDirectories(dir);
@@ -101,7 +102,7 @@ public class WorldProvider implements IWorldProvider, Helper {
System.out.println("Baritone world data dir: " + dir); System.out.println("Baritone world data dir: " + dir);
synchronized (worldCache) { synchronized (worldCache) {
this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimension)); this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimension.getId()));
} }
} }
+6 -6
View File
@@ -28,8 +28,8 @@ import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import java.util.*; import java.util.*;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@@ -72,7 +72,7 @@ public enum WorldScanner implements IWorldScanner {
foundChunks = true; foundChunks = true;
int chunkX = xoff + playerChunkX; int chunkX = xoff + playerChunkX;
int chunkZ = zoff + playerChunkZ; int chunkZ = zoff + playerChunkZ;
Chunk chunk = chunkProvider.getLoadedChunk(chunkX, chunkZ); Chunk chunk = chunkProvider.getChunk(chunkX, chunkZ, false, false);
if (chunk == null) { if (chunk == null) {
continue; continue;
} }
@@ -99,7 +99,7 @@ public enum WorldScanner implements IWorldScanner {
} }
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z); Chunk chunk = chunkProvider.getChunk(pos.x, pos.z, false, false);
int playerY = ctx.playerFeet().getY(); int playerY = ctx.playerFeet().getY();
if (chunk == null || chunk.isEmpty()) { if (chunk == null || chunk.isEmpty()) {
@@ -134,7 +134,7 @@ public enum WorldScanner implements IWorldScanner {
int queued = 0; int queued = 0;
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) { for (int z = minZ; z <= maxZ; z++) {
Chunk chunk = chunkProvider.getLoadedChunk(x, z); Chunk chunk = chunkProvider.getChunk(x, z, false, false);
if (chunk != null && !chunk.isEmpty()) { if (chunk != null && !chunk.isEmpty()) {
queued++; queued++;
@@ -147,11 +147,11 @@ public enum WorldScanner implements IWorldScanner {
} }
private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) {
ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray(); ChunkSection[] chunkInternalStorageArray = chunk.getSections();
boolean foundWithinY = false; boolean foundWithinY = false;
for (int yIndex = 0; yIndex < 16; yIndex++) { for (int yIndex = 0; yIndex < 16; yIndex++) {
int y0 = coordinateIterationOrder[yIndex]; int y0 = coordinateIterationOrder[yIndex];
ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0]; ChunkSection extendedblockstorage = chunkInternalStorageArray[y0];
if (extendedblockstorage == null) { if (extendedblockstorage == null) {
continue; continue;
} }
@@ -68,7 +68,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
event.cancel(); event.cancel();
String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length()); String commandStr = msg.substring(forceRun ? FORCE_COMMAND_PREFIX.length() : prefix.length());
if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) { if (!runCommand(commandStr) && !commandStr.trim().isEmpty()) {
new CommandNotFoundException(CommandManager.expand(commandStr).getFirst()).handle(null, null); new CommandNotFoundException(CommandManager.expand(commandStr).getA()).handle(null, null);
} }
} else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) { } else if ((settings.chatControl.value || settings.chatControlAnyway.value) && runCommand(msg)) {
event.cancel(); event.cancel();
@@ -108,9 +108,9 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
return this.runCommand("help"); return this.runCommand("help");
} }
Tuple<String, List<ICommandArgument>> pair = CommandManager.expand(msg); Tuple<String, List<ICommandArgument>> pair = CommandManager.expand(msg);
String command = pair.getFirst(); String command = pair.getA();
String rest = msg.substring(pair.getFirst().length()); String rest = msg.substring(pair.getA().length());
ArgConsumer argc = new ArgConsumer(this.manager, pair.getSecond()); ArgConsumer argc = new ArgConsumer(this.manager, pair.getB());
if (!argc.hasAny()) { if (!argc.hasAny()) {
Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US)); Settings.Setting setting = settings.byLowerName.get(command.toLowerCase(Locale.US));
if (setting != null) { if (setting != null) {
@@ -127,7 +127,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
if (setting.getName().equals("logger")) { if (setting.getName().equals("logger")) {
continue; continue;
} }
if (setting.getName().equalsIgnoreCase(pair.getFirst())) { if (setting.getName().equalsIgnoreCase(pair.getA())) {
logRanCommand(command, rest); logRanCommand(command, rest);
try { try {
this.manager.execute(String.format("set %s %s", setting.getName(), argc.getString())); this.manager.execute(String.format("set %s %s", setting.getName(), argc.getString()));
@@ -138,7 +138,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
} }
// If the command exists, then handle echoing the input // If the command exists, then handle echoing the input
if (this.manager.getCommand(pair.getFirst()) != null) { if (this.manager.getCommand(pair.getA()) != null) {
logRanCommand(command, rest); logRanCommand(command, rest);
} }
@@ -36,7 +36,7 @@ import java.util.stream.Stream;
public class BuildCommand extends Command { public class BuildCommand extends Command {
private static final File schematicsDir = new File(Minecraft.getMinecraft().gameDir, "schematics"); private static final File schematicsDir = new File(mc.gameDir, "schematics");
public BuildCommand(IBaritone baritone) { public BuildCommand(IBaritone baritone) {
super(baritone, "build"); super(baritone, "build");
@@ -24,6 +24,7 @@ import baritone.api.command.datatypes.BlockById;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.util.registry.IRegistry;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -46,7 +47,7 @@ public class FindCommand extends Command {
toFind.stream() toFind.stream()
.flatMap(block -> .flatMap(block ->
ctx.worldData().getCachedWorld().getLocationsOf( ctx.worldData().getCachedWorld().getLocationsOf(
Block.REGISTRY.getNameForObject(block).getPath(), IRegistry.BLOCK.getKey(block).getPath(),
Integer.MAX_VALUE, Integer.MAX_VALUE,
origin.x, origin.x,
origin.y, origin.y,
@@ -26,10 +26,11 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.*; import java.util.*;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -47,7 +48,7 @@ public class FollowCommand extends Command {
FollowGroup group; FollowGroup group;
FollowList list; FollowList list;
List<Entity> entities = new ArrayList<>(); List<Entity> entities = new ArrayList<>();
List<Class<? extends Entity>> classes = new ArrayList<>(); List<EntityType> classes = new ArrayList<>();
if (args.hasExactlyOne()) { if (args.hasExactlyOne()) {
baritone.getFollowProcess().follow((group = args.getEnum(FollowGroup.class)).filter); baritone.getFollowProcess().follow((group = args.getEnum(FollowGroup.class)).filter);
} else { } else {
@@ -56,9 +57,9 @@ public class FollowCommand extends Command {
list = args.getEnum(FollowList.class); list = args.getEnum(FollowList.class);
while (args.hasAny()) { while (args.hasAny()) {
Object gotten = args.getDatatypeFor(list.datatype); Object gotten = args.getDatatypeFor(list.datatype);
if (gotten instanceof Class) { if (gotten instanceof EntityType) {
//noinspection unchecked //noinspection unchecked
classes.add((Class<? extends Entity>) gotten); classes.add((EntityType) gotten);
} else { } else {
entities.add((Entity) gotten); entities.add((Entity) gotten);
} }
@@ -66,7 +67,7 @@ public class FollowCommand extends Command {
baritone.getFollowProcess().follow( baritone.getFollowProcess().follow(
classes.isEmpty() classes.isEmpty()
? entities::contains ? entities::contains
: e -> classes.stream().anyMatch(c -> c.isInstance(e)) : e -> classes.stream().anyMatch(c -> c.getEntityClass().isInstance(e))
); );
} }
if (group != null) { if (group != null) {
@@ -79,7 +80,7 @@ public class FollowCommand extends Command {
.forEach(this::logDirect); .forEach(this::logDirect);
} else { } else {
classes.stream() classes.stream()
.map(EntityList::getKey) .map(IRegistry.ENTITY_TYPE::getKey)
.map(Objects::requireNonNull) .map(Objects::requireNonNull)
.map(ResourceLocation::toString) .map(ResourceLocation::toString)
.forEach(this::logDirect); .forEach(this::logDirect);
@@ -38,7 +38,7 @@ public class RenderCommand extends Command {
args.requireMax(0); args.requireMax(0);
BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos origin = ctx.playerFeet();
int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16; int renderDistance = (mc.gameSettings.renderDistanceChunks + 1) * 16;
mc.renderGlobal.markBlockRangeForRenderUpdate( mc.worldRenderer.markBlockRangeForRenderUpdate(
origin.x - renderDistance, origin.x - renderDistance,
0, 0,
origin.z - renderDistance, origin.z - renderDistance,
@@ -23,10 +23,10 @@ import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument; import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.exception.CommandUnhandledException; import baritone.api.command.exception.CommandUnhandledException;
import baritone.api.command.exception.ICommandException; import baritone.api.command.exception.ICommandException;
import baritone.command.argument.ArgConsumer;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.manager.ICommandManager; import baritone.api.command.manager.ICommandManager;
import baritone.api.command.registry.Registry; import baritone.api.command.registry.Registry;
import baritone.command.argument.ArgConsumer;
import baritone.command.argument.CommandArguments; import baritone.command.argument.CommandArguments;
import baritone.command.defaults.DefaultCommands; import baritone.command.defaults.DefaultCommands;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
@@ -35,6 +35,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* The default, internal implementation of {@link ICommandManager} * The default, internal implementation of {@link ICommandManager}
* *
@@ -94,8 +95,8 @@ public class CommandManager implements ICommandManager {
@Override @Override
public Stream<String> tabComplete(String prefix) { public Stream<String> tabComplete(String prefix) {
Tuple<String, List<ICommandArgument>> pair = expand(prefix, true); Tuple<String, List<ICommandArgument>> pair = expand(prefix, true);
String label = pair.getFirst(); String label = pair.getA();
List<ICommandArgument> args = pair.getSecond(); List<ICommandArgument> args = pair.getB();
if (args.isEmpty()) { if (args.isEmpty()) {
return new TabCompleteHelper() return new TabCompleteHelper()
.addCommands(this.baritone.getCommandManager()) .addCommands(this.baritone.getCommandManager())
@@ -107,8 +108,8 @@ public class CommandManager implements ICommandManager {
} }
private ExecutionWrapper from(Tuple<String, List<ICommandArgument>> expanded) { private ExecutionWrapper from(Tuple<String, List<ICommandArgument>> expanded) {
String label = expanded.getFirst(); String label = expanded.getA();
ArgConsumer args = new ArgConsumer(this, expanded.getSecond()); ArgConsumer args = new ArgConsumer(this, expanded.getB());
ICommand command = this.getCommand(label); ICommand command = this.getCommand(label);
return command == null ? null : new ExecutionWrapper(command, label, args); return command == null ? null : new ExecutionWrapper(command, label, args);
@@ -125,6 +126,7 @@ public class CommandManager implements ICommandManager {
} }
private static final class ExecutionWrapper { private static final class ExecutionWrapper {
private ICommand command; private ICommand command;
private String label; private String label;
private ArgConsumer args; private ArgConsumer args;
@@ -89,7 +89,7 @@ public final class GameEventHandler implements IEventBus, Helper {
// to make sure the chunk being unloaded is already loaded. // to make sure the chunk being unloaded is already loaded.
boolean isPreUnload = state == EventState.PRE boolean isPreUnload = state == EventState.PRE
&& type == ChunkEvent.Type.UNLOAD && type == ChunkEvent.Type.UNLOAD
&& world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ()); && world.getChunkProvider().getChunk(event.getX(), event.getZ(), false, false) != null;
if (isPostPopulate || isPreUnload) { if (isPostPopulate || isPreUnload) {
baritone.getWorldProvider().ifWorldLoaded(worldData -> { baritone.getWorldProvider().ifWorldLoaded(worldData -> {
@@ -114,7 +114,7 @@ public final class GameEventHandler implements IEventBus, Helper {
if (event.getState() == EventState.POST) { if (event.getState() == EventState.POST) {
cache.closeWorld(); cache.closeWorld();
if (event.getWorld() != null) { if (event.getWorld() != null) {
cache.initWorld(event.getWorld().provider.getDimensionType().getId()); cache.initWorld(event.getWorld().getDimension().getType());
} }
} }
@@ -85,7 +85,7 @@ public class CalculationContext {
this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread);
this.toolSet = new ToolSet(player); this.toolSet = new ToolSet(player);
this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway(); this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway();
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.getDimension().isNether();
this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6; this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value; this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value;
this.allowBreak = Baritone.settings().allowBreak.value; this.allowBreak = Baritone.settings().allowBreak.value;
@@ -25,7 +25,6 @@ import baritone.api.utils.*;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.BlockLiquid;
import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
@@ -123,7 +122,7 @@ public abstract class Movement implements IMovement, MovementHelper {
*/ */
@Override @Override
public MovementStatus update() { public MovementStatus update() {
ctx.player().capabilities.isFlying = false; ctx.player().abilities.isFlying = false;
currentState = updateState(currentState); currentState = updateState(currentState);
if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) {
currentState.setInput(Input.JUMP, true); currentState.setInput(Input.JUMP, true);
@@ -161,7 +160,7 @@ public abstract class Movement implements IMovement, MovementHelper {
if (!ctx.world().getEntitiesWithinAABB(EntityFallingBlock.class, new AxisAlignedBB(0, 0, 0, 1, 1.1, 1).offset(blockPos)).isEmpty() && Baritone.settings().pauseMiningForFallingBlocks.value) { if (!ctx.world().getEntitiesWithinAABB(EntityFallingBlock.class, new AxisAlignedBB(0, 0, 0, 1, 1.1, 1).offset(blockPos)).isEmpty() && Baritone.settings().pauseMiningForFallingBlocks.value) {
return false; return false;
} }
if (!MovementHelper.canWalkThrough(ctx, blockPos) && !(BlockStateInterface.getBlock(ctx, blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try if (!MovementHelper.canWalkThrough(ctx, blockPos)) { // can't break air, so don't try
somethingInTheWay = true; somethingInTheWay = true;
MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos));
Optional<Rotation> reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); Optional<Rotation> reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance());
@@ -177,7 +176,7 @@ public abstract class Movement implements IMovement, MovementHelper {
//i'm doing it anyway //i'm doing it anyway
//i dont care if theres snow in the way!!!!!!! //i dont care if theres snow in the way!!!!!!!
//you dont own me!!!! //you dont own me!!!!
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getEyePosition(1.0F),
VecUtils.getBlockPosCenter(blockPos), ctx.playerRotations()), true) VecUtils.getBlockPosCenter(blockPos), ctx.playerRotations()), true)
); );
// don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block // don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block
@@ -28,14 +28,21 @@ import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet; import baritone.utils.ToolSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.fluid.FlowingFluid;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.init.Fluids;
import net.minecraft.pathfinding.PathType;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.properties.SlabType;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IBlockReader;
import java.util.Optional; import java.util.Optional;
@@ -73,7 +80,7 @@ public interface MovementHelper extends ActionCosts, Helper {
&& BlockFalling.canFallThrough(bsi.get0(x, y - 1, z))) { // and if it would fall (i.e. it's unsupported) && BlockFalling.canFallThrough(bsi.get0(x, y - 1, z))) { // and if it would fall (i.e. it's unsupported)
return true; // dont break a block that is adjacent to unsupported gravel because it can cause really weird stuff return true; // dont break a block that is adjacent to unsupported gravel because it can cause really weird stuff
} }
return block instanceof BlockLiquid; return !state.getFluidState().isEmpty();
} }
static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) {
@@ -86,10 +93,10 @@ public interface MovementHelper extends ActionCosts, Helper {
static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block == Blocks.AIR) { // early return for most common case if (block instanceof BlockAir) { // early return for most common case
return true; return true;
} }
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull || block instanceof BlockTrapDoor) { if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.COBWEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockAbstractSkull || block == Blocks.BUBBLE_COLUMN || block instanceof BlockShulkerBox || block instanceof BlockSlab || block instanceof BlockTrapDoor) {
return false; return false;
} }
if (Baritone.settings().blocksToAvoid.value.contains(block)) { if (Baritone.settings().blocksToAvoid.value.contains(block)) {
@@ -101,10 +108,10 @@ public interface MovementHelper extends ActionCosts, Helper {
// be opened by just interacting. // be opened by just interacting.
return block != Blocks.IRON_DOOR; return block != Blocks.IRON_DOOR;
} }
if (block == Blocks.CARPET) { if (block instanceof BlockCarpet) {
return canWalkOn(bsi, x, y - 1, z); return canWalkOn(bsi, x, y - 1, z);
} }
if (block instanceof BlockSnow) { if (block instanceof BlockSnowLayer) {
// we've already checked doors and fence gates // we've already checked doors and fence gates
// so the only remaining dynamic isPassables are snow and trapdoor // so the only remaining dynamic isPassables are snow and trapdoor
// if they're cached as a top block, we don't know their metadata // if they're cached as a top block, we don't know their metadata
@@ -114,7 +121,7 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
// the check in BlockSnow.isPassable is layers < 5 // the check in BlockSnow.isPassable is layers < 5
// while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling
if (state.getValue(BlockSnow.LAYERS) >= 3) { if (state.get(BlockSnowLayer.LAYERS) >= 3) {
return false; return false;
} }
// ok, it's low enough we could walk through it, but is it supported? // ok, it's low enough we could walk through it, but is it supported?
@@ -123,18 +130,21 @@ public interface MovementHelper extends ActionCosts, Helper {
if (isFlowing(x, y, z, state, bsi)) { if (isFlowing(x, y, z, state, bsi)) {
return false; // Don't walk through flowing liquids return false; // Don't walk through flowing liquids
} }
if (block instanceof BlockLiquid) { IFluidState fluidState = state.getFluidState();
if (fluidState.getFluid() instanceof WaterFluid) {
if (Baritone.settings().assumeWalkOnWater.value) { if (Baritone.settings().assumeWalkOnWater.value) {
return false; return false;
} }
IBlockState up = bsi.get0(x, y + 1, z); IBlockState up = bsi.get0(x, y + 1, z);
if (up.getBlock() instanceof BlockLiquid || up.getBlock() instanceof BlockLilyPad) { if (!up.getFluidState().isEmpty() || up.getBlock() instanceof BlockLilyPad) {
return false; return false;
} }
return block == Blocks.WATER || block == Blocks.FLOWING_WATER; return true;
} }
// every block that overrides isPassable with anything more complicated than a "return true;" or "return false;"
return block.isPassable(bsi.access, bsi.isPassableBlockPos.setPos(x, y, z)); // has already been accounted for above
// therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null
return state.allowsMovement(bsi.access, BlockPos.ORIGIN, PathType.LAND); // workaround for future compatibility =P
} }
/** /**
@@ -159,29 +169,30 @@ public interface MovementHelper extends ActionCosts, Helper {
return fullyPassable(ctx.world(), pos, ctx.world().getBlockState(pos)); return fullyPassable(ctx.world(), pos, ctx.world().getBlockState(pos));
} }
static boolean fullyPassable(IBlockAccess access, BlockPos pos, IBlockState state) { static boolean fullyPassable(IBlockReader access, BlockPos pos, IBlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block == Blocks.AIR) { // early return for most common case if (block instanceof BlockAir) { // early return for most common case
return true; return true;
} }
// exceptions - blocks that are isPassable true, but we can't actually jump through // exceptions - blocks that are isPassable true, but we can't actually jump through
if (block == Blocks.FIRE if (block == Blocks.FIRE
|| block == Blocks.TRIPWIRE || block == Blocks.TRIPWIRE
|| block == Blocks.WEB || block == Blocks.COBWEB
|| block == Blocks.VINE || block == Blocks.VINE
|| block == Blocks.LADDER || block == Blocks.LADDER
|| block == Blocks.COCOA || block == Blocks.COCOA
|| block instanceof BlockDoor || block instanceof BlockDoor
|| block instanceof BlockFenceGate || block instanceof BlockFenceGate
|| block instanceof BlockSnow || block instanceof BlockSnow
|| block instanceof BlockLiquid || !state.getFluidState().isEmpty()
|| block instanceof BlockTrapDoor || block instanceof BlockTrapDoor
|| block instanceof BlockEndPortal || block instanceof BlockEndPortal
|| block instanceof BlockSkull) { || block instanceof BlockSkull
|| block instanceof BlockShulkerBox) {
return false; return false;
} }
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters // door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
return block.isPassable(access, pos); return state.allowsMovement(access, pos, PathType.LAND);
} }
static boolean isReplaceable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { static boolean isReplaceable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) {
@@ -196,20 +207,19 @@ public interface MovementHelper extends ActionCosts, Helper {
* } * }
*/ */
Block block = state.getBlock(); Block block = state.getBlock();
if (block == Blocks.AIR || isWater(block)) { if (block instanceof BlockAir) {
// early return for common cases hehe // early return for common cases hehe
return true; return true;
} }
if (block instanceof BlockSnow) { if (block instanceof BlockSnowLayer) {
// as before, default to true (mostly because it would otherwise make long distance pathing through snowy biomes impossible) // as before, default to true (mostly because it would otherwise make long distance pathing through snowy biomes impossible)
if (!bsi.worldContainsLoadedChunk(x, z)) { if (!bsi.worldContainsLoadedChunk(x, z)) {
return true; return true;
} }
return state.getValue(BlockSnow.LAYERS) == 1; return state.get(BlockSnowLayer.LAYERS) == 1;
} }
if (block instanceof BlockDoublePlant) { if (block == Blocks.LARGE_FERN || block == Blocks.TALL_GRASS) {
BlockDoublePlant.EnumPlantType kek = state.getValue(BlockDoublePlant.VARIANT); return true;
return kek == BlockDoublePlant.EnumPlantType.FERN || kek == BlockDoublePlant.EnumPlantType.GRASS;
} }
return state.getMaterial().isReplaceable(); return state.getMaterial().isReplaceable();
} }
@@ -242,16 +252,16 @@ public interface MovementHelper extends ActionCosts, Helper {
return true; return true;
} }
return state.getValue(BlockFenceGate.OPEN); return state.get(BlockFenceGate.OPEN);
} }
static boolean isHorizontalBlockPassable(BlockPos blockPos, IBlockState blockState, BlockPos playerPos, PropertyBool propertyOpen) { static boolean isHorizontalBlockPassable(BlockPos blockPos, IBlockState blockState, BlockPos playerPos, BooleanProperty propertyOpen) {
if (playerPos.equals(blockPos)) { if (playerPos.equals(blockPos)) {
return false; return false;
} }
EnumFacing.Axis facing = blockState.getValue(BlockHorizontal.FACING).getAxis(); EnumFacing.Axis facing = blockState.get(BlockHorizontal.HORIZONTAL_FACING).getAxis();
boolean open = blockState.getValue(propertyOpen); boolean open = blockState.get(propertyOpen);
EnumFacing.Axis playerFacing; EnumFacing.Axis playerFacing;
if (playerPos.north().equals(blockPos) || playerPos.south().equals(blockPos)) { if (playerPos.north().equals(blockPos) || playerPos.south().equals(blockPos)) {
@@ -265,13 +275,15 @@ public interface MovementHelper extends ActionCosts, Helper {
return (facing == playerFacing) == open; return (facing == playerFacing) == open;
} }
static boolean avoidWalkingInto(Block block) { static boolean avoidWalkingInto(IBlockState state) {
return block instanceof BlockLiquid Block block = state.getBlock();
|| block == Blocks.MAGMA return !state.getFluidState().isEmpty()
|| block == Blocks.MAGMA_BLOCK
|| block == Blocks.CACTUS || block == Blocks.CACTUS
|| block == Blocks.FIRE || block == Blocks.FIRE
|| block == Blocks.END_PORTAL || block == Blocks.END_PORTAL
|| block == Blocks.WEB; || block == Blocks.COBWEB
|| block == Blocks.BUBBLE_COLUMN;
} }
/** /**
@@ -288,7 +300,7 @@ public interface MovementHelper extends ActionCosts, Helper {
*/ */
static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block == Blocks.AIR || block == Blocks.MAGMA) { if (block instanceof BlockAir || block == Blocks.MAGMA_BLOCK || block == Blocks.BUBBLE_COLUMN) {
// early return for most common case (air) // early return for most common case (air)
// plus magma, which is a normal cube but it hurts you // plus magma, which is a normal cube but it hurts you
return false; return false;
@@ -305,33 +317,31 @@ public interface MovementHelper extends ActionCosts, Helper {
if (block == Blocks.ENDER_CHEST || block == Blocks.CHEST) { if (block == Blocks.ENDER_CHEST || block == Blocks.CHEST) {
return true; return true;
} }
if (isWater(block)) { if (isWater(state)) {
// since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()"
// BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability
Block up = bsi.get0(x, y + 1, z).getBlock(); IBlockState upState = bsi.get0(x, y + 1, z);
if (up == Blocks.WATERLILY || up == Blocks.CARPET) { Block up = upState.getBlock();
if (up == Blocks.LILY_PAD || up instanceof BlockCarpet) {
return true; return true;
} }
if (isFlowing(x, y, z, state, bsi) || block == Blocks.FLOWING_WATER) { if (isFlowing(x, y, z, state, bsi) || upState.getFluidState().getFluid() == Fluids.FLOWING_WATER) {
// the only scenario in which we can walk on flowing water is if it's under still water with jesus off // the only scenario in which we can walk on flowing water is if it's under still water with jesus off
return isWater(up) && !Baritone.settings().assumeWalkOnWater.value; return isWater(upState) && !Baritone.settings().assumeWalkOnWater.value;
} }
// if assumeWalkOnWater is on, we can only walk on water if there isn't water above it // if assumeWalkOnWater is on, we can only walk on water if there isn't water above it
// if assumeWalkOnWater is off, we can only walk on water if there is water above it // if assumeWalkOnWater is off, we can only walk on water if there is water above it
return isWater(up) ^ Baritone.settings().assumeWalkOnWater.value; return isWater(upState) ^ Baritone.settings().assumeWalkOnWater.value;
} }
if (Baritone.settings().assumeWalkOnLava.value && isLava(block) && !isFlowing(x, y, z, state, bsi)) { if (Baritone.settings().assumeWalkOnLava.value && isLava(state) && !isFlowing(x, y, z, state, bsi)) {
return true; return true;
} }
if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) { if (block == Blocks.GLASS || block instanceof BlockStainedGlass) {
return true; return true;
} }
if (block instanceof BlockSlab) { if (block instanceof BlockSlab) {
if (!Baritone.settings().allowWalkOnBottomSlab.value) { if (!Baritone.settings().allowWalkOnBottomSlab.value) {
if (((BlockSlab) block).isDouble()) { return state.isTopSolid();
return true;
}
return state.getValue(BlockSlab.HALF) != BlockSlab.EnumBlockHalf.BOTTOM;
} }
return true; return true;
} }
@@ -370,7 +380,7 @@ public interface MovementHelper extends ActionCosts, Helper {
// can we look at the center of a side face of this block and likely be able to place? // can we look at the center of a side face of this block and likely be able to place?
// (thats how this check is used) // (thats how this check is used)
// therefore dont include weird things that we technically could place against (like carpet) but practically can't // therefore dont include weird things that we technically could place against (like carpet) but practically can't
return state.isBlockNormalCube() || state.isFullBlock() || state.getBlock() == Blocks.GLASS || state.getBlock() == Blocks.STAINED_GLASS; return state.isBlockNormalCube() || state.isFullCube() || state.getBlock() == Blocks.GLASS || state.getBlock() instanceof BlockStainedGlass;
} }
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) {
@@ -380,7 +390,7 @@ public interface MovementHelper extends ActionCosts, Helper {
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) {
Block block = state.getBlock(); Block block = state.getBlock();
if (!canWalkThrough(context.bsi, x, y, z, state)) { if (!canWalkThrough(context.bsi, x, y, z, state)) {
if (block instanceof BlockLiquid) { if (!state.getFluidState().isEmpty()) {
return COST_INF; return COST_INF;
} }
double mult = context.breakCostMultiplierAt(x, y, z, state); double mult = context.breakCostMultiplierAt(x, y, z, state);
@@ -410,8 +420,7 @@ public interface MovementHelper extends ActionCosts, Helper {
static boolean isBottomSlab(IBlockState state) { static boolean isBottomSlab(IBlockState state) {
return state.getBlock() instanceof BlockSlab return state.getBlock() instanceof BlockSlab
&& !((BlockSlab) state.getBlock()).isDouble() && state.get(BlockSlab.TYPE) == SlabType.BOTTOM;
&& state.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM;
} }
/** /**
@@ -448,11 +457,12 @@ public interface MovementHelper extends ActionCosts, Helper {
* Returns whether or not the specified block is * Returns whether or not the specified block is
* water, regardless of whether or not it is flowing. * water, regardless of whether or not it is flowing.
* *
* @param b The block * @param state The block state
* @return Whether or not the block is water * @return Whether or not the block is water
*/ */
static boolean isWater(Block b) { static boolean isWater(IBlockState state) {
return b == Blocks.FLOWING_WATER || b == Blocks.WATER; Fluid f = state.getFluidState().getFluid();
return f == Fluids.WATER || f == Fluids.FLOWING_WATER;
} }
/** /**
@@ -464,11 +474,12 @@ public interface MovementHelper extends ActionCosts, Helper {
* @return Whether or not the block is water * @return Whether or not the block is water
*/ */
static boolean isWater(IPlayerContext ctx, BlockPos bp) { static boolean isWater(IPlayerContext ctx, BlockPos bp) {
return isWater(BlockStateInterface.getBlock(ctx, bp)); return isWater(BlockStateInterface.get(ctx, bp));
} }
static boolean isLava(Block b) { static boolean isLava(IBlockState state) {
return b == Blocks.FLOWING_LAVA || b == Blocks.LAVA; Fluid f = state.getFluidState().getFluid();
return f == Fluids.LAVA || f == Fluids.FLOWING_LAVA;
} }
/** /**
@@ -479,20 +490,25 @@ public interface MovementHelper extends ActionCosts, Helper {
* @return Whether or not the block is a liquid * @return Whether or not the block is a liquid
*/ */
static boolean isLiquid(IPlayerContext ctx, BlockPos p) { static boolean isLiquid(IPlayerContext ctx, BlockPos p) {
return BlockStateInterface.getBlock(ctx, p) instanceof BlockLiquid; return isLiquid(BlockStateInterface.get(ctx, p));
}
static boolean isLiquid(IBlockState blockState) {
return !blockState.getFluidState().isEmpty();
} }
static boolean possiblyFlowing(IBlockState state) { static boolean possiblyFlowing(IBlockState state) {
// Will be IFluidState in 1.13 IFluidState fluidState = state.getFluidState();
return state.getBlock() instanceof BlockLiquid return fluidState.getFluid() instanceof FlowingFluid
&& state.getValue(BlockLiquid.LEVEL) != 0; && fluidState.getFluid().getLevel(fluidState) != 8;
} }
static boolean isFlowing(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { static boolean isFlowing(int x, int y, int z, IBlockState state, BlockStateInterface bsi) {
if (!(state.getBlock() instanceof BlockLiquid)) { IFluidState fluidState = state.getFluidState();
if (!(fluidState.getFluid() instanceof FlowingFluid)) {
return false; return false;
} }
if (state.getValue(BlockLiquid.LEVEL) != 0) { if (fluidState.getFluid().getLevel(fluidState) != 8) {
return true; return true;
} }
return possiblyFlowing(bsi.get0(x + 1, y, z)) return possiblyFlowing(bsi.get0(x + 1, y, z))
@@ -523,7 +539,7 @@ public interface MovementHelper extends ActionCosts, Helper {
double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D;
Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance());
if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(placeAt)) { if (res != null && res.type == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(placeAt)) {
state.setTarget(new MovementState.MovementTarget(place, true)); state.setTarget(new MovementState.MovementTarget(place, true));
found = true; found = true;
@@ -145,7 +145,7 @@ public class MovementDescend extends Movement {
IBlockState ontoBlock = context.get(destX, newY, destZ); IBlockState ontoBlock = context.get(destX, newY, destZ);
int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY
double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar; double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar;
if (MovementHelper.isWater(ontoBlock.getBlock())) { if (MovementHelper.isWater(ontoBlock)) {
if (!MovementHelper.canWalkThrough(context.bsi, destX, newY, destZ, ontoBlock)) { if (!MovementHelper.canWalkThrough(context.bsi, destX, newY, destZ, ontoBlock)) {
return false; return false;
} }
@@ -224,7 +224,7 @@ public class MovementDescend extends Movement {
double destZ = (src.getZ() + 0.5) * 0.17 + (dest.getZ() + 0.5) * 0.83; double destZ = (src.getZ() + 0.5) * 0.17 + (dest.getZ() + 0.5) * 0.83;
EntityPlayerSP player = ctx.player(); EntityPlayerSP player = ctx.player();
state.setTarget(new MovementState.MovementTarget( state.setTarget(new MovementState.MovementTarget(
new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), new Rotation(RotationUtils.calcRotationFromVec3d(player.getEyePosition(1.0F),
new Vec3d(destX, dest.getY(), destZ), new Vec3d(destX, dest.getY(), destZ),
new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch),
false false
@@ -256,7 +256,7 @@ public class MovementDescend extends Movement {
return true; return true;
} }
for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks
if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(ctx, into.up(y)))) { if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, into.up(y)))) {
return true; return true;
} }
} }
@@ -116,17 +116,18 @@ public class MovementDiagonal extends Movement {
if (fromDown == Blocks.SOUL_SAND) { if (fromDown == Blocks.SOUL_SAND) {
multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
} }
Block cuttingOver1 = context.get(x, y - 1, destZ).getBlock(); IBlockState cuttingOver1 = context.get(x, y - 1, destZ);
if (cuttingOver1 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver1)) { if (cuttingOver1.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver1)) {
return; return;
} }
Block cuttingOver2 = context.get(destX, y - 1, z).getBlock(); IBlockState cuttingOver2 = context.get(destX, y - 1, z);
if (cuttingOver2 == Blocks.MAGMA || MovementHelper.isLava(cuttingOver2)) { if (cuttingOver2.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver2)) {
return; return;
} }
Block startIn = context.getBlock(x, y, z);
boolean water = false; boolean water = false;
if (MovementHelper.isWater(startIn) || MovementHelper.isWater(destInto.getBlock())) { IBlockState startState = context.get(x, y, z);
Block startIn = startState.getBlock();
if (MovementHelper.isWater(startState) || MovementHelper.isWater(destInto)) {
if (ascend) { if (ascend) {
return; return;
} }
@@ -146,8 +147,8 @@ public class MovementDiagonal extends Movement {
boolean BMid = MovementHelper.canWalkThrough(context.bsi, destX, y + 1, z); boolean BMid = MovementHelper.canWalkThrough(context.bsi, destX, y + 1, z);
boolean BLow = MovementHelper.canWalkThrough(context.bsi, destX, y, z, pb2); boolean BLow = MovementHelper.canWalkThrough(context.bsi, destX, y, z, pb2);
if ((!(ATop && AMid && ALow) && !(BTop && BMid && BLow)) // no option if ((!(ATop && AMid && ALow) && !(BTop && BMid && BLow)) // no option
|| MovementHelper.avoidWalkingInto(pb0.getBlock()) // bad || MovementHelper.avoidWalkingInto(pb0) // bad
|| MovementHelper.avoidWalkingInto(pb2.getBlock()) // bad || MovementHelper.avoidWalkingInto(pb2) // bad
|| (ATop && AMid && MovementHelper.canWalkOn(context.bsi, x, y, destZ, pb0)) // we could just ascend || (ATop && AMid && MovementHelper.canWalkOn(context.bsi, x, y, destZ, pb0)) // we could just ascend
|| (BTop && BMid && MovementHelper.canWalkOn(context.bsi, destX, y, z, pb2)) // we could just ascend || (BTop && BMid && MovementHelper.canWalkOn(context.bsi, destX, y, z, pb2)) // we could just ascend
|| (!ATop && AMid && ALow) // head bonk A || (!ATop && AMid && ALow) // head bonk A
@@ -174,7 +175,7 @@ public class MovementDiagonal extends Movement {
return; return;
} }
IBlockState pb3 = context.get(destX, y + 1, z); IBlockState pb3 = context.get(destX, y + 1, z);
if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2.getBlock()) && pb2.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb3.getBlock()))) { if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2) && pb2.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb3))) {
// at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction
return; return;
} }
@@ -183,7 +184,7 @@ public class MovementDiagonal extends Movement {
// and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible // and finally, if the cost is nonzero for both ways to approach this diagonal, it's not possible
return; return;
} }
if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0.getBlock()) && pb0.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb1.getBlock()))) { if (optionB == 0 && ((MovementHelper.avoidWalkingInto(pb0) && pb0.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb1))) {
// and now that option B is fully calculated, see if we can edge around that way // and now that option B is fully calculated, see if we can edge around that way
return; return;
} }
@@ -34,6 +34,7 @@ import net.minecraft.block.Block;
import net.minecraft.block.BlockLadder; import net.minecraft.block.BlockLadder;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -91,10 +92,11 @@ public class MovementFall extends Movement {
BlockPos playerFeet = ctx.playerFeet(); BlockPos playerFeet = ctx.playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()); Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations());
Rotation targetRotation = null; Rotation targetRotation = null;
Block destBlock = ctx.world().getBlockState(dest).getBlock(); IBlockState destState = ctx.world().getBlockState(dest);
boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER; Block destBlock = destState.getBlock();
boolean isWater = destState.getFluidState().getFluid() instanceof WaterFluid;
if (!isWater && willPlaceBucket() && !playerFeet.equals(dest)) { if (!isWater && willPlaceBucket() && !playerFeet.equals(dest)) {
if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().provider.isNether()) { if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().getDimension().isNether()) {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
@@ -160,7 +162,7 @@ public class MovementFall extends Movement {
for (int i = 0; i < 15; i++) { for (int i = 0; i < 15; i++) {
IBlockState state = ctx.world().getBlockState(ctx.playerFeet().down(i)); IBlockState state = ctx.world().getBlockState(ctx.playerFeet().down(i));
if (state.getBlock() == Blocks.LADDER) { if (state.getBlock() == Blocks.LADDER) {
return state.getValue(BlockLadder.FACING); return state.get(BlockLadder.FACING);
} }
} }
return null; return null;
@@ -28,10 +28,11 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockStairs;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.init.Fluids;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import java.util.HashSet; import java.util.HashSet;
@@ -78,7 +79,7 @@ public class MovementParkour extends Movement {
// second most common case -- we could just traverse not parkour // second most common case -- we could just traverse not parkour
return; return;
} }
if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks if (MovementHelper.avoidWalkingInto(adj) && !(adj.getFluidState().getFluid() instanceof WaterFluid)) { // magma sucks
return; return;
} }
if (!MovementHelper.fullyPassable(context, x + xDiff, y + 1, z + zDiff)) { if (!MovementHelper.fullyPassable(context, x + xDiff, y + 1, z + zDiff)) {
@@ -91,7 +92,7 @@ public class MovementParkour extends Movement {
return; return;
} }
IBlockState standingOn = context.get(x, y - 1, z); IBlockState standingOn = context.get(x, y - 1, z);
if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn) || standingOn.getBlock() instanceof BlockLiquid) { if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn) || standingOn.getFluidState().getFluid() != Fluids.EMPTY) {
return; return;
} }
int maxJump; int maxJump;
@@ -177,7 +178,7 @@ public class MovementParkour extends Movement {
private static boolean checkOvershootSafety(BlockStateInterface bsi, int x, int y, int z) { private static boolean checkOvershootSafety(BlockStateInterface bsi, int x, int y, int z) {
// we're going to walk into these two blocks after the landing of the parkour anyway, so make sure they aren't avoidWalkingInto // we're going to walk into these two blocks after the landing of the parkour anyway, so make sure they aren't avoidWalkingInto
return !MovementHelper.avoidWalkingInto(bsi.get0(x, y, z).getBlock()) && !MovementHelper.avoidWalkingInto(bsi.get0(x, y + 1, z).getBlock()); return !MovementHelper.avoidWalkingInto(bsi.get0(x, y, z)) && !MovementHelper.avoidWalkingInto(bsi.get0(x, y + 1, z));
} }
private static double costFromJumpDistance(int dist) { private static double costFromJumpDistance(int dist) {
@@ -65,7 +65,7 @@ public class MovementPillar extends Movement {
if (fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE) { if (fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE) {
return COST_INF; // can't pillar from a ladder or vine onto something that isn't also climbable return COST_INF; // can't pillar from a ladder or vine onto something that isn't also climbable
} }
if (fromDown.getBlock() instanceof BlockSlab && !((BlockSlab) fromDown.getBlock()).isDouble() && fromDown.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM) { if (fromDown.getBlock() instanceof BlockSlab && !fromDown.isTopSolid()) {
return COST_INF; // can't pillar up from a bottom slab onto a non ladder return COST_INF; // can't pillar up from a bottom slab onto a non ladder
} }
} }
@@ -77,9 +77,9 @@ public class MovementPillar extends Movement {
if (toBreakBlock instanceof BlockFenceGate) { // see issue #172 if (toBreakBlock instanceof BlockFenceGate) { // see issue #172
return COST_INF; return COST_INF;
} }
Block srcUp = null; IBlockState srcUp = null;
if (MovementHelper.isWater(toBreakBlock) && MovementHelper.isWater(from)) { // TODO should this also be allowed if toBreakBlock is air? if (MovementHelper.isWater(toBreak) && MovementHelper.isWater(fromState)) { // TODO should this also be allowed if toBreakBlock is air?
srcUp = context.get(x, y + 1, z).getBlock(); srcUp = context.get(x, y + 1, z);
if (MovementHelper.isWater(srcUp)) { if (MovementHelper.isWater(srcUp)) {
return LADDER_UP_ONE_COST; // allow ascending pillars of water, but only if we're already in one return LADDER_UP_ONE_COST; // allow ascending pillars of water, but only if we're already in one
} }
@@ -91,11 +91,11 @@ public class MovementPillar extends Movement {
if (placeCost >= COST_INF) { if (placeCost >= COST_INF) {
return COST_INF; return COST_INF;
} }
if (fromDown.getBlock() == Blocks.AIR) { if (fromDown.getBlock() instanceof BlockAir) {
placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air
} }
} }
if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) { if ((MovementHelper.isLiquid(fromState) && !MovementHelper.canPlaceAgainst(context.bsi, x, y - 1, z, fromDown)) || (MovementHelper.isLiquid(fromDown) && context.assumeWalkOnWater)) {
// otherwise, if we're standing in water, we cannot pillar // otherwise, if we're standing in water, we cannot pillar
// if we're standing on water and assumeWalkOnWater is true, we cannot pillar // if we're standing on water and assumeWalkOnWater is true, we cannot pillar
// if we're standing on water and assumeWalkOnWater is false, we must have ascended to here, or sneak backplaced, so it is possible to pillar again // if we're standing on water and assumeWalkOnWater is false, we must have ascended to here, or sneak backplaced, so it is possible to pillar again
@@ -113,9 +113,9 @@ public class MovementPillar extends Movement {
if (check.getBlock() instanceof BlockFalling) { if (check.getBlock() instanceof BlockFalling) {
// see MovementAscend's identical check for breaking a falling block above our head // see MovementAscend's identical check for breaking a falling block above our head
if (srcUp == null) { if (srcUp == null) {
srcUp = context.get(x, y + 1, z).getBlock(); srcUp = context.get(x, y + 1, z);
} }
if (!(toBreakBlock instanceof BlockFalling) || !(srcUp instanceof BlockFalling)) { if (!(toBreakBlock instanceof BlockFalling) || !(srcUp.getBlock() instanceof BlockFalling)) {
return COST_INF; return COST_INF;
} }
} }
@@ -170,7 +170,7 @@ public class MovementPillar extends Movement {
} }
IBlockState fromDown = BlockStateInterface.get(ctx, src); IBlockState fromDown = BlockStateInterface.get(ctx, src);
if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { if (MovementHelper.isWater(fromDown) && MovementHelper.isWater(ctx, dest)) {
// stay centered while swimming up a water column // stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false)); state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
@@ -184,7 +184,7 @@ public class MovementPillar extends Movement {
} }
boolean ladder = fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE; boolean ladder = fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE;
boolean vine = fromDown.getBlock() == Blocks.VINE; boolean vine = fromDown.getBlock() == Blocks.VINE;
Rotation rotation = RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), Rotation rotation = RotationUtils.calcRotationFromVec3d(ctx.player().getEyePosition(1.0F),
VecUtils.getBlockPosCenter(positionToPlace), VecUtils.getBlockPosCenter(positionToPlace),
new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch)); new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch));
if (!ladder) { if (!ladder) {
@@ -193,7 +193,7 @@ public class MovementPillar extends Movement {
boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder; boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder;
if (ladder) { if (ladder) {
BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.get(BlockLadder.FACING).getOpposite());
if (against == null) { if (against == null) {
logDirect("Unable to climb vines. Consider disabling allowVines."); logDirect("Unable to climb vines. Consider disabling allowVines.");
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
@@ -33,7 +33,9 @@ import baritone.utils.BlockStateInterface;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.state.properties.SlabType;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -71,11 +73,12 @@ public class MovementTraverse extends Movement {
IBlockState pb0 = context.get(destX, y + 1, destZ); IBlockState pb0 = context.get(destX, y + 1, destZ);
IBlockState pb1 = context.get(destX, y, destZ); IBlockState pb1 = context.get(destX, y, destZ);
IBlockState destOn = context.get(destX, y - 1, destZ); IBlockState destOn = context.get(destX, y - 1, destZ);
Block srcDown = context.getBlock(x, y - 1, z); IBlockState down = context.get(x, y - 1, z);
Block srcDown = down.getBlock();
if (MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge if (MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge
double WC = WALK_ONE_BLOCK_COST; double WC = WALK_ONE_BLOCK_COST;
boolean water = false; boolean water = false;
if (MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock())) { if (MovementHelper.isWater(pb0) || MovementHelper.isWater(pb1)) {
WC = context.waterWalkSpeed; WC = context.waterWalkSpeed;
water = true; water = true;
} else { } else {
@@ -112,8 +115,8 @@ public class MovementTraverse extends Movement {
return COST_INF; return COST_INF;
} }
if (MovementHelper.isReplaceable(destX, y - 1, destZ, destOn, context.bsi)) { if (MovementHelper.isReplaceable(destX, y - 1, destZ, destOn, context.bsi)) {
boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock()); boolean throughWater = MovementHelper.isWater(pb0) || MovementHelper.isWater(pb1);
if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { if (MovementHelper.isWater(destOn) && throughWater) {
// this happens when assume walk on water is true and this is a traverse in water, which isn't allowed // this happens when assume walk on water is true and this is a traverse in water, which isn't allowed
return COST_INF; return COST_INF;
} }
@@ -139,10 +142,10 @@ public class MovementTraverse extends Movement {
} }
} }
// now that we've checked all possible directions to side place, we actually need to backplace // now that we've checked all possible directions to side place, we actually need to backplace
if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && !((BlockSlab) srcDown).isDouble())) { if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && down.get(BlockSlab.TYPE) != SlabType.DOUBLE)) {
return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/ return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/
} }
if (srcDown == Blocks.FLOWING_WATER || srcDown == Blocks.WATER) { if (down.getFluidState() instanceof WaterFluid) {
return COST_INF; // this is obviously impossible return COST_INF; // this is obviously impossible
} }
WC = WC * (SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST);//since we are sneak backplacing, we are sneaking lol WC = WC * (SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST);//since we are sneak backplacing, we are sneaking lol
@@ -167,10 +170,10 @@ public class MovementTraverse extends Movement {
return state; return state;
} }
// and if it's fine to walk into the blocks in front // and if it's fine to walk into the blocks in front
if (MovementHelper.avoidWalkingInto(pb0.getBlock())) { if (MovementHelper.avoidWalkingInto(pb0)) {
return state; return state;
} }
if (MovementHelper.avoidWalkingInto(pb1.getBlock())) { if (MovementHelper.avoidWalkingInto(pb1)) {
return state; return state;
} }
// and we aren't already pressed up against the block // and we aren't already pressed up against the block
@@ -251,8 +254,8 @@ public class MovementTraverse extends Movement {
return state; return state;
} }
BlockPos into = dest.subtract(src).add(dest); BlockPos into = dest.subtract(src).add(dest);
Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); IBlockState intoBelow = BlockStateInterface.get(ctx, into);
Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); IBlockState intoAbove = BlockStateInterface.get(ctx, into.up());
if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, feet) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, feet) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) {
state.setInput(Input.SPRINT, true); state.setInput(Input.SPRINT, true);
} }
@@ -260,7 +263,7 @@ public class MovementTraverse extends Movement {
IBlockState destDown = BlockStateInterface.get(ctx, dest.down()); IBlockState destDown = BlockStateInterface.get(ctx, dest.down());
BlockPos against = positionsToBreak[0]; BlockPos against = positionsToBreak[0];
if (feet.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) { if (feet.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) {
against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.getValue(BlockLadder.FACING).getOpposite()); against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.get(BlockLadder.FACING).getOpposite());
if (against == null) { if (against == null) {
logDirect("Unable to climb vines. Consider disabling allowVines."); logDirect("Unable to climb vines. Consider disabling allowVines.");
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
@@ -32,7 +32,6 @@ import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.movements.*; import baritone.pathing.movement.movements.*;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.BlockLiquid;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -130,7 +129,7 @@ public class PathExecutor implements IPathExecutor, Helper {
Tuple<Double, BlockPos> status = closestPathPos(path); Tuple<Double, BlockPos> status = closestPathPos(path);
if (possiblyOffPath(status, MAX_DIST_FROM_PATH)) { if (possiblyOffPath(status, MAX_DIST_FROM_PATH)) {
ticksAway++; ticksAway++;
System.out.println("FAR AWAY FROM PATH FOR " + ticksAway + " TICKS. Current distance: " + status.getFirst() + ". Threshold: " + MAX_DIST_FROM_PATH); System.out.println("FAR AWAY FROM PATH FOR " + ticksAway + " TICKS. Current distance: " + status.getA() + ". Threshold: " + MAX_DIST_FROM_PATH);
if (ticksAway > MAX_TICKS_AWAY) { if (ticksAway > MAX_TICKS_AWAY) {
logDebug("Too far away from path for too long, cancelling path"); logDebug("Too far away from path for too long, cancelling path");
cancel(); cancel();
@@ -303,7 +302,7 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
private boolean possiblyOffPath(Tuple<Double, BlockPos> status, double leniency) { private boolean possiblyOffPath(Tuple<Double, BlockPos> status, double leniency) {
double distanceFromPath = status.getFirst(); double distanceFromPath = status.getA();
if (distanceFromPath > leniency) { if (distanceFromPath > leniency) {
// when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path // when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path
if (path.movements().get(pathPosition) instanceof MovementFall) { if (path.movements().get(pathPosition) instanceof MovementFall) {
@@ -323,7 +322,7 @@ public class PathExecutor implements IPathExecutor, Helper {
* @return Whether or not it was possible to snap to the current player feet * @return Whether or not it was possible to snap to the current player feet
*/ */
public boolean snipsnapifpossible() { public boolean snipsnapifpossible() {
if (!ctx.player().onGround && !(ctx.world().getBlockState(ctx.playerFeet()).getBlock() instanceof BlockLiquid)) { if (!ctx.player().onGround && ctx.world().getFluidState(ctx.playerFeet()).isEmpty()) {
// if we're falling in the air, and not in water, don't splice // if we're falling in the air, and not in water, don't splice
return false; return false;
} else { } else {
@@ -426,7 +425,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (current instanceof MovementFall) { if (current instanceof MovementFall) {
Tuple<Vec3d, BlockPos> data = overrideFall((MovementFall) current); Tuple<Vec3d, BlockPos> data = overrideFall((MovementFall) current);
if (data != null) { if (data != null) {
BetterBlockPos fallDest = new BetterBlockPos(data.getSecond()); BetterBlockPos fallDest = new BetterBlockPos(data.getB());
if (!path.positions().contains(fallDest)) { if (!path.positions().contains(fallDest)) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
@@ -437,7 +436,7 @@ public class PathExecutor implements IPathExecutor, Helper {
return true; return true;
} }
clearKeys(); clearKeys();
behavior.baritone.getLookBehavior().updateTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), data.getFirst(), ctx.playerRotations()), false); behavior.baritone.getLookBehavior().updateTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), data.getA(), ctx.playerRotations()), false);
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true); behavior.baritone.getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true);
return true; return true;
} }
@@ -529,10 +528,10 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
} }
} }
if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) { if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)))) {
return false; return false;
} }
return !MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock()); // codacy smh my head return !MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2))); // codacy smh my head
} }
private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) { private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) {
@@ -28,7 +28,6 @@ import baritone.pathing.path.PathExecutor;
import baritone.utils.BaritoneProcessHelper; import baritone.utils.BaritoneProcessHelper;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.EmptyChunk;
@@ -104,7 +103,7 @@ public final class BackfillProcess extends BaritoneProcessHelper {
.keySet() .keySet()
.stream() .stream()
.filter(pos -> ctx.world().getBlockState(pos).getBlock() == Blocks.AIR) .filter(pos -> ctx.world().getBlockState(pos).getBlock() == Blocks.AIR)
.filter(pos -> ctx.world().mayPlace(Blocks.DIRT, pos, false, EnumFacing.UP, null)) .filter(pos -> baritone.getBuilderProcess().placementPlausible(pos, Blocks.DIRT.getDefaultState()))
.filter(pos -> !partOfCurrentMovement(pos)) .filter(pos -> !partOfCurrentMovement(pos))
.sorted(Comparator.<BlockPos>comparingDouble(ctx.player()::getDistanceSq).reversed()) .sorted(Comparator.<BlockPos>comparingDouble(ctx.player()::getDistanceSq).reversed())
.collect(Collectors.toList()); .collect(Collectors.toList());
@@ -45,14 +45,19 @@ import baritone.utils.schematic.SchematicSystem;
import baritone.utils.schematic.schematica.SchematicaHelper; import baritone.utils.schematic.schematica.SchematicaHelper;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.block.BlockAir; import net.minecraft.block.BlockAir;
import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockFlowingFluid;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.math.*; import net.minecraft.util.math.*;
import net.minecraft.util.math.shapes.VoxelShape;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -143,11 +148,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (SchematicaHelper.isSchematicaPresent()) { if (SchematicaHelper.isSchematicaPresent()) {
Optional<Tuple<IStaticSchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic(); Optional<Tuple<IStaticSchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic();
if (schematic.isPresent()) { if (schematic.isPresent()) {
IStaticSchematic s = schematic.get().getFirst(); IStaticSchematic s = schematic.get().getA();
this.build( this.build(
schematic.get().getFirst().toString(), schematic.get().getA().toString(),
Baritone.settings().mapArtMode.value ? new MapArtSchematic(s) : s, Baritone.settings().mapArtMode.value ? new MapArtSchematic(s) : s,
schematic.get().getSecond() schematic.get().getB()
); );
} else { } else {
logDirect("No schematic currently open"); logDirect("No schematic currently open");
@@ -183,7 +188,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return null; return null;
} }
IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable); IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable);
if (state.getBlock() == Blocks.AIR) { if (state.getBlock() instanceof BlockAir) {
return null; return null;
} }
return state; return state;
@@ -206,7 +211,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
continue; // irrelevant continue; // irrelevant
} }
IBlockState curr = bcc.bsi.get0(x, y, z); IBlockState curr = bcc.bsi.get0(x, y, z);
if (curr.getBlock() != Blocks.AIR && !(curr.getBlock() instanceof BlockLiquid) && !valid(curr, desired)) { if (!(curr.getBlock() instanceof BlockAir) && !(curr.getBlock() == Blocks.WATER || curr.getBlock() == Blocks.LAVA) && !valid(curr, desired)) {
BetterBlockPos pos = new BetterBlockPos(x, y, z); BetterBlockPos pos = new BetterBlockPos(x, y, z);
Optional<Rotation> rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); Optional<Rotation> rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance());
if (rot.isPresent()) { if (rot.isPresent()) {
@@ -248,7 +253,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
IBlockState curr = bcc.bsi.get0(x, y, z); IBlockState curr = bcc.bsi.get0(x, y, z);
if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) {
if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() instanceof BlockAir) {
continue; continue;
} }
desirableOnHotbar.add(desired); desirableOnHotbar.add(desired);
@@ -263,6 +268,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return Optional.empty(); return Optional.empty();
} }
public boolean placementPlausible(BlockPos pos, IBlockState state) {
VoxelShape voxelshape = state.getCollisionShape(ctx.world(), pos);
return voxelshape.isEmpty() || ctx.world().checkNoEntityCollision(null, voxelshape.withOffset(pos.getX(), pos.getY(), pos.getZ()));
}
private Optional<Placement> possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { private Optional<Placement> possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) {
for (EnumFacing against : EnumFacing.values()) { for (EnumFacing against : EnumFacing.values()) {
BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against);
@@ -270,17 +280,20 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) {
continue; continue;
} }
if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) { if (!toPlace.isValidPosition(ctx.world(), new BetterBlockPos(x, y, z))) {
continue; continue;
} }
AxisAlignedBB aabb = placeAgainstState.getBoundingBox(ctx.world(), placeAgainstPos); if (!placementPlausible(new BetterBlockPos(x, y, z), toPlace)) {
continue;
}
AxisAlignedBB aabb = placeAgainstState.getShape(ctx.world(), placeAgainstPos).getBoundingBox();
for (Vec3d placementMultiplier : aabbSideMultipliers(against)) { for (Vec3d placementMultiplier : aabbSideMultipliers(against)) {
double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x); double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x);
double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y); double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y);
double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z); double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z);
Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations()); Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations());
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance()); RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance());
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) { if (result != null && result.type == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) {
OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot); OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot);
if (hotbar.isPresent()) { if (hotbar.isPresent()) {
return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot)); return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot));
@@ -302,18 +315,24 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
// the state depends on the facing of the player sometimes // the state depends on the facing of the player sometimes
ctx.player().rotationYaw = rot.getYaw(); ctx.player().rotationYaw = rot.getYaw();
ctx.player().rotationPitch = rot.getPitch(); ctx.player().rotationPitch = rot.getPitch();
IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( BlockItemUseContext meme = new BlockItemUseContext(new ItemUseContext(
ctx.world(), ctx.player(),
stack,
result.getBlockPos().offset(result.sideHit), result.getBlockPos().offset(result.sideHit),
result.sideHit, result.sideHit,
(float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP (float) result.hitVec.x - result.getBlockPos().getX(),
(float) result.hitVec.y - result.getBlockPos().getY(), (float) result.hitVec.y - result.getBlockPos().getY(),
(float) result.hitVec.z - result.getBlockPos().getZ(), (float) result.hitVec.z - result.getBlockPos().getZ()
stack.getItem().getMetadata(stack.getMetadata()), ));
ctx.player() IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(meme);
);
ctx.player().rotationYaw = originalYaw; ctx.player().rotationYaw = originalYaw;
ctx.player().rotationPitch = originalPitch; ctx.player().rotationPitch = originalPitch;
if (wouldBePlaced == null) {
continue;
}
if (!meme.canPlace()) {
continue;
}
if (valid(wouldBePlaced, desired)) { if (valid(wouldBePlaced, desired)) {
return OptionalInt.of(i); return OptionalInt.of(i);
} }
@@ -423,8 +442,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) {
// we'd like to pause to break this block // we'd like to pause to break this block
// only change look direction if it's safe (don't want to fuck up an in progress parkour for example // only change look direction if it's safe (don't want to fuck up an in progress parkour for example
Rotation rot = toBreak.get().getSecond(); Rotation rot = toBreak.get().getB();
BetterBlockPos pos = toBreak.get().getFirst(); BetterBlockPos pos = toBreak.get().getA();
baritone.getLookBehavior().updateTarget(rot, true); baritone.getLookBehavior().updateTarget(rot, true);
MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos));
if (ctx.player().isSneaking()) { if (ctx.player().isSneaking()) {
@@ -587,7 +606,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
placeable.add(pos); placeable.add(pos);
} }
} else { } else {
if (state.getBlock() instanceof BlockLiquid) { if (state.getBlock() instanceof BlockFlowingFluid) {
// if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it // if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it
// TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks // TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks
if (!MovementHelper.possiblyFlowing(state)) { if (!MovementHelper.possiblyFlowing(state)) {
@@ -663,14 +682,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) { private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) {
if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen? if (!(ctx.world().getBlockState(pos).getBlock() instanceof BlockAir)) { // TODO can this even happen?
return new GoalPlace(pos); return new GoalPlace(pos);
} }
boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; boolean allowSameLevel = !(ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir);
IBlockState current = ctx.world().getBlockState(pos); IBlockState current = ctx.world().getBlockState(pos);
for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) {
//noinspection ConstantConditions //noinspection ConstantConditions
if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current).getBlock(), pos, false, facing, null)) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && placementPlausible(pos, bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current))) {
return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel); return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel);
} }
} }
@@ -763,7 +782,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
continue; continue;
} }
// <toxic cloud> // <toxic cloud>
result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player())); result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.player(), stack, ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ))));
// </toxic cloud> // </toxic cloud>
} }
return result; return result;
@@ -773,10 +792,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (desired == null) { if (desired == null) {
return true; return true;
} }
// TODO more complicated comparison logic I guess if (current.getBlock() instanceof BlockAir && desired.getBlock() instanceof BlockAir) {
if (current.getBlock() instanceof BlockLiquid && Baritone.settings().okIfWater.value) {
return true; return true;
} }
if ((current.getBlock() == Blocks.WATER || current.getBlock() == Blocks.LAVA) && Baritone.settings().okIfWater.value) {
return true;
}
// TODO more complicated comparison logic I guess
if (desired.getBlock() instanceof BlockAir && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) { if (desired.getBlock() instanceof BlockAir && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) {
return true; return true;
} }
@@ -822,7 +844,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
IBlockState sch = getSchematic(x, y, z, current); IBlockState sch = getSchematic(x, y, z, current);
if (sch != null) { if (sch != null) {
// TODO this can return true even when allowPlace is off.... is that an issue? // TODO this can return true even when allowPlace is off.... is that an issue?
if (sch.getBlock() == Blocks.AIR) { if (sch.getBlock() instanceof BlockAir) {
// we want this to be air, but they're asking if they can place here // we want this to be air, but they're asking if they can place here
// this won't be a schematic block, this will be a throwaway // this won't be a schematic block, this will be a throwaway
return placeBlockCost * 2; // we're going to have to break it eventually return placeBlockCost * 2; // we're going to have to break it eventually
@@ -855,7 +877,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
IBlockState sch = getSchematic(x, y, z, current); IBlockState sch = getSchematic(x, y, z, current);
if (sch != null) { if (sch != null) {
if (sch.getBlock() == Blocks.AIR) { if (sch.getBlock() instanceof BlockAir) {
// it should be air // it should be air
// regardless of current contents, we can break it // regardless of current contents, we can break it
return 1; return 1;
+10 -12
View File
@@ -37,9 +37,7 @@ import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -73,17 +71,17 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
Items.BEETROOT_SEEDS, Items.BEETROOT_SEEDS,
Items.BEETROOT, Items.BEETROOT,
Items.MELON_SEEDS, Items.MELON_SEEDS,
Items.MELON, Items.MELON_SLICE,
Item.getItemFromBlock(Blocks.MELON_BLOCK), Blocks.MELON.asItem(),
Items.WHEAT_SEEDS, Items.WHEAT_SEEDS,
Items.WHEAT, Items.WHEAT,
Items.PUMPKIN_SEEDS, Items.PUMPKIN_SEEDS,
Item.getItemFromBlock(Blocks.PUMPKIN), Blocks.PUMPKIN.asItem(),
Items.POTATO, Items.POTATO,
Items.CARROT, Items.CARROT,
Items.NETHER_WART, Items.NETHER_WART,
Items.REEDS, Blocks.SUGAR_CANE.asItem(),
Item.getItemFromBlock(Blocks.CACTUS) Blocks.CACTUS.asItem()
); );
public FarmProcess(Baritone baritone) { public FarmProcess(Baritone baritone) {
@@ -107,9 +105,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
POTATOES((BlockCrops) Blocks.POTATOES), POTATOES((BlockCrops) Blocks.POTATOES),
BEETROOT((BlockCrops) Blocks.BEETROOTS), BEETROOT((BlockCrops) Blocks.BEETROOTS),
PUMPKIN(Blocks.PUMPKIN, state -> true), PUMPKIN(Blocks.PUMPKIN, state -> true),
MELON(Blocks.MELON_BLOCK, state -> true), MELON(Blocks.MELON, state -> true),
NETHERWART(Blocks.NETHER_WART, state -> state.getValue(BlockNetherWart.AGE) >= 3), NETHERWART(Blocks.NETHER_WART, state -> state.get(BlockNetherWart.AGE) >= 3),
SUGARCANE(Blocks.REEDS, null) { SUGARCANE(Blocks.SUGAR_CANE, null) {
@Override @Override
public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) {
if (Baritone.settings().replantCrops.value) { if (Baritone.settings().replantCrops.value) {
@@ -159,7 +157,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
} }
private boolean isBoneMeal(ItemStack stack) { private boolean isBoneMeal(ItemStack stack) {
return !stack.isEmpty() && stack.getItem() instanceof ItemDye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.WHITE; return !stack.isEmpty() && stack.getItem().equals(Items.BONE_MEAL);
} }
private boolean isNetherWart(ItemStack stack) { private boolean isNetherWart(ItemStack stack) {
@@ -235,7 +233,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance()); Optional<Rotation> rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance());
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) { if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) {
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
if (result.typeOfHit == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) { if (result.type == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) {
baritone.getLookBehavior().updateTarget(rot.get(), true); baritone.getLookBehavior().updateTarget(rot.get(), true);
if (ctx.isLookingAt(pos)) { if (ctx.isLookingAt(pos)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
@@ -71,7 +71,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
if (entity == null) { if (entity == null) {
return false; return false;
} }
if (entity.isDead) { if (!entity.isAlive()) {
return false; return false;
} }
if (entity.equals(ctx.player())) { if (entity.equals(ctx.player())) {
@@ -215,7 +215,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG
if (!Baritone.settings().enterPortal.value) { if (!Baritone.settings().enterPortal.value) {
return false; return false;
} }
return block == Blocks.PORTAL; return block == Blocks.NETHER_PORTAL;
} }
private boolean rightClickOnArrival(Block block) { private boolean rightClickOnArrival(Block block) {
@@ -24,13 +24,18 @@ import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.Helper; import baritone.api.utils.Helper;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.client.GameSettings;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.tutorial.TutorialSteps; import net.minecraft.client.tutorial.TutorialSteps;
import net.minecraft.util.HttpUtil;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.*; import net.minecraft.world.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/** /**
* Responsible for automatically testing Baritone's pathing algorithm by automatically creating a world with a specific * Responsible for automatically testing Baritone's pathing algorithm by automatically creating a world with a specific
* seed, setting a specified goal, and only allowing a certain amount of ticks to pass before the pathing test is * seed, setting a specified goal, and only allowing a certain amount of ticks to pass before the pathing test is
@@ -91,11 +96,11 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
if (mc.getIntegratedServer() != null) { if (mc.getIntegratedServer() != null) {
mc.getIntegratedServer().setDifficultyForAllWorlds(EnumDifficulty.PEACEFUL); mc.getIntegratedServer().setDifficultyForAllWorlds(EnumDifficulty.PEACEFUL);
for (final WorldServer world : mc.getIntegratedServer().worlds) { for (final WorldServer world : mc.getIntegratedServer().getWorlds()) {
// If the world has initialized, set the spawn point to our defined starting position // If the world has initialized, set the spawn point to our defined starting position
if (world != null) { if (world != null) {
world.setSpawnPoint(STARTING_POSITION); world.setSpawnPoint(STARTING_POSITION);
world.getGameRules().setOrCreateGameRule("spawnRadius", "0"); world.getGameRules().setOrCreateGameRule("spawnRadius", "0", mc.getIntegratedServer());
} }
} }
} }
@@ -105,7 +110,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// Force the integrated server to share the world to LAN so that // Force the integrated server to share the world to LAN so that
// the ingame pause menu gui doesn't actually pause our game // the ingame pause menu gui doesn't actually pause our game
if (mc.isSingleplayer() && !mc.getIntegratedServer().getPublic()) { if (mc.isSingleplayer() && !mc.getIntegratedServer().getPublic()) {
mc.getIntegratedServer().shareToLAN(GameType.SURVIVAL, false); mc.getIntegratedServer().shareToLAN(GameType.SURVIVAL, false, HttpUtil.getSuitableLanPort());
} }
// For the first 200 ticks, wait for the world to generate // For the first 200 ticks, wait for the world to generate
@@ -127,7 +132,16 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// If we have reached our goal, print a message and safely close the game // If we have reached our goal, print a message and safely close the game
if (GOAL.isInGoal(ctx.playerFeet())) { if (GOAL.isInGoal(ctx.playerFeet())) {
System.out.println("Successfully pathed to " + ctx.playerFeet() + " in " + event.getCount() + " ticks"); System.out.println("Successfully pathed to " + ctx.playerFeet() + " in " + event.getCount() + " ticks");
try {
File file = new File("success");
System.out.println("Writing success to " + file.getAbsolutePath());
Files.write(file.getAbsoluteFile().toPath(), "Success!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
mc.shutdown(); mc.shutdown();
mc.shutdownMinecraftApplet();
System.exit(0);
} }
// If we have exceeded the expected number of ticks to complete the pathing // If we have exceeded the expected number of ticks to complete the pathing
@@ -49,7 +49,7 @@ public final class BlockBreakHelper implements Helper {
public void tick(boolean isLeftClick) { public void tick(boolean isLeftClick) {
RayTraceResult trace = ctx.objectMouseOver(); RayTraceResult trace = ctx.objectMouseOver();
boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; boolean isBlockTrace = trace != null && trace.type == RayTraceResult.Type.BLOCK;
if (isLeftClick && isBlockTrace) { if (isLeftClick && isBlockTrace) {
if (!didBreakLastTick) { if (!didBreakLastTick) {
@@ -39,7 +39,7 @@ public class BlockPlaceHelper implements Helper {
return; return;
} }
RayTraceResult mouseOver = ctx.objectMouseOver(); RayTraceResult mouseOver = ctx.objectMouseOver();
if (!rightClickRequested || ctx.player().isRowingBoat() || mouseOver == null || mouseOver.getBlockPos() == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) { if (!rightClickRequested || ctx.player().isRowingBoat() || mouseOver == null || mouseOver.getBlockPos() == null || mouseOver.type != RayTraceResult.Type.BLOCK) {
return; return;
} }
rightClickTimer = Baritone.settings().rightClickSpeed.value; rightClickTimer = Baritone.settings().rightClickSpeed.value;
@@ -30,7 +30,7 @@ import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IBlockReader;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
@@ -43,9 +43,9 @@ public class BlockStateInterface {
private final Long2ObjectMap<Chunk> loadedChunks; private final Long2ObjectMap<Chunk> loadedChunks;
private final WorldData worldData; private final WorldData worldData;
protected final IBlockAccess world; protected final IBlockReader world;
public final BlockPos.MutableBlockPos isPassableBlockPos; public final BlockPos.MutableBlockPos isPassableBlockPos;
public final IBlockAccess access; public final IBlockReader access;
private Chunk prev = null; private Chunk prev = null;
private CachedRegion prevCached = null; private CachedRegion prevCached = null;
@@ -72,7 +72,7 @@ public class BlockStateInterface {
this.loadedChunks = worldLoaded; // this will only be used on the main thread this.loadedChunks = worldLoaded; // this will only be used on the main thread
} }
this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.value; this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.value;
if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) { if (!Minecraft.getInstance().isCallingFromMinecraftThread()) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
this.isPassableBlockPos = new BlockPos.MutableBlockPos(); this.isPassableBlockPos = new BlockPos.MutableBlockPos();
@@ -17,14 +17,11 @@
package baritone.utils; package baritone.utils;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.fluid.IFluidState;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IBlockReader;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.Biome;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@@ -33,7 +30,7 @@ import javax.annotation.Nullable;
* @since 11/5/2019 * @since 11/5/2019
*/ */
@SuppressWarnings("NullableProblems") @SuppressWarnings("NullableProblems")
public final class BlockStateInterfaceAccessWrapper implements IBlockAccess { public final class BlockStateInterfaceAccessWrapper implements IBlockReader {
private final BlockStateInterface bsi; private final BlockStateInterface bsi;
@@ -47,11 +44,6 @@ public final class BlockStateInterfaceAccessWrapper implements IBlockAccess {
throw new UnsupportedOperationException("getTileEntity not supported by BlockStateInterfaceAccessWrapper"); throw new UnsupportedOperationException("getTileEntity not supported by BlockStateInterfaceAccessWrapper");
} }
@Override
public int getCombinedLight(BlockPos pos, int lightValue) {
throw new UnsupportedOperationException("getCombinedLight not supported by BlockStateInterfaceAccessWrapper");
}
@Override @Override
public IBlockState getBlockState(BlockPos pos) { public IBlockState getBlockState(BlockPos pos) {
// BlockStateInterface#get0(BlockPos) btfo! // BlockStateInterface#get0(BlockPos) btfo!
@@ -59,22 +51,7 @@ public final class BlockStateInterfaceAccessWrapper implements IBlockAccess {
} }
@Override @Override
public boolean isAirBlock(BlockPos pos) { public IFluidState getFluidState(BlockPos blockPos) {
return this.bsi.get0(pos.getX(), pos.getY(), pos.getZ()).getMaterial() == Material.AIR; return getBlockState(blockPos).getFluidState();
}
@Override
public Biome getBiome(BlockPos pos) {
throw new UnsupportedOperationException("getBiome not supported by BlockStateInterfaceAccessWrapper");
}
@Override
public int getStrongPower(BlockPos pos, EnumFacing direction) {
throw new UnsupportedOperationException("getStrongPower not supported by BlockStateInterfaceAccessWrapper");
}
@Override
public WorldType getWorldType() {
return this.bsi.world.getWorldType();
} }
} }
+208 -23
View File
@@ -26,25 +26,21 @@ import baritone.api.utils.Helper;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
import java.awt.*; import java.awt.*;
import java.nio.FloatBuffer; import java.nio.FloatBuffer;
import java.nio.IntBuffer; import java.nio.IntBuffer;
import java.util.Collections; import java.util.Collections;
import static org.lwjgl.opengl.GL11.*;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
import static org.lwjgl.opengl.GL11.*;
public class GuiClick extends GuiScreen { public class GuiClick extends GuiScreen {
@@ -63,22 +59,25 @@ public class GuiClick extends GuiScreen {
} }
@Override @Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) { public void render(int mouseX, int mouseY, float partialTicks) {
int mx = Mouse.getX(); double mx = mc.mouseHelper.getMouseX();
int my = Mouse.getY(); double my = mc.mouseHelper.getMouseY();
my = mc.mainWindow.getHeight() - my;
my *= mc.mainWindow.getFramebufferHeight() / (double) mc.mainWindow.getHeight();
mx *= mc.mainWindow.getFramebufferWidth() / (double) mc.mainWindow.getWidth();
Vec3d near = toWorld(mx, my, 0); Vec3d near = toWorld(mx, my, 0);
Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv
if (near != null && far != null) { if (near != null && far != null) {
Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ); Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ);
RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true); RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), RayTraceFluidMode.NEVER, false, true);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result != null && result.type == RayTraceResult.Type.BLOCK) {
currentMouseOver = result.getBlockPos(); currentMouseOver = result.getBlockPos();
} }
} }
} }
@Override @Override
protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
if (mouseButton == 0) { if (mouseButton == 0) {
if (clickStart != null && !clickStart.equals(currentMouseOver)) { if (clickStart != null && !clickStart.equals(currentMouseOver)) {
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections(); BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections();
@@ -99,17 +98,19 @@ public class GuiClick extends GuiScreen {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up())); BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up()));
} }
clickStart = null; clickStart = null;
return super.mouseReleased(mouseX, mouseY, mouseButton);
} }
@Override @Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) {
clickStart = currentMouseOver; clickStart = currentMouseOver;
return super.mouseClicked(mouseX, mouseY, mouseButton);
} }
public void onRender() { public void onRender() {
GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear()); GlStateManager.getFloatv(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear());
GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.getFloatv(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear());
GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); GL11.glGetIntegerv(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear());
if (currentMouseOver != null) { if (currentMouseOver != null) {
Entity e = mc.getRenderViewEntity(); Entity e = mc.getRenderViewEntity();
@@ -117,16 +118,16 @@ public class GuiClick extends GuiScreen {
PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN); PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN);
if (clickStart != null && !clickStart.equals(currentMouseOver)) { if (clickStart != null && !clickStart.equals(currentMouseOver)) {
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); GlStateManager.color4f(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.lineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
GlStateManager.disableTexture2D(); GlStateManager.disableTexture2D();
GlStateManager.depthMask(false); GlStateManager.depthMask(false);
GlStateManager.disableDepth(); GlStateManager.disableDepthTest();
BetterBlockPos a = new BetterBlockPos(currentMouseOver); BetterBlockPos a = new BetterBlockPos(currentMouseOver);
BetterBlockPos b = new BetterBlockPos(clickStart); BetterBlockPos b = new BetterBlockPos(clickStart);
IRenderer.drawAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1)); IRenderer.drawAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
GlStateManager.enableDepth(); GlStateManager.enableDepthTest();
GlStateManager.depthMask(true); GlStateManager.depthMask(true);
GlStateManager.enableTexture2D(); GlStateManager.enableTexture2D();
@@ -136,10 +137,194 @@ public class GuiClick extends GuiScreen {
} }
private Vec3d toWorld(double x, double y, double z) { private Vec3d toWorld(double x, double y, double z) {
boolean result = GLU.gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear()); boolean result = gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear());
if (result) { if (result) {
return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2)); return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2));
} }
return null; return null;
} }
// skidded from lwjgl2 :ok_hand:
// its uhhhhh mit license so its ok
// here is the uhh license
/*
* Copyright (c) 2002-2007 Lightweight Java Game Library Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'Light Weight Java Game Library' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public static boolean gluUnProject(
float winx,
float winy,
float winz,
FloatBuffer modelMatrix,
FloatBuffer projMatrix,
IntBuffer viewport,
FloatBuffer obj_pos) {
FloatBuffer finalMatrix = BufferUtils.createFloatBuffer(16);
float[] in = new float[4];
float[] out = new float[4];
__gluMultMatricesf(modelMatrix, projMatrix, finalMatrix);
if (!__gluInvertMatrixf(finalMatrix, finalMatrix))
return false;
in[0] = winx;
in[1] = winy;
in[2] = winz;
in[3] = 1.0f;
// Map x and y from window coordinates
in[0] = (in[0] - viewport.get(viewport.position() + 0)) / viewport.get(viewport.position() + 2);
in[1] = (in[1] - viewport.get(viewport.position() + 1)) / viewport.get(viewport.position() + 3);
// Map to range -1 to 1
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
__gluMultMatrixVecf(finalMatrix, in, out);
if (out[3] == 0.0)
return false;
out[3] = 1.0f / out[3];
obj_pos.put(obj_pos.position() + 0, out[0] * out[3]);
obj_pos.put(obj_pos.position() + 1, out[1] * out[3]);
obj_pos.put(obj_pos.position() + 2, out[2] * out[3]);
return true;
}
private static void __gluMultMatrixVecf(FloatBuffer m, float[] in, float[] out) {
for (int i = 0; i < 4; i++) {
out[i] =
in[0] * m.get(m.position() + 0 * 4 + i)
+ in[1] * m.get(m.position() + 1 * 4 + i)
+ in[2] * m.get(m.position() + 2 * 4 + i)
+ in[3] * m.get(m.position() + 3 * 4 + i);
}
}
private static void __gluMultMatricesf(FloatBuffer a, FloatBuffer b, FloatBuffer r) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
r.put(r.position() + i * 4 + j,
a.get(a.position() + i * 4 + 0) * b.get(b.position() + 0 * 4 + j) + a.get(a.position() + i * 4 + 1) * b.get(b.position() + 1 * 4 + j) + a.get(a.position() + i * 4 + 2) * b.get(b.position() + 2 * 4 + j) + a.get(a.position() + i * 4 + 3) * b.get(b.position() + 3 * 4 + j));
}
}
}
private static boolean __gluInvertMatrixf(FloatBuffer src, FloatBuffer inverse) {
int i, j, k, swap;
float t;
FloatBuffer temp = BufferUtils.createFloatBuffer(16);
for (i = 0; i < 16; i++) {
temp.put(i, src.get(i + src.position()));
}
__gluMakeIdentityf(inverse);
for (i = 0; i < 4; i++) {
/*
* * Look for largest element in column
*/
swap = i;
for (j = i + 1; j < 4; j++) {
/*
* if (fabs(temp[j][i]) > fabs(temp[i][i])) { swap = j;
*/
if (Math.abs(temp.get(j * 4 + i)) > Math.abs(temp.get(i * 4 + i))) {
swap = j;
}
}
if (swap != i) {
/*
* * Swap rows.
*/
for (k = 0; k < 4; k++) {
t = temp.get(i * 4 + k);
temp.put(i * 4 + k, temp.get(swap * 4 + k));
temp.put(swap * 4 + k, t);
t = inverse.get(i * 4 + k);
inverse.put(i * 4 + k, inverse.get(swap * 4 + k));
//inverse.put((i << 2) + k, inverse.get((swap << 2) + k));
inverse.put(swap * 4 + k, t);
//inverse.put((swap << 2) + k, t);
}
}
if (temp.get(i * 4 + i) == 0) {
/*
* * No non-zero pivot. The matrix is singular, which shouldn't *
* happen. This means the user gave us a bad matrix.
*/
return false;
}
t = temp.get(i * 4 + i);
for (k = 0; k < 4; k++) {
temp.put(i * 4 + k, temp.get(i * 4 + k) / t);
inverse.put(i * 4 + k, inverse.get(i * 4 + k) / t);
}
for (j = 0; j < 4; j++) {
if (j != i) {
t = temp.get(j * 4 + i);
for (k = 0; k < 4; k++) {
temp.put(j * 4 + k, temp.get(j * 4 + k) - temp.get(i * 4 + k) * t);
inverse.put(j * 4 + k, inverse.get(j * 4 + k) - inverse.get(i * 4 + k) * t);
/*inverse.put(
(j << 2) + k,
inverse.get((j << 2) + k) - inverse.get((i << 2) + k) * t);*/
}
}
}
}
return true;
}
private static final float[] IDENTITY_MATRIX =
new float[]{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f};
private static void __gluMakeIdentityf(FloatBuffer m) {
int oldPos = m.position();
m.put(IDENTITY_MATRIX);
m.position(oldPos);
}
} }
+5 -5
View File
@@ -40,20 +40,20 @@ public interface IRenderer {
static void glColor(Color color, float alpha) { static void glColor(Color color, float alpha) {
float[] colorComponents = color.getColorComponents(null); float[] colorComponents = color.getColorComponents(null);
GlStateManager.color(colorComponents[0], colorComponents[1], colorComponents[2], alpha); GlStateManager.color4f(colorComponents[0], colorComponents[1], colorComponents[2], alpha);
} }
static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) { static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GlStateManager.disableLighting(); GlStateManager.disableLighting();
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
glColor(color, alpha); glColor(color, alpha);
GlStateManager.glLineWidth(lineWidth); GlStateManager.lineWidth(lineWidth);
GlStateManager.disableTexture2D(); GlStateManager.disableTexture2D();
GlStateManager.depthMask(false); GlStateManager.depthMask(false);
if (ignoreDepth) { if (ignoreDepth) {
GlStateManager.disableDepth(); GlStateManager.disableDepthTest();
} }
} }
@@ -63,7 +63,7 @@ public interface IRenderer {
static void endLines(boolean ignoredDepth) { static void endLines(boolean ignoredDepth) {
if (ignoredDepth) { if (ignoredDepth) {
GlStateManager.enableDepth(); GlStateManager.enableDepthTest();
} }
GlStateManager.depthMask(true); GlStateManager.depthMask(true);
@@ -100,7 +100,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri
} }
} else { } else {
if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam
ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getInstance().gameSettings);
} }
} }
// only set it if it was previously incorrect // only set it if it was previously incorrect
+23 -17
View File
@@ -31,10 +31,12 @@ import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer; import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import java.awt.*; import java.awt.*;
import java.util.Collection; import java.util.Collection;
@@ -49,6 +51,9 @@ import static org.lwjgl.opengl.GL11.*;
*/ */
public final class PathRenderer implements IRenderer { public final class PathRenderer implements IRenderer {
private static final ResourceLocation TEXTURE_BEACON_BEAM = new ResourceLocation("textures/entity/beacon_beam.png");
private PathRenderer() {} private PathRenderer() {}
public static void render(RenderEvent event, PathingBehavior behavior) { public static void render(RenderEvent event, PathingBehavior behavior) {
@@ -58,8 +63,8 @@ public final class PathRenderer implements IRenderer {
((GuiClick) Helper.mc.currentScreen).onRender(); ((GuiClick) Helper.mc.currentScreen).onRender();
} }
int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); int thisPlayerDimension = behavior.baritone.getPlayerContext().world().getDimension().getType().getId();
int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId(); int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().getDimension().getType().getId();
if (thisPlayerDimension != currentRenderViewDimension) { if (thisPlayerDimension != currentRenderViewDimension) {
// this is a path for a bot in a different dimension, don't render it // this is a path for a bot in a different dimension, don't render it
@@ -149,7 +154,6 @@ public final class PathRenderer implements IRenderer {
} }
alpha = 0.4F * (1.0F - (float) (i - fadeStart) / (float) (fadeEnd - fadeStart)); alpha = 0.4F * (1.0F - (float) (i - fadeStart) / (float) (fadeEnd - fadeStart));
} }
IRenderer.glColor(color, alpha); IRenderer.glColor(color, alpha);
} }
@@ -161,6 +165,7 @@ public final class PathRenderer implements IRenderer {
IRenderer.endLines(settings.renderPathIgnoreDepth.value); IRenderer.endLines(settings.renderPathIgnoreDepth.value);
} }
public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) { public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) {
double vpX = renderManager.viewerPosX; double vpX = renderManager.viewerPosX;
double vpY = renderManager.viewerPosY; double vpY = renderManager.viewerPosY;
@@ -186,14 +191,9 @@ public final class PathRenderer implements IRenderer {
positions.forEach(pos -> { positions.forEach(pos -> {
IBlockState state = bsi.get0(pos); IBlockState state = bsi.get0(pos);
AxisAlignedBB toDraw; VoxelShape shape = state.getShape(player.world, pos);
AxisAlignedBB toDraw = shape.isEmpty() ? VoxelShapes.fullCube().getBoundingBox() : shape.getBoundingBox();
if (state.getBlock().equals(Blocks.AIR)) { toDraw = toDraw.offset(pos);
toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(player.world, pos);
} else {
toDraw = state.getSelectedBoundingBox(player.world, pos);
}
IRenderer.drawAABB(toDraw, .002D); IRenderer.drawAABB(toDraw, .002D);
}); });
@@ -233,10 +233,11 @@ public final class PathRenderer implements IRenderer {
if (settings.renderGoalXZBeacon.value) { if (settings.renderGoalXZBeacon.value) {
glPushAttrib(GL_LIGHTING_BIT); glPushAttrib(GL_LIGHTING_BIT);
Helper.mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); TileEntityBeaconRenderer a;
Helper.mc.getTextureManager().bindTexture(TEXTURE_BEACON_BEAM);
if (settings.renderGoalIgnoreDepth.value) { if (settings.renderGoalIgnoreDepth.value) {
GlStateManager.disableDepth(); GlStateManager.disableDepthTest();
} }
TileEntityBeaconRenderer.renderBeamSegment( TileEntityBeaconRenderer.renderBeamSegment(
@@ -245,14 +246,18 @@ public final class PathRenderer implements IRenderer {
goalPos.getZ() - renderPosZ, goalPos.getZ() - renderPosZ,
partialTicks, partialTicks,
1.0, 1.0,
player.world.getTotalWorldTime(), player.world.getGameTime(),
0, 0,
256, 256,
color.getColorComponents(null) color.getColorComponents(null),
// Arguments filled by the private method lol
0.2D,
0.25D
); );
if (settings.renderGoalIgnoreDepth.value) { if (settings.renderGoalIgnoreDepth.value) {
GlStateManager.enableDepth(); GlStateManager.enableDepthTest();
} }
glPopAttrib(); glPopAttrib();
@@ -295,6 +300,7 @@ public final class PathRenderer implements IRenderer {
renderHorizontalQuad(minX, maxX, minZ, maxZ, y1); renderHorizontalQuad(minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(minX, maxX, minZ, maxZ, y2); renderHorizontalQuad(minX, maxX, minZ, maxZ, y2);
buffer.begin(GL_LINES, DefaultVertexFormats.POSITION); buffer.begin(GL_LINES, DefaultVertexFormats.POSITION);
buffer.pos(minX, minY, minZ).endVertex(); buffer.pos(minX, minY, minZ).endVertex();
buffer.pos(minX, maxY, minZ).endVertex(); buffer.pos(minX, maxY, minZ).endVertex();
+3 -10
View File
@@ -24,7 +24,6 @@ import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.init.Enchantments; import net.minecraft.init.Enchantments;
import net.minecraft.init.MobEffects; import net.minecraft.init.MobEffects;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool; import net.minecraft.item.ItemTool;
@@ -76,19 +75,13 @@ public class ToolSet {
} }
/** /**
* Evaluate the material cost of a possible tool. The priority matches the * Evaluate the material cost of a possible tool. Will return 1 for tools, -1 for other
* listed order in the Item.ToolMaterial enum.
* *
* @param itemStack a possibly empty ItemStack * @param itemStack a possibly empty ItemStack
* @return values range from -1 to 4 * @return Either 1 or -1
*/ */
private int getMaterialCost(ItemStack itemStack) { private int getMaterialCost(ItemStack itemStack) {
if (itemStack.getItem() instanceof ItemTool) { return itemStack.getItem() instanceof ItemTool ? 1 : -1;
ItemTool tool = (ItemTool) itemStack.getItem();
return ToolMaterial.valueOf(tool.getToolMaterialName()).ordinal();
} else {
return -1;
}
} }
public boolean hasSilkTouch(ItemStack stack) { public boolean hasSilkTouch(ItemStack stack) {
@@ -17,12 +17,10 @@
package baritone.utils.accessor; package baritone.utils.accessor;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.chunk.storage.IChunkLoader;
/** /**
* @author Brady * @author Brady
* @see WorldProvider
* @since 8/4/2018 * @since 8/4/2018
*/ */
public interface IChunkProviderServer { public interface IChunkProviderServer {
@@ -45,7 +45,6 @@ public class MapArtSchematic extends MaskSchematic {
for (int x = 0; x < schematic.widthX(); x++) { for (int x = 0; x < schematic.widthX(); x++) {
for (int z = 0; z < schematic.lengthZ(); z++) { for (int z = 0; z < schematic.lengthZ(); z++) {
IBlockState[] column = schematic.getColumn(x, z); IBlockState[] column = schematic.getColumn(x, z);
OptionalInt lowestBlockY = lastIndexMatching(column, state -> !(state.getBlock() instanceof BlockAir)); OptionalInt lowestBlockY = lastIndexMatching(column, state -> !(state.getBlock() instanceof BlockAir));
if (lowestBlockY.isPresent()) { if (lowestBlockY.isPresent()) {
heightMap[x][z] = lowestBlockY.getAsInt(); heightMap[x][z] = lowestBlockY.getAsInt();
@@ -58,7 +58,7 @@ public enum DefaultSchematicFormats implements ISchematicFormat {
@Override @Override
public IStaticSchematic parse(InputStream input) throws IOException { public IStaticSchematic parse(InputStream input) throws IOException {
NBTTagCompound nbt = CompressedStreamTools.readCompressed(input); NBTTagCompound nbt = CompressedStreamTools.readCompressed(input);
int version = nbt.getInteger("Version"); int version = nbt.getInt("Version");
switch (version) { switch (version) {
case 1: case 1:
case 2: case 2:
@@ -21,6 +21,9 @@ import baritone.utils.schematic.StaticSchematic;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.datafix.fixes.ItemIntIDToString;
import net.minecraft.util.registry.IRegistry;
/** /**
* @author Brady * @author Brady
@@ -33,14 +36,14 @@ public final class MCEditSchematic extends StaticSchematic {
if (!type.equals("Alpha")) { if (!type.equals("Alpha")) {
throw new IllegalStateException("bad schematic " + type); throw new IllegalStateException("bad schematic " + type);
} }
this.x = schematic.getInteger("Width"); this.x = schematic.getInt("Width");
this.y = schematic.getInteger("Height"); this.y = schematic.getInt("Height");
this.z = schematic.getInteger("Length"); this.z = schematic.getInt("Length");
byte[] blocks = schematic.getByteArray("Blocks"); byte[] blocks = schematic.getByteArray("Blocks");
byte[] metadata = schematic.getByteArray("Data"); // byte[] metadata = schematic.getByteArray("Data");
byte[] additional = null; byte[] additional = null;
if (schematic.hasKey("AddBlocks")) { if (schematic.contains("AddBlocks")) {
byte[] addBlocks = schematic.getByteArray("AddBlocks"); byte[] addBlocks = schematic.getByteArray("AddBlocks");
additional = new byte[addBlocks.length * 2]; additional = new byte[addBlocks.length * 2];
for (int i = 0; i < addBlocks.length; i++) { for (int i = 0; i < addBlocks.length; i++) {
@@ -59,9 +62,10 @@ public final class MCEditSchematic extends StaticSchematic {
// additional is 0 through 15 inclusive since it's & 0xF above // additional is 0 through 15 inclusive since it's & 0xF above
blockID |= additional[blockInd] << 8; blockID |= additional[blockInd] << 8;
} }
Block block = Block.REGISTRY.getObjectById(blockID); Block block = IRegistry.BLOCK.get(ResourceLocation.tryCreate(ItemIntIDToString.getItem(blockID)));
int meta = metadata[blockInd] & 0xFF; // int meta = metadata[blockInd] & 0xFF;
this.states[x][z][y] = block.getStateFromMeta(meta); // this.states[x][z][y] = block.getStateFromMeta(meta);
this.states[x][z][y] = block.getDefaultState();
} }
} }
} }
@@ -21,10 +21,11 @@ import baritone.utils.schematic.StaticSchematic;
import baritone.utils.type.VarInt; import baritone.utils.type.VarInt;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.state.IProperty;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -39,15 +40,15 @@ import java.util.regex.Pattern;
public final class SpongeSchematic extends StaticSchematic { public final class SpongeSchematic extends StaticSchematic {
public SpongeSchematic(NBTTagCompound nbt) { public SpongeSchematic(NBTTagCompound nbt) {
this.x = nbt.getInteger("Width"); this.x = nbt.getInt("Width");
this.y = nbt.getInteger("Height"); this.y = nbt.getInt("Height");
this.z = nbt.getInteger("Length"); this.z = nbt.getInt("Length");
this.states = new IBlockState[this.x][this.z][this.y]; this.states = new IBlockState[this.x][this.z][this.y];
Int2ObjectArrayMap<IBlockState> palette = new Int2ObjectArrayMap<>(); Int2ObjectArrayMap<IBlockState> palette = new Int2ObjectArrayMap<>();
NBTTagCompound paletteTag = nbt.getCompoundTag("Palette"); NBTTagCompound paletteTag = nbt.getCompound("Palette");
for (String tag : paletteTag.getKeySet()) { for (String tag : paletteTag.keySet()) {
int index = paletteTag.getInteger(tag); int index = paletteTag.getInt(tag);
SerializedBlockState serializedState = SerializedBlockState.getFromString(tag); SerializedBlockState serializedState = SerializedBlockState.getFromString(tag);
if (serializedState == null) { if (serializedState == null) {
@@ -106,11 +107,11 @@ public final class SpongeSchematic extends StaticSchematic {
private IBlockState deserialize() { private IBlockState deserialize() {
if (this.blockState == null) { if (this.blockState == null) {
Block block = Block.REGISTRY.getObject(this.resourceLocation); Block block = IRegistry.BLOCK.get(this.resourceLocation);
this.blockState = block.getDefaultState(); this.blockState = block.getDefaultState();
this.properties.keySet().stream().sorted(String::compareTo).forEachOrdered(key -> { this.properties.keySet().stream().sorted(String::compareTo).forEachOrdered(key -> {
IProperty<?> property = block.getBlockState().getProperty(key); IProperty<?> property = block.getStateContainer().getProperty(key);
if (property != null) { if (property != null) {
this.blockState = setPropertyValue(this.blockState, property, this.properties.get(key)); this.blockState = setPropertyValue(this.blockState, property, this.properties.get(key));
} }
@@ -146,9 +147,9 @@ public final class SpongeSchematic extends StaticSchematic {
} }
private static <T extends Comparable<T>> IBlockState setPropertyValue(IBlockState state, IProperty<T> property, String value) { private static <T extends Comparable<T>> IBlockState setPropertyValue(IBlockState state, IProperty<T> property, String value) {
Optional<T> parsed = property.parseValue(value).toJavaUtil(); Optional<T> parsed = property.parseValue(value);
if (parsed.isPresent()) { if (parsed.isPresent()) {
return state.withProperty(property, parsed.get()); return state.with(property, parsed.get());
} else { } else {
throw new IllegalArgumentException("Invalid value for property " + property); throw new IllegalArgumentException("Invalid value for property " + property);
} }