Compare commits

...

71 Commits

Author SHA1 Message Date
Leijurv
96bcabff8b v1.5.0 2020-02-13 12:04:29 -08:00
Leijurv
0a1fe857dc cant walk through honey blocks 2020-02-13 12:03:09 -08:00
Brady
49aaa55172 Fix click 2020-02-09 13:38:46 -06:00
Leijurv
e03e251541 fix crouching 2020-02-05 17:45:22 -08:00
Leijurv
f5380881f4 brady fix mixins im incompetent 2020-02-05 16:10:55 -08:00
Leijurv
a022778fb6 cursed but fixes blockoptionalmeta 2020-02-05 15:14:32 -08:00
Leijurv
8543a99fba compiles and can path 2020-02-05 14:54:03 -08:00
Brady
997888fe85 Merge branch '1.14.4' into 1.15.1 2020-01-10 20:15:43 -06:00
Brady
94a2e13561 Merge branch '1.13.2' into 1.14.4 2020-01-10 20:14:46 -06:00
Brady
f7041022d0 Merge branch 'master' into 1.13.2 2020-01-10 20:13:57 -06:00
Brady
710170ef2d Fix RelativeGoalXZ coordinate mix-up
Basically for many months now RelativeGoalXZ produced (~X, ~Y), not (~X, ~Z).
2020-01-10 20:10:16 -06:00
Brady
2d2030ecdf Fix renderGoalXZBeacon 2020-01-10 20:07:33 -06:00
Brady
a3dec3a47e Render stuff should be fixed now.
There is likely a better solution, but I think this is fine in order to keep things in-line with the development over at Mojang.
2020-01-10 19:37:00 -06:00
Brady
eb348120d9 Fix Mixins 2020-01-10 18:59:57 -06:00
Brady
27cb708d40 Fix some render stuff but it's still broken 2020-01-09 20:09:49 -06:00
Leijurv
36bbe430d4 add fixmes 2020-01-09 17:27:28 -08:00
Leijurv
80952e091d comment out anything that isn't instantly obvious how to fix (e.g. anything involving rendering) 2020-01-09 17:15:05 -08:00
Leijurv
760ac5dd8f v1.4.4 2020-01-04 21:58:55 -08:00
Leijurv
dd76d2eabc v1.3.6 2020-01-04 21:58:21 -08:00
Leijurv
fb22cf05eb v1.2.11 2020-01-04 21:57:16 -08:00
Brady
92966dc57c Merge branch '1.13.2' into 1.14.4 2019-12-31 21:57:55 -06: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
Brady
adff391e45 Merge branch 'schematic-formats' 2019-12-31 18:25:21 -06:00
Brady
4a05837b01 Requested changes 2019-12-31 17:44:20 -06:00
Leijurv
1edd7126fd Merge branch 'master' into 1.13.2 2019-12-31 15:44:03 -08:00
Leijurv
a0014fda12 Merge pull request #1216 from FTC55/master
Fixed a rather obnoxious bug that would require a full restart of the client.
2019-12-31 15:35:01 -08:00
FTC55
04190af340 ...more than I thought. Autoreformatted file x2 2019-12-31 19:45:08 +01:00
FTC55
4b10904b97 Git missed some changes. Autoreformatted files. 2019-12-31 19:43:54 +01:00
FTC55
bbb25acff3 Fixed the bug, merged CancelCommand into ExecutionControlCommands 2019-12-31 19:31:30 +01:00
Brady
fcfa022232 Clean up BlockOptionalMeta comment and add behavioral clarification 2019-12-30 02:27:20 -06:00
Brady
220ee30d35 Appease Codacy 2019-12-27 21:28:05 -06:00
Brady
812bc0d8c4 Remove redundant parser layer 2019-12-27 01:14:31 -06:00
Brady
d712839c25 Make Schematica respect mapArtMode setting 2019-12-25 01:35:10 -06:00
Brady
eee705b371 Schematic Format API support 2019-12-24 17:20:00 -06:00
Brady
77bdf6e444 Fix MapSchematic 2019-12-23 18:05:50 -06:00
Brady
0a858c040c Working 2019-12-19 22:15:14 -06:00
Brady
eea5b69b6c Utilize new FillSchematic 2019-12-19 12:03:02 -06:00
Brady
6759917a2f Additional clean up 2019-12-19 11:58:47 -06:00
Brady
aa3bd80ab2 Clean ups 2019-12-19 11:40:38 -06:00
Brady
ea8d7fb3b9 Improve file extension fallback mechanism 2019-12-18 15:19:58 -06:00
Brady
b4ddf38116 Check if state is null 2019-12-18 10:27:34 -06:00
Brady
5c9f028103 Initial sponge support 2019-12-18 10:24:43 -06:00
Leijurv
937d4cc884 whoops 2019-12-13 20:46:12 -08:00
Leijurv
2c3e1f4232 builder stuff, fixes #1059 2019-12-13 20:09:04 -08:00
Leijurv
ddc681fe77 build repeat count 2019-11-24 11:11:28 -08:00
Leijurv
2b71b31cfa Merge pull request #1087 from cabaletta/ispassable-crash-fix
Fix isPassable crash
2019-11-10 22:52:29 -08:00
Leijurv
ed144e995b apparently this usage of > was an invalid javadoc command lol 2019-11-10 14:04:27 -08:00
Brady
7e3a2d3c0a Create a BlockStateInterface specialized IBlockAccess wrapper 2019-11-05 18:17:10 -06:00
Leijurv
152285043d Update USAGE.md 2019-11-05 11:50:27 -08:00
Leijurv
ce52201e45 Merge pull request #1097 from greg904/fix-goto-errmsg
Remove error message when running goto with less than 3 args
2019-10-29 21:33:27 -07:00
Leijurv
45ea776090 Update README.md 2019-10-28 10:47:20 -07:00
Leijurv
2ae16d8bb1 configurable block reach distance 2019-10-26 16:01:08 -07:00
Greg Depoire--Ferrer
23fc6c8b49 Add a space between sentences in error message 2019-10-25 14:49:57 +02:00
Greg Depoire--Ferrer
0db4b193e1 Remove hack, add comment, don't use default when arg is required 2019-10-25 14:49:08 +02:00
Greg Depoire--Ferrer
82d520d808 Don't print invalid type error to stderr 2019-10-25 14:42:36 +02:00
Brady
5201d39adf Retain old method signature 2019-10-24 15:20:23 -05:00
Brady
f02c33d95a Fix improper tick count incrementation 2019-10-23 17:47:20 -05:00
Brady
43ab4f7d3b Fix isPassable crash 2019-10-22 15:58:10 -05: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
6341f9fcb4 Merge pull request #1072 from 0-x-2-2/disable-autotest-mob-spawning
Disable harmful mob spawning in Travis auto test.
2019-10-17 12:05:24 -07:00
0x22
66ffd1e0d9 Disable harmful mob spawning in Travis auto test. 2019-10-17 14:35:28 -04:00
Leijurv
e65c854e6a Update USAGE.md 2019-10-15 11:25:35 -07:00
Brady
4eca960a4c Specify range in IWorldScanner#repack 2019-10-14 15:45:41 -05:00
Leijurv
214225c08d v1.4.3 2019-10-13 22:53:05 -07:00
Leijurv
05b5894348 a much better way to deal with this 2019-10-13 10:53:25 -07:00
Leijurv
69bceb43f8 Update USAGE.md 2019-10-12 13:07:12 -07:00
Leijurv
6a8807b0fa documentation stuff 2019-10-12 10:43:01 -07:00
Leijurv
105c7d438a v1.3.5 2019-10-11 17:29:27 -07:00
Leijurv
e49549117b v1.2.10 2019-10-11 17:08:28 -07:00
75 changed files with 1331 additions and 907 deletions

View File

@@ -19,7 +19,7 @@
![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.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactclient.net/)
[![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/)

View File

@@ -8,11 +8,23 @@ Baritone commands can also by default be typed in the chatbox. However if you ma
To disable direct chat control (with no prefix), turn off the `chatControl` setting. To disable chat control with the `#` prefix, turn off the `prefixControl` setting. In Impact, `.b` cannot be disabled. Be careful that you don't leave yourself with all control methods disabled (if you do, reset your settings by deleting the file `minecraft/baritone/settings.txt` and relaunching).
# For Baritone 1.2.10+, 1.3.5+, 1.4.2+
Lots of the commands have changed, BUT `#help` is improved vastly (its clickable! commands have tab completion! oh my!).
Try `#help` I promise it won't just send you back here =)
"wtf where is cleararea" -> look at `#help sel`
"wtf where is goto death, goto waypoint" -> look at `#help wp` (a "tag" is like "home" (created automatically on right clicking a bed) or "death" (created automatically on death) or "user" (has to be created manually)). So you might want `#wp save user coolbiome` then, to set the goal `#wp goal coolbiome` then `#path` to path to it. For death, `#wp goal death` (remember stuff is clickable!).
just look at `#help` lmao
# Commands
**All** of these commands may need a prefix before them, as above ^.
`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java#L47).
`help`
To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`.
@@ -38,12 +50,6 @@ Some common examples:
- `version` to get the version of Baritone you're running
- `damn` daniel
New commands:
- `sel` to manage selections
- some others
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java).
All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/Settings.java">here</a>. If you find HTML easier to read than Javadoc, you can look <a href="https://baritone.leijurv.com/baritone/api/Settings.html#field.detail">here</a>.

View File

@@ -16,11 +16,10 @@
*/
group 'baritone'
version '1.4.2'
version '1.5.0'
buildscript {
repositories {
jcenter()
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
@@ -29,6 +28,7 @@ buildscript {
name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/'
}
jcenter()
}
dependencies {
@@ -82,7 +82,7 @@ task sourceJar(type: Jar, dependsOn: classes) {
}
minecraft {
mappings channel: 'snapshot', version: '20190814-1.14.3'
mappings channel: 'snapshot', version: '20200205-1.15.1'
reobfMappings 'notch'
runs {
@@ -138,7 +138,7 @@ repositories {
}
dependencies {
minecraft 'com.github.ImpactDevelopment:Vanilla:1.14.4'
minecraft 'com.github.ImpactDevelopment:Vanilla:1.15.2'
runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl'

View File

@@ -21,6 +21,7 @@ import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommand;
import baritone.api.command.ICommandSystem;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import baritone.api.schematic.ISchematicSystem;
import java.util.List;
import java.util.Objects;
@@ -82,4 +83,9 @@ public interface IBaritoneProvider {
* @return The {@link ICommandSystem} instance.
*/
ICommandSystem getCommandSystem();
/**
* @return The {@link ISchematicSystem} instance.
*/
ISchematicSystem getSchematicSystem();
}

View File

@@ -30,8 +30,8 @@ import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
/**
@@ -181,6 +181,20 @@ public final class Settings {
Blocks.TRAPPED_CHEST
)));
/**
* A list of blocks to be treated as if they're air.
* <p>
* If a schematic asks for air at a certain position, and that position currently contains a block on this list, it will be treated as correct.
*/
public final Setting<List<Block>> buildIgnoreBlocks = new Setting<>(new ArrayList<>(Arrays.asList(
)));
/**
* If this is true, the builder will treat all non-air blocks as correct. It will only place new blocks.
*/
public final Setting<Boolean> buildIgnoreExisting = new Setting<>(false);
/**
* If this setting is true, Baritone will never break a block that is adjacent to an unsupported falling block.
* <p>
@@ -231,7 +245,7 @@ public final class Settings {
/**
* If we overshoot a traverse and end up one block beyond the destination, mark it as successful anyway.
* <p>
* This helps with speed at >=20m/s
* This helps with speed exceeding 20m/s
*/
public final Setting<Boolean> overshootTraverse = new Setting<>(true);
@@ -250,6 +264,11 @@ public final class Settings {
*/
public final Setting<Double> randomLooking113 = new Setting<>(2d);
/**
* Block reach distance
*/
public final Setting<Float> blockReachDistance = new Setting<>(4.5f);
/**
* How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable
*/
@@ -740,6 +759,11 @@ public final class Settings {
*/
public final Setting<Vec3i> buildRepeat = new Setting<>(new Vec3i(0, 0, 0));
/**
* How many times to buildrepeat. -1 for infinite.
*/
public final Setting<Integer> buildRepeatCount = new Setting<>(-1);
/**
* Allow standing above a block while mining it, in BuilderProcess
* <p>
@@ -789,6 +813,12 @@ public final class Settings {
*/
public final Setting<Boolean> schematicOrientationZ = new Setting<>(false);
/**
* The fallback used by the build command when no extension is specified. This may be useful if schematics of a
* particular format are used often, and the user does not wish to have to specify the extension with every usage.
*/
public final Setting<String> schematicFallbackExtension = new Setting<>("schematic");
/**
* Distance to scan every tick for updates. Expanding this beyond player reach distance (i.e. setting it to 6 or above)
* is only necessary in very large schematics where rescanning the whole thing is costly.
@@ -928,6 +958,11 @@ public final class Settings {
*/
public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getInstance().ingameGUI.getChatGUI()::printChatMessage);
/**
* Print out ALL command exceptions as a stack trace to stdout, even simple syntax errors
*/
public final Setting<Boolean> verboseCommandExceptions = new Setting<>(false);
/**
* The size of the box that is rendered when the current goal is a GoalYLevel
*/

View File

@@ -81,6 +81,4 @@ public interface ICachedWorld {
* in a new thread by default.
*/
void save();
}

View File

@@ -77,10 +77,20 @@ public interface IWorldScanner {
}
/**
* Repacks 40 chunks around the player.
* Overload of {@link #repack(IPlayerContext, int)} where the value of the {@code range} parameter is {@code 40}.
*
* @param ctx The player context for that player.
* @return The number of chunks queued for repacking.
* @param ctx The player, describing the origin
* @return The amount of chunks successfully queued for repacking
*/
int repack(IPlayerContext ctx);
/**
* Queues the chunks in a square formation around the specified player, using the specified
* range, which represents 1/2 the square's dimensions, where the player is in the center.
*
* @param ctx The player, describing the origin
* @param range The range to repack
* @return The amount of chunks successfully queued for repacking
*/
int repack(IPlayerContext ctx, int range);
}

View File

@@ -38,38 +38,26 @@ public enum RelativeGoal implements IDatatypePost<Goal, BetterBlockPos> {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
List<IDatatypePostFunction<Double, Double>> coords = new ArrayList<>();
final IArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably
for (int i = 0; i < 3; i++) {
if (copy.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) {
coords.add(o -> consumer.getDatatypePost(RelativeCoordinate.INSTANCE, o));
copy.get(); // Consume so we actually decrement the remaining arguments
}
GoalBlock goalBlock = consumer.peekDatatypePostOrNull(RelativeGoalBlock.INSTANCE, origin);
if (goalBlock != null) {
return goalBlock;
}
switch (coords.size()) {
case 0:
return new GoalBlock(origin);
case 1:
return new GoalYLevel(
MathHelper.floor(coords.get(0).apply((double) origin.y))
);
case 2:
return new GoalXZ(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.z))
);
case 3:
return new GoalBlock(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.y)),
MathHelper.floor(coords.get(2).apply((double) origin.z))
);
default:
throw new IllegalStateException("Unexpected coords size: " + coords.size());
GoalXZ goalXZ = consumer.peekDatatypePostOrNull(RelativeGoalXZ.INSTANCE, origin);
if (goalXZ != null) {
return goalXZ;
}
GoalYLevel goalYLevel = consumer.peekDatatypePostOrNull(RelativeGoalYLevel.INSTANCE, origin);
if (goalYLevel != null) {
return goalYLevel;
}
// when the user doesn't input anything, default to the origin
return new GoalBlock(origin);
}
@Override

View File

@@ -37,7 +37,7 @@ public enum RelativeGoalXZ implements IDatatypePost<GoalXZ, BetterBlockPos> {
final IArgConsumer consumer = ctx.getConsumer();
return new GoalXZ(
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)),
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y))
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z))
);
}

View File

@@ -22,4 +22,8 @@ public abstract class CommandErrorMessageException extends CommandException {
protected CommandErrorMessageException(String reason) {
super(reason);
}
protected CommandErrorMessageException(String reason, Throwable cause) {
super(reason, cause);
}
}

View File

@@ -22,4 +22,8 @@ public abstract class CommandException extends Exception implements ICommandExce
protected CommandException(String reason) {
super(reason);
}
protected CommandException(String reason, Throwable cause) {
super(reason, cause);
}
}

View File

@@ -23,12 +23,21 @@ public abstract class CommandInvalidArgumentException extends CommandErrorMessag
public final ICommandArgument arg;
protected CommandInvalidArgumentException(ICommandArgument arg, String reason) {
super(String.format(
"Error at argument #%s: %s",
arg.getIndex() == -1 ? "<unknown>" : Integer.toString(arg.getIndex() + 1),
reason
));
protected CommandInvalidArgumentException(ICommandArgument arg, String message) {
super(formatMessage(arg, message));
this.arg = arg;
}
protected CommandInvalidArgumentException(ICommandArgument arg, String message, Throwable cause) {
super(formatMessage(arg, message), cause);
this.arg = arg;
}
private static String formatMessage(ICommandArgument arg, String message) {
return String.format(
"Error at argument #%s: %s",
arg.getIndex() == -1 ? "<unknown>" : Integer.toString(arg.getIndex() + 1),
message
);
}
}

View File

@@ -26,7 +26,7 @@ public class CommandInvalidTypeException extends CommandInvalidArgumentException
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) {
super(arg, String.format("Expected %s.\nMore details: %s", expected, cause.getMessage()));
super(arg, String.format("Expected %s", expected), cause);
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) {
@@ -34,6 +34,6 @@ public class CommandInvalidTypeException extends CommandInvalidArgumentException
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) {
super(arg, String.format("Expected %s, but got %s instead.\nMore details: %s", expected, got, cause.getMessage()));
super(arg, String.format("Expected %s, but got %s instead", expected, got), cause);
}
}

View File

@@ -37,7 +37,7 @@ public class CommandUnhandledException extends RuntimeException implements IComm
@Override
public void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect("An unhandled exception occurred." +
HELPER.logDirect("An unhandled exception occurred. " +
"The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues",
TextFormatting.RED);

View File

@@ -17,6 +17,8 @@
package baritone.api.event.events;
import com.mojang.blaze3d.matrix.MatrixStack;
/**
* @author Brady
* @since 8/5/2018
@@ -28,8 +30,12 @@ public final class RenderEvent {
*/
private final float partialTicks;
public RenderEvent(float partialTicks) {
private final MatrixStack modelViewStack, projectionStack;
public RenderEvent(float partialTicks, MatrixStack modelViewStack, MatrixStack projectionStack) {
this.partialTicks = partialTicks;
this.modelViewStack = modelViewStack;
this.projectionStack = projectionStack;
}
/**
@@ -38,4 +44,12 @@ public final class RenderEvent {
public final float getPartialTicks() {
return this.partialTicks;
}
public final MatrixStack getModelViewStack() {
return this.modelViewStack;
}
public final MatrixStack getProjectionStack() {
return this.projectionStack;
}
}

View File

@@ -19,22 +19,20 @@ package baritone.api.event.events;
import baritone.api.event.events.type.EventState;
import java.util.function.BiFunction;
public final class TickEvent {
private static int overallTickCount;
private final EventState state;
private final Type type;
private final int count;
private static int overallTickCount;
public TickEvent(EventState state, Type type) {
public TickEvent(EventState state, Type type, int count) {
this.state = state;
this.type = type;
this.count = incrementCount();
}
private static synchronized int incrementCount() {
return overallTickCount++;
this.count = count;
}
public int getCount() {
@@ -49,6 +47,10 @@ public final class TickEvent {
return state;
}
public static synchronized BiFunction<EventState, Type, TickEvent> createNextProvider() {
final int count = overallTickCount++;
return (state, type) -> new TickEvent(state, type, count);
}
public enum Type {
/**

View File

@@ -23,6 +23,10 @@ public abstract class AbstractSchematic implements ISchematic {
protected int y;
protected int z;
public AbstractSchematic() {
this(0, 0, 0);
}
public AbstractSchematic(int x, int y, int z) {
this.x = x;
this.y = y;

View File

@@ -32,6 +32,10 @@ public class FillSchematic extends AbstractSchematic {
this.bom = bom;
}
public FillSchematic(int x, int y, int z, BlockState state) {
this(x, y, z, new BlockOptionalMeta(state.getBlock()));
}
public BlockOptionalMeta getBom() {
return bom;
}

View File

@@ -0,0 +1,44 @@
/*
* 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.api.schematic;
import baritone.api.command.registry.Registry;
import baritone.api.schematic.format.ISchematicFormat;
import java.io.File;
import java.util.Optional;
/**
* @author Brady
* @since 12/23/2019
*/
public interface ISchematicSystem {
/**
* @return The registry of supported schematic formats
*/
Registry<ISchematicFormat> getRegistry();
/**
* Attempts to find an {@link ISchematicFormat} that supports the specified schematic file.
*
* @param file A schematic file
* @return The corresponding format for the file, {@link Optional#empty()} if no candidates were found.
*/
Optional<ISchematicFormat> getByFile(File file);
}

View File

@@ -0,0 +1,60 @@
/*
* 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.api.schematic;
import net.minecraft.block.BlockState;
/**
* A static schematic is capable of providing the desired state at a given position without
* additional context. Schematics of this type are expected to have non-varying contents.
*
* @see #getDirect(int, int, int)
*
* @author Brady
* @since 12/24/2019
*/
public interface IStaticSchematic extends ISchematic {
/**
* Gets the {@link BlockState} for a given position in this schematic. It should be guaranteed
* that the return value of this method will not change given that the parameters are the same.
*
* @param x The X block position
* @param y The Y block position
* @param z The Z block position
* @return The desired state at the specified position.
*/
BlockState getDirect(int x, int y, int z);
/**
* Returns an {@link BlockState} array of size {@link #heightY()} which contains all
* desired block states in the specified vertical column. The index of {@link BlockState}s
* in the array are equivalent to their Y position in the schematic.
*
* @param x The X column position
* @param z The Z column position
* @return An {@link BlockState} array
*/
default BlockState[] getColumn(int x, int z) {
BlockState[] column = new BlockState[this.heightY()];
for (int i = 0; i < this.heightY(); i++) {
column[i] = getDirect(x, i, z);
}
return column;
}
}

View File

@@ -0,0 +1,45 @@
/*
* 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.api.schematic.format;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* The base of a {@link ISchematic} file format
*
* @author Brady
* @since 12/23/2019
*/
public interface ISchematicFormat {
/**
* @return The parser for creating schematics of this format
*/
IStaticSchematic parse(InputStream input) throws IOException;
/**
* @param file The file to check against
* @return Whether or not the specified file matches this schematic format
*/
boolean isFileType(File file);
}

View File

@@ -20,24 +20,19 @@ package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.block.*;
import net.minecraft.client.Minecraft;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.resources.*;
import net.minecraft.state.IProperty;
import net.minecraft.state.properties.*;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Unit;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.storage.loot.*;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -50,8 +45,8 @@ public final class BlockOptionalMeta {
private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations;
private static LootTableManager manager;
private static LootPredicateManager predicate = new LootPredicateManager();
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) {
@@ -70,154 +65,12 @@ public final class BlockOptionalMeta {
MatchResult matchResult = matcher.toMatchResult();
ResourceLocation id = new ResourceLocation(matchResult.group(1));
if (!Registry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID");
}
block = Registry.BLOCK.getValue(id).orElse(null);
block = BlockUtils.stringToBlockRequired(matchResult.group(1));
blockstates = getStates(block);
stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates);
}
static {
Map<Object, Object> _normalizations = new HashMap<>();
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
put.accept(Direction.NORTH);
put.accept(Direction.Axis.Y);
put.accept(Half.BOTTOM);
put.accept(StairsShape.STRAIGHT);
put.accept(AttachFace.FLOOR);
put.accept(DoubleBlockHalf.UPPER);
put.accept(SlabType.BOTTOM);
put.accept(DoorHingeSide.LEFT);
put.accept(BedPart.HEAD);
put.accept(RailShape.NORTH_SOUTH);
_normalizations.put(BannerBlock.ROTATION, 0);
_normalizations.put(BedBlock.OCCUPIED, false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[0], false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[1], false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[2], false);
_normalizations.put(AbstractButtonBlock.POWERED, false);
// _normalizations.put(BlockCactus.AGE, 0);
// _normalizations.put(BlockCauldron.LEVEL, 0);
// _normalizations.put(BlockChorusFlower.AGE, 0);
_normalizations.put(ChorusPlantBlock.NORTH, false);
_normalizations.put(ChorusPlantBlock.EAST, false);
_normalizations.put(ChorusPlantBlock.SOUTH, false);
_normalizations.put(ChorusPlantBlock.WEST, false);
_normalizations.put(ChorusPlantBlock.UP, false);
_normalizations.put(ChorusPlantBlock.DOWN, false);
// _normalizations.put(BlockCocoa.AGE, 0);
// _normalizations.put(BlockCrops.AGE, 0);
_normalizations.put(SnowyDirtBlock.SNOWY, false);
_normalizations.put(DoorBlock.OPEN, false);
_normalizations.put(DoorBlock.POWERED, false);
// _normalizations.put(BlockFarmland.MOISTURE, 0);
_normalizations.put(FenceBlock.NORTH, false);
_normalizations.put(FenceBlock.EAST, false);
_normalizations.put(FenceBlock.WEST, false);
_normalizations.put(FenceBlock.SOUTH, false);
// _normalizations.put(BlockFenceGate.POWERED, false);
// _normalizations.put(BlockFenceGate.IN_WALL, false);
_normalizations.put(FireBlock.AGE, 0);
_normalizations.put(FireBlock.NORTH, false);
_normalizations.put(FireBlock.EAST, false);
_normalizations.put(FireBlock.SOUTH, false);
_normalizations.put(FireBlock.WEST, false);
_normalizations.put(FireBlock.UP, false);
// _normalizations.put(BlockFrostedIce.AGE, 0);
_normalizations.put(GrassBlock.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(LeavesBlock.DISTANCE, false);
// _normalizations.put(BlockLeaves.DECAYABLE, false);
// _normalizations.put(BlockObserver.POWERED, false);
_normalizations.put(PaneBlock.NORTH, false);
_normalizations.put(PaneBlock.EAST, false);
_normalizations.put(PaneBlock.WEST, false);
_normalizations.put(PaneBlock.SOUTH, false);
// _normalizations.put(BlockPistonBase.EXTENDED, false);
// _normalizations.put(BlockPressurePlate.POWERED, false);
// _normalizations.put(BlockPressurePlateWeighted.POWER, false);
// _normalizations.put(BlockRailDetector.POWERED, false);
// _normalizations.put(BlockRailPowered.POWERED, false);
_normalizations.put(RedstoneWireBlock.NORTH, false);
_normalizations.put(RedstoneWireBlock.EAST, false);
_normalizations.put(RedstoneWireBlock.SOUTH, false);
_normalizations.put(RedstoneWireBlock.WEST, false);
// _normalizations.put(BlockReed.AGE, false);
_normalizations.put(SaplingBlock.STAGE, 0);
_normalizations.put(StandingSignBlock.ROTATION, 0);
_normalizations.put(StemBlock.AGE, 0);
_normalizations.put(TripWireBlock.NORTH, false);
_normalizations.put(TripWireBlock.EAST, false);
_normalizations.put(TripWireBlock.WEST, false);
_normalizations.put(TripWireBlock.SOUTH, false);
_normalizations.put(VineBlock.NORTH, false);
_normalizations.put(VineBlock.EAST, false);
_normalizations.put(VineBlock.SOUTH, false);
_normalizations.put(VineBlock.WEST, false);
_normalizations.put(VineBlock.UP, false);
_normalizations.put(WallBlock.UP, false);
_normalizations.put(WallBlock.NORTH, false);
_normalizations.put(WallBlock.EAST, false);
_normalizations.put(WallBlock.WEST, false);
_normalizations.put(WallBlock.SOUTH, false);
normalizations = Collections.unmodifiableMap(_normalizations);
}
private static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) {
//noinspection unchecked
return (P) value;
}
private static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) {
//noinspection unchecked
return (C) value;
}
public static BlockState normalize(BlockState state) {
BlockState newState = state;
for (IProperty<?> property : state.getProperties()) {
Class<?> valueClass = property.getValueClass();
if (normalizations.containsKey(property)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(property))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(state.get(property))) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(state.get(property)))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(valueClass)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(valueClass))
);
} catch (IllegalArgumentException ignored) {}
}
}
return newState;
}
public static int stateMeta(BlockState state) {
return state.hashCode();
}
private static Set<BlockState> getStates(@Nonnull Block block) {
return new HashSet<>(block.getStateContainer().getValidStates());
}
@@ -285,7 +138,7 @@ public final class BlockOptionalMeta {
rpl.reloadPacksFromFinders();
IResourcePack thePack = ((ResourcePackInfo) rpl.getAllPacks().iterator().next()).getResourcePack();
IReloadableResourceManager resourceManager = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA, null);
manager = new LootTableManager();
manager = new LootTableManager(predicate);
resourceManager.addReloadListener(manager);
try {
resourceManager.reloadResourcesAndThen(new ThreadPerTaskExecutor(Thread::new), new ThreadPerTaskExecutor(Thread::new), Collections.singletonList(thePack), CompletableFuture.completedFuture(Unit.INSTANCE)).get();
@@ -296,10 +149,11 @@ public final class BlockOptionalMeta {
return manager;
}
private static List<Item> drops(Block b) {
if (!Minecraft.getInstance().isOnExecutionThread()) {
throw new IllegalStateException();
}
public static LootPredicateManager getPredicateManager() {
return predicate;
}
private static synchronized List<Item> drops(Block b) {
return drops.computeIfAbsent(b, block -> {
ResourceLocation lootTableLocation = block.getLootTable();
if (lootTableLocation == LootTables.EMPTY) {

View File

@@ -56,7 +56,7 @@ public interface IPlayerContext {
default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ);
BetterBlockPos feet = new BetterBlockPos(player().getPositionVec().x, player().getPositionVec().y + 0.1251, player().getPositionVec().z);
// sometimes when calling this from another thread or while world is null, it'll throw a NullPointerException
// that causes the game to immediately crash
@@ -76,11 +76,11 @@ public interface IPlayerContext {
}
default Vec3d playerFeetAsVec() {
return new Vec3d(player().posX, player().posY, player().posZ);
return new Vec3d(player().getPositionVec().x, player().getPositionVec().y, player().getPositionVec().z);
}
default Vec3d playerHead() {
return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ);
return new Vec3d(player().getPositionVec().x, player().getPositionVec().y + player().getEyeHeight(), player().getPositionVec().z);
}
default Rotation playerRotations() {

View File

@@ -20,6 +20,7 @@ package baritone.api.utils;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.container.ClickType;
import baritone.api.BaritoneAPI;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
@@ -56,6 +57,6 @@ public interface IPlayerController {
void setHittingBlock(boolean hittingBlock);
default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : 4.5F;
return this.getGameType().isCreative() ? 5.0F : BaritoneAPI.getSettings().blockReachDistance.value;
}
}

View File

@@ -105,7 +105,7 @@ public final class VecUtils {
* @see #getBlockPosCenter(BlockPos)
*/
public static double entityDistanceToCenter(Entity entity, BlockPos pos) {
return distanceToCenter(pos, entity.posX, entity.posY, entity.posZ);
return distanceToCenter(pos, entity.getPositionVec().x, entity.getPositionVec().y, entity.getPositionVec().z);
}
/**
@@ -118,6 +118,6 @@ public final class VecUtils {
* @see #getBlockPosCenter(BlockPos)
*/
public static double entityFlatDistanceToCenter(Entity entity, BlockPos pos) {
return distanceToCenter(pos, entity.posX, pos.getY() + 0.5, entity.posZ);
return distanceToCenter(pos, entity.getPositionVec().x, pos.getY() + 0.5, entity.getPositionVec().z);
}
}

View File

@@ -22,7 +22,7 @@ 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.screen.ChatScreen;
import net.minecraft.client.gui.CommandSuggestionHelper;
import net.minecraft.client.gui.widget.TextFieldWidget;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
@@ -40,27 +40,28 @@ import java.util.stream.Stream;
* @author Brady
* @since 10/9/2019
*/
@Mixin(ChatScreen.class)
public class MixinChatScreen {
@Shadow
protected TextFieldWidget inputField;
@Mixin(CommandSuggestionHelper.class)
public class MixinCommandSuggestionHelper {
@Shadow
@Final
protected List<String> commandUsage;
private TextFieldWidget field_228095_d_;
@Shadow
private CompletableFuture<Suggestions> pendingSuggestions;
@Final
private List<String> field_228103_l_;
@Shadow
private CompletableFuture<Suggestions> field_228107_p_;
@Inject(
method = "updateSuggestion",
method = "func_228111_a_",
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()));
String prefix = this.field_228095_d_.getText().substring(0, Math.min(this.field_228095_d_.getText().length(), this.field_228095_d_.getCursorPosition()));
TabCompleteEvent event = new TabCompleteEvent(prefix);
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onPreTabComplete(event);
@@ -74,14 +75,14 @@ public class MixinChatScreen {
ci.cancel();
// TODO: Support populating the command usage
this.commandUsage.clear();
this.field_228103_l_.clear();
if (event.completions.length == 0) {
this.pendingSuggestions = Suggestions.empty();
this.field_228107_p_ = 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
int offset = this.field_228095_d_.getText().endsWith(" ")
? this.field_228095_d_.getCursorPosition()
: this.field_228095_d_.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))
@@ -91,8 +92,8 @@ public class MixinChatScreen {
StringRange.between(offset, offset + suggestionList.stream().mapToInt(s -> s.getText().length()).max().orElse(0)),
suggestionList);
this.pendingSuggestions = new CompletableFuture<>();
this.pendingSuggestions.complete(suggestions);
this.field_228107_p_ = new CompletableFuture<>();
this.field_228107_p_.complete(suggestions);
}
}
}

View File

@@ -20,29 +20,23 @@ package baritone.launch.mixins;
import baritone.utils.accessor.IEntityRenderManager;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(EntityRendererManager.class)
public class MixinEntityRenderManager implements IEntityRenderManager {
@Shadow
private double renderPosX;
@Shadow
private double renderPosY;
@Shadow
private double renderPosZ;
@Override
public double renderPosX() {
return renderPosX;
return ((EntityRendererManager) (Object) this).info.getProjectedView().x;
}
@Override
public double renderPosY() {
return renderPosY;
return ((EntityRendererManager) (Object) this).info.getProjectedView().y;
}
@Override
public double renderPosZ() {
return renderPosZ;
return ((EntityRendererManager) (Object) this).info.getProjectedView().z;
}
}

View File

@@ -20,26 +20,31 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.RenderEvent;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.Matrix4f;
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;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
@Inject(
method = "updateCameraAndRender(FJ)V",
method = "renderWorld",
at = @At(
value = "INVOKE_STRING",
target = "Lnet/minecraft/profiler/IProfiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"}
)
),
locals = LocalCapture.CAPTURE_FAILHARD
)
private void renderWorldPass(float partialTicks, long finishTimeNano, CallbackInfo ci) {
private void renderWorldPass(float partialTicks, long finishTimeNano, MatrixStack modelViewMatrix, CallbackInfo ci, boolean flag, ActiveRenderInfo activerenderinfo, MatrixStack projectionMatrix, float f, Matrix4f matrix4f) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks));
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks, modelViewMatrix, projectionMatrix));
}
}
}

View File

@@ -21,6 +21,7 @@ import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootPredicateManager;
import net.minecraft.world.storage.loot.LootTableManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@@ -56,4 +57,18 @@ public class MixinLootContext {
}
return server.getLootTableManager();
}
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/MinecraftServer.func_229736_aP_()Lnet/minecraft/world/storage/loot/LootPredicateManager;"
)
)
private LootPredicateManager getLootPredicateManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getPredicateManager();
}
return server.func_229736_aP_();
}
}

View File

@@ -19,7 +19,6 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent;
import baritone.api.event.events.type.EventState;
@@ -28,10 +27,6 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockRayTraceResult;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@@ -39,7 +34,8 @@ 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;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.function.BiFunction;
/**
* @author Brady
@@ -54,7 +50,7 @@ public class MixinMinecraft {
public ClientWorld world;
@Inject(
method = "init",
method = "<init>",
at = @At("RETURN")
)
private void postInit(CallbackInfo ci) {
@@ -62,11 +58,8 @@ public class MixinMinecraft {
}
@Inject(
method = "init",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/Minecraft.startTimerHackThread()V"
)
method = "startTimerHackThread",
at = @At("HEAD")
)
private void preInit(CallbackInfo ci) {
BaritoneAutoTest.INSTANCE.onPreInit();
@@ -84,13 +77,15 @@ public class MixinMinecraft {
)
)
private void runTick(CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
final BiFunction<EventState, TickEvent.Type, TickEvent> tickProvider = TickEvent.createNextProvider();
TickEvent.Type type = ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().world() != null
for (IBaritone baritone : BaritoneAPI.getProvider().getAllBaritones()) {
TickEvent.Type type = baritone.getPlayerContext().player() != null && baritone.getPlayerContext().world() != null
? TickEvent.Type.IN
: TickEvent.Type.OUT;
ibaritone.getGameEventHandler().onTick(new TickEvent(EventState.PRE, type));
baritone.getGameEventHandler().onTick(tickProvider.apply(EventState.PRE, type));
}
}
@@ -144,16 +139,24 @@ public class MixinMinecraft {
return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.passEvents;
}
@Inject(
// TODO
// FIXME
// bradyfix
// i cant mixin
// lol
// https://discordapp.com/channels/208753003996512258/503692253881958400/674760939681349652
// https://discordapp.com/channels/208753003996512258/503692253881958400/674756457966862376
/*@Inject(
method = "rightClickMouse",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/entity/player/ClientPlayerEntity.swingArm(Lnet/minecraft/util/Hand;)V"
target = "net/minecraft/client/entity/player/ClientPlayerEntity.swingArm(Lnet/minecraft/util/Hand;)V",
ordinal = 1
),
locals = LocalCapture.CAPTURE_FAILHARD
)
private void onBlockUse(CallbackInfo ci, Hand var1[], int var2, int var3, Hand enumhand, ItemStack itemstack, BlockRayTraceResult raytrace, int i, ActionResultType enumactionresult) {
private void onBlockUse(CallbackInfo ci, Hand var1[], int var2, int var3, Hand enumhand, ItemStack itemstack, EntityRayTraceResult rt, Entity ent, ActionResultType art, BlockRayTraceResult raytrace, int i, ActionResultType enumactionresult) {
// rightClickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(raytrace.getPos(), BlockInteractEvent.Type.USE));
}
}*/
}

View File

@@ -18,22 +18,22 @@
package baritone.launch.mixins;
import baritone.utils.accessor.IBitArray;
import baritone.utils.accessor.IBlockStateContainer;
import baritone.utils.accessor.IPalettedContainer;
import net.minecraft.block.BlockState;
import net.minecraft.util.BitArray;
import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.world.chunk.IBlockStatePalette;
import net.minecraft.util.palette.IPalette;
import net.minecraft.util.palette.PalettedContainer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(BlockStateContainer.class)
public abstract class MixinBlockStateContainer implements IBlockStateContainer {
@Mixin(PalettedContainer.class)
public abstract class MixinPalettedContainer implements IPalettedContainer {
@Shadow
protected BitArray storage;
@Shadow
protected IBlockStatePalette<BlockState> palette;
protected IPalette<BlockState> palette;
@Override
public BlockState getAtPalette(int index) {

View File

@@ -9,8 +9,7 @@
},
"client": [
"MixinBitArray",
"MixinBlockStateContainer",
"MixinChatScreen",
"MixinCommandSuggestionHelper",
"MixinChunkArray",
"MixinClientChunkProvider",
"MixinClientPlayerEntity",
@@ -23,6 +22,7 @@
"MixinLootContext",
"MixinMinecraft",
"MixinNetworkManager",
"MixinPalettedContainer",
"MixinPlayerController",
"MixinScreen"
]

View File

@@ -21,9 +21,11 @@ import baritone.api.IBaritone;
import baritone.api.IBaritoneProvider;
import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommandSystem;
import baritone.api.schematic.ISchematicSystem;
import baritone.command.BaritoneChatControl;
import baritone.cache.WorldScanner;
import baritone.command.CommandSystem;
import baritone.utils.schematic.SchematicSystem;
import java.util.Collections;
import java.util.List;
@@ -64,4 +66,9 @@ public final class BaritoneProvider implements IBaritoneProvider {
public ICommandSystem getCommandSystem() {
return CommandSystem.INSTANCE;
}
@Override
public ISchematicSystem getSchematicSystem() {
return SchematicSystem.INSTANCE;
}
}

View File

@@ -137,7 +137,7 @@ public final class InventoryBehavior extends Behavior {
public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
BlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z));
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && maybe.equals(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().posX, ctx.player().posY, ctx.player().posZ), Direction.UP, ctx.playerFeet(), false)) {}))))) {
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && maybe.equals(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().getPositionVec().x, ctx.player().getPositionVec().y, ctx.player().getPositionVec().z), Direction.UP, ctx.playerFeet(), false)) {}))))) {
return true; // gotem
}
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock().equals(maybe.getBlock()))) {

View File

@@ -381,8 +381,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
BetterBlockPos feet = ctx.playerFeet();
if (!MovementHelper.canWalkOn(ctx, feet.down())) {
if (ctx.player().onGround) {
double playerX = ctx.player().posX;
double playerZ = ctx.player().posZ;
double playerX = ctx.player().getPositionVec().x;
double playerZ = ctx.player().getPositionVec().z;
ArrayList<BetterBlockPos> closest = new ArrayList<>();
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {

View File

@@ -23,7 +23,7 @@ import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.util.palette.PalettedContainer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection;
@@ -59,7 +59,7 @@ public final class ChunkPacker {
// since a bitset is initialized to all zero, and air is saved as zeros
continue;
}
BlockStateContainer<BlockState> bsc = extendedblockstorage.getData();
PalettedContainer<BlockState> bsc = extendedblockstorage.getData();
int yReal = y0 << 4;
// the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x;
// for better cache locality, iterate in that order

View File

@@ -22,11 +22,12 @@ import baritone.api.cache.IWorldScanner;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IBlockStateContainer;
import baritone.utils.accessor.IPalettedContainer;
import net.minecraft.block.BlockState;
import net.minecraft.client.multiplayer.ClientChunkProvider;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.AbstractChunkProvider;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection;
@@ -109,6 +110,41 @@ public enum WorldScanner implements IWorldScanner {
return res;
}
@Override
public int repack(IPlayerContext ctx) {
return this.repack(ctx, 40);
}
@Override
public int repack(IPlayerContext ctx, int range) {
AbstractChunkProvider chunkProvider = ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet();
int playerChunkX = playerPos.getX() >> 4;
int playerChunkZ = playerPos.getZ() >> 4;
int minX = playerChunkX - range;
int minZ = playerChunkZ - range;
int maxX = playerChunkX + range;
int maxZ = playerChunkZ + range;
int queued = 0;
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, false);
if (chunk != null && !chunk.isEmpty()) {
queued++;
cachedWorld.queueForPacking(chunk);
}
}
}
return queued;
}
private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) {
ChunkSection[] chunkInternalStorageArray = chunk.getSections();
boolean foundWithinY = false;
@@ -119,7 +155,7 @@ public enum WorldScanner implements IWorldScanner {
continue;
}
int yReal = y0 << 4;
IBlockStateContainer bsc = (IBlockStateContainer) section.getData();
IPalettedContainer bsc = (IPalettedContainer) section.getData();
// storageArray uses an optimized algorithm that's faster than getAt
// creating this array and then using getAtPalette is faster than even getFast(int index)
int[] storage = bsc.storageArray();
@@ -145,26 +181,4 @@ public enum WorldScanner implements IWorldScanner {
}
return foundWithinY;
}
public int repack(IPlayerContext ctx) {
ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet();
int playerChunkX = playerPos.getX() >> 4;
int playerChunkZ = playerPos.getZ() >> 4;
int queued = 0;
for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) {
for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, null, false);
if (chunk != null && !chunk.isEmpty()) {
queued++;
cachedWorld.queueForPacking(chunk);
}
}
}
return queued;
}
}

View File

@@ -17,7 +17,9 @@
package baritone.command.argument;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.datatypes.IDatatype;
import baritone.api.command.datatypes.IDatatypeContext;
@@ -27,7 +29,6 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.exception.CommandNotEnoughArgumentsException;
import baritone.api.command.exception.CommandTooManyArgumentsException;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.manager.ICommandManager;
import java.util.ArrayList;
@@ -316,8 +317,10 @@ public class ArgConsumer implements IArgConsumer {
try {
return datatype.apply(this.context, original);
} catch (Exception e) {
e.printStackTrace();
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName());
if (Baritone.settings().verboseCommandExceptions.value) {
e.printStackTrace();
}
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
}
}
@@ -346,7 +349,10 @@ public class ArgConsumer implements IArgConsumer {
try {
return datatype.get(this.context);
} catch (Exception e) {
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName());
if (Baritone.settings().verboseCommandExceptions.value) {
e.printStackTrace();
}
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
}
}

View File

@@ -17,6 +17,7 @@
package baritone.command.defaults;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.Command;
@@ -26,11 +27,11 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.command.argument.IArgConsumer;
import net.minecraft.client.Minecraft;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;
public class BuildCommand extends Command {
@@ -44,8 +45,8 @@ public class BuildCommand extends Command {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile();
if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) {
file = new File(file.getAbsolutePath() + ".schematic");
if (FilenameUtils.getExtension(file.getAbsolutePath()).isEmpty()) {
file = new File(file.getAbsolutePath() + "." + Baritone.settings().schematicFallbackExtension);
}
BetterBlockPos origin = ctx.playerFeet();
BetterBlockPos buildOrigin;

View File

@@ -1,61 +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.command.defaults;
import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class CancelCommand extends Command {
public CancelCommand(IBaritone baritone) {
super(baritone, "cancel", "stop");
}
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
baritone.getPathingBehavior().cancelEverything();
logDirect("ok canceled");
}
@Override
public Stream<String> tabComplete(String label, IArgConsumer args) {
return Stream.empty();
}
@Override
public String getShortDesc() {
return "Cancel what Baritone is currently doing";
}
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The cancel command tells Baritone to stop whatever it's currently doing.",
"",
"Usage:",
"> cancel"
);
}
}

View File

@@ -24,52 +24,53 @@ import java.util.*;
public final class DefaultCommands {
private DefaultCommands() {}
private DefaultCommands() {
}
public static List<ICommand> createAll(IBaritone baritone) {
Objects.requireNonNull(baritone);
List<ICommand> commands = new ArrayList<>(Arrays.asList(
new HelpCommand(baritone),
new SetCommand(baritone),
new CommandAlias(baritone, Arrays.asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"),
new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"),
new GoalCommand(baritone),
new GotoCommand(baritone),
new PathCommand(baritone),
new ProcCommand(baritone),
new VersionCommand(baritone),
new RepackCommand(baritone),
new BuildCommand(baritone),
new SchematicaCommand(baritone),
new ComeCommand(baritone),
new AxisCommand(baritone),
new CancelCommand(baritone),
new ForceCancelCommand(baritone),
new GcCommand(baritone),
new InvertCommand(baritone),
new TunnelCommand(baritone),
new RenderCommand(baritone),
new FarmCommand(baritone),
new ChestsCommand(baritone),
new FollowCommand(baritone),
new ExploreFilterCommand(baritone),
new ReloadAllCommand(baritone),
new SaveAllCommand(baritone),
new ExploreCommand(baritone),
new BlacklistCommand(baritone),
new FindCommand(baritone),
new MineCommand(baritone),
new ClickCommand(baritone),
new ThisWayCommand(baritone),
new WaypointsCommand(baritone),
new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"),
new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"),
new SelCommand(baritone)
new HelpCommand(baritone),
new SetCommand(baritone),
new CommandAlias(baritone, Arrays.asList("modified", "mod", "baritone", "modifiedsettings"), "List modified settings", "set modified"),
new CommandAlias(baritone, "reset", "Reset all settings or just one", "set reset"),
new GoalCommand(baritone),
new GotoCommand(baritone),
new PathCommand(baritone),
new ProcCommand(baritone),
new VersionCommand(baritone),
new RepackCommand(baritone),
new BuildCommand(baritone),
new SchematicaCommand(baritone),
new ComeCommand(baritone),
new AxisCommand(baritone),
new ForceCancelCommand(baritone),
new GcCommand(baritone),
new InvertCommand(baritone),
new TunnelCommand(baritone),
new RenderCommand(baritone),
new FarmCommand(baritone),
new ChestsCommand(baritone),
new FollowCommand(baritone),
new ExploreFilterCommand(baritone),
new ReloadAllCommand(baritone),
new SaveAllCommand(baritone),
new ExploreCommand(baritone),
new BlacklistCommand(baritone),
new FindCommand(baritone),
new MineCommand(baritone),
new ClickCommand(baritone),
new ThisWayCommand(baritone),
new WaypointsCommand(baritone),
new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"),
new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"),
new SelCommand(baritone)
));
PauseResumeCommands prc = new PauseResumeCommands(baritone);
ExecutionControlCommands prc = new ExecutionControlCommands(baritone);
commands.add(prc.pauseCommand);
commands.add(prc.resumeCommand);
commands.add(prc.pausedCommand);
commands.add(prc.cancelCommand);
return Collections.unmodifiableList(commands);
}
}

View File

@@ -18,13 +18,13 @@
package baritone.command.defaults;
import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.process.IBaritoneProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.command.Command;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.command.argument.IArgConsumer;
import java.util.Arrays;
import java.util.List;
@@ -37,13 +37,14 @@ import java.util.stream.Stream;
* TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE
* REQUEST_PAUSE} as needed.
*/
public class PauseResumeCommands {
public class ExecutionControlCommands {
Command pauseCommand;
Command resumeCommand;
Command pausedCommand;
Command cancelCommand;
public PauseResumeCommands(IBaritone baritone) {
public ExecutionControlCommands(IBaritone baritone) {
// array for mutability, non-field so reflection can't touch it
final boolean[] paused = {false};
baritone.getPathingControlManager().registerProcess(
@@ -64,7 +65,8 @@ public class PauseResumeCommands {
}
@Override
public void onLostControl() {}
public void onLostControl() {
}
@Override
public double priority() {
@@ -169,5 +171,36 @@ public class PauseResumeCommands {
);
}
};
cancelCommand = new Command(baritone, "cancel", "stop") {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
if (paused[0]) {
paused[0] = false;
}
baritone.getPathingBehavior().cancelEverything();
logDirect("ok canceled");
}
@Override
public Stream<String> tabComplete(String label, IArgConsumer args) {
return Stream.empty();
}
@Override
public String getShortDesc() {
return "Cancel what Baritone is currently doing";
}
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The cancel command tells Baritone to stop whatever it's currently doing.",
"",
"Usage:",
"> cancel"
);
}
};
}
}

View File

@@ -41,9 +41,13 @@ public class GotoCommand extends Command {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) { // if we have a numeric first argument...
// If we have a numeric first argument, then parse arguments as coordinates.
// Note: There is no reason to want to go where you're already at so there
// is no need to handle the case of empty arguments.
if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) {
args.requireMax(3);
BetterBlockPos origin = baritone.getPlayerContext().playerFeet();
Goal goal = args.getDatatypePostOrNull(RelativeGoal.INSTANCE, origin);
Goal goal = args.getDatatypePost(RelativeGoal.INSTANCE, origin);
logDirect(String.format("Going to: %s", goal.toString()));
baritone.getCustomGoalProcess().setGoalAndPath(goal);
return;

View File

@@ -68,7 +68,7 @@ public class SelCommand extends Command {
float lineWidth = Baritone.settings().selectionLineWidth.value;
boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value;
IRenderer.startLines(color, opacity, lineWidth, ignoreDepth);
IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1)));
IRenderer.drawAABB(event.getModelViewStack(), new AxisAlignedBB(pos1, pos1.add(1, 1, 1)));
IRenderer.endLines(ignoreDepth);
}
});

View File

@@ -37,6 +37,7 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockReader;
import java.util.Optional;
@@ -90,7 +91,7 @@ public interface MovementHelper extends ActionCosts, Helper {
if (block instanceof AirBlock) { // early return for most common case
return true;
}
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.COBWEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof AbstractSkullBlock || block == Blocks.BUBBLE_COLUMN || block instanceof ShulkerBoxBlock || block instanceof SlabBlock || block instanceof TrapDoorBlock) {
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.COBWEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof AbstractSkullBlock || block == Blocks.BUBBLE_COLUMN || block instanceof ShulkerBoxBlock || block instanceof SlabBlock || block instanceof TrapDoorBlock || block == Blocks.HONEY_BLOCK) {
return false;
}
if (Baritone.settings().blocksToAvoid.value.contains(block)) {
@@ -138,7 +139,7 @@ public interface MovementHelper extends ActionCosts, Helper {
// every block that overrides isPassable with anything more complicated than a "return true;" or "return false;"
// 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(null, BlockPos.ZERO, PathType.LAND); // workaround for future compatibility =P
return state.allowsMovement(bsi.access, BlockPos.ZERO, PathType.LAND); // workaround for future compatibility =P
}
/**
@@ -152,10 +153,18 @@ public interface MovementHelper extends ActionCosts, Helper {
* @return Whether or not the block at the specified position
*/
static boolean fullyPassable(CalculationContext context, int x, int y, int z) {
return fullyPassable(context.get(x, y, z));
return fullyPassable(
context.bsi.access,
context.bsi.isPassableBlockPos.setPos(x, y, z),
context.bsi.get0(x, y, z)
);
}
static boolean fullyPassable(BlockState state) {
static boolean fullyPassable(IPlayerContext ctx, BlockPos pos) {
return fullyPassable(ctx.world(), pos, ctx.world().getBlockState(pos));
}
static boolean fullyPassable(IBlockReader access, BlockPos pos, BlockState state) {
Block block = state.getBlock();
if (block instanceof AirBlock) { // early return for most common case
return true;
@@ -178,7 +187,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return false;
}
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
return state.allowsMovement(null, null, PathType.LAND);
return state.allowsMovement(access, pos, PathType.LAND);
}
static boolean isReplaceable(int x, int y, int z, BlockState state, BlockStateInterface bsi) {

View File

@@ -176,7 +176,7 @@ public class MovementAscend extends Movement {
ticksWithoutPlacement++;
if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) {
state.setInput(Input.SNEAK, true);
if (ctx.player().isSneaking()) {
if (ctx.player().isCrouching()) {
state.setInput(Input.CLICK_RIGHT, true);
}
}
@@ -199,8 +199,8 @@ public class MovementAscend extends Movement {
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().getPositionVec().x) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().getPositionVec().z);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().getPositionVec().x) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().getPositionVec().z);
double lateralMotion = xAxis * ctx.player().getMotion().z + zAxis * ctx.player().getMotion().x;
if (Math.abs(lateralMotion) > 0.1) {

View File

@@ -212,11 +212,11 @@ public class MovementDescend extends Movement {
BlockPos playerFeet = ctx.playerFeet();
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - dest.getY() < 0.5)) { // lilypads
if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().getPositionVec().y - dest.getY() < 0.5)) { // lilypads
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
return state.setStatus(MovementStatus.SUCCESS);
/* else {
// System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY()));
// System.out.println(player().getPositionVec().y + " " + playerFeet.getY() + " " + (player().getPositionVec().y - playerFeet.getY()));
}*/
}
if (safeMode()) {
@@ -231,11 +231,11 @@ public class MovementDescend extends Movement {
)).setInput(Input.MOVE_FORWARD, true);
return state;
}
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().getPositionVec().z - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
double x = ctx.player().posX - (src.getX() + 0.5);
double z = ctx.player().posZ - (src.getZ() + 0.5);
double x = ctx.player().getPositionVec().x - (src.getX() + 0.5);
double z = ctx.player().getPositionVec().z - (src.getZ() + 0.5);
double fromStart = Math.sqrt(x * x + z * z);
if (!playerFeet.equals(dest) || ab > 0.25) {
if (numTicks++ < 20 && fromStart < 1.25) {

View File

@@ -226,7 +226,7 @@ public class MovementDiagonal extends Movement {
} else if (!playerInValidPosition() && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
if (dest.y > src.y && ctx.player().posY < src.y + 0.1 && ctx.player().collidedHorizontally) {
if (dest.y > src.y && ctx.player().getPositionVec().y < src.y + 0.1 && ctx.player().collidedHorizontally) {
state.setInput(Input.JUMP, true);
}
if (sprint()) {

View File

@@ -84,8 +84,8 @@ public class MovementDownward extends Movement {
} else if (!playerInValidPosition()) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().getPositionVec().z - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
if (numTicks++ < 10 && ab < 0.2) {

View File

@@ -100,7 +100,7 @@ public class MovementFall extends Movement {
return state.setStatus(MovementStatus.UNREACHABLE);
}
if (ctx.player().posY - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) {
if (ctx.player().getPositionVec().y - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER);
targetRotation = new Rotation(toDest.getYaw(), 90.0F);
@@ -115,7 +115,7 @@ public class MovementFall extends Movement {
} else {
state.setTarget(new MovementTarget(toDest, false));
}
if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads
if (playerFeet.equals(dest) && (ctx.player().getPositionVec().y - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads
if (isWater) { // only match water, not flowing water (which we cannot pick up with a bucket)
if (PlayerInventory.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY);
@@ -134,7 +134,7 @@ public class MovementFall extends Movement {
}
}
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder)
if (Math.abs(ctx.player().posX + ctx.player().getMotion().x - destCenter.x) > 0.1 || Math.abs(ctx.player().posZ + ctx.player().getMotion().z - destCenter.z) > 0.1) {
if (Math.abs(ctx.player().getPositionVec().x + ctx.player().getMotion().x - destCenter.x) > 0.1 || Math.abs(ctx.player().getPositionVec().z + ctx.player().getMotion().z - destCenter.z) > 0.1) {
if (!ctx.player().onGround && Math.abs(ctx.player().getMotion().y) > 0.4) {
state.setInput(Input.SNEAK, true);
}
@@ -144,7 +144,7 @@ public class MovementFall extends Movement {
if (avoid == null) {
avoid = src.subtract(dest);
} else {
double dist = Math.abs(avoid.getX() * (destCenter.x - avoid.getX() / 2.0 - ctx.player().posX)) + Math.abs(avoid.getZ() * (destCenter.z - avoid.getZ() / 2.0 - ctx.player().posZ));
double dist = Math.abs(avoid.getX() * (destCenter.x - avoid.getX() / 2.0 - ctx.player().getPositionVec().x)) + Math.abs(avoid.getZ() * (destCenter.z - avoid.getZ() / 2.0 - ctx.player().getPositionVec().z));
if (dist < 0.6) {
state.setInput(Input.MOVE_FORWARD, true);
} else if (!ctx.player().onGround) {

View File

@@ -115,7 +115,7 @@ public class MovementParkour extends Movement {
return;
}
BlockState destInto = context.bsi.get0(destX, y, destZ);
if (!MovementHelper.fullyPassable(destInto)) {
if (!MovementHelper.fullyPassable(context.bsi.access, context.bsi.isPassableBlockPos.setPos(destX, y, destZ), destInto)) {
if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ, destInto) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) {
res.x = destX;
res.y = y + 1;
@@ -246,19 +246,19 @@ public class MovementParkour extends Movement {
// but i did it anyway
return state.setStatus(MovementStatus.SUCCESS);
}
if (ctx.player().posY - ctx.playerFeet().getY() < 0.094) { // lilypads
if (ctx.player().getPositionVec().y - ctx.playerFeet().getY() < 0.094) { // lilypads
state.setStatus(MovementStatus.SUCCESS);
}
} else if (!ctx.playerFeet().equals(src)) {
if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - src.y > 0.0001) {
if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().getPositionVec().y - src.y > 0.0001) {
if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) {
// go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory
state.setInput(Input.CLICK_RIGHT, true);
}
// prevent jumping too late by checking for ascend
if (dist == 3 && !ascend) { // this is a 2 block gap, dest = src + direction * 3
double xDiff = (src.x + 0.5) - ctx.player().posX;
double zDiff = (src.z + 0.5) - ctx.player().posZ;
double xDiff = (src.x + 0.5) - ctx.player().getPositionVec().x;
double zDiff = (src.z + 0.5) - ctx.player().getPositionVec().z;
double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff));
if (distFromStart < 0.7) {
return state;

View File

@@ -172,7 +172,7 @@ public class MovementPillar extends Movement {
// stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) {
if (Math.abs(ctx.player().getPositionVec().x - destCenter.x) > 0.2 || Math.abs(ctx.player().getPositionVec().z - destCenter.z) > 0.2) {
state.setInput(Input.MOVE_FORWARD, true);
}
if (ctx.playerFeet().equals(dest)) {
@@ -218,11 +218,11 @@ public class MovementPillar extends Movement {
}
state.setInput(Input.SNEAK, ctx.player().posY > dest.getY() || ctx.player().posY < src.getY() + 0.2D); // delay placement by 1 tick for ncp compatibility
state.setInput(Input.SNEAK, ctx.player().getPositionVec().y > dest.getY() || ctx.player().getPositionVec().y < src.getY() + 0.2D); // delay placement by 1 tick for ncp compatibility
// since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak
double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().getPositionVec().z - (dest.getZ() + 0.5);
double dist = Math.sqrt(diffX * diffX + diffZ * diffZ);
double flatMotion = Math.sqrt(ctx.player().getMotion().x * ctx.player().getMotion().x + ctx.player().getMotion().z * ctx.player().getMotion().z);
if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why
@@ -236,7 +236,7 @@ public class MovementPillar extends Movement {
state.setTarget(new MovementState.MovementTarget(rotation, true));
} else if (flatMotion < 0.05) {
// If our Y coordinate is above our goal, stop jumping
state.setInput(Input.JUMP, ctx.player().posY < dest.getY());
state.setInput(Input.JUMP, ctx.player().getPositionVec().y < dest.getY());
}
@@ -251,7 +251,7 @@ public class MovementPillar extends Movement {
state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping
state.setInput(Input.CLICK_LEFT, true);
blockIsThere = false;
} else if (ctx.player().isSneaking() && (ctx.isLookingAt(src.down()) || ctx.isLookingAt(src)) && ctx.player().posY > dest.getY() + 0.1) {
} else if (ctx.player().isCrouching() && (ctx.isLookingAt(src.down()) || ctx.isLookingAt(src)) && ctx.player().getPositionVec().y > dest.getY() + 0.1) {
state.setInput(Input.CLICK_RIGHT, true);
}
}

View File

@@ -175,7 +175,7 @@ public class MovementTraverse extends Movement {
return state;
}
// and we aren't already pressed up against the block
double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D)));
double dist = Math.max(Math.abs(ctx.player().getPositionVec().x - (dest.getX() + 0.5D)), Math.abs(ctx.player().getPositionVec().z - (dest.getZ() + 0.5D)));
if (dist < 0.83) {
return state;
}
@@ -245,7 +245,7 @@ public class MovementTraverse extends Movement {
}
Block low = BlockStateInterface.get(ctx, src).getBlock();
Block high = BlockStateInterface.get(ctx, src.up()).getBlock();
if (ctx.player().posY > src.y + 0.1D && !ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) {
if (ctx.player().getPositionVec().y > src.y + 0.1D && !ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) {
// hitting W could cause us to climb the ladder instead of going forward
// wait until we're on the ground
return state;
@@ -272,21 +272,21 @@ public class MovementTraverse extends Movement {
wasTheBridgeBlockAlwaysThere = false;
Block standingOn = BlockStateInterface.get(ctx, feet.down()).getBlock();
if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof SlabBlock) { // see issue #118
double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ));
double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().getPositionVec().x), Math.abs(dest.getZ() + 0.5 - ctx.player().getPositionVec().z));
if (dist < 0.85) { // 0.5 + 0.3 + epsilon
MovementHelper.moveTowards(ctx, state, dest);
return state.setInput(Input.MOVE_FORWARD, false)
.setInput(Input.MOVE_BACK, true);
}
}
double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D)));
double dist1 = Math.max(Math.abs(ctx.player().getPositionVec().x - (dest.getX() + 0.5D)), Math.abs(ctx.player().getPositionVec().z - (dest.getZ() + 0.5D)));
PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false);
if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.SNEAK, true);
}
switch (p) {
case READY_TO_PLACE: {
if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.value) {
if (ctx.player().isCrouching() || Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.CLICK_RIGHT, true);
}
return state;
@@ -319,7 +319,7 @@ public class MovementTraverse extends Movement {
Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
float pitch = backToFace.getPitch();
double dist2 = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ));
double dist2 = Math.max(Math.abs(ctx.player().getPositionVec().x - faceX), Math.abs(ctx.player().getPositionVec().z - faceZ));
if (dist2 < 0.29) { // see issue #208
float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw();
state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true));

View File

@@ -414,7 +414,7 @@ public class PathExecutor implements IPathExecutor, Helper {
// playerFeet adds 0.1251 to account for soul sand
// farmland is 0.9375
// 0.07 is to account for farmland
if (ctx.player().posY >= center.getY() - 0.07) {
if (ctx.player().getPositionVec().y >= center.getY() - 0.07) {
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false);
return true;
}
@@ -466,7 +466,7 @@ public class PathExecutor implements IPathExecutor, Helper {
}
for (int y = next.getDest().y; y <= movement.getSrc().y + 1; y++) {
BlockPos chk = new BlockPos(next.getDest().x, y, next.getDest().z);
if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) {
if (!MovementHelper.fullyPassable(ctx, chk)) {
break outer;
}
}
@@ -485,17 +485,17 @@ public class PathExecutor implements IPathExecutor, Helper {
}
private static boolean skipNow(IPlayerContext ctx, IMovement current) {
double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX));
double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().getPositionVec().z)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().getPositionVec().x));
if (offTarget > 0.1) {
return false;
}
// we are centered
BlockPos headBonk = current.getSrc().subtract(current.getDirection()).up(2);
if (MovementHelper.fullyPassable(ctx.world().getBlockState(headBonk))) {
if (MovementHelper.fullyPassable(ctx, headBonk)) {
return true;
}
// wait 0.3
double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().posX)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().posZ));
double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().getPositionVec().x)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().getPositionVec().z));
return flatDist > 0.8;
}
@@ -524,7 +524,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (x == 1) {
chk = chk.add(current.getDirection());
}
if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) {
if (!MovementHelper.fullyPassable(ctx, chk)) {
return false;
}
}

View File

@@ -25,8 +25,14 @@ import baritone.api.pathing.goals.GoalGetToBlock;
import baritone.api.process.IBuilderProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.schematic.FillSchematic;
import baritone.api.schematic.ISchematic;
import baritone.api.utils.*;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.Rotation;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
@@ -34,9 +40,8 @@ import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.PathingCommandContext;
import baritone.utils.schematic.FillSchematic;
import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.Schematic;
import baritone.utils.schematic.SchematicSystem;
import baritone.utils.schematic.schematica.SchematicaHelper;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.block.AirBlock;
@@ -57,7 +62,6 @@ import net.minecraft.util.math.shapes.VoxelShape;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import static baritone.api.pathing.movement.ActionCosts.COST_INF;
@@ -73,6 +77,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private int ticks;
private boolean paused;
private int layer;
private int numRepeats;
private List<BlockState> approxPlaceable;
public BuilderProcess(Baritone baritone) {
@@ -99,6 +104,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
this.origin = new Vec3i(x, y, z);
this.paused = false;
this.layer = 0;
this.numRepeats = 0;
this.observedCompleted = new LongOpenHashSet();
}
@@ -117,27 +123,38 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
@Override
public boolean build(String name, File schematic, Vec3i origin) {
CompoundNBT tag;
try (FileInputStream fileIn = new FileInputStream(schematic)) {
tag = CompressedStreamTools.readCompressed(fileIn);
} catch (IOException e) {
Optional<ISchematicFormat> format = SchematicSystem.INSTANCE.getByFile(schematic);
if (!format.isPresent()) {
return false;
}
ISchematic parsed;
try {
parsed = format.get().parse(new FileInputStream(schematic));
} catch (Exception e) {
e.printStackTrace();
return false;
}
//noinspection ConstantConditions
if (tag == null) {
return false;
if (Baritone.settings().mapArtMode.value) {
parsed = new MapArtSchematic((IStaticSchematic) parsed);
}
build(name, parse(tag), origin);
build(name, parsed, origin);
return true;
}
@Override
public void buildOpenSchematic() {
if (SchematicaHelper.isSchematicaPresent()) {
Optional<Tuple<ISchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic();
Optional<Tuple<IStaticSchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic();
if (schematic.isPresent()) {
this.build(schematic.get().getA().toString(), schematic.get().getA(), schematic.get().getB());
IStaticSchematic s = schematic.get().getA();
this.build(
schematic.get().getA().toString(),
Baritone.settings().mapArtMode.value ? new MapArtSchematic(s) : s,
schematic.get().getB()
);
} else {
logDirect("No schematic currently open");
}
@@ -159,10 +176,6 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return new ArrayList<>(approxPlaceable);
}
private static ISchematic parse(CompoundNBT schematic) {
return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(schematic);
}
@Override
public boolean isActive() {
return schematic != null;
@@ -407,7 +420,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return onTick(calcFailed, isSafeToCancel);
}
Vec3i repeat = Baritone.settings().buildRepeat.value;
if (repeat.equals(new Vec3i(0, 0, 0))) {
int max = Baritone.settings().buildRepeatCount.value;
numRepeats++;
if (repeat.equals(new Vec3i(0, 0, 0)) || (max != -1 && numRepeats >= max)) {
logDirect("Done building");
onLostControl();
return null;
@@ -430,7 +445,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
BetterBlockPos pos = toBreak.get().getA();
baritone.getLookBehavior().updateTarget(rot, true);
MovementHelper.switchToBestToolFor(ctx, bcc.get(pos));
if (ctx.player().isSneaking()) {
if (ctx.player().isCrouching()) {
// really horrible bug where a block is visible for breaking while sneaking but not otherwise
// so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break
// and is unable since it's unsneaked in the intermediary tick
@@ -747,6 +762,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
schematic = null;
realSchematic = null;
layer = 0;
numRepeats = 0;
paused = false;
observedCompleted = null;
}
@@ -765,7 +781,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
continue;
}
// <toxic cloud>
result.add(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().posX, ctx.player().posY, ctx.player().posZ), Direction.UP, ctx.playerFeet(), false)) {})));
result.add(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().getPositionVec().x, ctx.player().getPositionVec().y, ctx.player().getPositionVec().z), Direction.UP, ctx.playerFeet(), false)) {})));
// </toxic cloud>
}
return result;
@@ -782,6 +798,12 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return true;
}
// TODO more complicated comparison logic I guess
if (desired.getBlock() instanceof AirBlock && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) {
return true;
}
if (!(current.getBlock() instanceof AirBlock) && Baritone.settings().buildIgnoreExisting.value) {
return true;
}
return current.equals(desired);
}

View File

@@ -282,7 +282,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
ItemEntity ei = (ItemEntity) entity;
if (PICKUP_DROPPED.contains(ei.getItem().getItem())) {
// +0.1 because of farmland's 0.9375 dummy height lol
goalz.add(new GoalBlock(new BlockPos(entity.posX, entity.posY + 0.1, entity.posZ)));
goalz.add(new GoalBlock(new BlockPos(entity.getPositionVec().x, entity.getPositionVec().y + 0.1, entity.getPositionVec().z)));
}
}
}

View File

@@ -60,7 +60,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
pos = new BlockPos(following);
} else {
GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.value, Baritone.settings().followOffsetDistance.value);
pos = new BlockPos(g.getX(), following.posY, g.getZ());
pos = new BlockPos(g.getX(), following.getPositionVec().y, g.getZ());
}
return new GoalNear(pos, Baritone.settings().followRadius.value);
}

View File

@@ -5,6 +5,7 @@ import baritone.api.event.events.RenderEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.selection.ISelection;
import baritone.utils.IRenderer;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.util.math.AxisAlignedBB;
public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
@@ -18,7 +19,7 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
baritone.getGameEventHandler().registerEventListener(this);
}
public static void renderSelections(ISelection[] selections) {
public static void renderSelections(MatrixStack stack, ISelection[] selections) {
float opacity = settings.selectionOpacity.value;
boolean ignoreDepth = settings.renderSelectionIgnoreDepth.value;
float lineWidth = settings.selectionLineWidth.value;
@@ -30,20 +31,20 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth);
for (ISelection selection : selections) {
IRenderer.drawAABB(selection.aabb(), SELECTION_BOX_EXPANSION);
IRenderer.drawAABB(stack, selection.aabb(), SELECTION_BOX_EXPANSION);
}
if (settings.renderSelectionCorners.value) {
IRenderer.glColor(settings.colorSelectionPos1.value, opacity);
for (ISelection selection : selections) {
IRenderer.drawAABB(new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1)));
IRenderer.drawAABB(stack, new AxisAlignedBB(selection.pos1(), selection.pos1().add(1, 1, 1)));
}
IRenderer.glColor(settings.colorSelectionPos2.value, opacity);
for (ISelection selection : selections) {
IRenderer.drawAABB(new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1)));
IRenderer.drawAABB(stack, new AxisAlignedBB(selection.pos2(), selection.pos2().add(1, 1, 1)));
}
}
@@ -52,6 +53,6 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
@Override
public void onRenderPass(RenderEvent event) {
renderSelections(manager.getSelections());
renderSelections(event.getModelViewStack(), manager.getSelections());
}
}

View File

@@ -31,13 +31,13 @@ import net.minecraft.client.settings.AmbientOcclusionStatus;
import net.minecraft.client.settings.CloudOption;
import net.minecraft.client.settings.ParticleStatus;
import net.minecraft.client.tutorial.TutorialSteps;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.util.HTTPUtil;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.GameType;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.*;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.server.ServerWorld;
import java.io.File;
import java.io.IOException;
@@ -95,7 +95,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
if (mc.currentScreen instanceof MainMenuScreen) {
System.out.println("Beginning Baritone automatic test routine");
mc.displayGuiScreen(null);
WorldSettings worldsettings = new WorldSettings(TEST_SEED, GameType.getByName("survival"), true, false, WorldType.DEFAULT);
WorldSettings worldsettings = new WorldSettings(TEST_SEED, GameType.SURVIVAL, true, false, WorldType.DEFAULT);
mc.launchIntegratedServer("BaritoneAutoTest", "BaritoneAutoTest", worldsettings);
}
@@ -104,6 +104,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// If the integrated server is launched and the world has initialized, set the spawn point
// to our defined starting position
if (server != null && server.getWorld(DimensionType.OVERWORLD) != null) {
server.setDifficultyForAllWorlds(Difficulty.PEACEFUL, true);
if (mc.player == null) {
server.execute(() -> {
server.getWorld(DimensionType.OVERWORLD).setSpawnPoint(STARTING_POSITION);
@@ -113,6 +114,17 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
throw new IllegalStateException(result + "");
}
});
for (final ServerWorld world : mc.getIntegratedServer().getWorlds()) {
// If the world has initialized, set the spawn point to our defined starting position
if (world != null) {
// I would rather do this than try to mess with poz
CompoundNBT nbt = world.getGameRules().write();
nbt.putString("spawnRadius", "0");
world.getGameRules().read(nbt);
world.setSpawnPoint(STARTING_POSITION);
}
}
}
}
@@ -121,7 +133,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// Force the integrated server to share the world to LAN so that
// the ingame pause menu gui doesn't actually pause our game
if (mc.isSingleplayer() && !mc.getIntegratedServer().getPublic()) {
mc.getIntegratedServer().shareToLAN(GameType.getByName("survival"), false, HTTPUtil.getSuitableLanPort());
mc.getIntegratedServer().shareToLAN(GameType.SURVIVAL, false, HTTPUtil.getSuitableLanPort());
}
// For the first 200 ticks, wait for the world to generate
@@ -163,5 +175,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
}
}
private BaritoneAutoTest() {}
private BaritoneAutoTest() {
}
}

View File

@@ -28,6 +28,7 @@ import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientChunkProvider;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection;
@@ -42,6 +43,9 @@ public class BlockStateInterface {
private final ClientChunkProvider provider;
private final WorldData worldData;
protected final IBlockReader world;
public final BlockPos.Mutable isPassableBlockPos;
public final IBlockReader access;
private Chunk prev = null;
private CachedRegion prevCached = null;
@@ -59,6 +63,7 @@ public class BlockStateInterface {
}
public BlockStateInterface(World world, WorldData worldData, boolean copyLoadedChunks) {
this.world = world;
this.worldData = worldData;
if (copyLoadedChunks) {
this.provider = ((IClientChunkProvider) world.getChunkProvider()).createThreadSafeCopy();
@@ -69,6 +74,8 @@ public class BlockStateInterface {
if (!Minecraft.getInstance().isOnExecutionThread()) {
throw new IllegalStateException();
}
this.isPassableBlockPos = new BlockPos.Mutable();
this.access = new BlockStateInterfaceAccessWrapper(this);
}
public boolean worldContainsLoadedChunk(int blockX, int blockZ) {

View File

@@ -0,0 +1,57 @@
/*
* 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.utils;
import net.minecraft.block.BlockState;
import net.minecraft.fluid.IFluidState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import javax.annotation.Nullable;
/**
* @author Brady
* @since 11/5/2019
*/
@SuppressWarnings("NullableProblems")
public final class BlockStateInterfaceAccessWrapper implements IBlockReader {
private final BlockStateInterface bsi;
BlockStateInterfaceAccessWrapper(BlockStateInterface bsi) {
this.bsi = bsi;
}
@Nullable
@Override
public TileEntity getTileEntity(BlockPos pos) {
throw new UnsupportedOperationException("getTileEntity not supported by BlockStateInterfaceAccessWrapper");
}
@Override
public BlockState getBlockState(BlockPos pos) {
// BlockStateInterface#get0(BlockPos) btfo!
return this.bsi.get0(pos.getX(), pos.getY(), pos.getZ());
}
@Override
public IFluidState getFluidState(BlockPos blockPos) {
return getBlockState(blockPos).getFluidState();
}
}

View File

@@ -23,21 +23,20 @@ import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalTwoBlocks;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Helper;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.renderer.Matrix4f;
import net.minecraft.client.renderer.Vector4f;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.*;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Collections;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
@@ -45,11 +44,7 @@ import static org.lwjgl.opengl.GL11.*;
public class GuiClick extends Screen implements Helper {
// My name is Brady and I grant leijurv permission to use this pasted code
private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16);
private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16);
private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16);
private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3);
private Matrix4f projectionViewMatrix;
private BlockPos clickStart;
private BlockPos currentMouseOver;
@@ -67,9 +62,10 @@ public class GuiClick extends Screen implements Helper {
public void render(int mouseX, int mouseY, float partialTicks) {
double mx = mc.mouseHelper.getMouseX();
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();
my = mc.getMainWindow().getHeight() - my;
my *= mc.getMainWindow().getFramebufferHeight() / (double) mc.getMainWindow().getHeight();
mx *= mc.getMainWindow().getFramebufferWidth() / (double) mc.getMainWindow().getWidth();
Vec3d near = toWorld(mx, my, 0);
Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv
if (near != null && far != null) {
@@ -114,224 +110,52 @@ public class GuiClick extends Screen implements Helper {
return super.mouseClicked(mouseX, mouseY, mouseButton);
}
public void onRender() {
GlStateManager.getMatrix(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear());
GlStateManager.getMatrix(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear());
GL11.glGetIntegerv(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear());
public void onRender(MatrixStack modelViewStack, MatrixStack projectionStack) {
this.projectionViewMatrix = projectionStack.getLast().getPositionMatrix().copy();
this.projectionViewMatrix.multiply(modelViewStack.getLast().getPositionMatrix());
this.projectionViewMatrix.invert();
if (currentMouseOver != null) {
Entity e = mc.getRenderViewEntity();
// drawSingleSelectionBox WHEN?
PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN);
PathRenderer.drawManySelectionBoxes(modelViewStack, e, Collections.singletonList(currentMouseOver), Color.CYAN);
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
GlStateManager.enableBlend();
GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
GlStateManager.color4f(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F);
GlStateManager.lineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
GlStateManager.disableTexture();
GlStateManager.depthMask(false);
GlStateManager.disableDepthTest();
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
RenderSystem.color4f(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F);
RenderSystem.lineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
RenderSystem.disableTexture();
RenderSystem.depthMask(false);
RenderSystem.disableDepthTest();
BetterBlockPos a = new BetterBlockPos(currentMouseOver);
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));
GlStateManager.enableDepthTest();
IRenderer.drawAABB(modelViewStack, 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));
RenderSystem.enableDepthTest();
GlStateManager.depthMask(true);
GlStateManager.enableTexture();
GlStateManager.disableBlend();
RenderSystem.depthMask(true);
RenderSystem.enableTexture();
RenderSystem.disableBlend();
}
}
}
private Vec3d toWorld(double x, double y, double z) {
boolean result = gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear());
if (result) {
return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2));
if (this.projectionViewMatrix == null) {
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);
x /= mc.getMainWindow().getWidth();
y /= mc.getMainWindow().getHeight();
x = x * 2 - 1;
y = y * 2 - 1;
Vector4f pos = new Vector4f((float) x, (float) y, (float) z, 1.0F);
pos.transform(this.projectionViewMatrix);
if (pos.getW() == 0) {
return null;
}
}
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);
pos.perspectiveDivide();
return new Vec3d(pos.getX(), pos.getY(), pos.getZ());
}
}

View File

@@ -21,8 +21,10 @@ import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import baritone.api.utils.Helper;
import baritone.utils.accessor.IEntityRenderManager;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Matrix4f;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.AxisAlignedBB;
@@ -40,20 +42,20 @@ public interface IRenderer {
static void glColor(Color color, float alpha) {
float[] colorComponents = color.getColorComponents(null);
GlStateManager.color4f(colorComponents[0], colorComponents[1], colorComponents[2], alpha);
RenderSystem.color4f(colorComponents[0], colorComponents[1], colorComponents[2], alpha);
}
static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
GlStateManager.enableBlend();
GlStateManager.disableLighting();
GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
RenderSystem.enableBlend();
RenderSystem.disableLighting();
RenderSystem.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
glColor(color, alpha);
GlStateManager.lineWidth(lineWidth);
GlStateManager.disableTexture();
GlStateManager.depthMask(false);
RenderSystem.lineWidth(lineWidth);
RenderSystem.disableTexture();
RenderSystem.depthMask(false);
if (ignoreDepth) {
GlStateManager.disableDepthTest();
RenderSystem.disableDepthTest();
}
}
@@ -63,50 +65,51 @@ public interface IRenderer {
static void endLines(boolean ignoredDepth) {
if (ignoredDepth) {
GlStateManager.enableDepthTest();
RenderSystem.enableDepthTest();
}
GlStateManager.depthMask(true);
GlStateManager.enableTexture();
GlStateManager.enableLighting();
GlStateManager.disableBlend();
RenderSystem.depthMask(true);
RenderSystem.enableTexture();
RenderSystem.enableLighting();
RenderSystem.disableBlend();
}
static void drawAABB(AxisAlignedBB aabb) {
static void drawAABB(MatrixStack stack, AxisAlignedBB aabb) {
AxisAlignedBB toDraw = aabb.offset(-renderManager.renderPosX(), -renderManager.renderPosY(), -renderManager.renderPosZ());
Matrix4f matrix4f = stack.getLast().getPositionMatrix();
buffer.begin(GL_LINES, DefaultVertexFormats.POSITION);
// bottom
buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
// top
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
// corners
buffer.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
buffer.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.minZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.maxX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.minY, (float) toDraw.maxZ).endVertex();
buffer.pos(matrix4f, (float) toDraw.minX, (float) toDraw.maxY, (float) toDraw.maxZ).endVertex();
tessellator.draw();
}
static void drawAABB(AxisAlignedBB aabb, double expand) {
drawAABB(aabb.grow(expand, expand, expand));
static void drawAABB(MatrixStack stack, AxisAlignedBB aabb, double expand) {
drawAABB(stack, aabb.grow(expand, expand, expand));
}
}

View File

@@ -26,8 +26,10 @@ import baritone.api.utils.Helper;
import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.behavior.PathingBehavior;
import baritone.pathing.path.PathExecutor;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.block.BlockState;
import net.minecraft.client.renderer.Matrix4f;
import net.minecraft.client.renderer.tileentity.BeaconTileEntityRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.Entity;
@@ -72,7 +74,7 @@ public final class PathRenderer implements IRenderer, Helper {
float partialTicks = event.getPartialTicks();
Goal goal = behavior.getGoal();
if (Helper.mc.currentScreen instanceof GuiClick) {
((GuiClick) Helper.mc.currentScreen).onRender();
((GuiClick) Helper.mc.currentScreen).onRender(event.getModelViewStack(), event.getProjectionStack());
}
int thisPlayerDimension = behavior.baritone.getPlayerContext().world().getDimension().getType().getId();
@@ -93,7 +95,7 @@ public final class PathRenderer implements IRenderer, Helper {
}
if (goal != null && settings.renderGoal.value) {
drawDankLitGoalBox(renderView, goal, partialTicks, settings.colorGoalBox.value);
drawDankLitGoalBox(event.getModelViewStack(), renderView, goal, partialTicks, settings.colorGoalBox.value);
}
if (!settings.renderPath.value) {
@@ -103,9 +105,9 @@ public final class PathRenderer implements IRenderer, Helper {
PathExecutor current = behavior.getCurrent(); // this should prevent most race conditions?
PathExecutor next = behavior.getNext(); // like, now it's not possible for current!=null to be true, then suddenly false because of another thread
if (current != null && settings.renderSelectionBoxes.value) {
drawManySelectionBoxes(renderView, current.toBreak(), settings.colorBlocksToBreak.value);
drawManySelectionBoxes(renderView, current.toPlace(), settings.colorBlocksToPlace.value);
drawManySelectionBoxes(renderView, current.toWalkInto(), settings.colorBlocksToWalkInto.value);
drawManySelectionBoxes(event.getModelViewStack(), renderView, current.toBreak(), settings.colorBlocksToBreak.value);
drawManySelectionBoxes(event.getModelViewStack(), renderView, current.toPlace(), settings.colorBlocksToPlace.value);
drawManySelectionBoxes(event.getModelViewStack(), renderView, current.toWalkInto(), settings.colorBlocksToWalkInto.value);
}
//drawManySelectionBoxes(player, Collections.singletonList(behavior.pathStart()), partialTicks, Color.WHITE);
@@ -113,27 +115,27 @@ public final class PathRenderer implements IRenderer, Helper {
// Render the current path, if there is one
if (current != null && current.getPath() != null) {
int renderBegin = Math.max(current.getPosition() - 3, 0);
drawPath(current.getPath(), renderBegin, settings.colorCurrentPath.value, settings.fadePath.value, 10, 20);
drawPath(event.getModelViewStack(), current.getPath(), renderBegin, settings.colorCurrentPath.value, settings.fadePath.value, 10, 20);
}
if (next != null && next.getPath() != null) {
drawPath(next.getPath(), 0, settings.colorNextPath.value, settings.fadePath.value, 10, 20);
drawPath(event.getModelViewStack(), next.getPath(), 0, settings.colorNextPath.value, settings.fadePath.value, 10, 20);
}
// If there is a path calculation currently running, render the path calculation process
behavior.getInProgress().ifPresent(currentlyRunning -> {
currentlyRunning.bestPathSoFar().ifPresent(p -> {
drawPath(p, 0, settings.colorBestPathSoFar.value, settings.fadePath.value, 10, 20);
drawPath(event.getModelViewStack(), p, 0, settings.colorBestPathSoFar.value, settings.fadePath.value, 10, 20);
});
currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> {
drawPath(mr, 0, settings.colorMostRecentConsidered.value, settings.fadePath.value, 10, 20);
drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), settings.colorMostRecentConsidered.value);
drawPath(event.getModelViewStack(), mr, 0, settings.colorMostRecentConsidered.value, settings.fadePath.value, 10, 20);
drawManySelectionBoxes(event.getModelViewStack(), renderView, Collections.singletonList(mr.getDest()), settings.colorMostRecentConsidered.value);
});
});
}
public static void drawPath(IPath path, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) {
public static void drawPath(MatrixStack stack, IPath path, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) {
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
int fadeStart = fadeStart0 + startIndex;
@@ -169,7 +171,7 @@ public final class PathRenderer implements IRenderer, Helper {
IRenderer.glColor(color, alpha);
}
drawLine(start.x, start.y, start.z, end.x, end.y, end.z);
drawLine(stack, start.x, start.y, start.z, end.x, end.y, end.z);
tessellator.draw();
}
@@ -178,24 +180,26 @@ public final class PathRenderer implements IRenderer, Helper {
}
public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) {
public static void drawLine(MatrixStack stack, double x1, double y1, double z1, double x2, double y2, double z2) {
Matrix4f matrix4f = stack.getLast().getPositionMatrix();
double vpX = posX();
double vpY = posY();
double vpZ = posZ();
boolean renderPathAsFrickinThingy = !settings.renderPathAsLine.value;
buffer.begin(renderPathAsFrickinThingy ? GL_LINE_STRIP : GL_LINES, DefaultVertexFormats.POSITION);
buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex();
buffer.pos(x2 + 0.5D - vpX, y2 + 0.5D - vpY, z2 + 0.5D - vpZ).endVertex();
buffer.pos(matrix4f, (float) (x1 + 0.5D - vpX), (float) (y1 + 0.5D - vpY), (float) (z1 + 0.5D - vpZ)).endVertex();
buffer.pos(matrix4f, (float) (x2 + 0.5D - vpX), (float) (y2 + 0.5D - vpY), (float) (z2 + 0.5D - vpZ)).endVertex();
if (renderPathAsFrickinThingy) {
buffer.pos(x2 + 0.5D - vpX, y2 + 0.53D - vpY, z2 + 0.5D - vpZ).endVertex();
buffer.pos(x1 + 0.5D - vpX, y1 + 0.53D - vpY, z1 + 0.5D - vpZ).endVertex();
buffer.pos(x1 + 0.5D - vpX, y1 + 0.5D - vpY, z1 + 0.5D - vpZ).endVertex();
buffer.pos(matrix4f, (float) (x2 + 0.5D - vpX), (float) (y2 + 0.53D - vpY), (float) (z2 + 0.5D - vpZ)).endVertex();
buffer.pos(matrix4f, (float) (x1 + 0.5D - vpX), (float) (y1 + 0.53D - vpY), (float) (z1 + 0.5D - vpZ)).endVertex();
buffer.pos(matrix4f, (float) (x1 + 0.5D - vpX), (float) (y1 + 0.5D - vpY), (float) (z1 + 0.5D - vpZ)).endVertex();
}
}
public static void drawManySelectionBoxes(Entity player, Collection<BlockPos> positions, Color color) {
public static void drawManySelectionBoxes(MatrixStack stack, Entity player, Collection<BlockPos> positions, Color color) {
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderSelectionBoxesIgnoreDepth.value);
//BlockPos blockpos = movingObjectPositionIn.getBlockPos();
@@ -206,13 +210,13 @@ public final class PathRenderer implements IRenderer, Helper {
VoxelShape shape = state.getShape(player.world, pos);
AxisAlignedBB toDraw = shape.isEmpty() ? VoxelShapes.fullCube().getBoundingBox() : shape.getBoundingBox();
toDraw = toDraw.offset(pos);
IRenderer.drawAABB(toDraw, .002D);
IRenderer.drawAABB(stack, toDraw, .002D);
});
IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value);
}
public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) {
public static void drawDankLitGoalBox(MatrixStack stack, Entity player, Goal goal, float partialTicks, Color color) {
double renderPosX = posX();
double renderPosY = posY();
double renderPosZ = posZ();
@@ -247,27 +251,32 @@ public final class PathRenderer implements IRenderer, Helper {
Helper.mc.getTextureManager().bindTexture(TEXTURE_BEACON_BEAM);
if (settings.renderGoalIgnoreDepth.value) {
GlStateManager.disableDepthTest();
RenderSystem.disableDepthTest();
}
stack.push(); // push
stack.translate(goalPos.getX() - renderPosX, -renderPosY, goalPos.getZ() - renderPosZ); // translate
BeaconTileEntityRenderer.renderBeamSegment(
goalPos.getX() - renderPosX,
-renderPosY,
goalPos.getZ() - renderPosZ,
stack,
mc.getRenderTypeBuffers().getBufferSource(),
TEXTURE_BEACON_BEAM,
partialTicks,
1.0,
1.0F,
player.world.getGameTime(),
0,
256,
color.getColorComponents(null),
// Arguments filled by the private method lol
0.2D,
0.25D
0.2F,
0.25F
);
stack.pop(); // pop
if (settings.renderGoalIgnoreDepth.value) {
GlStateManager.enableDepthTest();
RenderSystem.enableDepthTest();
}
glPopAttrib();
@@ -285,18 +294,18 @@ public final class PathRenderer implements IRenderer, Helper {
maxY = 256 - renderPosY;
} else if (goal instanceof GoalComposite) {
for (Goal g : ((GoalComposite) goal).goals()) {
drawDankLitGoalBox(player, g, partialTicks, color);
drawDankLitGoalBox(stack, player, g, partialTicks, color);
}
return;
} else if (goal instanceof GoalInverted) {
drawDankLitGoalBox(player, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value);
drawDankLitGoalBox(stack, player, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value);
return;
} else if (goal instanceof GoalYLevel) {
GoalYLevel goalpos = (GoalYLevel) goal;
minX = player.posX - settings.yLevelBoxSize.value - renderPosX;
minZ = player.posZ - settings.yLevelBoxSize.value - renderPosZ;
maxX = player.posX + settings.yLevelBoxSize.value - renderPosX;
maxZ = player.posZ + settings.yLevelBoxSize.value - renderPosZ;
minX = player.getPositionVec().x - settings.yLevelBoxSize.value - renderPosX;
minZ = player.getPositionVec().z - settings.yLevelBoxSize.value - renderPosZ;
maxX = player.getPositionVec().x + settings.yLevelBoxSize.value - renderPosX;
maxZ = player.getPositionVec().z + settings.yLevelBoxSize.value - renderPosZ;
minY = ((GoalYLevel) goal).level - renderPosY;
maxY = minY + 2;
y1 = 1 + y + goalpos.level - renderPosY;
@@ -307,31 +316,32 @@ public final class PathRenderer implements IRenderer, Helper {
IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
renderHorizontalQuad(minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(minX, maxX, minZ, maxZ, y2);
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y2);
Matrix4f matrix4f = stack.getLast().getPositionMatrix();
buffer.begin(GL_LINES, DefaultVertexFormats.POSITION);
buffer.pos(minX, minY, minZ).endVertex();
buffer.pos(minX, maxY, minZ).endVertex();
buffer.pos(maxX, minY, minZ).endVertex();
buffer.pos(maxX, maxY, minZ).endVertex();
buffer.pos(maxX, minY, maxZ).endVertex();
buffer.pos(maxX, maxY, maxZ).endVertex();
buffer.pos(minX, minY, maxZ).endVertex();
buffer.pos(minX, maxY, maxZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) minY, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) maxY, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) minY, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) maxY, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) minY, (float) maxZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) maxY, (float) maxZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) minY, (float) maxZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) maxY, (float) maxZ).endVertex();
tessellator.draw();
IRenderer.endLines(settings.renderGoalIgnoreDepth.value);
}
private static void renderHorizontalQuad(double minX, double maxX, double minZ, double maxZ, double y) {
private static void renderHorizontalQuad(MatrixStack stack, double minX, double maxX, double minZ, double maxZ, double y) {
if (y != 0) {
Matrix4f matrix4f = stack.getLast().getPositionMatrix();
buffer.begin(GL_LINE_LOOP, DefaultVertexFormats.POSITION);
buffer.pos(minX, y, minZ).endVertex();
buffer.pos(maxX, y, minZ).endVertex();
buffer.pos(maxX, y, maxZ).endVertex();
buffer.pos(minX, y, maxZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) y, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) y, (float) minZ).endVertex();
buffer.pos(matrix4f, (float) maxX, (float) y, (float) maxZ).endVertex();
buffer.pos(matrix4f, (float) minX, (float) y, (float) maxZ).endVertex();
tessellator.draw();
}
}

View File

@@ -29,7 +29,7 @@ public class PlayerMovementInput extends MovementInput {
}
@Override
public void tick(boolean p_217607_1_, boolean p_217607_2_) {
public void func_225607_a_(boolean p_225607_1_) {
this.moveStrafe = 0.0F;
this.moveForward = 0.0F;
@@ -51,7 +51,7 @@ public class PlayerMovementInput extends MovementInput {
this.moveStrafe--;
}
if (this.sneak = handler.isInputForcedDown(Input.SNEAK)) {
if (this.field_228350_h_ = handler.isInputForcedDown(Input.SNEAK)) {
this.moveStrafe *= 0.3D;
this.moveForward *= 0.3D;
}

View File

@@ -19,7 +19,7 @@ package baritone.utils.accessor;
import net.minecraft.block.BlockState;
public interface IBlockStateContainer {
public interface IPalettedContainer {
BlockState getAtPalette(int index);

View File

@@ -19,23 +19,32 @@ package baritone.utils.schematic;
import net.minecraft.block.AirBlock;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.MaskSchematic;
import java.util.OptionalInt;
import java.util.function.Predicate;
public class MapArtSchematic extends Schematic {
public class MapArtSchematic extends MaskSchematic {
private final int[][] heightMap;
public MapArtSchematic(CompoundNBT schematic) {
public MapArtSchematic(IStaticSchematic schematic) {
super(schematic);
heightMap = new int[widthX][lengthZ];
this.heightMap = generateHeightMap(schematic);
}
for (int x = 0; x < widthX; x++) {
for (int z = 0; z < lengthZ; z++) {
BlockState[] column = states[x][z];
@Override
protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
return y >= this.heightMap[x][z];
}
private static int[][] generateHeightMap(IStaticSchematic schematic) {
int[][] heightMap = new int[schematic.widthX()][schematic.lengthZ()];
for (int x = 0; x < schematic.widthX(); x++) {
for (int z = 0; z < schematic.lengthZ(); z++) {
BlockState[] column = schematic.getColumn(x, z);
OptionalInt lowestBlockY = lastIndexMatching(column, state -> !(state.getBlock() instanceof AirBlock));
if (lowestBlockY.isPresent()) {
heightMap[x][z] = lowestBlockY.getAsInt();
@@ -44,9 +53,9 @@ public class MapArtSchematic extends Schematic {
System.out.println("Letting it be whatever");
heightMap[x][z] = 256;
}
}
}
return heightMap;
}
private static <T> OptionalInt lastIndexMatching(T[] arr, Predicate<? super T> predicate) {
@@ -57,10 +66,4 @@ public class MapArtSchematic extends Schematic {
}
return OptionalInt.empty();
}
@Override
public boolean inSchematic(int x, int y, int z, BlockState currentState) {
// in map art, we only care about coordinates in or above the art
return super.inSchematic(x, y, z, currentState) && y >= heightMap[x][z];
}
}

View File

@@ -0,0 +1,51 @@
/*
* 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.utils.schematic;
import baritone.api.command.registry.Registry;
import baritone.api.schematic.ISchematicSystem;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.utils.schematic.format.DefaultSchematicFormats;
import java.io.File;
import java.util.Arrays;
import java.util.Optional;
/**
* @author Brady
* @since 12/24/2019
*/
public enum SchematicSystem implements ISchematicSystem {
INSTANCE;
private final Registry<ISchematicFormat> registry = new Registry<>();
SchematicSystem() {
Arrays.stream(DefaultSchematicFormats.values()).forEach(this.registry::register);
}
@Override
public Registry<ISchematicFormat> getRegistry() {
return this.registry;
}
@Override
public Optional<ISchematicFormat> getByFile(File file) {
return this.registry.stream().filter(format -> format.isFileType(file)).findFirst();
}
}

View File

@@ -17,42 +17,34 @@
package baritone.utils.schematic;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.AbstractSchematic;
import baritone.api.schematic.IStaticSchematic;
import net.minecraft.block.BlockState;
import java.util.List;
public class FillSchematic implements ISchematic {
/**
* Default implementation of {@link IStaticSchematic}
*
* @author Brady
* @since 12/23/2019
*/
public class StaticSchematic extends AbstractSchematic implements IStaticSchematic {
private final int widthX;
private final int heightY;
private final int lengthZ;
private final BlockState state;
public FillSchematic(int widthX, int heightY, int lengthZ, BlockState state) {
this.widthX = widthX;
this.heightY = heightY;
this.lengthZ = lengthZ;
this.state = state;
}
protected BlockState[][][] states;
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return state;
return this.states[x][z][y];
}
@Override
public int widthX() {
return widthX;
public BlockState getDirect(int x, int y, int z) {
return this.states[x][z][y];
}
@Override
public int heightY() {
return heightY;
}
@Override
public int lengthZ() {
return lengthZ;
public BlockState[] getColumn(int x, int z) {
return this.states[x][z];
}
}

View File

@@ -0,0 +1,82 @@
/*
* 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.utils.schematic.format;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.utils.schematic.format.defaults.MCEditSchematic;
import baritone.utils.schematic.format.defaults.SpongeSchematic;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.CompressedStreamTools;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* Default implementations of {@link ISchematicFormat}
*
* @author Brady
* @since 12/13/2019
*/
public enum DefaultSchematicFormats implements ISchematicFormat {
/**
* The MCEdit schematic specification. Commonly denoted by the ".schematic" file extension.
*/
MCEDIT("schematic") {
@Override
public IStaticSchematic parse(InputStream input) throws IOException {
return new MCEditSchematic(CompressedStreamTools.readCompressed(input));
}
},
/**
* The SpongePowered Schematic Specification. Commonly denoted by the ".schem" file extension.
*
* @see <a href="https://github.com/SpongePowered/Schematic-Specification">Sponge Schematic Specification</a>
*/
SPONGE("schem") {
@Override
public IStaticSchematic parse(InputStream input) throws IOException {
CompoundNBT nbt = CompressedStreamTools.readCompressed(input);
int version = nbt.getInt("Version");
switch (version) {
case 1:
case 2:
return new SpongeSchematic(nbt);
default:
throw new UnsupportedOperationException("Unsupported Version of a Sponge Schematic");
}
}
};
private final String extension;
DefaultSchematicFormats(String extension) {
this.extension = extension;
}
@Override
public boolean isFileType(File file) {
return this.extension.equalsIgnoreCase(FilenameUtils.getExtension(file.getAbsolutePath()));
}
}

View File

@@ -15,34 +15,35 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.schematic;
package baritone.utils.schematic.format.defaults;
import baritone.api.schematic.ISchematic;
import baritone.utils.schematic.StaticSchematic;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.datafix.fixes.ItemIntIDToString;
import net.minecraft.util.registry.Registry;
import java.util.List;
/**
* @author Brady
* @since 12/27/2019
*/
public final class MCEditSchematic extends StaticSchematic {
public class Schematic implements ISchematic {
public final int widthX;
public final int heightY;
public final int lengthZ;
protected final BlockState[][][] states;
public Schematic(CompoundNBT schematic) {
/*String type = schematic.getString("Materials");
public MCEditSchematic(CompoundNBT schematic) {
String type = schematic.getString("Materials");
if (!type.equals("Alpha")) {
throw new IllegalStateException("bad schematic " + type);
}
widthX = schematic.getInteger("Width");
heightY = schematic.getInteger("Height");
lengthZ = schematic.getInteger("Length");
this.x = schematic.getInt("Width");
this.y = schematic.getInt("Height");
this.z = schematic.getInt("Length");
byte[] blocks = schematic.getByteArray("Blocks");
byte[] metadata = schematic.getByteArray("Data");
// byte[] metadata = schematic.getByteArray("Data");
byte[] additional = null;
if (schematic.hasKey("AddBlocks")) {
if (schematic.contains("AddBlocks")) {
byte[] addBlocks = schematic.getByteArray("AddBlocks");
additional = new byte[addBlocks.length * 2];
for (int i = 0; i < addBlocks.length; i++) {
@@ -50,43 +51,23 @@ public class Schematic implements ISchematic {
additional[i * 2 + 1] = (byte) ((addBlocks[i] >> 0) & 0xF); // upper nibble
}
}
states = new BlockState[widthX][lengthZ][heightY];
for (int y = 0; y < heightY; y++) {
for (int z = 0; z < lengthZ; z++) {
for (int x = 0; x < widthX; x++) {
int blockInd = (y * lengthZ + z) * widthX + x;
this.states = new BlockState[this.x][this.z][this.y];
for (int y = 0; y < this.y; y++) {
for (int z = 0; z < this.z; z++) {
for (int x = 0; x < this.x; x++) {
int blockInd = (y * this.z + z) * this.x + x;
int blockID = blocks[blockInd] & 0xFF;
if (additional != null) {
// additional is 0 through 15 inclusive since it's & 0xF above
blockID |= additional[blockInd] << 8;
}
Block block = Block.REGISTRY.getObjectById(blockID);
int meta = metadata[blockInd] & 0xFF;
states[x][z][y] = block.getStateFromMeta(meta);
Block block = Registry.BLOCK.getOrDefault(ResourceLocation.tryCreate(ItemIntIDToString.getItem(blockID)));
// int meta = metadata[blockInd] & 0xFF;
// this.states[x][z][y] = block.getStateFromMeta(meta);
this.states[x][z][y] = block.getDefaultState();
}
}
}*/
throw new UnsupportedOperationException("1.13 be like: numeric IDs btfo");
}
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return states[x][z][y];
}
@Override
public int widthX() {
return widthX;
}
@Override
public int heightY() {
return heightY;
}
@Override
public int lengthZ() {
return lengthZ;
}
}
}

View File

@@ -0,0 +1,158 @@
/*
* 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.utils.schematic.format.defaults;
import baritone.utils.schematic.StaticSchematic;
import baritone.utils.type.VarInt;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.state.IProperty;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Brady
* @since 12/27/2019
*/
public final class SpongeSchematic extends StaticSchematic {
public SpongeSchematic(CompoundNBT nbt) {
this.x = nbt.getInt("Width");
this.y = nbt.getInt("Height");
this.z = nbt.getInt("Length");
this.states = new BlockState[this.x][this.z][this.y];
Int2ObjectArrayMap<BlockState> palette = new Int2ObjectArrayMap<>();
CompoundNBT paletteTag = nbt.getCompound("Palette");
for (String tag : paletteTag.keySet()) {
int index = paletteTag.getInt(tag);
SerializedBlockState serializedState = SerializedBlockState.getFromString(tag);
if (serializedState == null) {
throw new IllegalArgumentException("Unable to parse palette tag");
}
BlockState state = serializedState.deserialize();
if (state == null) {
throw new IllegalArgumentException("Unable to deserialize palette tag");
}
palette.put(index, state);
}
// BlockData is stored as an NBT byte[], however, the actual data that is represented is a varint[]
byte[] rawBlockData = nbt.getByteArray("BlockData");
int[] blockData = new int[this.x * this.y * this.z];
int offset = 0;
for (int i = 0; i < blockData.length; i++) {
if (offset >= rawBlockData.length) {
throw new IllegalArgumentException("No remaining bytes in BlockData for complete schematic");
}
VarInt varInt = VarInt.read(rawBlockData, offset);
blockData[i] = varInt.getValue();
offset += varInt.getSize();
}
for (int y = 0; y < this.y; y++) {
for (int z = 0; z < this.z; z++) {
for (int x = 0; x < this.x; x++) {
int index = (y * this.z + z) * this.x + x;
BlockState state = palette.get(blockData[index]);
if (state == null) {
throw new IllegalArgumentException("Invalid Palette Index " + index);
}
this.states[x][z][y] = state;
}
}
}
}
private static final class SerializedBlockState {
private static final Pattern REGEX = Pattern.compile("(?<location>(\\w+:)?\\w+)(\\[(?<properties>(\\w+=\\w+,?)+)])?");
private final ResourceLocation resourceLocation;
private final Map<String, String> properties;
private BlockState blockState;
private SerializedBlockState(ResourceLocation resourceLocation, Map<String, String> properties) {
this.resourceLocation = resourceLocation;
this.properties = properties;
}
private BlockState deserialize() {
if (this.blockState == null) {
Block block = Registry.BLOCK.getOrDefault(this.resourceLocation);
this.blockState = block.getDefaultState();
this.properties.keySet().stream().sorted(String::compareTo).forEachOrdered(key -> {
IProperty<?> property = block.getStateContainer().getProperty(key);
if (property != null) {
this.blockState = setPropertyValue(this.blockState, property, this.properties.get(key));
}
});
}
return this.blockState;
}
private static SerializedBlockState getFromString(String s) {
Matcher m = REGEX.matcher(s);
if (!m.matches()) {
return null;
}
try {
String location = m.group("location");
String properties = m.group("properties");
ResourceLocation resourceLocation = new ResourceLocation(location);
Map<String, String> propertiesMap = new HashMap<>();
if (properties != null) {
for (String property : properties.split(",")) {
String[] split = property.split("=");
propertiesMap.put(split[0], split[1]);
}
}
return new SerializedBlockState(resourceLocation, propertiesMap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static <T extends Comparable<T>> BlockState setPropertyValue(BlockState state, IProperty<T> property, String value) {
Optional<T> parsed = property.parseValue(value);
if (parsed.isPresent()) {
return state.with(property, parsed.get());
} else {
throw new IllegalArgumentException("Invalid value for property " + property);
}
}
}
}

View File

@@ -17,14 +17,14 @@
package baritone.utils.schematic.schematica;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import com.github.lunatrius.schematica.client.world.SchematicWorld;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import java.util.List;
public final class SchematicAdapter implements ISchematic {
public final class SchematicAdapter implements IStaticSchematic {
private final SchematicWorld schematic;
@@ -34,7 +34,12 @@ public final class SchematicAdapter implements ISchematic {
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return schematic.getSchematic().getBlockState(new BlockPos(x, y, z));
return this.getDirect(x, y, z);
}
@Override
public BlockState getDirect(int x, int y, int z) {
return this.schematic.getSchematic().getBlockState(new BlockPos(x, y, z));
}
@Override

View File

@@ -17,7 +17,7 @@
package baritone.utils.schematic.schematica;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import com.github.lunatrius.schematica.Schematica;
import com.github.lunatrius.schematica.proxy.ClientProxy;
import net.minecraft.util.Tuple;
@@ -37,7 +37,7 @@ public enum SchematicaHelper {
}
}
public static Optional<Tuple<ISchematic, BlockPos>> getOpenSchematic() {
public static Optional<Tuple<IStaticSchematic, BlockPos>> getOpenSchematic() {
return Optional.ofNullable(ClientProxy.schematic)
.map(world -> new Tuple<>(new SchematicAdapter(world), world.position));
}

View File

@@ -0,0 +1,95 @@
/*
* 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.utils.type;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.bytes.ByteList;
/**
* @author Brady
* @since 12/19/2019
*/
public final class VarInt {
private final int value;
private final byte[] serialized;
private final int size;
public VarInt(int value) {
this.value = value;
this.serialized = serialize0(this.value);
this.size = this.serialized.length;
}
/**
* @return The integer value that is represented by this {@link VarInt}.
*/
public final int getValue() {
return this.value;
}
/**
* @return The size of this {@link VarInt}, in bytes, once serialized.
*/
public final int getSize() {
return this.size;
}
public final byte[] serialize() {
return this.serialized;
}
private static byte[] serialize0(int valueIn) {
ByteList bytes = new ByteArrayList();
int value = valueIn;
while ((value & 0x80) != 0) {
bytes.add((byte) (value & 0x7F | 0x80));
value >>>= 7;
}
bytes.add((byte) (value & 0xFF));
return bytes.toByteArray();
}
public static VarInt read(byte[] bytes) {
return read(bytes, 0);
}
public static VarInt read(byte[] bytes, int start) {
int value = 0;
int size = 0;
int index = start;
while (true) {
byte b = bytes[index++];
value |= (b & 0x7F) << size++ * 7;
if (size > 5) {
throw new IllegalArgumentException("VarInt size cannot exceed 5 bytes");
}
// Most significant bit denotes another byte is to be read.
if ((b & 0x80) == 0) {
break;
}
}
return new VarInt(value);
}
}