Compare commits

...

285 Commits

Author SHA1 Message Date
Leijurv
606e9bf97c v1.5.1 2020-02-14 15:28:37 -08:00
Leijurv
47ae75a9d6 Merge branch '1.14.4' into 1.15.2 2020-02-14 15:26:34 -08:00
Leijurv
25587e317a fix link click crash 2020-02-14 15:26:03 -08:00
Leijurv
b3ba129fc5 honey is stupid lets just not 2020-02-13 18:59:08 -08:00
Leijurv
746b7b5c88 not unscuffed, just differently scuffed 2020-02-13 18:57:32 -08:00
Brady
db2f6ec78d Update mappings to 20200213-1.15.1 2020-02-13 14:44:29 -06:00
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
c528dba0ea v1.4.2 2019-10-11 17:52:11 -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
Leijurv
2b3a302a5f Merge branch '1.13.2' into 1.14.4 2019-10-11 17:04:53 -07:00
Leijurv
1c00e167ca Merge branch 'master' into 1.13.2 2019-10-11 16:56:04 -07:00
Leijurv
861ee5049a unscuff 2019-10-11 16:15:38 -07:00
Brady
2f9efae457 Refactors to improve consistency 2019-10-11 18:15:14 -05:00
Brady
c1fe588de4 Leijurv is crying and shaking right now 2019-10-11 18:08:39 -05:00
Brady
8fa2dac261 This should fix tab complete scuff 2019-10-11 17:59:36 -05:00
Leijurv
5e9b439591 avery byte scuff btfo 2019-10-10 17:47:26 -07:00
Leijurv
f0ae31f455 fake merge of master into 1.13.2 2019-10-09 20:45:55 -07:00
Leijurv
dc7d64fb88 Merge commit 'ce2fc6f2514245987659b378687f795ab641cf1e' into 1.13.2 2019-10-09 20:44:22 -07:00
Brady
42306055ee Backport anti-poz from 1.13.2 branch to 1.12.2/master 2019-10-09 21:29:48 -05:00
Brady
62df244db7 Initial Brigadier overriden tab completion 2019-10-09 21:19:58 -05:00
Leijurv
ce2fc6f251 no more allowVines crash 2019-10-09 10:50:12 -07:00
Brady
0b2bab6549 Clean up performance Mixins 2019-10-07 17:25:09 -05:00
Brady
eb619adf4a Whoops! 2019-10-07 16:50:43 -05:00
Brady
4d05b152f0 Create ICommand to go alongside Command default implementation 2019-10-07 16:46:21 -05:00
Brady
c908552174 Clarify the default arg parsers 2019-10-07 10:08:52 -05:00
Brady
f1bbdc177f Collapse the sub-packages under helpers 2019-10-07 10:06:05 -05:00
Brady
9591b6fdef Move IArgConsumer from *.helpers.arguments to *.argument 2019-10-07 10:00:04 -05:00
Leijurv
84a257faf4 fix air scuff 2019-10-06 17:37:07 -07:00
Leijurv
34620a448e Merge branch '1.13.2' into 1.14.4 2019-10-06 17:36:25 -07:00
Leijurv
2b4d6f4aa0 Merge branch 'master' into 1.13.2 2019-10-06 17:32:35 -07:00
Leijurv
8f0a8b6f56 fix inefficient schematic block lookups 2019-10-06 17:32:25 -07:00
Leijurv
e54d63576f Merge branch '1.13.2' into 1.14.4 2019-10-06 17:02:41 -07:00
Leijurv
7e505fc68f fix dropped items scanning 2019-10-06 16:00:26 -07:00
Leijurv
9c323aba91 Merge branch 'master' into 1.13.2 2019-10-06 15:51:27 -07:00
Leijurv
d1c2a0491c only one goto target 2019-10-06 13:49:24 -07:00
Leijurv
d19039e3e5 goto is back 2019-10-06 13:44:37 -07:00
Leijurv
22d5cb8068 loiter around ores to anticipate a possible drop 2019-10-06 13:26:29 -07:00
Leijurv
5f0d3a4018 resume builder too 2019-10-06 13:24:50 -07:00
Brady
889e288524 Refactor *.util.command to *.command 2019-10-06 15:21:21 -05:00
Leijurv
06805057d4 unscuff js code 2019-10-05 19:49:38 -07:00
Leijurv
6e1e355a61 Merge pull request #1016 from joerez/feature/1015/goal-revamps
#1015 Feature/1015/goal revamps
2019-10-05 19:42:02 -07:00
Joerez
9843e8048d issue-1015 better handling
Delete org.eclipse.buildship.core.prefs

Delete .project

issue-1015 removed unessesary conversion

issue-1015 users can use k in their #todo arguments to multiply the goal by 1000
2019-10-05 19:31:32 -07:00
Brady
29d8ab43f2 un-poz some Command stuff 2019-10-04 19:22:15 -05:00
Brady
1440e81ea4 IArgParser API 2019-10-04 18:12:36 -05:00
Brady
bfd8773efa Make getBaritoneForPlayer null-safe 2019-10-04 09:20:26 -05:00
Brady
3a3d880d81 ArgConsumer API separation 2019-10-04 08:55:02 -05:00
Leijurv
089c5fb095 fix buildinlayers crash 2019-10-01 14:29:19 -07:00
Brady
f1fb109d40 Remove ICommandExecution due to redundancy 2019-09-30 21:41:30 -05:00
Leijurv
ae9671bff0 meme fix, things work now 2019-09-30 17:57:09 -07:00
Leijurv
d256f05787 Merge branch 'master' into 1.13.2 2019-09-30 17:52:47 -07:00
Leijurv
47e6a039ef delet 2019-09-30 17:04:33 -07:00
Brady
b8c8b1eb69 Merge pull request #952 from cabaletta/commands
Commands
2019-09-30 18:45:22 -05:00
Leijurv
8a396db80e fix brainlet block breaking issue 2019-09-28 16:28:58 -07:00
Brady
6a90b57ced Some basic API/Main separation 2019-09-28 10:21:07 -05:00
Brady
a75b90fcef crucial performance optimization 2019-09-27 17:07:40 -05:00
Brady
9981af67d5 Remove debug code 2019-09-27 11:10:57 -05:00
Brady
cf60a5f3bd Clean up some things with DefaultCommands 2019-09-27 10:18:46 -05:00
Brady
a04742085e Add documentation to datatypes 2019-09-27 09:54:55 -05:00
Brady
b75a78f3d3 Fix the scuff 2019-09-26 23:33:37 -05:00
Brady
45bea50c91 Fix remaining usages to be in-line with previous commit 2019-09-26 23:20:45 -05:00
Brady
5ba1e67ea0 Don't print stack-traces to chat, just inform the user of the error 2019-09-26 23:18:05 -05:00
Brady
1064a79e1d Fix javadoc errors 2019-09-26 22:59:15 -05:00
Brady
3803bc631b Basically game on the imports 2019-09-26 19:02:21 -05:00
Brady
0b39b3e7b4 FORCE_COMMAND_PREFIX should be exposed to the API 2019-09-26 18:59:29 -05:00
Brady
2f480fcec2 BaritoneChatControl -> main 2019-09-26 18:57:08 -05:00
Brady
a8b1badd8a Remove the special command system exclusions from proguard config 2019-09-26 18:55:15 -05:00
Brady
f8f214ca90 Fix some null substitutions 2019-09-26 18:52:29 -05:00
Brady
595f5a35e0 Datatype Singletons 2019-09-26 18:49:26 -05:00
Brady
9f271b1f44 Future-compatibility for multiple Baritone instances 2019-09-25 18:27:47 -05:00
Brady
7292245b55 Rename PlayerByUsername to NearbyPlayer 2019-09-22 14:41:30 -05:00
Brady
9ffca6ad66 Minor javadoc tidy up 2019-09-21 17:45:53 -05:00
Brady
376c93bd3b Consistent Stream.of usage over Arrays.stream 2019-09-21 17:37:13 -05:00
Brady
204f9d2e31 Fix redundant Stream.of usage 2019-09-21 17:25:20 -05:00
Brady
e4353e489f Get rid of default implementation of IArgParser 2019-09-21 17:11:15 -05:00
Brady
b88af1d682 CommandManager is now Baritone instance dependent 2019-09-21 02:40:03 -05:00
Brady
9d2f83d8d6 Fix unused imports 2019-09-21 02:11:46 -05:00
Brady
ea4f34cb0f No more passing Settings to execute and tabComplete 2019-09-21 02:07:10 -05:00
Brady
b7eaae88a8 Checked Command Exceptions 2019-09-20 18:32:43 -05:00
Leijurv
e70d18f046 Merge pull request #963 from 0-x-2-2/commands
Merge master into commands.
2019-09-20 13:34:09 -07:00
0x22
5a83b791bb Merge remote-tracking branch 'upstream/master' into commands 2019-09-20 16:29:54 -04:00
Brady
eaa426dd66 Fix poor usage of Cloneable
Because super.clone() isn't being called, the idea of "Cloneable" isn't upheld.
2019-09-20 09:51:57 -05:00
Leijurv
fc43ef9308 Merge pull request #956 from LoganDark/commands
Pulling in logandark's uncommitted changes to commands staging
2019-09-19 21:49:27 -07:00
Logan Darklock
8b4ac3893e Tweaks and \n fix 2019-09-19 21:40:55 -07:00
Brady
a0f412f255 Some ArgParser cleanups 2019-09-19 21:24:44 -05:00
Leijurv
0a2e3f98f9 freecam meme 2019-09-19 18:23:05 -07:00
Leijurv
6cc29712e2 fix mine ordering 2019-09-19 17:53:50 -07:00
Leijurv
fae24beaed Merge pull request #954 from 0-x-2-2/commands
Attempt to "fix" travis.
2019-09-19 17:10:26 -07:00
0x22
394775fb9a Attempt to "fix" travis. 2019-09-19 20:06:18 -04:00
Leijurv
5d9209ce80 Merge pull request #953 from 0-x-2-2/commands
Removed very angry code. Started feeding Codacy.
2019-09-19 16:30:42 -07:00
Leijurv
aff3103f36 Merge pull request #941 from BlueBlazeTech/patch-1
Updated Standards section of CODE_OF_CONDUCT.md
2019-09-19 16:07:05 -07:00
0x22
6f2529c243 Removed very angry code. Started feeding Codacy. 2019-09-19 18:54:24 -04:00
Leijurv
e976224258 a moderate amount of gamer 2019-09-19 15:31:21 -07:00
Leijurv
050b6046d7 small tweaks 2019-09-19 14:43:18 -07:00
Leijurv
f0c78751bf no more asList static 2019-09-19 14:40:58 -07:00
Leijurv
2870d2d69e Merge pull request #951 from 0-x-2-2/commands
Fix a MAJOR bug caused by the JetBrains™ AutoFormatter™
2019-09-19 14:38:00 -07:00
0x22
fbabbe69c0 Fix a MAJOR bug caused by the JetBrains™ AutoFormatter™ 2019-09-19 17:36:06 -04:00
Leijurv
b63c54b657 remove isNull and nonNull 2019-09-19 14:34:45 -07:00
Leijurv
3c914de690 Merge pull request #950 from 0-x-2-2/commands
Remove retarded MC field.
2019-09-19 14:07:59 -07:00
0x22
307d6a0628 Remove retarded MC field 2019-09-19 17:05:15 -04:00
Leijurv
61d4f102ba its too many blank lines 2019-09-19 13:43:40 -07:00
Leijurv
0a38e6f690 standardize on this 2019-09-19 13:40:46 -07:00
Leijurv
23a592ec01 it launches 2019-09-19 13:30:40 -07:00
Leijurv
396a96d604 reformat 2019-09-19 12:53:15 -07:00
Leijurv
0504a1d4bf Merge pull request #949 from LoganDark/commands
Commands
2019-09-19 12:51:21 -07:00
Leijurv
fa905b8844 fix breaking blocks 2019-09-19 12:29:33 -07:00
BlueBlazeTech
7f58847f88 Updated Standards section of CODE_OF_CONDUCT.md
added additional details to standards
-line 20
-line 17
-line 32
2019-09-18 09:37:40 -06:00
Leijurv
5f674b86f8 add a setting to scan a larger radius every tick 2019-09-16 23:17:20 -07:00
Leijurv
cccd61e050 add ability to build from opposite corner 2019-09-15 11:37:09 -07:00
Leijurv
bf03a000d1 diagonal ascend 2019-09-09 23:06:36 -07:00
Logan Darklock
fc63c16ee0 initialize chat control only once ever 2019-09-07 00:21:54 -07:00
Logan Darklock
1bb4e44b71 bom import * 2019-09-06 17:50:55 -07:00
Logan Darklock
147884f76d mineprocess reformat too 2019-09-06 17:46:26 -07:00
Logan Darklock
240af75ff7 that specific continuation indent 2019-09-06 17:45:34 -07:00
Logan Darklock
c54dcdba24 "stAnDaRd" ConTinuATion InDEnT 2019-09-06 17:41:27 -07:00
Logan Darklock
9db07faf49 import * 2019-09-06 17:31:41 -07:00
Logan Darklock
aefc82e47c Review 2 2019-09-06 17:22:55 -07:00
Logan Darklock
957f62ffbb Merge branch 'upstream' into commands 2019-09-06 04:01:16 -07:00
Logan Darklock
8a001a2438 Review 2019-09-06 03:59:10 -07:00
Leijurv
f8d4e22b13 Update SETUP.md 2019-09-04 17:15:46 -07:00
Leijurv
243e6e3b99 Update README.md 2019-09-04 17:15:27 -07:00
Logan Darklock
69e3481a32 move default commands to main module 2019-09-04 11:17:36 -07:00
Logan Darklock
daa0d0c859 copyright notices 2019-09-04 09:16:36 -07:00
Logan Darklock
72402052ae Merge branch 'master' into commands 2019-09-04 09:06:43 -07:00
Logan Darklock
5ee1e738f4 Fix RelativePath and build command 2019-09-04 02:30:24 -07:00
Logan Darklock
382ad0079c DrawAABB changes, set command bugfix, sel rendering change, selection setting name changes 2019-09-03 23:46:20 -07:00
Logan Darklock
8dc4ff26d6 Persistent renderManager, selection transparency setting, drawAABB fixes 2019-09-03 22:55:56 -07:00
Logan Darklock
755a3f0154 Fix #sel selectors 2019-09-03 21:58:20 -07:00
Logan Darklock
b51dccc737 DON'T THROW EXCEPTIONS IN SCHEMATICS AA 2019-09-03 21:57:20 -07:00
Logan Darklock
620fc9af64 Sliiightly more efficient AbstractSchematic#approxPlaceable() 2019-09-03 21:44:45 -07:00
Logan Darklock
991283182c Fix some bugs with schematics 2019-09-03 08:35:16 -07:00
Logan Darklock
1413bd2f05 LOL CONTACT 2019-09-03 06:27:36 -07:00
Logan Darklock
faa8c727c3 correct sel help 2019-09-03 06:14:22 -07:00
Logan Darklock
65d2bdaf2b Selection shifting and such 2019-09-03 06:09:02 -07:00
Leijurv
17ca9ec43d Update USAGE.md 2019-09-02 23:13:14 -07:00
Logan Darklock
289971557a Fix bug with a few old commands that causes pagination to not work 2019-09-02 19:50:14 -07:00
Logan Darklock
d1a0b735d9 First working version of WorldEdit-like commands(!!!) 2019-09-02 16:18:07 -07:00
Logan Darklock
bc0f2b59da First version of selection stuff; nothing supports it yet 2019-09-02 11:29:48 -07:00
Logan Darklock
98bb3fba9c Pass current blockstate to schematics 2019-09-02 03:00:21 -07:00
Logan Darklock
b405a610bb ground work for more build commands 2019-09-01 15:53:13 -07:00
Leijurv
3e3df0b493 Merge pull request #894 from LoganDark/prefer-silk-touch
Setting to prefer silk touch, fixes #883
2019-09-01 15:33:14 -07:00
Logan Darklock
c1749057d9 Merge branch 'prefer-silk-touch' into commands 2019-09-01 15:19:17 -07:00
Logan Darklock
150f7a9fd9 extra parenthesis 2019-09-01 15:18:59 -07:00
Logan Darklock
6411fd80aa Merge prefer-silk-touch 2019-09-01 15:02:09 -07:00
Logan Darklock
0b953a237d Fix logic error 2019-09-01 15:01:02 -07:00
Logan Darklock
48f6d338a6 Merge upstream master 2019-09-01 14:48:42 -07:00
Logan Darklock
afc575d080 Setting to prefer silk touch, fixes #883 2019-09-01 14:47:01 -07:00
Logan Darklock
384b9b4704 Prefer silk touch setting 2019-09-01 14:45:31 -07:00
Logan Darklock
ce329d7fb3 Waypoints command 2019-09-01 14:18:59 -07:00
Logan Darklock
287615b0a1 Merge branch 'master' of https://github.com/cabaletta/baritone into commands 2019-09-01 13:22:03 -07:00
Logan Darklock
b96692f2d9 Save settings... 2019-09-01 13:12:06 -07:00
Leijurv
1b8aea2e6d Merge pull request #890 from LoganDark/censoring
Coordinate censoring
2019-09-01 10:30:24 -07:00
Logan Darklock
97ce377b9c Merge branch 'censoring' into commands 2019-09-01 10:16:14 -07:00
Logan Darklock
f1973b14c7 Remove MixinBlockPos since we now only log BetterBlockPos 2019-09-01 10:15:41 -07:00
Logan Darklock
73bd2cdcc3 Merge branch 'censoring' into commands 2019-09-01 10:09:12 -07:00
Logan Darklock
9038310150 Rename SettingsUtil.possiblyCensorCoordinate to maybeCensor 2019-09-01 10:06:50 -07:00
Logan Darklock
07fb09b4cc Merge branch 'censoring' into commands 2019-09-01 10:01:46 -07:00
Logan Darklock
ef38051826 Coordinate censoring 2019-09-01 09:50:47 -07:00
Logan Darklock
445037b614 Coordinate censoring 2019-09-01 09:47:27 -07:00
Logan Darklock
44ec969203 yeah 2019-09-01 00:17:42 -07:00
Logan Darklock
444cde1ee9 Improve blockstate filter in BlockOptionalMeta 2019-08-31 23:08:51 -07:00
Logan Darklock
cf12cbbcf4 Don't care about meta in bom if we have none 2019-08-31 20:58:22 -07:00
Logan Darklock
bb2f4da6b6 Fix baritoneHash calculation 2019-08-31 20:53:58 -07:00
Logan Darklock
4bca6cc1a5 Scan ItemStacks correctly 2019-08-31 20:43:03 -07:00
Logan Darklock
544ae24b64 YES I DID IT 2019-08-31 19:08:43 -07:00
Logan Darklock
8fc80a285c Waypoint hashcode + removed one unused line from followcommand 2019-08-31 18:52:24 -07:00
Logan Darklock
6ed86cb3c7 Hopefully speed up BlockOptionalMeta 2019-08-31 10:28:01 -07:00
Logan Darklock
84f45ebb48 Fix file tab completion in production environments 2019-08-31 07:55:24 -07:00
Logan Darklock
90fb17b89f Told Proguard not to touch things it doesn't understand 2019-08-31 07:36:23 -07:00
Logan Darklock
d54e846f91 Proguard likes to fuck up my command framework in the build. This error makes it more clear when that happens 2019-08-31 07:16:02 -07:00
Logan Darklock
ee71819bb2 remove unnecessary import 2019-08-31 06:42:16 -07:00
Logan Darklock
2ee313a795 Don't break Forge world loading 2019-08-31 06:38:36 -07:00
Logan Darklock
b924e8511b fix imports 2019-08-31 02:14:38 -07:00
Logan Darklock
15e9d756b7 Remove unused toArrayBad function... 2019-08-31 01:59:45 -07:00
Logan Darklock
8be879465a Merge branch 'master' of https://github.com/cabaletta/baritone into commands 2019-08-31 01:05:24 -07:00
Logan Darklock
5e0b333cfd fix comment & make final int final 2019-08-31 01:04:22 -07:00
Logan Darklock
efa243386c Make scanChunkInto even faster 2019-08-31 01:00:37 -07:00
Logan Darklock
ae6ee5688c add toArray, scanChunkInto usage coming soon 2019-08-31 00:51:42 -07:00
Logan Darklock
9f3eaac3df increase efficiency of scanChunkInto by ~25% 2019-08-30 22:52:20 -07:00
Logan Darklock
c938983ff5 thisway command + fixed fromDirection for you + fixed double/float argparsers 2019-08-30 22:27:30 -07:00
Logan Darklock
172ce3a054 click 2019-08-30 18:00:34 -07:00
Logan Darklock
69ca48287e prune before checking size 2019-08-30 17:20:20 -07:00
Logan Darklock
a6726f4e96 extend cache on threshold 2019-08-30 17:19:44 -07:00
Logan Darklock
b6c91b5062 speed up cache stuff 2019-08-30 17:13:09 -07:00
Logan Darklock
fe47245b73 Fix searchWorld cache and also speed and stuff 2019-08-30 17:12:05 -07:00
Logan Darklock
d687e1203a BlockOptionalMeta 2019-08-30 15:38:15 -07:00
Leijurv
0280fcb2da Merge pull request #879 from Orinion/fix-waypoint-bug
Check if waypoint name is Tag
2019-08-30 13:39:55 -07:00
Logan Darklock
4354d09c20 some efficiency fixes to filters + qol for leijurv 2019-08-30 12:25:59 -07:00
Logan Darklock
e3c4d06b2b Initial commit of commands 2019-08-30 11:55:25 -07:00
Orinion
6327c8492f fix codestyle 2019-08-30 11:54:04 +02:00
Leijurv
e7412d0d46 Merge pull request #867 from Orinion/master
Add replantCrops setting
2019-08-29 17:46:41 -07:00
Orinion
6a181abdcb Check if waypoint name is Tag
before, saving a waypint with a tag name would not result in an error, but you would not be able to run "goto" on it. see #869
2019-08-30 02:43:59 +02:00
Orinion
65a9b1a78a Make replantCrops override replantNetherWart
When replantCrops is false, baritone will not replant nether wart.
Also fixed spacing.
2019-08-29 10:36:31 +02:00
Leijurv
5ce644718e Merge pull request #871 from babbaj/cla$$
Replace klass with cla$$
2019-08-28 17:51:50 -07:00
Babbaj
a7add6bc13 Replace klass with cla$$ 2019-08-28 20:37:05 -04:00
Orinion
d2a046c8b4 Add replantCrops setting
add replantCrops setting, simmilar to replantNetherWart for the other crops.
2019-08-28 20:15:41 +02:00
Leijurv
33080a4e1c v1.2.9 2019-08-23 15:23:54 -07:00
Leijurv
dae6cc8e20 maintain current behavior 2019-08-23 15:23:36 -07:00
Leijurv
a2159d62e5 quite annoying 2019-08-23 15:23:00 -07:00
Leijurv
a092a0ba94 update badges 2019-08-23 15:22:59 -07:00
Leijurv
33faf5c9b0 Merge pull request #835 from IronException/master
added things to avoid
2019-08-23 15:22:42 -07:00
IronException
d927207b67 added things to avoid
Signs should also be avoided. A lot of history can get lost
2019-08-22 17:44:27 +02:00
Leijurv
02419f8b07 v1.4.1 2019-08-20 15:25:30 -07:00
Leijurv
ddeb2a5c14 perhaps fix concurrent modification issues 2019-08-20 15:07:36 -07:00
Leijurv
8973b73bfa reduce spamminess 2019-08-20 14:58:00 -07:00
Leijurv
4557bab3c4 maybe travis fix 2019-08-20 14:49:16 -07:00
Leijurv
6e185b580c Merge branch '1.13.2' into 1.14.4 2019-08-20 14:33:18 -07:00
Leijurv
a9ba05bf5e Merge branch 'master' into 1.13.2 2019-08-20 14:28:59 -07:00
Leijurv
b9f0da7d27 major unscuff of builder 2019-08-20 11:23:23 -07:00
Leijurv
1c36bf3300 repack on mine cmd 2019-08-17 22:01:53 -07:00
Leijurv
cca137d526 Merge pull request #808 from reb0rt/patch-2
Stop parseGoal from removing the last argument (when it shouldn't)
2019-08-17 21:13:59 -07:00
Leijurv
4e73880d4a Merge branch '1.14.4' of github.com:cabaletta/baritone into 1.14.4 2019-08-17 20:29:32 -07:00
reb0rt
24da012903 Stop parseGoal from removing the last argument
isNumeric returns false if the input is anything other than a positive integer. This meant that baritone wouldn't properly set goals if they ended in anything other than a positive integer.
2019-08-18 13:04:39 +10:00
Leijurv
e53b207148 Merge branch '1.13.2' into 1.14.4 2019-08-17 16:09:45 -07:00
Leijurv
0eb7a5aed6 Merge pull request #805 from Graicc/master
Added amount of block mining to documentation
2019-08-17 09:37:03 -07:00
Graicc
5cbf1eef5f Grammer fix 2019-08-17 12:02:26 -04:00
Graicc
ed4fba330d Added mining certain amount of blocks to USAGE.md 2019-08-17 11:59:30 -04:00
227 changed files with 11906 additions and 1829 deletions

2
.gitignore vendored
View File

@@ -16,6 +16,8 @@ classes/
# IntelliJ Files
.idea/
*.iml
*.ipr
*.iws
/logs/
# Copyright Files

View File

@@ -14,10 +14,10 @@ appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* No Anime
* No Anime (including uwu's or owo's)
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Giving and gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
@@ -29,7 +29,7 @@ Examples of unacceptable behavior by participants include:
* ~~Trolling, insulting/derogatory comments, and personal or political attacks~~
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
address, without explicit permission or consent
* Other conduct which could reasonably be considered inappropriate in a
professional setting

View File

@@ -19,9 +19,9 @@
![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-brightgreen.svg)](https://impactdevelopment.github.io/)
[![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-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
[![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/)
[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/)
@@ -29,9 +29,9 @@
A Minecraft pathfinder bot.
Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797).

View File

@@ -1,6 +1,6 @@
# Installation
The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone.
For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1).
@@ -103,4 +103,4 @@ $ gradlew build
![Image](https://i.imgur.com/PE6r9iN.png)
- Double click on **build** to run it
- Double click on **build** to run it

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`.
@@ -24,7 +36,7 @@ Some common examples:
- `goal clear` to clear the goal
- `cancel` or `stop` to stop everything
- `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part)
- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.)
- `mine diamond_ore iron_ore` to mine diamond ore or iron ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`.
- `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area.
- `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type.
- `save waypointName` to save a waypoint. `goto waypointName` to go to it.
@@ -38,7 +50,6 @@ Some common examples:
- `version` to get the version of Baritone you're running
- `damn` daniel
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.0'
version '1.5.1'
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: '20200213-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

@@ -34,12 +34,12 @@ public final class BaritoneAPI {
private static final Settings settings;
static {
settings = new Settings();
SettingsUtil.readAndApply(settings);
ServiceLoader<IBaritoneProvider> baritoneLoader = ServiceLoader.load(IBaritoneProvider.class);
Iterator<IBaritoneProvider> instances = baritoneLoader.iterator();
provider = instances.next();
settings = new Settings();
SettingsUtil.readAndApply(settings);
}
public static IBaritoneProvider getProvider() {

View File

@@ -23,8 +23,10 @@ import baritone.api.cache.IWorldProvider;
import baritone.api.event.listener.IEventBus;
import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.process.*;
import baritone.api.selection.ISelectionManager;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext;
import baritone.api.command.manager.ICommandManager;
/**
* @author Brady
@@ -32,15 +34,6 @@ import baritone.api.utils.IPlayerContext;
*/
public interface IBaritone {
/**
* Call as soon as Minecraft is ready, initializes all of the processes, behaviors, etc. This will
* only effectively be ran once, any additional calls are redundant because the initialization state
* is saved.
* <p>
* Or whenever your overeager utility client wants.
*/
void init();
/**
* @return The {@link IPathingBehavior} instance
* @see IPathingBehavior
@@ -128,6 +121,18 @@ public interface IBaritone {
*/
IEventBus getGameEventHandler();
/**
* @return The {@link ISelectionManager} instance
* @see ISelectionManager
*/
ISelectionManager getSelectionManager();
/**
* @return The {@link ICommandManager} instance
* @see ICommandManager
*/
ICommandManager getCommandManager();
/**
* Open click
*/

View File

@@ -18,12 +18,16 @@
package baritone.api;
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;
/**
* Provides the present {@link IBaritone} instances
* Provides the present {@link IBaritone} instances, as well as non-baritone instance related APIs.
*
* @author leijurv
*/
@@ -57,7 +61,7 @@ public interface IBaritoneProvider {
*/
default IBaritone getBaritoneForPlayer(ClientPlayerEntity player) {
for (IBaritone baritone : getAllBaritones()) {
if (player.equals(baritone.getPlayerContext().player())) {
if (Objects.equals(player, baritone.getPlayerContext().player())) {
return baritone;
}
}
@@ -71,4 +75,17 @@ public interface IBaritoneProvider {
* @return The {@link IWorldScanner} instance.
*/
IWorldScanner getWorldScanner();
/**
* Returns the {@link ICommandSystem} instance. This is not bound to a specific {@link IBaritone}
* instance because {@link ICommandSystem} itself controls global behavior for {@link ICommand}s.
*
* @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;
/**
@@ -140,6 +140,13 @@ public final class Settings {
*/
public final Setting<Boolean> allowDiagonalDescend = new Setting<>(false);
/**
* Allow diagonal ascending
* <p>
* Actually pretty safe, much safer than diagonal descend tbh
*/
public final Setting<Boolean> allowDiagonalAscend = new Setting<>(false);
/**
* Allow mining the block directly beneath its feet
* <p>
@@ -174,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>
@@ -224,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);
@@ -241,7 +262,17 @@ public final class Settings {
/**
* How many degrees to randomize the yaw every tick. Set to 0 to disable
*/
public final Setting<Double> randomLooking = new Setting<>(2d);
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
*/
public final Setting<Double> randomLooking = new Setting<>(0.01d);
/**
* This is the big A* setting.
@@ -485,15 +516,20 @@ public final class Settings {
public final Setting<Boolean> chatControl = new Setting<>(true);
/**
* A second override over chatControl to force it on
* Some clients like Impact try to force chatControl to off, so here's a second setting to do it anyway
*/
public final Setting<Boolean> removePrefix = new Setting<>(false);
public final Setting<Boolean> chatControlAnyway = new Setting<>(false);
/**
* Render the path
*/
public final Setting<Boolean> renderPath = new Setting<>(true);
/**
* Render the path as a line instead of a frickin thingy
*/
public final Setting<Boolean> renderPathAsLine = new Setting<>(false);
/**
* Render the goal
*/
@@ -594,10 +630,41 @@ public final class Settings {
public final Setting<Float> cachedChunksOpacity = new Setting<>(0.5f);
/**
* Whether or not to use the "#" command prefix
* Whether or not to allow you to run Baritone commands with the prefix
*/
public final Setting<Boolean> prefixControl = new Setting<>(true);
/**
* The command prefix for chat control
*/
public final Setting<String> prefix = new Setting<>("#");
/**
* Use a short Baritone prefix [B] instead of [Baritone] when logging to chat
*/
public final Setting<Boolean> shortBaritonePrefix = new Setting<>(false);
/**
* Echo commands to chat when they are run
*/
public final Setting<Boolean> echoCommands = new Setting<>(true);
/**
* Censor coordinates in goals and block positions
*/
public final Setting<Boolean> censorCoordinates = new Setting<>(false);
/**
* Censor arguments to ran commands, to hide, for example, coordinates to #goal
*/
public final Setting<Boolean> censorRanCommands = new Setting<>(false);
/**
* Always prefer silk touch tools over regular tools. This will not sacrifice speed, but it will always prefer silk
* touch tools over other tools of the same speed. This includes always choosing ANY silk touch tool over your hand.
*/
public final Setting<Boolean> preferSilkTouch = new Setting<>(false);
/**
* Don't stop walking forward when you need to break blocks in your way
*/
@@ -659,7 +726,12 @@ public final class Settings {
public final Setting<Integer> exploreMaintainY = new Setting<>(64);
/**
* Replant nether wart while farming
* Replant normal Crops while farming and leave cactus and sugarcane to regrow
*/
public final Setting<Boolean> replantCrops = new Setting<>(true);
/**
* Replant nether wart while farming. This setting only has an effect when replantCrops is also enabled
*/
public final Setting<Boolean> replantNetherWart = new Setting<>(false);
@@ -687,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>
@@ -701,11 +778,71 @@ public final class Settings {
*/
public final Setting<Boolean> goalBreakFromAbove = new Setting<>(false);
/**
* Build in map art mode, which makes baritone only care about the top block in each column
*/
public final Setting<Boolean> mapArtMode = new Setting<>(false);
/**
* Override builder's behavior to not attempt to correct blocks that are currently water
*/
public final Setting<Boolean> okIfWater = new Setting<>(false);
/**
* The set of incorrect blocks can never grow beyond this size
*/
public final Setting<Integer> incorrectSize = new Setting<>(100);
/**
* Multiply the cost of breaking a block that's correct in the builder's schematic by this coefficient
*/
public final Setting<Double> breakCorrectBlockPenaltyMultiplier = new Setting<>(10d);
/**
* When this setting is true, build a schematic with the highest X coordinate being the origin, instead of the lowest
*/
public final Setting<Boolean> schematicOrientationX = new Setting<>(false);
/**
* When this setting is true, build a schematic with the highest Y coordinate being the origin, instead of the lowest
*/
public final Setting<Boolean> schematicOrientationY = new Setting<>(false);
/**
* When this setting is true, build a schematic with the highest Z coordinate being the origin, instead of the lowest
*/
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.
*/
public final Setting<Integer> builderTickScanRadius = new Setting<>(5);
/**
* While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)?
*/
public final Setting<Boolean> mineScanDroppedItems = new Setting<>(true);
/**
* While mining, wait this number of milliseconds after mining an ore to see if it will drop an item
* instead of immediately going onto the next one
* <p>
* Thanks Louca
*/
public final Setting<Long> mineDropLoiterDurationMSThanksLouca = new Setting<>(250L);
/**
* Trim incorrect positions too far away, helps performance but hurts reliability in very large schematics
*/
public final Setting<Boolean> distanceTrim = new Setting<>(true);
/**
* Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore.
* <p>
@@ -821,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
*/
@@ -866,6 +1008,51 @@ public final class Settings {
*/
public final Setting<Color> colorGoalBox = new Setting<>(Color.GREEN);
/**
* The color of the goal box when it's inverted
*/
public final Setting<Color> colorInvertedGoalBox = new Setting<>(Color.RED);
/**
* The color of all selections
*/
public final Setting<Color> colorSelection = new Setting<>(Color.CYAN);
/**
* The color of the selection pos 1
*/
public final Setting<Color> colorSelectionPos1 = new Setting<>(Color.BLACK);
/**
* The color of the selection pos 2
*/
public final Setting<Color> colorSelectionPos2 = new Setting<>(Color.ORANGE);
/**
* The opacity of the selection. 0 is completely transparent, 1 is completely opaque
*/
public final Setting<Float> selectionOpacity = new Setting<>(.5f);
/**
* Line width of the goal when rendered, in pixels
*/
public final Setting<Float> selectionLineWidth = new Setting<>(2F);
/**
* Render selections
*/
public final Setting<Boolean> renderSelection = new Setting<>(true);
/**
* Ignore depth when rendering selections
*/
public final Setting<Boolean> renderSelectionIgnoreDepth = new Setting<>(true);
/**
* Render selection corners
*/
public final Setting<Boolean> renderSelectionCorners = new Setting<>(true);
/**
* A map of lowercase setting field names to their respective setting
@@ -880,6 +1067,7 @@ public final class Settings {
public final Map<Setting<?>, Type> settingTypes;
public final class Setting<T> {
public T value;
public final T defaultValue;
private String name;
@@ -962,10 +1150,10 @@ public final class Settings {
}
@SuppressWarnings("unchecked")
public <T> List<Setting<T>> getAllValuesByType(Class<T> klass) {
public <T> List<Setting<T>> getAllValuesByType(Class<T> cla$$) {
List<Setting<T>> result = new ArrayList<>();
for (Setting<?> setting : allSettings) {
if (setting.getValueClass().equals(klass)) {
if (setting.getValueClass().equals(cla$$)) {
result.add((Setting<T>) setting);
}
}

View File

@@ -64,9 +64,17 @@ public interface IPathingBehavior extends IBehavior {
Goal getGoal();
/**
* @return Whether or not a path is currently being executed.
* @return Whether or not a path is currently being executed. This will be false if there's currently a pause.
* @see #hasPath()
*/
default boolean isPathing() {
boolean isPathing();
/**
* @return If there is a current path. Note that the path is not necessarily being executed, for example when there
* is a pause in effect.
* @see #isPathing()
*/
default boolean hasPath() {
return getCurrent() != null;
}

View File

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

View File

@@ -17,12 +17,9 @@
package baritone.api.cache;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.ArrayUtils;
import baritone.api.utils.BetterBlockPos;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.*;
/**
* A marker for a position in the world.
@@ -60,7 +57,7 @@ public interface IWaypoint {
*
* @return The block position of this waypoint
*/
BlockPos getLocation();
BetterBlockPos getLocation();
enum Tag {
@@ -92,20 +89,48 @@ public interface IWaypoint {
/**
* The names for the tag, anything that the tag can be referred to as.
*/
private final String[] names;
public final String[] names;
Tag(String... names) {
this.names = names;
}
/**
* Finds a tag from one of the names that could be used to identify said tag.
*
* @param name The name of the tag
* @return The tag, if one is found, otherwise, {@code null}
* @return A name that can be passed to {@link #getByName(String)} to retrieve this tag
*/
public static Tag fromString(String name) {
return TAG_LIST.stream().filter(tag -> ArrayUtils.contains(tag.names, name.toLowerCase())).findFirst().orElse(null);
public String getName() {
return names[0];
}
/**
* Gets a tag by one of its names.
*
* @param name The name to search for.
* @return The tag, if found, or null.
*/
public static Tag getByName(String name) {
for (Tag action : Tag.values()) {
for (String alias : action.names) {
if (alias.equalsIgnoreCase(name)) {
return action;
}
}
}
return null;
}
/**
* @return All tag names.
*/
public static String[] getAllNames() {
Set<String> names = new HashSet<>();
for (Tag tag : Tag.values()) {
names.addAll(Arrays.asList(tag.names));
}
return names.toArray(new String[0]);
}
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.cache;
import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
@@ -33,28 +34,63 @@ public interface IWorldScanner {
/**
* Scans the world, up to the specified max chunk radius, for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param blocks The blocks to scan for
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param filter The blocks to scan for
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
* returned, if the value is negative, then this condition doesn't apply.
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @param maxSearchRadius The maximum chunk search radius
* @return The matching block positions
*/
List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
List<BlockPos> scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius);
default List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> filter, int max, int yLevelThreshold, int maxSearchRadius) {
return scanChunkRadius(ctx, new BlockOptionalMetaLookup(filter.toArray(new Block[0])), max, yLevelThreshold, maxSearchRadius);
}
/**
* Scans a single chunk for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param filter The blocks to scan for
* @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @return The matching block positions
*/
List<BlockPos> scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold);
/**
* Scans a single chunk for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param blocks The blocks to scan for
* @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
* returned, if the value is negative, then this condition doesn't apply.
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @return The matching block positions
*/
List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold);
default List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold) {
return scanChunk(ctx, new BlockOptionalMetaLookup(blocks), pos, max, yLevelThreshold);
}
/**
* Overload of {@link #repack(IPlayerContext, int)} where the value of the {@code range} parameter is {@code 40}.
*
* @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

@@ -17,7 +17,7 @@
package baritone.api.cache;
import net.minecraft.util.math.BlockPos;
import baritone.api.utils.BetterBlockPos;
import java.util.Date;
@@ -31,9 +31,9 @@ public class Waypoint implements IWaypoint {
private final String name;
private final Tag tag;
private final long creationTimestamp;
private final BlockPos location;
private final BetterBlockPos location;
public Waypoint(String name, Tag tag, BlockPos location) {
public Waypoint(String name, Tag tag, BetterBlockPos location) {
this(name, tag, location, System.currentTimeMillis());
}
@@ -46,7 +46,7 @@ public class Waypoint implements IWaypoint {
* @param location The waypoint location
* @param creationTimestamp When the waypoint was created
*/
public Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) {
public Waypoint(String name, Tag tag, BetterBlockPos location, long creationTimestamp) {
this.name = name;
this.tag = tag;
this.location = location;
@@ -55,7 +55,7 @@ public class Waypoint implements IWaypoint {
@Override
public int hashCode() {
return name.hashCode() + tag.hashCode() + location.hashCode(); //lol
return name.hashCode() ^ tag.hashCode() ^ location.hashCode() ^ Long.hashCode(creationTimestamp);
}
@Override
@@ -74,13 +74,18 @@ public class Waypoint implements IWaypoint {
}
@Override
public BlockPos getLocation() {
public BetterBlockPos getLocation() {
return this.location;
}
@Override
public String toString() {
return name + " " + location.toString() + " " + new Date(creationTimestamp).toString();
return String.format(
"%s %s %s",
name,
BetterBlockPos.from(location).toString(),
new Date(creationTimestamp).toString()
);
}
@Override

View File

@@ -0,0 +1,68 @@
/*
* 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.command;
import baritone.api.IBaritone;
import baritone.api.utils.IPlayerContext;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A default implementation of {@link ICommand} which provides easy access to the
* command's bound {@link IBaritone} instance, {@link IPlayerContext} and an easy
* way to provide multiple valid command execution names through the default constructor.
* <p>
* So basically, you should use it because it provides a small amount of boilerplate,
* but you're not forced to use it.
*
* @see ICommand
*
* @author LoganDark
*/
public abstract class Command implements ICommand {
protected IBaritone baritone;
protected IPlayerContext ctx;
/**
* The names of this command. This is what you put after the command prefix.
*/
protected final List<String> names;
/**
* Creates a new Baritone control command.
*
* @param names The names of this command. This is what you put after the command prefix.
*/
protected Command(IBaritone baritone, String... names) {
this.names = Collections.unmodifiableList(Stream.of(names)
.map(s -> s.toLowerCase(Locale.US))
.collect(Collectors.toList()));
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
}
@Override
public final List<String> getNames() {
return this.names;
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.command;
import baritone.api.Settings;
import java.util.UUID;
/**
* @author Brady
* @since 9/26/2019
*/
public interface IBaritoneChatControl {
/**
* In certain cases chat components need to execute commands for you. For example, the paginator automatically runs
* commands when you click the forward and back arrows to show you the previous/next page.
* <p>
* If the prefix is changed in the meantime, then the command will go to chat. That's no good. So here's a permanent
* prefix that forces a command to run, regardless of the current prefix, chat/prefix control being enabled, etc.
* <p>
* If used right (by both developers and users), it should be impossible to expose a command accidentally to the
* server. As a rule of thumb, if you have a clickable chat component, always use this prefix. If you're suggesting
* a command (a component that puts text into your text box, or something else), use {@link Settings#prefix}.
*/
String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString());
}

View File

@@ -0,0 +1,67 @@
/*
* 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.command;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.utils.Helper;
import java.util.List;
import java.util.stream.Stream;
/**
* The base for a command.
*
* @author Brady
* @since 10/7/2019
*/
public interface ICommand extends Helper {
/**
* Called when this command is executed.
*/
void execute(String label, IArgConsumer args) throws CommandException;
/**
* Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions
* list.
*/
Stream<String> tabComplete(String label, IArgConsumer args) throws CommandException;
/**
* @return A <b>single-line</b> string containing a short description of this command's purpose.
*/
String getShortDesc();
/**
* @return A list of lines that will be printed by the help command when the user wishes to view them.
*/
List<String> getLongDesc();
/**
* @return A list of the names that can be accepted to have arguments passed to this command
*/
List<String> getNames();
/**
* @return {@code true} if this command should be hidden from the help menu
*/
default boolean hiddenFromHelp() {
return false;
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.command;
import baritone.api.command.argparser.IArgParserManager;
/**
* @author Brady
* @since 10/4/2019
*/
public interface ICommandSystem {
IArgParserManager getParserManager();
}

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.command.argparser;
import baritone.api.command.argument.ICommandArgument;
public interface IArgParser<T> {
/**
* @return the class of this parser.
*/
Class<T> getTarget();
/**
* A stateless argument parser is just that. It takes a {@link ICommandArgument} and outputs its type.
*/
interface Stateless<T> extends IArgParser<T> {
/**
* @param arg The argument to parse.
* @return What it was parsed into.
* @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an
* appropriate error.
*/
T parseArg(ICommandArgument arg) throws Exception;
}
/**
* A stated argument parser is similar to a stateless one. It also takes a {@link ICommandArgument}, but it also
* takes a second argument that can be any type, referred to as the state.
*/
interface Stated<T, S> extends IArgParser<T> {
Class<S> getStateType();
/**
* @param arg The argument to parse.
* @param state Can be anything.
* @return What it was parsed into.
* @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an
* appropriate error.
*/
T parseArg(ICommandArgument arg, S state) throws Exception;
}
}

View File

@@ -0,0 +1,69 @@
/*
* 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.command.argparser;
import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.registry.Registry;
/**
* Used to retrieve {@link IArgParser} instances from the registry, by their target class.
* It can be assumed that a {@link IArgParser} exists for {@link Integer}, {@link Long},
* {@link Float}, {@link Double} and {@link Boolean}.
*
* @author Brady
* @since 10/4/2019
*/
public interface IArgParserManager {
/**
* @param type The type trying to be parsed
* @return A parser that can parse arguments into this class, if found.
*/
<T> IArgParser.Stateless<T> getParserStateless(Class<T> type);
/**
* @param type The type trying to be parsed
* @return A parser that can parse arguments into this class, if found.
*/
<T, S> IArgParser.Stated<T, S> getParserStated(Class<T> type, Class<S> stateKlass);
/**
* Attempt to parse the specified argument with a stateless {@link IArgParser} that outputs the specified class.
*
* @param type The type to try and parse the argument into.
* @param arg The argument to parse.
* @return An instance of the specified class.
* @throws CommandInvalidTypeException If the parsing failed
*/
<T> T parseStateless(Class<T> type, ICommandArgument arg) throws CommandInvalidTypeException;
/**
* Attempt to parse the specified argument with a stated {@link IArgParser} that outputs the specified class.
*
* @param type The type to try and parse the argument into.
* @param arg The argument to parse.
* @param state The state to pass to the {@link IArgParser.Stated}.
* @return An instance of the specified class.
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser.Stated
*/
<T, S> T parseStated(Class<T> type, Class<S> stateKlass, ICommandArgument arg, S state) throws CommandInvalidTypeException;
Registry<IArgParser> getRegistry();
}

View File

@@ -0,0 +1,594 @@
/*
* 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.command.argument;
import baritone.api.command.ICommand;
import baritone.api.command.exception.CommandTooManyArgumentsException;
import baritone.api.utils.Helper;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.datatypes.IDatatype;
import baritone.api.command.datatypes.IDatatypeFor;
import baritone.api.command.datatypes.IDatatypePost;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.exception.CommandNotEnoughArgumentsException;
import net.minecraft.util.Direction;
import java.util.Deque;
import java.util.LinkedList;
import java.util.stream.Stream;
/**
* The {@link IArgConsumer} is how {@link ICommand}s read the arguments passed to them. This class has many benefits:
*
* <ul>
* <li>Mutability. The whole concept of the {@link IArgConsumer}} is to let you gradually consume arguments in any way
* you'd like. You can change your consumption based on earlier arguments, for subcommands for example.</li>
* <li>You don't need to keep track of your consumption. The {@link IArgConsumer}} keeps track of the arguments you
* consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you
* need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!</li>
* <li>Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example,
* look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many
* {@code getDatatype...} methods.</li>
* <li>It's very easy to throw detailed exceptions. The {@link IArgConsumer}} has many different methods that can
* enforce the number of arguments, the type of arguments, and more, throwing different types of
* {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed
* data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error
* handlers can do their job and log the error to chat.</li>
* </ul>
*/
public interface IArgConsumer {
LinkedList<ICommandArgument> getArgs();
Deque<ICommandArgument> getConsumed();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>at least</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMost(int)
* @see #hasExactly(int)
*/
boolean has(int num);
/**
* @return {@code true} if there is <i>at least</i> 1 argument left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMostOne()
* @see #hasExactlyOne()
*/
boolean hasAny();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>at most</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMost(int)
* @see #hasExactly(int)
*/
boolean hasAtMost(int num);
/**
* @return {@code true} if there is <i>at most</i> 1 argument left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMostOne()
* @see #hasExactlyOne()
*/
boolean hasAtMostOne();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>exactly</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMost(int)
*/
boolean hasExactly(int num);
/**
* @return {@code true} if there is <i>exactly</i> 1 argument left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMostOne()
*/
boolean hasExactlyOne();
/**
* @param index The index to peek
* @return The argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one. This does not
* mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #peekString(int)
* @see #peekAs(Class, int)
* @see #get()
*/
ICommandArgument peek(int index) throws CommandNotEnoughArgumentsException;
/**
* @return The next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peek(int)
* @see #peekString()
* @see #peekAs(Class)
* @see #get()
*/
ICommandArgument peek() throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param type The type to check for
* @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next
* argument
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #getAs(Class)
*/
boolean is(Class<?> type, int index) throws CommandNotEnoughArgumentsException;
/**
* @param type The type to check for
* @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next
* argument
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peek()
* @see #getAs(Class)
*/
boolean is(Class<?> type) throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @return The value of the argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one
* This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #peekString()
*/
String peekString(int index) throws CommandNotEnoughArgumentsException;
/**
* @return The value of the next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peekString(int)
* @see #getString()
*/
String peekString() throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value
* @throws java.util.NoSuchElementException If the constant couldn't be found
* @see #peekEnumOrNull(Class)
* @see #getEnum(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnum(Class<E> enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see #peekEnumOrNull(Class)
* @see #getEnum(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnum(Class<E> enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value. If no constant could be found, null
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnumOrNull(Class<E> enumClass, int index) throws CommandNotEnoughArgumentsException;
/**
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value. If no constant could be found, null
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnumOrNull(Class<E> enumClass) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param index The index to peek
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T peekAs(Class<T> type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #peekAs(Class, int)
* @see #peekAsOrDefault(Class, Object)
* @see #peekAsOrNull(Class)
*/
<T> T peekAs(Class<T> type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The value to return if the argument can't be parsed
* @param index The index to peek
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrDefault(Class, Object)
* @see #peekAs(Class, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T peekAsOrDefault(Class<T> type, T def, int index) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The value to return if the argument can't be parsed
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAs(Class)
* @see #peekAsOrNull(Class)
*/
<T> T peekAsOrDefault(Class<T> type, T def) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param index The index to peek
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrNull(Class)
* @see #peekAs(Class, int)
* @see #peekAsOrDefault(Class, Object, int)
*/
<T> T peekAsOrNull(Class<T> type, int index) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrNull(Class, int)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object)
*/
<T> T peekAsOrNull(Class<T> type) throws CommandNotEnoughArgumentsException;
<T> T peekDatatype(IDatatypeFor<T> datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O> T peekDatatype(IDatatypePost<T, O> datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O> T peekDatatype(IDatatypePost<T, O> datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T> T peekDatatypeOrNull(IDatatypeFor<T> datatype);
<T, O> T peekDatatypeOrNull(IDatatypePost<T, O> datatype);
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePostOrDefault(D datatype, O original, T def);
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePostOrNull(D datatype, O original);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @return The datatype instance
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeFor(Class<D> datatype);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @param def The default value
* @return The datatype instance, or {@code def} if it throws an exception
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeForOrDefault(Class<D> datatype, T def);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @return The datatype instance, or {@code null} if it throws an exception
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeForOrNull(Class<D> datatype);
/**
* Gets the next argument and returns it. This consumes the first argument so that subsequent calls will return
* later arguments
*
* @return The next argument
* @throws CommandNotEnoughArgumentsException If there's less than one argument left
*/
ICommandArgument get() throws CommandNotEnoughArgumentsException;
/**
* Gets the value of the next argument and returns it. This consumes the first argument so that subsequent calls
* will return later arguments
*
* @return The value of the next argument
* @throws CommandNotEnoughArgumentsException If there's less than one argument left
*/
String getString() throws CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link Direction#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnum(Class<E> enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link Direction#UP}
*
* @param enumClass The enum class to search
* @param def The default value
* @return An enum constant of that class with the same name as the next argument's value, or {@code def} if it
* couldn't be found
* @see #getEnum(Class)
* @see #getEnumOrNull(Class)
* @see #peekEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnumOrDefault(Class<E> enumClass, E def) throws CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link Direction#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value, or {@code null} if it
* couldn't be found
* @see #getEnum(Class)
* @see #getEnumOrDefault(Class, Enum)
* @see #peekEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnumOrNull(Class<E> enumClass) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #get()
* @see #getAsOrDefault(Class, Object)
* @see #getAsOrNull(Class)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAs(Class<T> type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The default value
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #get()
* @see #getAs(Class)
* @see #getAsOrNull(Class)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAsOrDefault(Class<T> type, T def) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #get()
* @see #getAs(Class)
* @see #getAsOrDefault(Class, Object)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAsOrNull(Class<T> type) throws CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T getDatatypePostOrDefault(D datatype, O original, T _default);
<T, O, D extends IDatatypePost<T, O>> T getDatatypePostOrNull(D datatype, O original);
<T, D extends IDatatypeFor<T>> T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, D extends IDatatypeFor<T>> T getDatatypeForOrDefault(D datatype, T def);
<T, D extends IDatatypeFor<T>> T getDatatypeForOrNull(D datatype);
<T extends IDatatype> Stream<String> tabCompleteDatatype(T datatype);
/**
* Returns the "raw rest" of the string. For example, from a string <code>arg1 arg2&nbsp;&nbsp;arg3</code>, split
* into three {@link ICommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}:
*
* <ul>
* <li>{@code rawRest()} would return <code>arg1 arg2&nbsp;&nbsp;arg3</code></li>
* <li>After calling {@link #get()}, {@code rawRest()} would return <code>arg2&nbsp;&nbsp;arg3</code> (note the
* double space - it is preserved!)</li>
* <li>After calling {@link #get()} again, {@code rawRest()} would return {@code "arg3"}</li>
* <li>After calling {@link #get()} one last time, {@code rawRest()} would return {@code ""}</li>
* </ul>
*
* @return The "raw rest" of the string.
*/
String rawRest();
/**
* @param min The minimum amount of arguments to require.
* @throws CommandNotEnoughArgumentsException If there are less than {@code min} arguments left.
* @see #requireMax(int)
* @see #requireExactly(int)
*/
void requireMin(int min) throws CommandNotEnoughArgumentsException;
/**
* @param max The maximum amount of arguments allowed.
* @throws CommandTooManyArgumentsException If there are more than {@code max} arguments left.
* @see #requireMin(int)
* @see #requireExactly(int)
*/
void requireMax(int max) throws CommandTooManyArgumentsException;
/**
* @param args The exact amount of arguments to require.
* @throws CommandNotEnoughArgumentsException If there are less than {@code args} arguments left.
* @throws CommandTooManyArgumentsException If there are more than {@code args} arguments left.
* @see #requireMin(int)
* @see #requireMax(int)
*/
void requireExactly(int args) throws CommandException;
/**
* @return If this {@link IArgConsumer}} has consumed at least one argument.
* @see #consumed()
* @see #consumedString()
*/
boolean hasConsumed();
/**
* @return The last argument this {@link IArgConsumer}} has consumed, or an "unknown" argument, indicated by a
* comamnd argument index that has a value of {@code -1}, if no arguments have been consumed yet.
* @see #consumedString()
* @see #hasConsumed()
*/
ICommandArgument consumed();
/**
* @return The value of thelast argument this {@link IArgConsumer}} has consumed, or an empty string if no arguments
* have been consumed yet
* @see #consumed()
* @see #hasConsumed()
*/
String consumedString();
/**
* @return A copy of this {@link IArgConsumer}}. It has the same arguments (both consumed and not), but does not
* affect or mutate this instance. Useful for the various {@code peek} functions
*/
IArgConsumer copy();
}

View File

@@ -0,0 +1,101 @@
/*
* 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.command.argument;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.exception.CommandInvalidTypeException;
import net.minecraft.util.Direction;
/**
* A {@link ICommandArgument} is an immutable object representing one command argument. It contains data on the index of
* that argument, its value, and the rest of the string that argument was found in
* <p>
* You're recommended to use {@link IArgConsumer}}s to handle these.
*
* @author Brady
* @since 10/2/2019
*/
public interface ICommandArgument {
/**
* @return The index of this command argument in the list of command arguments generated
*/
int getIndex();
/**
* @return The raw value of just this argument
*/
String getValue();
/**
* @return The raw value of the remaining arguments after this one was captured
*/
String getRawRest();
/**
* Gets an enum value from the enum class with the same name as this argument's value
* <p>
* For example if you getEnum as an {@link Direction}, and this argument's value is "up", it will return {@link
* Direction#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as this argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see IArgConsumer#peekEnum(Class)
* @see IArgConsumer#peekEnum(Class, int)
* @see IArgConsumer#peekEnumOrNull(Class)
* @see IArgConsumer#peekEnumOrNull(Class, int)
* @see IArgConsumer#getEnum(Class)
* @see IArgConsumer#getEnumOrNull(Class)
*/
<E extends Enum<?>> E getEnum(Class<E> enumClass) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
*/
<T> T getAs(Class<T> type) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return If the parser succeeded
*/
<T> boolean is(Class<T> type);
/**
* Tries to use a <b>stated</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
*/
<T, S> T getAs(Class<T> type, Class<S> stateType, S state) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stated</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return If the parser succeeded
*/
<T, S> boolean is(Class<T> type, Class<S> stateType, S state);
}

View File

@@ -0,0 +1,53 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import java.util.stream.Stream;
public enum BlockById implements IDatatypeFor<Block> {
INSTANCE;
@Override
public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Block block;
if ((block = Registry.BLOCK.getValue(id).orElse(null)) == null) {
throw new IllegalArgumentException("no block found by that id");
}
return block;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(
Registry.BLOCK.keySet()
.stream()
.map(Object::toString)
)
.filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import java.util.stream.Stream;
public enum EntityClassById implements IDatatypeFor<EntityType> {
INSTANCE;
@Override
public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
EntityType entity;
if ((entity = Registry.ENTITY_TYPE.getValue(id).orElse(null)) == null) {
throw new IllegalArgumentException("no entity found by that id");
}
return entity;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(Registry.ENTITY_TYPE.stream().map(Object::toString))
.filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.command.datatypes;
import baritone.api.utils.BlockOptionalMeta;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
public enum ForBlockOptionalMeta implements IDatatypeFor<BlockOptionalMeta> {
INSTANCE;
@Override
public BlockOptionalMeta get(IDatatypeContext ctx) throws CommandException {
return new BlockOptionalMeta(ctx.getConsumer().getString());
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
return ctx.getConsumer().tabCompleteDatatype(BlockById.INSTANCE);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.Direction;
import java.util.Locale;
import java.util.stream.Stream;
public enum ForDirection implements IDatatypeFor<Direction> {
INSTANCE;
@Override
public Direction get(IDatatypeContext ctx) throws CommandException {
return Direction.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US));
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(Stream.of(Direction.values())
.map(Direction::getName).map(String::toLowerCase))
.filterPrefix(ctx.getConsumer().getString())
.stream();
}
}

View File

@@ -0,0 +1,81 @@
/*
* 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.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.cache.IWaypoint;
import baritone.api.cache.IWaypointCollection;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
import java.util.Comparator;
import java.util.stream.Stream;
public enum ForWaypoints implements IDatatypeFor<IWaypoint[]> {
INSTANCE;
@Override
public IWaypoint[] get(IDatatypeContext ctx) throws CommandException {
final String input = ctx.getConsumer().getString();
final IWaypoint.Tag tag = IWaypoint.Tag.getByName(input);
// If the input doesn't resolve to a valid tag, resolve by name
return tag == null
? getWaypointsByName(ctx.getBaritone(), input)
: getWaypointsByTag(ctx.getBaritone(), tag);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(getWaypointNames(ctx.getBaritone()))
.sortAlphabetically()
.prepend(IWaypoint.Tag.getAllNames())
.filterPrefix(ctx.getConsumer().getString())
.stream();
}
public static IWaypointCollection waypoints(IBaritone baritone) {
return baritone.getWorldProvider().getCurrentWorld().getWaypoints();
}
public static IWaypoint[] getWaypoints(IBaritone baritone) {
return waypoints(baritone).getAllWaypoints().stream()
.sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed())
.toArray(IWaypoint[]::new);
}
public static String[] getWaypointNames(IBaritone baritone) {
return Stream.of(getWaypoints(baritone))
.map(IWaypoint::getName)
.filter(name -> !name.isEmpty())
.toArray(String[]::new);
}
public static IWaypoint[] getWaypointsByTag(IBaritone baritone, IWaypoint.Tag tag) {
return waypoints(baritone).getByTag(tag).stream()
.sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed())
.toArray(IWaypoint[]::new);
}
public static IWaypoint[] getWaypointsByName(IBaritone baritone, String name) {
return Stream.of(getWaypoints(baritone))
.filter(waypoint -> waypoint.getName().equalsIgnoreCase(name))
.toArray(IWaypoint[]::new);
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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.command.datatypes;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
/**
* An {@link IDatatype} is similar to an {@link IArgParser} in the sense that it is capable of consuming an argument
* to transform it into a usable form as the code desires.
* <p>
* A fundamental difference is that an {@link IDatatype} is capable of consuming multiple arguments. For example,
* {@link RelativeBlockPos} is an {@link IDatatypePost} which requires at least 3 {@link RelativeCoordinate} arguments
* to be specified.
* <p>
* Another difference is that an {@link IDatatype} can be tab-completed, providing comprehensive auto completion
* that can substitute based on existing input or provide possibilities for the next piece of input.
*
* @see IDatatypeContext
* @see IDatatypeFor
* @see IDatatypePost
*/
public interface IDatatype {
/**
* Attempts to complete missing or partial input provided through the {@link IArgConsumer}} provided by
* {@link IDatatypeContext#getConsumer()} in order to aide the user in executing commands.
* <p>
* One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values
* the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide
* accurate information using the same methods used to parse arguments in the first place.
*
* @param ctx The argument consumer to tab complete
* @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS.
* @see IArgConsumer#tabCompleteDatatype(IDatatype)
*/
Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException;
}

View File

@@ -0,0 +1,47 @@
/*
* 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.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.command.argument.IArgConsumer;
/**
* Provides an {@link IDatatype} with contextual information so
* that it can perform the desired operation on the target level.
*
* @see IDatatype
*
* @author Brady
* @since 9/26/2019
*/
public interface IDatatypeContext {
/**
* Provides the {@link IBaritone} instance that is associated with the action relating to datatype handling.
*
* @return The context {@link IBaritone} instance.
*/
IBaritone getBaritone();
/**
* Provides the {@link IArgConsumer}} to fetch input information from.
*
* @return The context {@link IArgConsumer}}.
*/
IArgConsumer getConsumer();
}

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.command.datatypes;
import baritone.api.command.exception.CommandException;
import java.util.function.Supplier;
/**
* An {@link IDatatype} which acts as a {@link Supplier}, in essence. The only difference
* is that it requires an {@link IDatatypeContext} to be provided due to the expectation that
* implementations of {@link IDatatype} are singletons.
*/
public interface IDatatypeFor<T> extends IDatatype {
/**
* Consumes the desired amount of arguments from the specified {@link IDatatypeContext}, and
* then returns the parsed value. This method will more than likely return a {@link IllegalArgumentException}
* if the expected input does not conform to a parseable value. As far as a {@link CommandException} being
* thrown is concerned, see the note below for specifics.
*
* @see IDatatypeContext
*
* @param ctx The context
* @return The parsed data-type
* @throws CommandException If there was an issue parsing using another type or arguments could not be polled.
*/
T get(IDatatypeContext ctx) throws CommandException;
}

View File

@@ -0,0 +1,41 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
import java.util.function.Function;
/**
* An {@link IDatatype} which acts as a {@link Function}, in essence. The only difference
* is that it requires an {@link IDatatypeContext} to be provided due to the expectation that
* implementations of {@link IDatatype} are singletons.
*/
public interface IDatatypePost<T, O> extends IDatatype {
/**
* Takes the expected input and transforms it based on the value held by {@code original}. If {@code original}
* is null, it is expected that the implementation of this method has a case to handle it, such that a
* {@link NullPointerException} will never be thrown as a result.
*
* @param ctx The datatype context
* @param original The transformable value
* @return The transformed value
*/
T apply(IDatatypeContext ctx, O original) throws CommandException;
}

View File

@@ -0,0 +1,29 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
/**
* @author Brady
* @since 9/26/2019
*/
public interface IDatatypePostFunction<T, O> {
T apply(O original) throws CommandException;
}

View File

@@ -0,0 +1,56 @@
/*
* 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.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.text.ITextComponent;
import java.util.List;
import java.util.stream.Stream;
/**
* An {@link IDatatype} used to resolve nearby players, those within
* render distance of the target {@link IBaritone} instance.
*/
public enum NearbyPlayer implements IDatatypeFor<PlayerEntity> {
INSTANCE;
@Override
public PlayerEntity get(IDatatypeContext ctx) throws CommandException {
final String username = ctx.getConsumer().getString();
return getPlayers(ctx).stream()
.filter(s -> s.getName().getString().equalsIgnoreCase(username))
.findFirst().orElse(null);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(getPlayers(ctx).stream().map(PlayerEntity::getName).map(ITextComponent::getString))
.filterPrefix(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
private static List<? extends PlayerEntity> getPlayers(IDatatypeContext ctx) {
return ctx.getBaritone().getPlayerContext().world().getPlayers();
}
}

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.api.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
public enum RelativeBlockPos implements IDatatypePost<BetterBlockPos, BetterBlockPos> {
INSTANCE;
@Override
public BetterBlockPos apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
return new BetterBlockPos(
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x),
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y),
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z)
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAny() && !consumer.has(4)) {
while (consumer.has(2)) {
if (consumer.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) {
break;
}
consumer.get();
}
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,64 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public enum RelativeCoordinate implements IDatatypePost<Double, Double> {
INSTANCE;
private static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)([k-k]?)|)$");
@Override
public Double apply(IDatatypeContext ctx, Double origin) throws CommandException {
if (origin == null) {
origin = 0.0D;
}
Matcher matcher = PATTERN.matcher(ctx.getConsumer().getString());
if (!matcher.matches()) {
throw new IllegalArgumentException("pattern doesn't match");
}
boolean isRelative = !matcher.group(1).isEmpty();
double offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2).replaceAll("k", ""));
if (matcher.group(2).contains("k")) {
offset *= 1000;
}
if (isRelative) {
return origin + offset;
}
return offset;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
final IArgConsumer consumer = ctx.getConsumer();
if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) {
return Stream.of("~");
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystems;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Stream;
import static baritone.api.utils.Helper.HELPER;
public enum RelativeFile implements IDatatypePost<File, File> {
INSTANCE;
@Override
public File apply(IDatatypeContext ctx, File original) throws CommandException {
if (original == null) {
original = new File("./");
}
Path path;
try {
path = FileSystems.getDefault().getPath(ctx.getConsumer().getString());
} catch (InvalidPathException e) {
throw new IllegalArgumentException("invalid path");
}
return getCanonicalFileUnchecked(original.toPath().resolve(path).toFile());
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
return Stream.empty();
}
/**
* Seriously
*
* @param file File
* @return Canonical file of file
* @author LoganDark
*/
private static File getCanonicalFileUnchecked(File file) {
try {
return file.getCanonicalFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static Stream<String> tabComplete(IArgConsumer consumer, File base0) throws CommandException {
// I will not make the caller deal with this, seriously
// Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit -LoganDark
// lol owned -Brady
File base = getCanonicalFileUnchecked(base0);
String currentPathStringThing = consumer.getString();
Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing);
Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath();
boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator);
File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing);
return Stream.of(Objects.requireNonNull(getCanonicalFileUnchecked(
useParent
? currentFile.getParentFile()
: currentFile
).listFiles()))
.map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) +
(f.isDirectory() ? File.separator : ""))
.filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US)))
.filter(s -> !s.contains(" "));
}
public static File gameDir() {
File gameDir = HELPER.mc.gameDir.getAbsoluteFile();
if (gameDir.getName().equals(".")) {
return gameDir.getParentFile();
}
return gameDir;
}
}

View File

@@ -0,0 +1,67 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.pathing.goals.GoalYLevel;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public enum RelativeGoal implements IDatatypePost<Goal, BetterBlockPos> {
INSTANCE;
@Override
public Goal apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
GoalBlock goalBlock = consumer.peekDatatypePostOrNull(RelativeGoalBlock.INSTANCE, origin);
if (goalBlock != null) {
return goalBlock;
}
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
public Stream<String> tabComplete(IDatatypeContext ctx) {
return ctx.getConsumer().tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalBlock implements IDatatypePost<GoalBlock, BetterBlockPos> {
INSTANCE;
@Override
public GoalBlock apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
return new GoalBlock(
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))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(3)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalXZ implements IDatatypePost<GoalXZ, BetterBlockPos> {
INSTANCE;
@Override
public GoalXZ apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
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.z))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(2)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalYLevel;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalYLevel implements IDatatypePost<GoalYLevel, BetterBlockPos> {
INSTANCE;
@Override
public GoalYLevel apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
return new GoalYLevel(
MathHelper.floor(ctx.getConsumer().getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(1)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.command.exception;
public abstract class CommandErrorMessageException extends CommandException {
protected CommandErrorMessageException(String reason) {
super(reason);
}
protected CommandErrorMessageException(String reason, Throwable cause) {
super(reason, cause);
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.command.exception;
public abstract class CommandException extends Exception implements ICommandException {
protected CommandException(String reason) {
super(reason);
}
protected CommandException(String reason, Throwable cause) {
super(reason, cause);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.command.exception;
import baritone.api.command.argument.ICommandArgument;
public abstract class CommandInvalidArgumentException extends CommandErrorMessageException {
public final ICommandArgument arg;
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

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandInvalidStateException extends CommandErrorMessageException {
public CommandInvalidStateException(String reason) {
super(reason);
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.command.exception;
import baritone.api.command.argument.ICommandArgument;
public class CommandInvalidTypeException extends CommandInvalidArgumentException {
public CommandInvalidTypeException(ICommandArgument arg, String expected) {
super(arg, String.format("Expected %s", expected));
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) {
super(arg, String.format("Expected %s", expected), cause);
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) {
super(arg, String.format("Expected %s, but got %s instead", expected, got));
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) {
super(arg, String.format("Expected %s, but got %s instead", expected, got), cause);
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandNoParserForTypeException extends CommandUnhandledException {
public CommandNoParserForTypeException(Class<?> klass) {
super(String.format("Could not find a handler for type %s", klass.getSimpleName()));
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandNotEnoughArgumentsException extends CommandErrorMessageException {
public CommandNotEnoughArgumentsException(int minArgs) {
super(String.format("Not enough arguments (expected at least %d)", minArgs));
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
public class CommandNotFoundException extends CommandException {
public final String command;
public CommandNotFoundException(String command) {
super(String.format("Command not found: %s", command));
this.command = command;
}
@Override
public void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect(getMessage());
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandTooManyArgumentsException extends CommandErrorMessageException {
public CommandTooManyArgumentsException(int maxArgs) {
super(String.format("Too many arguments (expected at most %d)", maxArgs));
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import net.minecraft.util.text.TextFormatting;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
public class CommandUnhandledException extends RuntimeException implements ICommandException {
public CommandUnhandledException(String message) {
super(message);
}
public CommandUnhandledException(Throwable cause) {
super(cause);
}
@Override
public void handle(ICommand command, List<ICommandArgument> args) {
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);
this.printStackTrace();
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import net.minecraft.util.text.TextFormatting;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
/**
* The base for a Baritone Command Exception, checked or unchecked. Provides a
* {@link #handle(ICommand, List)} method that is used to provide useful output
* to the user for diagnosing issues that may have occurred during execution.
* <p>
* Anything implementing this interface should be assignable to {@link Exception}.
*
* @author Brady
* @since 9/20/2019
*/
public interface ICommandException {
/**
* @see Exception#getMessage()
* @return The exception details
*/
String getMessage();
/**
* Called when this exception is thrown, to handle the exception.
*
* @param command The command that threw it.
* @param args The arguments the command was called with.
*/
default void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect(this.getMessage(), TextFormatting.RED);
}
}

View File

@@ -0,0 +1,184 @@
/*
* 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.command.helpers;
import baritone.api.utils.Helper;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.argument.IArgConsumer;
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 net.minecraft.util.text.event.HoverEvent;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class Paginator<E> implements Helper {
public final List<E> entries;
public int pageSize = 8;
public int page = 1;
public Paginator(List<E> entries) {
this.entries = entries;
}
public Paginator(E... entries) {
this.entries = Arrays.asList(entries);
}
public Paginator<E> setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public int getMaxPage() {
return (entries.size() - 1) / pageSize + 1;
}
public boolean validPage(int page) {
return page > 0 && page <= getMaxPage();
}
public Paginator<E> skipPages(int pages) {
page += pages;
return this;
}
public void display(Function<E, ITextComponent> transform, String commandPrefix) {
int offset = (page - 1) * pageSize;
for (int i = offset; i < offset + pageSize; i++) {
if (i < entries.size()) {
logDirect(transform.apply(entries.get(i)));
} else {
logDirect("--", TextFormatting.DARK_GRAY);
}
}
boolean hasPrevPage = commandPrefix != null && validPage(page - 1);
boolean hasNextPage = commandPrefix != null && validPage(page + 1);
ITextComponent prevPageComponent = new StringTextComponent("<<");
if (hasPrevPage) {
prevPageComponent.getStyle()
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format("%s %d", commandPrefix, page - 1)
))
.setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new StringTextComponent("Click to view previous page")
));
} else {
prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
}
ITextComponent nextPageComponent = new StringTextComponent(">>");
if (hasNextPage) {
nextPageComponent.getStyle()
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format("%s %d", commandPrefix, page + 1)
))
.setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new StringTextComponent("Click to view next page")
));
} else {
nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
}
ITextComponent pagerComponent = new StringTextComponent("");
pagerComponent.getStyle().setColor(TextFormatting.GRAY);
pagerComponent.appendSibling(prevPageComponent);
pagerComponent.appendText(" | ");
pagerComponent.appendSibling(nextPageComponent);
pagerComponent.appendText(String.format(" %d/%d", page, getMaxPage()));
logDirect(pagerComponent);
}
public void display(Function<E, ITextComponent> transform) {
display(transform, null);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
int page = 1;
consumer.requireMax(1);
if (consumer.hasAny()) {
page = consumer.getAs(Integer.class);
if (!pagi.validPage(page)) {
throw new CommandInvalidTypeException(
consumer.consumed(),
String.format(
"a valid page (1-%d)",
pagi.getMaxPage()
),
consumer.consumed().getValue()
);
}
}
pagi.skipPages(page - pagi.page);
if (pre != null) {
pre.run();
}
pagi.display(transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, new Paginator<>(elems), pre, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, Arrays.asList(elems), pre, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, pagi, null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, new Paginator<>(elems), null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, Arrays.asList(elems), null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, pagi, pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, new Paginator<>(elems), pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, Arrays.asList(elems), pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, pagi, null, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, new Paginator<>(elems), null, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, Arrays.asList(elems), null, transform, null);
}
}

View File

@@ -0,0 +1,288 @@
/*
* 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.command.helpers;
import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import baritone.api.event.events.TabCompleteEvent;
import baritone.api.utils.SettingsUtil;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.manager.ICommandManager;
import net.minecraft.util.ResourceLocation;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* The {@link TabCompleteHelper} is a <b>single-use</b> object that helps you handle tab completion. It includes helper
* methods for appending and prepending streams, sorting, filtering by prefix, and so on.
* <p>
* The recommended way to use this class is:
* <ul>
* <li>Create a new instance with the empty constructor</li>
* <li>Use {@code append}, {@code prepend} or {@code add<something>} methods to add completions</li>
* <li>Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using
* {@link #filterPrefix(String)}</li>
* <li>Get the stream using {@link #stream()}</li>
* <li>Pass it up to whatever's calling your tab complete function (i.e.
* {@link ICommandManager#tabComplete(String)} or {@link IArgConsumer}#tabCompleteDatatype(IDatatype)})</li>
* </ul>
* <p>
* For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an
* array.
*/
public class TabCompleteHelper {
private Stream<String> stream;
public TabCompleteHelper(String[] base) {
stream = Stream.of(base);
}
public TabCompleteHelper(List<String> base) {
stream = base.stream();
}
public TabCompleteHelper() {
stream = Stream.empty();
}
/**
* Appends the specified stream to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to append
* @return This {@link TabCompleteHelper} after having appended the stream
* @see #append(String...)
* @see #append(Class)
*/
public TabCompleteHelper append(Stream<String> source) {
stream = Stream.concat(stream, source);
return this;
}
/**
* Appends the specified strings to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to append
* @return This {@link TabCompleteHelper} after having appended the strings
* @see #append(Stream)
* @see #append(Class)
*/
public TabCompleteHelper append(String... source) {
return append(Stream.of(source));
}
/**
* Appends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining
*
* @param num The enum to append the values of
* @return This {@link TabCompleteHelper} after having appended the values
* @see #append(Stream)
* @see #append(String...)
*/
public TabCompleteHelper append(Class<? extends Enum<?>> num) {
return append(
Stream.of(num.getEnumConstants())
.map(Enum::name)
.map(String::toLowerCase)
);
}
/**
* Prepends the specified stream to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to prepend
* @return This {@link TabCompleteHelper} after having prepended the stream
* @see #prepend(String...)
* @see #prepend(Class)
*/
public TabCompleteHelper prepend(Stream<String> source) {
stream = Stream.concat(source, stream);
return this;
}
/**
* Prepends the specified strings to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to prepend
* @return This {@link TabCompleteHelper} after having prepended the strings
* @see #prepend(Stream)
* @see #prepend(Class)
*/
public TabCompleteHelper prepend(String... source) {
return prepend(Stream.of(source));
}
/**
* Prepends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining
*
* @param num The enum to prepend the values of
* @return This {@link TabCompleteHelper} after having prepended the values
* @see #prepend(Stream)
* @see #prepend(String...)
*/
public TabCompleteHelper prepend(Class<? extends Enum<?>> num) {
return prepend(
Stream.of(num.getEnumConstants())
.map(Enum::name)
.map(String::toLowerCase)
);
}
/**
* Apply the specified {@code transform} to every element <b>currently</b> in this {@link TabCompleteHelper} and
* return this object for chaining
*
* @param transform The transform to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper map(Function<String, String> transform) {
stream = stream.map(transform);
return this;
}
/**
* Apply the specified {@code filter} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param filter The filter to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filter(Predicate<String> filter) {
stream = stream.filter(filter);
return this;
}
/**
* Apply the specified {@code sort} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param comparator The comparator to use
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sort(Comparator<String> comparator) {
stream = stream.sorted(comparator);
return this;
}
/**
* Sort every element <b>currently</b> in this {@link TabCompleteHelper} alphabetically and return this object for
* chaining
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sortAlphabetically() {
return sort(String.CASE_INSENSITIVE_ORDER);
}
/**
* Filter out any element that doesn't start with {@code prefix} and return this object for chaining
*
* @param prefix The prefix to filter for
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filterPrefix(String prefix) {
return filter(x -> x.toLowerCase(Locale.US).startsWith(prefix.toLowerCase(Locale.US)));
}
/**
* Filter out any element that doesn't start with {@code prefix} and return this object for chaining
* <p>
* Assumes every element in this {@link TabCompleteHelper} is a {@link ResourceLocation}
*
* @param prefix The prefix to filter for
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filterPrefixNamespaced(String prefix) {
return filterPrefix(new ResourceLocation(prefix).toString());
}
/**
* @return An array containing every element in this {@link TabCompleteHelper}
* @see #stream()
*/
public String[] build() {
return stream.toArray(String[]::new);
}
/**
* @return A stream containing every element in this {@link TabCompleteHelper}
* @see #build()
*/
public Stream<String> stream() {
return stream;
}
/**
* Appends every command in the specified {@link ICommandManager} to this {@link TabCompleteHelper}
*
* @param manager A command manager
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addCommands(ICommandManager manager) {
return append(manager.getRegistry().descendingStream()
.flatMap(command -> command.getNames().stream())
.distinct()
);
}
/**
* Appends every setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addSettings() {
return append(
BaritoneAPI.getSettings().allSettings.stream()
.map(Settings.Setting::getName)
.filter(s -> !s.equalsIgnoreCase("logger"))
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
/**
* Appends every modified setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addModifiedSettings() {
return append(
SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream()
.map(Settings.Setting::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
/**
* Appends every {@link Boolean} setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addToggleableSettings() {
return append(
BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream()
.map(Settings.Setting::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.command.manager;
import baritone.api.IBaritone;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.registry.Registry;
import net.minecraft.util.Tuple;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Brady
* @since 9/21/2019
*/
public interface ICommandManager {
IBaritone getBaritone();
Registry<ICommand> getRegistry();
/**
* @param name The command name to search for.
* @return The command, if found.
*/
ICommand getCommand(String name);
boolean execute(String string);
boolean execute(Tuple<String, List<ICommandArgument>> expanded);
Stream<String> tabComplete(Tuple<String, List<ICommandArgument>> expanded);
Stream<String> tabComplete(String prefix);
}

View File

@@ -0,0 +1,135 @@
/*
* 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.command.registry;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This registry class allows for registration and unregistration of a certain type. This is mainly designed for use by
* event handlers where newly registered ones are encountered first during iteration and can therefore override older
* ones. In Baritone, this is used for commands and argument parsers so that mods and addons can extend Baritone's
* functionality without resorting to hacks, wrappers, or mixins.
*
* @param <V> The entry type that will be stored in this registry. This can be anything, really - preferably anything
* that works as a HashMap key, as that's what's used to keep track of which entries are registered or not.
*/
public class Registry<V> {
/**
* An internal linked list of all the entries that are currently registered. This is a linked list so that entries
* can be inserted at the beginning, which means that newer entries are encountered first during iteration. This is
* an important property of the registry that makes it more useful than a simple list, and also the reason it does
* not just use a map.
*/
private final Deque<V> _entries = new LinkedList<>();
/**
* A HashSet containing every entry currently registered. Entries are added to this set when something is registered
* and removed from the set when they are unregistered. An entry being present in this set indicates that it is
* currently registered, can be removed, and should not be reregistered until it is removed.
*/
private final Set<V> registered = new HashSet<>();
/**
* The collection of entries that are currently in this registry. This is a collection (and not a list) because,
* internally, entries are stored in a linked list, which is not the same as a normal list.
*/
public final Collection<V> entries = Collections.unmodifiableCollection(_entries);
/**
* @param entry The entry to check.
* @return If this entry is currently registered in this registry.
*/
public boolean registered(V entry) {
return registered.contains(entry);
}
/**
* Ensures that the entry {@code entry} is registered.
*
* @param entry The entry to register.
* @return A boolean indicating whether or not this is a new registration. No matter the value of this boolean, the
* entry is always guaranteed to now be in this registry. This boolean simply indicates if the entry was <i>not</i>
* in the map prior to this method call.
*/
public boolean register(V entry) {
if (!registered(entry)) {
_entries.addFirst(entry);
registered.add(entry);
return true;
}
return false;
}
/**
* Unregisters this entry from this registry. After this method call, the entry is guaranteed to be removed from the
* registry, since each entry only ever appears once.
*
* @param entry The entry to unregister.
*/
public void unregister(V entry) {
if (registered(entry)) {
return;
}
_entries.remove(entry);
registered.remove(entry);
}
/**
* Returns an iterator that iterates over each entry in this registry, with the newest elements iterated over first.
* Internally, as new elements are prepended to the registry rather than appended to the end, this order is the best
* way to search through the registry if you want to discover newer items first.
*/
public Iterator<V> iterator() {
return _entries.iterator();
}
/**
* Returns an iterator that iterates over each entry in this registry, in the order they were added. Internally,
* this iterates through the registry backwards, as new elements are prepended to the registry rather than appended
* to the end. You should only do this when you need to, for example, list elements in order - it is almost always
* fine to simply use {@link Iterable#forEach(Consumer) forEach} on the {@link #entries} collection instead.
*/
public Iterator<V> descendingIterator() {
return _entries.descendingIterator();
}
/**
* Returns a stream that contains each entry in this registry, with the newest elements ordered first. Internally,
* as new elements are prepended to the registry rather than appended to the end, this order is the best way to
* search through the registry if you want to discover newer items first.
*/
public Stream<V> stream() {
return _entries.stream();
}
/**
* Returns a stream that returns each entry in this registry, in the order they were added. Internally, this orders
* the registry backwards, as new elements are prepended to the registry rather than appended to the end. You should
* only use this when you need to, for example, list elements in order - it is almost always fine to simply use the
* regular {@link #stream()} method instead.
*/
public Stream<V> descendingStream() {
return StreamSupport.stream(Spliterators.spliterator(
descendingIterator(),
_entries.size(),
Spliterator.SIZED | Spliterator.SUBSIZED
), false);
}
}

View File

@@ -17,6 +17,9 @@
package baritone.api.event.events;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.Matrix4f;
/**
* @author Brady
* @since 8/5/2018
@@ -28,8 +31,13 @@ public final class RenderEvent {
*/
private final float partialTicks;
public RenderEvent(float partialTicks) {
private final Matrix4f projectionMatrix;
private final MatrixStack modelViewStack;
public RenderEvent(float partialTicks, MatrixStack modelViewStack, Matrix4f projectionMatrix) {
this.partialTicks = partialTicks;
this.modelViewStack = modelViewStack;
this.projectionMatrix = projectionMatrix;
}
/**
@@ -38,4 +46,12 @@ public final class RenderEvent {
public final float getPartialTicks() {
return this.partialTicks;
}
public MatrixStack getModelViewStack() {
return this.modelViewStack;
}
public Matrix4f getProjectionMatrix() {
return this.projectionMatrix;
}
}

View File

@@ -0,0 +1,35 @@
/*
* 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.event.events;
import baritone.api.event.events.type.Cancellable;
import baritone.api.event.events.type.Overrideable;
/**
* @author LoganDark
*/
public final class TabCompleteEvent extends Cancellable {
public final String prefix;
public String[] completions;
public TabCompleteEvent(String prefix) {
this.prefix = prefix;
this.completions = null;
}
}

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

@@ -0,0 +1,53 @@
/*
* 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.event.events.type;
/**
* @author LoganDark
*/
public class Overrideable<T> {
private T value;
private boolean modified;
public Overrideable(T current) {
value = current;
}
public T get() {
return value;
}
public void set(T newValue) {
value = newValue;
modified = true;
}
public boolean wasModified() {
return modified;
}
@Override
public String toString() {
return String.format(
"Overrideable{modified=%b,value=%s}",
modified,
value.toString()
);
}
}

View File

@@ -39,6 +39,9 @@ public interface AbstractGameEventListener extends IGameEventListener {
@Override
default void onSendChatMessage(ChatEvent event) {}
@Override
default void onPreTabComplete(TabCompleteEvent event) {}
@Override
default void onChunkEvent(ChunkEvent event) {}

View File

@@ -55,6 +55,13 @@ public interface IGameEventListener {
*/
void onSendChatMessage(ChatEvent event);
/**
* Runs whenever the client player tries to tab complete in chat.
*
* @param event The event
*/
void onPreTabComplete(TabCompleteEvent event);
/**
* Runs before and after whenever a chunk is either loaded, unloaded, or populated.
*

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -67,7 +68,12 @@ public class GoalBlock implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalBlock{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalBlock{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
/**

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -61,6 +62,11 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalGetToBlock{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalGetToBlock{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.pathing.goals;
/**
* Invert any goal.
* <p>
* In the old chat control system, #invert just tried to pick a {@link GoalRunAway} that <i>effectively</i> inverted the
* current goal. This goal just reverses the heuristic to act as a TRUE invert. Inverting a Y level? Baritone tries to
* get away from that Y level. Inverting a GoalBlock? Baritone will try to make distance whether it's in the X, Y or Z
* directions. And of course, you can always invert a GoalXZ.
*
* @author LoganDark
*/
public class GoalInverted implements Goal {
public final Goal origin;
public GoalInverted(Goal origin) {
this.origin = origin;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return false;
}
@Override
public double heuristic(int x, int y, int z) {
return -origin.heuristic(x, y, z);
}
@Override
public String toString() {
return String.format("GoalInverted{%s}", origin.toString());
}
}

View File

@@ -17,10 +17,12 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
public class GoalNear implements Goal, IGoalRenderPos {
private final int x;
private final int y;
private final int z;
@@ -56,11 +58,12 @@ public class GoalNear implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalNear{" +
"x=" + x +
", y=" + y +
", z=" + z +
", rangeSq=" + rangeSq +
"}";
return String.format(
"GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z),
rangeSq
);
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.math.BlockPos;
import java.util.Arrays;
@@ -82,7 +83,11 @@ public class GoalRunAway implements Goal {
@Override
public String toString() {
if (maintainY != null) {
return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from);
return String.format(
"GoalRunAwayFromMaintainY y=%s, %s",
SettingsUtil.maybeCensor(maintainY),
Arrays.asList(from)
);
} else {
return "GoalRunAwayFrom" + Arrays.asList(from);
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
@@ -24,6 +25,7 @@ import net.minecraft.util.math.BlockPos;
* Dig a tunnel in a certain direction, but if you have to deviate from the path, go back to where you started
*/
public class GoalStrictDirection implements Goal {
public final int x;
public final int y;
public final int z;
@@ -64,12 +66,13 @@ public class GoalStrictDirection implements Goal {
@Override
public String toString() {
return "GoalStrictDirection{" +
"x=" + x +
", y=" + y +
", z=" + z +
", dx=" + dx +
", dz=" + dz +
"}";
return String.format(
"GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z),
SettingsUtil.maybeCensor(dx),
SettingsUtil.maybeCensor(dz)
);
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -73,6 +74,11 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalTwoBlocks{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalTwoBlocks{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -18,6 +18,8 @@
package baritone.api.pathing.goals;
import baritone.api.BaritoneAPI;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@@ -45,6 +47,11 @@ public class GoalXZ implements Goal {
this.z = z;
}
public GoalXZ(BetterBlockPos pos) {
this.x = pos.x;
this.z = pos.z;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return x == this.x && z == this.z;
@@ -59,7 +66,11 @@ public class GoalXZ implements Goal {
@Override
public String toString() {
return "GoalXZ{x=" + x + ",z=" + z + "}";
return String.format(
"GoalXZ{x=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(z)
);
}
public static double calculate(double xDiff, double zDiff) {
@@ -87,7 +98,7 @@ public class GoalXZ implements Goal {
float theta = (float) Math.toRadians(yaw);
double x = origin.x - MathHelper.sin(theta) * distance;
double z = origin.z + MathHelper.cos(theta) * distance;
return new GoalXZ((int) x, (int) z);
return new GoalXZ(MathHelper.floor(x), MathHelper.floor(z));
}
public int getX() {

View File

@@ -18,6 +18,7 @@
package baritone.api.pathing.goals;
import baritone.api.pathing.movement.ActionCosts;
import baritone.api.utils.SettingsUtil;
/**
* Useful for mining (getting to diamond / iron level)
@@ -59,6 +60,9 @@ public class GoalYLevel implements Goal, ActionCosts {
@Override
public String toString() {
return "GoalYLevel{y=" + level + "}";
return String.format(
"GoalYLevel{y=%s}",
SettingsUtil.maybeCensor(level)
);
}
}

View File

@@ -17,12 +17,14 @@
package baritone.api.process;
import baritone.api.utils.ISchematic;
import baritone.api.schematic.ISchematic;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import java.io.File;
import java.util.List;
/**
* @author Brady
@@ -58,7 +60,16 @@ public interface IBuilderProcess extends IBaritoneProcess {
void pause();
boolean isPaused();
void resume();
void clearArea(BlockPos corner1, BlockPos corner2);
/**
* @return A list of block states that are estimated to be placeable by this builder process. You can use this in
* schematics, for example, to pick a state that the builder process will be happy with, because any variation will
* cause it to give up. This is updated every tick, but only while the builder process is active.
*/
List<BlockState> getApproxPlaceable();
}

View File

@@ -20,6 +20,7 @@ package baritone.api.process;
import java.nio.file.Path;
public interface IExploreProcess extends IBaritoneProcess {
void explore(int centerX, int centerZ);
void applyJsonFilter(Path path, boolean invert) throws Exception;

View File

@@ -18,5 +18,6 @@
package baritone.api.process;
public interface IFarmProcess extends IBaritoneProcess {
void farm();
}

View File

@@ -17,6 +17,7 @@
package baritone.api.process;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.Block;
/**
@@ -24,7 +25,11 @@ import net.minecraft.block.Block;
*/
public interface IGetToBlockProcess extends IBaritoneProcess {
void getToBlock(Block block);
void getToBlock(BlockOptionalMeta block);
default void getToBlock(Block block) {
getToBlock(new BlockOptionalMeta(block));
}
boolean blacklistClosest();
}

View File

@@ -17,8 +17,12 @@
package baritone.api.process;
import baritone.api.utils.BlockOptionalMeta;
import baritone.api.utils.BlockOptionalMetaLookup;
import net.minecraft.block.Block;
import java.util.stream.Stream;
/**
* @author Brady
* @since 9/23/2018
@@ -28,9 +32,9 @@ public interface IMineProcess extends IBaritoneProcess {
/**
* Begin to search for and mine the specified blocks until
* the number of specified items to get from the blocks that
* are mined. This is based on the first target block to mine.
* are mined.
*
* @param quantity The number of items to get from blocks mined
* @param quantity The total number of items to get
* @param blocks The blocks to mine
*/
void mineByName(int quantity, String... blocks);
@@ -41,9 +45,18 @@ public interface IMineProcess extends IBaritoneProcess {
* are mined. This is based on the first target block to mine.
*
* @param quantity The number of items to get from blocks mined
* @param blocks The blocks to mine
* @param filter The blocks to mine
*/
void mine(int quantity, Block... blocks);
void mine(int quantity, BlockOptionalMetaLookup filter);
/**
* Begin to search for and mine the specified blocks.
*
* @param filter The blocks to mine
*/
default void mine(BlockOptionalMetaLookup filter) {
mine(0, filter);
}
/**
* Begin to search for and mine the specified blocks.
@@ -54,6 +67,38 @@ public interface IMineProcess extends IBaritoneProcess {
mineByName(0, blocks);
}
/**
* Begin to search for and mine the specified blocks.
*
* @param boms The blocks to mine
*/
default void mine(int quantity, BlockOptionalMeta... boms) {
mine(quantity, new BlockOptionalMetaLookup(boms));
}
/**
* Begin to search for and mine the specified blocks.
*
* @param boms The blocks to mine
*/
default void mine(BlockOptionalMeta... boms) {
mine(0, boms);
}
/**
* Begin to search for and mine the specified blocks.
*
* @param quantity The total number of items to get
* @param blocks The blocks to mine
*/
default void mine(int quantity, Block... blocks) {
mine(quantity, new BlockOptionalMetaLookup(
Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new)
));
}
/**
* Begin to search for and mine the specified blocks.
*

View File

@@ -15,41 +15,36 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.schematic;
package baritone.api.schematic;
import baritone.api.utils.ISchematic;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
public abstract class AbstractSchematic implements ISchematic {
public class AirSchematic implements ISchematic {
protected int x;
protected int y;
protected int z;
private final int widthX;
private final int heightY;
private final int lengthZ;
public AirSchematic(int widthX, int heightY, int lengthZ) {
this.widthX = widthX;
this.heightY = heightY;
this.lengthZ = lengthZ;
public AbstractSchematic() {
this(0, 0, 0);
}
@Override
public BlockState desiredState(int x, int y, int z) {
return Blocks.AIR.getDefaultState();
public AbstractSchematic(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int widthX() {
return widthX;
return x;
}
@Override
public int heightY() {
return heightY;
return y;
}
@Override
public int lengthZ() {
return lengthZ;
return z;
}
}

View File

@@ -0,0 +1,74 @@
/*
* 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;
import java.util.ArrayList;
import java.util.List;
public class CompositeSchematic extends AbstractSchematic {
private final List<CompositeSchematicEntry> schematics;
private CompositeSchematicEntry[] schematicArr;
private void recalcArr() {
schematicArr = schematics.toArray(new CompositeSchematicEntry[0]);
for (CompositeSchematicEntry entry : schematicArr) {
this.x = Math.max(x, entry.x + entry.schematic.widthX());
this.y = Math.max(y, entry.y + entry.schematic.heightY());
this.z = Math.max(z, entry.z + entry.schematic.lengthZ());
}
}
public CompositeSchematic(int x, int y, int z) {
super(x, y, z);
schematics = new ArrayList<>();
recalcArr();
}
public void put(ISchematic extra, int x, int y, int z) {
schematics.add(new CompositeSchematicEntry(extra, x, y, z));
recalcArr();
}
private CompositeSchematicEntry getSchematic(int x, int y, int z, BlockState currentState) {
for (CompositeSchematicEntry entry : schematicArr) {
if (x >= entry.x && y >= entry.y && z >= entry.z &&
entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) {
return entry;
}
}
return null;
}
@Override
public boolean inSchematic(int x, int y, int z, BlockState currentState) {
CompositeSchematicEntry entry = getSchematic(x, y, z, currentState);
return entry != null && entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState);
}
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
CompositeSchematicEntry entry = getSchematic(x, y, z, current);
if (entry == null) {
throw new IllegalStateException("couldn't find schematic for this position");
}
return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current, approxPlaceable);
}
}

View File

@@ -0,0 +1,33 @@
/*
* 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;
public class CompositeSchematicEntry {
public final ISchematic schematic;
public final int x;
public final int y;
public final int z;
public CompositeSchematicEntry(ISchematic schematic, int x, int y, int z) {
this.schematic = schematic;
this.x = x;
this.y = y;
this.z = z;
}
}

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.api.schematic;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import java.util.List;
public class FillSchematic extends AbstractSchematic {
private final BlockOptionalMeta bom;
public FillSchematic(int x, int y, int z, BlockOptionalMeta bom) {
super(x, y, z);
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;
}
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
if (bom.matches(current)) {
return current;
} else if (current.getBlock() != Blocks.AIR) {
return Blocks.AIR.getDefaultState();
}
for (BlockState placeable : approxPlaceable) {
if (bom.matches(placeable)) {
return placeable;
}
}
return bom.getAnyBlockState();
}
}

View File

@@ -15,14 +15,16 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils;
package baritone.api.schematic;
import net.minecraft.block.BlockState;
import net.minecraft.util.Direction;
import java.util.List;
/**
* Basic representation of a schematic. Provides the dimensions and
* the desired statefor a given position relative to the origin.
* Basic representation of a schematic. Provides the dimensions and the desired state for a given position relative to
* the origin.
*
* @author leijurv
*/
@@ -36,12 +38,13 @@ public interface ISchematic {
* However, in the case of something like a map art, anything that's below the level of the map art doesn't matter,
* so this function should return false in that case. (i.e. it doesn't really have to be air below the art blocks)
*
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @param currentState The current state of that block in the world, or null
* @return Whether or not the specified position is within the bounds of this schematic
*/
default boolean inSchematic(int x, int y, int z) {
default boolean inSchematic(int x, int y, int z, BlockState currentState) {
return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ();
}
@@ -61,12 +64,14 @@ public interface ISchematic {
/**
* Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0).
*
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @param current The current state of that block in the world, or null
* @param approxPlaceable The list of blockstates estimated to be placeable
* @return The desired block state at the specified position
*/
BlockState desiredState(int x, int y, int z);
BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable);
/**
* @return The width (X axis length) of this schematic

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,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 net.minecraft.block.BlockState;
import java.util.List;
public abstract class MaskSchematic extends AbstractSchematic {
private final ISchematic schematic;
public MaskSchematic(ISchematic schematic) {
super(schematic.widthX(), schematic.heightY(), schematic.lengthZ());
this.schematic = schematic;
}
protected abstract boolean partOfMask(int x, int y, int z, BlockState currentState);
@Override
public boolean inSchematic(int x, int y, int z, BlockState currentState) {
return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState);
}
@Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return schematic.desiredState(x, y, z, current, approxPlaceable);
}
}

View File

@@ -0,0 +1,41 @@
/*
* 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.utils.BlockOptionalMetaLookup;
import net.minecraft.block.BlockState;
public class ReplaceSchematic extends MaskSchematic {
private final BlockOptionalMetaLookup filter;
private final Boolean[][][] cache;
public ReplaceSchematic(ISchematic schematic, BlockOptionalMetaLookup filter) {
super(schematic);
this.filter = filter;
this.cache = new Boolean[widthX()][heightY()][lengthZ()];
}
@Override
protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
if (cache[x][y][z] == null) {
cache[x][y][z] = filter.has(currentState);
}
return cache[x][y][z];
}
}

View File

@@ -0,0 +1,32 @@
/*
* 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;
public class ShellSchematic extends MaskSchematic {
public ShellSchematic(ISchematic schematic) {
super(schematic);
}
@Override
protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1;
}
}

View File

@@ -0,0 +1,32 @@
/*
* 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;
public class WallsSchematic extends MaskSchematic {
public WallsSchematic(ISchematic schematic) {
super(schematic);
}
@Override
protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1;
}
}

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

@@ -0,0 +1,91 @@
/*
* 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.selection;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3i;
/**
* A selection is an immutable object representing the current selection. The selection is commonly used for certain
* types of build commands, however it can be used for anything.
*/
public interface ISelection {
/**
* @return The first corner of this selection. This is meant to preserve the user's original first corner.
*/
BetterBlockPos pos1();
/**
* @return The second corner of this selection. This is meant to preserve the user's original second corner.
*/
BetterBlockPos pos2();
/**
* @return The {@link BetterBlockPos} with the lowest x, y, and z position in the selection.
*/
BetterBlockPos min();
/**
* @return The opposite corner from the {@link #min()}.
*/
BetterBlockPos max();
/**
* @return The size of this ISelection.
*/
Vec3i size();
/**
* @return An {@link AxisAlignedBB} encompassing all blocks in this selection.
*/
AxisAlignedBB aabb();
/**
* Returns a new {@link ISelection} expanded in the specified direction by the specified number of blocks.
*
* @param direction The direction to expand the selection.
* @param blocks How many blocks to expand it.
* @return A new selection, expanded as specified.
*/
ISelection expand(Direction direction, int blocks);
/**
* Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks.
* <p>
* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it
* is DOWN, the top of the selection will be shifted down.
*
* @param direction The direction to contract the selection.
* @param blocks How many blocks to contract it.
* @return A new selection, contracted as specified.
*/
ISelection contract(Direction direction, int blocks);
/**
* Returns a new {@link ISelection} shifted in the specified direction by the specified number of blocks. This moves
* the whole selection.
*
* @param direction The direction to shift the selection.
* @param blocks How many blocks to shift it.
* @return A new selection, shifted as specified.
*/
ISelection shift(Direction direction, int blocks);
}

View File

@@ -0,0 +1,116 @@
/*
* 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.selection;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.Direction;
/**
* The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving
* the current selection.
*/
public interface ISelectionManager {
/**
* Adds a new selection. The added selection is returned.
*
* @param selection The new selection to add.
*/
ISelection addSelection(ISelection selection);
/**
* Adds a new {@link ISelection} constructed from the given block positions. The new selection is returned.
*
* @param pos1 One corner of the selection
* @param pos2 The new corner of the selection
*/
ISelection addSelection(BetterBlockPos pos1, BetterBlockPos pos2);
/**
* Removes the selection from the current selections.
*
* @param selection The selection to remove.
* @return The removed selection.
*/
ISelection removeSelection(ISelection selection);
/**
* Removes all selections.
*
* @return The selections that were removed, sorted from oldest to newest..
*/
ISelection[] removeAllSelections();
/**
* @return The current selections, sorted from oldest to newest.
*/
ISelection[] getSelections();
/**
* For anything expecting only one selection, this method is provided. However, to enforce multi-selection support,
* this method will only return a selection if there is ONLY one.
*
* @return The only selection, or null if there isn't only one.
*/
ISelection getOnlySelection();
/**
* This method will always return the last selection. ONLY use this if you want to, for example, modify the most
* recent selection based on user input. ALWAYS use {@link #getOnlySelection()} or, ideally,
* {@link #getSelections()} for retrieving the content of selections.
*
* @return The last selection, or null if it doesn't exist.
*/
ISelection getLastSelection();
/**
* Replaces the specified {@link ISelection} with one expanded in the specified direction by the specified number of
* blocks. Returns the new selection.
*
* @param selection The selection to expand.
* @param direction The direction to expand the selection.
* @param blocks How many blocks to expand it.
* @return The new selection, expanded as specified.
*/
ISelection expand(ISelection selection, Direction direction, int blocks);
/**
* Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number
* of blocks.
* <p>
* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it
* is DOWN, the top of the selection will be shifted down.
*
* @param selection The selection to contract.
* @param direction The direction to contract the selection.
* @param blocks How many blocks to contract it.
* @return The new selection, contracted as specified.
*/
ISelection contract(ISelection selection, Direction direction, int blocks);
/**
* Replaces the specified {@link ISelection} with one shifted in the specified direction by the specified number of
* blocks. This moves the whole selection.
*
* @param selection The selection to shift.
* @param direction The direction to shift the selection.
* @param blocks How many blocks to shift it.
* @return The new selection, shifted as specified.
*/
ISelection shift(ISelection selection, Direction direction, int blocks);
}

View File

@@ -22,6 +22,8 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3i;
import javax.annotation.Nonnull;
/**
* A better BlockPos that has fewer hash collisions (and slightly more performant offsets)
* <p>
@@ -32,6 +34,9 @@ import net.minecraft.util.math.Vec3i;
* @author leijurv
*/
public final class BetterBlockPos extends BlockPos {
public static final BetterBlockPos ORIGIN = new BetterBlockPos(0, 0, 0);
public final int x;
public final int y;
public final int z;
@@ -51,6 +56,20 @@ public final class BetterBlockPos extends BlockPos {
this(pos.getX(), pos.getY(), pos.getZ());
}
/**
* Like constructor but returns null if pos is null, good if you just need to possibly censor coordinates
*
* @param pos The BlockPos, possibly null, to convert
* @return A BetterBlockPos or null if pos was null
*/
public static BetterBlockPos from(BlockPos pos) {
if (pos == null) {
return null;
}
return new BetterBlockPos(pos);
}
@Override
public int hashCode() {
return (int) longHash(x, y, z);
@@ -182,4 +201,15 @@ public final class BetterBlockPos extends BlockPos {
public BetterBlockPos west(int amt) {
return amt == 0 ? this : new BetterBlockPos(x - amt, y, z);
}
@Override
@Nonnull
public String toString() {
return String.format(
"BetterBlockPos{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -0,0 +1,166 @@
/*
* 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.utils;
import baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
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.util.ResourceLocation;
import net.minecraft.util.Unit;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.storage.loot.*;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class BlockOptionalMeta {
private final Block block;
private final Set<BlockState> blockstates;
private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static LootTableManager manager;
private static LootPredicateManager predicate = new LootPredicateManager();
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) {
this.block = block;
this.blockstates = getStates(block);
this.stateHashes = getStateHashes(blockstates);
this.stackHashes = getStackHashes(blockstates);
}
public BlockOptionalMeta(@Nonnull String selector) {
Matcher matcher = pattern.matcher(selector);
if (!matcher.find()) {
throw new IllegalArgumentException("invalid block selector");
}
MatchResult matchResult = matcher.toMatchResult();
block = BlockUtils.stringToBlockRequired(matchResult.group(1));
blockstates = getStates(block);
stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates);
}
private static Set<BlockState> getStates(@Nonnull Block block) {
return new HashSet<>(block.getStateContainer().getValidStates());
}
private static ImmutableSet<Integer> getStateHashes(Set<BlockState> blockstates) {
return ImmutableSet.copyOf(
blockstates.stream()
.map(BlockState::hashCode)
.toArray(Integer[]::new)
);
}
private static ImmutableSet<Integer> getStackHashes(Set<BlockState> blockstates) {
//noinspection ConstantConditions
return ImmutableSet.copyOf(
blockstates.stream()
.flatMap(state -> drops(state.getBlock())
.stream()
.map(item -> new ItemStack(item, 1))
)
.map(stack -> ((IItemStack) (Object) stack).getBaritoneHash())
.toArray(Integer[]::new)
);
}
public Block getBlock() {
return block;
}
public boolean matches(@Nonnull Block block) {
return block == this.block;
}
public boolean matches(@Nonnull BlockState blockstate) {
Block block = blockstate.getBlock();
return block == this.block && stateHashes.contains(blockstate.hashCode());
}
public boolean matches(ItemStack stack) {
//noinspection ConstantConditions
int hash = ((IItemStack) (Object) stack).getBaritoneHash();
hash -= stack.getDamage();
return stackHashes.contains(hash);
}
@Override
public String toString() {
return String.format("BlockOptionalMeta{block=%s}", block);
}
public BlockState getAnyBlockState() {
if (blockstates.size() > 0) {
return blockstates.iterator().next();
}
return null;
}
public static LootTableManager getManager() {
if (manager == null) {
ResourcePackList rpl = new ResourcePackList<>(ResourcePackInfo::new);
rpl.addPackFinder(new ServerPackFinder());
rpl.reloadPacksFromFinders();
IResourcePack thePack = ((ResourcePackInfo) rpl.getAllPacks().iterator().next()).getResourcePack();
IReloadableResourceManager resourceManager = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA, null);
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();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return manager;
}
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) {
return Collections.emptyList();
} else {
return getManager().getLootTableFromLocation(lootTableLocation).generate(new LootContext.Builder(null).withRandom(new Random()).withParameter(LootParameters.POSITION, BlockPos.ZERO).withParameter(LootParameters.TOOL, ItemStack.EMPTY).withNullableParameter(LootParameters.BLOCK_ENTITY, null).withParameter(LootParameters.BLOCK_STATE, block.getDefaultState()).build(LootParameterSets.BLOCK)).stream().map(ItemStack::getItem).collect(Collectors.toList());
}
});
}
}

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.api.utils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class BlockOptionalMetaLookup {
private final BlockOptionalMeta[] boms;
public BlockOptionalMetaLookup(BlockOptionalMeta... boms) {
this.boms = boms;
}
public BlockOptionalMetaLookup(Block... blocks) {
this.boms = Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public BlockOptionalMetaLookup(List<Block> blocks) {
this.boms = blocks.stream()
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public BlockOptionalMetaLookup(String... blocks) {
this.boms = Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public boolean has(Block block) {
for (BlockOptionalMeta bom : boms) {
if (bom.getBlock() == block) {
return true;
}
}
return false;
}
public boolean has(BlockState state) {
for (BlockOptionalMeta bom : boms) {
if (bom.matches(state)) {
return true;
}
}
return false;
}
public boolean has(ItemStack stack) {
for (BlockOptionalMeta bom : boms) {
if (bom.matches(stack)) {
return true;
}
}
return false;
}
public List<BlockOptionalMeta> blocks() {
return Arrays.asList(boms);
}
@Override
public String toString() {
return String.format(
"BlockOptionalMetaLookup{%s}",
Arrays.toString(boms)
);
}
}

View File

@@ -17,16 +17,15 @@
package baritone.api.utils;
import net.minecraft.block.AirBlock;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BlockUtils {
private static transient Map<String, Block> resourceCache = new HashMap<>();
public static String blockToString(Block block) {
@@ -41,7 +40,11 @@ public class BlockUtils {
public static Block stringToBlockRequired(String name) {
Block block = stringToBlockNullable(name);
Objects.requireNonNull(block);
if (block == null) {
throw new IllegalArgumentException(String.format("Invalid block name %s", name));
}
return block;
}
@@ -54,10 +57,7 @@ public class BlockUtils {
if (resourceCache.containsKey(name)) {
return null; // cached as null
}
block = Registry.BLOCK.getOrDefault(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name));
if (block instanceof AirBlock && !name.equals("air")) {
block = null;
}
block = Registry.BLOCK.getValue(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name)).orElse(null);
Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification
copy.put(name, block);
resourceCache = copy;

View File

@@ -1,723 +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.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.Settings;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IRememberedInventory;
import baritone.api.cache.IWaypoint;
import baritone.api.cache.Waypoint;
import baritone.api.event.events.ChatEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.pathing.goals.*;
import baritone.api.process.IBaritoneProcess;
import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IGetToBlockProcess;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientChunkProvider;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
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 net.minecraft.world.chunk.Chunk;
import net.minecraft.world.dimension.DimensionType;
import java.nio.file.Path;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.isNumeric;
public class ExampleBaritoneControl implements Helper, AbstractGameEventListener {
private static final String COMMAND_PREFIX = "#";
public final IBaritone baritone;
public final IPlayerContext ctx;
public ExampleBaritoneControl(IBaritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
baritone.getGameEventHandler().registerEventListener(this);
}
@Override
public void onSendChatMessage(ChatEvent event) {
String msg = event.getMessage();
if (BaritoneAPI.getSettings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) {
if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) {
logDirect("Invalid command");
}
event.cancel(); // always cancel if using prefixControl
return;
}
if (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().removePrefix.value) {
return;
}
if (runCommand(msg)) {
event.cancel();
}
}
public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =)
String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL
IPathingBehavior pathingBehavior = baritone.getPathingBehavior();
ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess();
List<Settings.Setting<Boolean>> toggleable = BaritoneAPI.getSettings().getAllValuesByType(Boolean.class);
for (Settings.Setting<Boolean> setting : toggleable) {
if (msg.equalsIgnoreCase(setting.getName())) {
setting.value ^= true;
logDirect("Toggled " + setting.getName() + " to " + setting.value);
SettingsUtil.save(BaritoneAPI.getSettings());
return true;
}
}
if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) {
logDirect("All settings that have been modified from their default values:");
for (Settings.Setting<?> setting : SettingsUtil.modifiedSettings(BaritoneAPI.getSettings())) {
logDirect(setting.toString());
}
return true;
}
if (msg.startsWith("settings")) {
String rest = msg.substring("settings".length());
try {
int page = Integer.parseInt(rest.trim());
int min = page * 10;
int max = Math.min(BaritoneAPI.getSettings().allSettings.size(), (page + 1) * 10);
logDirect("Settings " + min + " to " + (max - 1) + ":");
for (int i = min; i < max; i++) {
logDirect(BaritoneAPI.getSettings().allSettings.get(i).toString());
}
} catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol
ex.printStackTrace();
logDirect("All settings:");
for (Settings.Setting<?> setting : BaritoneAPI.getSettings().allSettings) {
logDirect(setting.toString());
}
logDirect("To get one page of ten settings at a time, do settings <num>");
}
return true;
}
if (msg.equals("") || msg.equals("help") || msg.equals("?")) {
ITextComponent component = MESSAGE_PREFIX.shallowCopy();
component.getStyle().setColor(TextFormatting.GRAY);
StringTextComponent helpLink = new StringTextComponent(" Click here for instructions on how to use Baritone (https://github.com/cabaletta/baritone/blob/master/USAGE.md)");
helpLink.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/cabaletta/baritone/blob/master/USAGE.md"));
component.appendSibling(helpLink);
BaritoneAPI.getSettings().logger.value.accept(component);
return true;
}
if (msg.contains(" ")) {
String settingName = msg.substring(0, msg.indexOf(' '));
String settingValue = msg.substring(msg.indexOf(' ') + 1);
Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(settingName);
if (setting != null) {
if (settingValue.equals("reset")) {
logDirect("Resetting setting " + settingName + " to default value.");
setting.reset();
} else {
try {
SettingsUtil.parseAndApply(BaritoneAPI.getSettings(), settingName, settingValue);
} catch (Exception ex) {
logDirect("Unable to parse setting");
return true;
}
}
SettingsUtil.save(BaritoneAPI.getSettings());
logDirect(setting.toString());
return true;
}
}
if (BaritoneAPI.getSettings().byLowerName.containsKey(msg)) {
Settings.Setting<?> setting = BaritoneAPI.getSettings().byLowerName.get(msg);
logDirect(setting.toString());
return true;
}
if (msg.startsWith("goal")) {
String rest = msg.substring(4).trim();
Goal goal;
if (rest.equals("clear") || rest.equals("none")) {
goal = null;
} else {
String[] params = rest.split(" ");
if (params[0].equals("")) {
params = new String[]{};
}
goal = parseGoal(params);
if (goal == null) {
return true;
}
}
customGoalProcess.setGoal(goal);
logDirect("Goal: " + goal);
return true;
}
if (msg.equals("crash")) {
StringBuilder meme = new StringBuilder();
CrashReport rep = new CrashReport("Manually triggered debug crash", new Throwable());
mc.addGraphicsAndWorldToCrashReport(rep);
rep.getSectionsInStringBuilder(meme);
System.out.println(meme);
logDirect(meme.toString());
logDirect("ok");
return true;
}
if (msg.equals("path")) {
if (pathingBehavior.getGoal() == null) {
logDirect("No goal.");
} else if (pathingBehavior.getGoal().isInGoal(ctx.playerFeet())) {
logDirect("Already in goal");
} else if (pathingBehavior.isPathing()) {
logDirect("Currently executing a path. Please cancel it first.");
} else {
customGoalProcess.setGoalAndPath(pathingBehavior.getGoal());
}
return true;
}
if (msg.equals("proc")) {
Optional<IBaritoneProcess> proc = baritone.getPathingControlManager().mostRecentInControl();
if (!proc.isPresent()) {
logDirect("No process is in control");
return true;
}
IBaritoneProcess p = proc.get();
logDirect("Class: " + p.getClass());
logDirect("Priority: " + p.priority());
logDirect("Temporary: " + p.isTemporary());
logDirect("Display name: " + p.displayName());
logDirect("Command: " + baritone.getPathingControlManager().mostRecentCommand());
return true;
}
if (msg.equals("version")) {
String version = ExampleBaritoneControl.class.getPackage().getImplementationVersion();
if (version == null) {
logDirect("No version detected. Either dev environment or broken install.");
} else {
logDirect("You are using Baritone v" + version);
}
return true;
}
if (msg.equals("repack") || msg.equals("rescan")) {
ClientChunkProvider cli = (ClientChunkProvider) ctx.world().getChunkProvider();
int playerChunkX = ctx.playerFeet().getX() >> 4;
int playerChunkZ = ctx.playerFeet().getZ() >> 4;
int count = 0;
for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) {
for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) {
Chunk chunk = cli.getChunk(x, z, null, false);
if (chunk != null) {
count++;
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk);
}
}
}
logDirect("Queued " + count + " chunks for repacking");
return true;
}
if (msg.startsWith("build")) {
String file;
BlockPos origin;
try {
String[] coords = msg.substring("build".length()).trim().split(" ");
file = coords[0] + ".schematic";
origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x, 1), parseOrDefault(coords[2], ctx.playerFeet().y, 1), parseOrDefault(coords[3], ctx.playerFeet().z, 1));
} catch (Exception ex) {
file = msg.substring(5).trim() + ".schematic";
origin = ctx.playerFeet();
}
logDirect("Loading '" + file + "' to build from origin " + origin);
boolean success = baritone.getBuilderProcess().build(file, origin);
logDirect(success ? "Loaded" : "Unable to load");
return true;
}
if (msg.startsWith("schematica")) {
baritone.getBuilderProcess().buildOpenSchematic();
return true;
}
if (msg.equals("come")) {
customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(Helper.mc.getRenderViewEntity())));
logDirect("Coming");
return true;
}
if (msg.equals("axis") || msg.equals("highway")) {
customGoalProcess.setGoalAndPath(new GoalAxis());
return true;
}
if (msg.equals("cancel") || msg.equals("stop")) {
pathingBehavior.cancelEverything();
logDirect("ok canceled");
return true;
}
if (msg.equals("forcecancel")) {
pathingBehavior.cancelEverything();
pathingBehavior.forceCancel();
logDirect("ok force canceled");
return true;
}
if (msg.equals("gc")) {
System.gc();
logDirect("Called System.gc();");
return true;
}
if (msg.equals("invert")) {
Goal goal = pathingBehavior.getGoal();
BlockPos runAwayFrom;
if (goal instanceof GoalXZ) {
runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ());
} else if (goal instanceof GoalBlock) {
runAwayFrom = ((GoalBlock) goal).getGoalPos();
} else {
logDirect("Goal must be GoalXZ or GoalBlock to invert");
logDirect("Inverting goal of player feet");
runAwayFrom = ctx.playerFeet();
}
customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) {
@Override
public boolean isInGoal(int x, int y, int z) {
return false;
}
});
return true;
}
if (msg.startsWith("cleararea")) {
String suffix = msg.substring("cleararea".length());
BlockPos corner1;
BlockPos corner2;
if (suffix.isEmpty()) {
// clear the area from the current goal to here
Goal goal = baritone.getPathingBehavior().getGoal();
if (!(goal instanceof GoalBlock)) {
logDirect("Need to specify goal of opposite corner");
return true;
}
corner1 = ((GoalBlock) goal).getGoalPos();
corner2 = ctx.playerFeet();
} else {
try {
String[] spl = suffix.split(" ");
corner1 = ctx.playerFeet();
corner2 = new BlockPos(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]), Integer.parseInt(spl[2]));
} catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {
logDirect("unable to parse");
return true;
}
}
baritone.getBuilderProcess().clearArea(corner1, corner2);
return true;
}
if (msg.equals("resume")) {
baritone.getBuilderProcess().resume();
logDirect("resumed");
return true;
}
if (msg.equals("pause")) {
baritone.getBuilderProcess().pause();
logDirect("paused");
return true;
}
if (msg.equals("reset")) {
for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) {
setting.reset();
}
SettingsUtil.save(BaritoneAPI.getSettings());
logDirect("Baritone settings reset");
return true;
}
if (msg.equals("tunnel")) {
customGoalProcess.setGoalAndPath(new GoalStrictDirection(ctx.playerFeet(), ctx.player().getHorizontalFacing()));
logDirect("tunneling");
return true;
}
if (msg.equals("render")) {
BetterBlockPos pf = ctx.playerFeet();
int dist = (Minecraft.getInstance().gameSettings.renderDistanceChunks + 1) * 16;
Minecraft.getInstance().worldRenderer.markBlockRangeForRenderUpdate(pf.x - dist, pf.y - 256, pf.z - dist, pf.x + dist, pf.y + 256, pf.z + dist);
logDirect("okay");
return true;
}
if (msg.equals("farm")) {
baritone.getFarmProcess().farm();
logDirect("farming");
return true;
}
if (msg.equals("chests")) {
for (Map.Entry<BlockPos, IRememberedInventory> entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) {
logDirect(entry.getKey() + "");
log(entry.getValue().getContents());
}
return true;
}
if (msg.startsWith("followentities")) {
baritone.getFollowProcess().follow(Entity.class::isInstance);
logDirect("Following any entities");
return true;
}
if (msg.startsWith("followplayers")) {
baritone.getFollowProcess().follow(PlayerEntity.class::isInstance); // O P P A
logDirect("Following any players");
return true;
}
if (msg.startsWith("followentity")) {
String name = msg.substring(12).trim();
Optional<Entity> toFollow = Optional.empty();
for (Entity entity : ctx.entities()) {
String entityName = entity.getName().getFormattedText().trim().toLowerCase();
if ((entityName.contains(name) || name.contains(entityName)) && !(entity instanceof ItemEntity || entity instanceof PlayerEntity)) { // We dont want it following players while `#follow` exists.
toFollow = Optional.of(entity);
}
}
if (!toFollow.isPresent()) {
logDirect("Entity not found");
return true;
}
Entity effectivelyFinal = toFollow.get();
baritone.getFollowProcess().follow(effectivelyFinal::equals);
logDirect("Following entity " + toFollow.get());
return true;
}
if (msg.startsWith("follow")) {
String name = msg.substring(6).trim();
Optional<Entity> toFollow = Optional.empty();
if (name.length() == 0) {
toFollow = ctx.getSelectedEntity();
} else {
for (PlayerEntity pl : ctx.world().getPlayers()) {
String theirName = pl.getName().getString().trim().toLowerCase();
if (!theirName.equals(ctx.player().getName().getString().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol
toFollow = Optional.of(pl);
}
}
}
if (!toFollow.isPresent()) {
logDirect("Not found");
return true;
}
Entity effectivelyFinal = toFollow.get();
baritone.getFollowProcess().follow(effectivelyFinal::equals);
logDirect("Following " + toFollow.get());
return true;
}
if (msg.startsWith("explorefilter")) {
// explorefilter blah.json
// means that entries in blah.json are already explored
// explorefilter blah.json invert
// means that entries in blah.json are NOT already explored
String path = msg.substring("explorefilter".length()).trim();
String[] parts = path.split(" ");
Path path1 = Minecraft.getInstance().gameDir.toPath().resolve(parts[0]);
boolean invert = parts.length > 1;
try {
baritone.getExploreProcess().applyJsonFilter(path1, invert);
logDirect("Loaded filter. Inverted: " + invert);
if (invert) {
logDirect("Chunks on this list will be treated as possibly unexplored, all others will be treated as certainly explored");
} else {
logDirect("Chunks on this list will be treated as certainly explored, all others will be treated as possibly unexplored");
}
} catch (Exception e) {
e.printStackTrace();
logDirect("Unable to load " + path1);
}
return true;
}
if (msg.equals("reloadall")) {
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().reloadAllFromDisk();
logDirect("ok");
return true;
}
if (msg.equals("saveall")) {
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().save();
logDirect("ok");
return true;
}
if (msg.startsWith("explore")) {
String rest = msg.substring("explore".length()).trim();
int centerX;
int centerZ;
try {
centerX = Integer.parseInt(rest.split(" ")[0]);
centerZ = Integer.parseInt(rest.split(" ")[1]);
} catch (Exception ex) {
centerX = ctx.playerFeet().x;
centerZ = ctx.playerFeet().z;
}
baritone.getExploreProcess().explore(centerX, centerZ);
logDirect("Exploring from " + centerX + "," + centerZ);
return true;
}
if (msg.equals("blacklist")) {
IGetToBlockProcess proc = baritone.getGetToBlockProcess();
if (!proc.isActive()) {
logDirect("GetToBlockProcess is not currently active");
return true;
}
if (proc.blacklistClosest()) {
logDirect("Blacklisted closest instances");
} else {
logDirect("No known locations, unable to blacklist");
}
return true;
}
if (msg.startsWith("find")) {
String blockType = msg.substring(4).trim();
ArrayList<BlockPos> locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4);
logDirect("Have " + locs.size() + " locations");
for (BlockPos pos : locs) {
Block actually = ctx.world().getBlockState(pos).getBlock();
if (!BlockUtils.blockToString(actually).equalsIgnoreCase(blockType)) {
logDebug("Was looking for " + blockType + " but actually found " + actually + " " + BlockUtils.blockToString(actually));
}
}
return true;
}
if (msg.startsWith("mine")) {
String[] blockTypes = msg.substring(4).trim().split(" ");
try {
int quantity = Integer.parseInt(blockTypes[1]);
Block block = BlockUtils.stringToBlockRequired(blockTypes[0]);
baritone.getMineProcess().mine(quantity, block);
logDirect("Will mine " + quantity + " " + blockTypes[0]);
return true;
} catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {}
for (String s : blockTypes) {
if (BlockUtils.stringToBlockNullable(s) == null) {
logDirect(s + " isn't a valid block name");
return true;
}
}
baritone.getMineProcess().mineByName(0, blockTypes);
logDirect("Started mining blocks of type " + Arrays.toString(blockTypes));
return true;
}
if (msg.equals("click")) {
baritone.openClick();
logDirect("aight dude");
return true;
}
if (msg.startsWith("thisway") || msg.startsWith("forward")) {
try {
Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
customGoalProcess.setGoal(goal);
logDirect("Goal: " + goal);
} catch (NumberFormatException ex) {
logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double.");
}
return true;
}
if (msg.startsWith("list") || msg.startsWith("get ") || msg.startsWith("show")) {
String waypointType = msg.substring(4).trim();
if (waypointType.endsWith("s")) {
// for example, "show deaths"
waypointType = waypointType.substring(0, waypointType.length() - 1);
}
IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType);
if (tag == null) {
logDirect("Not a valid tag. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase());
return true;
}
Set<IWaypoint> waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag);
// might as well show them from oldest to newest
List<IWaypoint> sorted = new ArrayList<>(waypoints);
sorted.sort(Comparator.comparingLong(IWaypoint::getCreationTimestamp));
logDirect("Waypoints under tag " + tag + ":");
for (IWaypoint waypoint : sorted) {
logDirect(waypoint.toString());
}
return true;
}
if (msg.startsWith("save")) {
String name = msg.substring(4).trim();
BlockPos pos = ctx.playerFeet();
if (name.contains(" ")) {
logDirect("Name contains a space, assuming it's in the format 'save waypointName X Y Z'");
String[] parts = name.split(" ");
if (parts.length != 4) {
logDirect("Unable to parse, expected four things");
return true;
}
try {
pos = new BlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]));
} catch (NumberFormatException ex) {
logDirect("Unable to parse coordinate integers");
return true;
}
name = parts[0];
}
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, IWaypoint.Tag.USER, pos));
logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints.");
return true;
}
if (msg.startsWith("delete")) {
String name = msg.substring(6).trim();
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
if (waypoint == null) {
logDirect("No user defined position under the name '" + name + "' found.");
return true;
}
baritone.getWorldProvider().getCurrentWorld().getWaypoints().removeWaypoint(waypoint);
logDirect("Deleted user defined position under name '" + name + "'.");
return true;
}
if (msg.startsWith("goto")) {
String waypointType = msg.substring(4).trim();
if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) {
// for example, "show deaths"
waypointType = waypointType.substring(0, waypointType.length() - 1);
}
IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType);
IWaypoint waypoint;
if (tag == null) {
String mining = waypointType;
Block block = BlockUtils.stringToBlockNullable(mining);
//logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase());
if (block == null) {
waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null);
if (waypoint == null) {
Goal goal = parseGoal(waypointType.split(" "));
if (goal != null) {
logDirect("Going to " + goal);
customGoalProcess.setGoalAndPath(goal);
}
return true;
}
} else {
baritone.getGetToBlockProcess().getToBlock(block);
return true;
}
} else {
waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(tag);
if (waypoint == null) {
logDirect("None saved for tag " + tag);
return true;
}
}
Goal goal = waypoint.getTag() == IWaypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
return true;
}
if (msg.equals("spawn") || msg.equals("bed")) {
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.BED);
if (waypoint == null) {
BlockPos spawnPoint = ctx.player().getBedLocation();
// for some reason the default spawnpoint is underground sometimes
Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ());
logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal);
customGoalProcess.setGoalAndPath(goal);
} else {
Goal goal = new GoalGetToBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
logDirect("Set goal to most recent bed " + goal);
}
return true;
}
if (msg.equals("sethome")) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", IWaypoint.Tag.HOME, ctx.playerFeet()));
logDirect("Saved. Say home to set goal.");
return true;
}
if (msg.equals("home")) {
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.HOME);
if (waypoint == null) {
logDirect("home not saved");
} else {
Goal goal = new GoalBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
logDirect("Going to saved home " + goal);
}
return true;
}
if (msg.equals("damn")) {
logDirect("daniel");
}
return false;
}
private int parseOrDefault(String str, int i, double dimensionFactor) {
return str.equals("~") ? i : str.startsWith("~") ? (int) (Integer.parseInt(str.substring(1)) * dimensionFactor) + i : (int) (Integer.parseInt(str) * dimensionFactor);
}
private void log(List<ItemStack> stacks) {
for (ItemStack stack : stacks) {
if (!stack.isEmpty()) {
logDirect(stack.getCount() + "x " + stack.getDisplayName() + "@" + stack.getDamage());
}
}
}
private Goal parseGoal(String[] params) {
Goal goal;
try {
BetterBlockPos playerFeet = ctx.playerFeet();
int length = params.length - 1; // length has to be smaller when a dimension parameter is added
if (params.length < 1 || (isNumeric(params[params.length - 1]) || params[params.length - 1].startsWith("~"))) {
length = params.length;
}
switch (length) {
case 0:
goal = new GoalBlock(playerFeet);
break;
case 1:
goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y, 1));
break;
case 2:
goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.z, calculateDimensionFactor(params[params.length - 1])));
break;
case 3:
goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x, calculateDimensionFactor(params[params.length - 1])), parseOrDefault(params[1], playerFeet.y, 1), parseOrDefault(params[2], playerFeet.z, calculateDimensionFactor(params[params.length - 1]))));
break;
default:
logDirect("unable to understand lol");
return null;
}
} catch (NumberFormatException ex) {
logDirect("unable to parse integer " + ex);
return null;
}
return goal;
}
private double calculateDimensionFactor(String to) {
return Math.pow(8, ctx.world().dimension.getType().getId() - getDimensionByName(to.toLowerCase()).getId());
}
private DimensionType getDimensionByName(String name) {
if ("the_end".contains(name)) {
return DimensionType.THE_END;
}
if ("the_overworld".contains(name) || "surface".contains(name)) {
return DimensionType.OVERWORLD;
}
if ("the_nether".contains(name) || "hell".contains(name)) {
return DimensionType.THE_NETHER;
}
return ctx.world().dimension.getType();
}
}

View File

@@ -23,7 +23,13 @@ import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import java.util.Arrays;
import java.util.stream.Stream;
/**
* An ease-of-access interface to provide the {@link Minecraft} game instance,
* chat and console logging mechanisms, and the Baritone chat prefix.
*
* @author Brady
* @since 8/1/2018
*/
@@ -34,16 +40,26 @@ public interface Helper {
*/
Helper HELPER = new Helper() {};
ITextComponent MESSAGE_PREFIX = new StringTextComponent(String.format(
"%s[%sBaritone%s]%s",
TextFormatting.DARK_PURPLE,
TextFormatting.LIGHT_PURPLE,
TextFormatting.DARK_PURPLE,
TextFormatting.GRAY
));
/**
* Instance of the game
*/
Minecraft mc = Minecraft.getInstance();
static ITextComponent getPrefix() {
// Inner text component
ITextComponent baritone = new StringTextComponent(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone");
baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE);
// Outer brackets
ITextComponent prefix = new StringTextComponent("");
prefix.getStyle().setColor(TextFormatting.DARK_PURPLE);
prefix.appendText("[");
prefix.appendSibling(baritone);
prefix.appendText("]");
return prefix;
}
/**
* Send a message to chat only if chatDebug is on
*
@@ -59,14 +75,40 @@ public interface Helper {
}
/**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command)
* Send components to chat with the [Baritone] prefix
*
* @param components The components to send
*/
default void logDirect(ITextComponent... components) {
ITextComponent component = new StringTextComponent("");
component.appendSibling(getPrefix());
component.appendSibling(new StringTextComponent(" "));
Arrays.asList(components).forEach(component::appendSibling);
mc.execute(() -> BaritoneAPI.getSettings().logger.value.accept(component));
}
/**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a
* direct response to a chat command)
*
* @param message The message to display in chat
* @param color The color to print that message in
*/
default void logDirect(String message, TextFormatting color) {
Stream.of(message.split("\n")).forEach(line -> {
ITextComponent component = new StringTextComponent(line.replace("\t", " "));
component.getStyle().setColor(color);
logDirect(component);
});
}
/**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a
* direct response to a chat command)
*
* @param message The message to display in chat
*/
default void logDirect(String message) {
ITextComponent component = MESSAGE_PREFIX.shallowCopy();
component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(new StringTextComponent(" " + message));
Minecraft.getInstance().execute(() -> BaritoneAPI.getSettings().logger.value.accept(component));
logDirect(message, TextFormatting.GRAY);
}
}

View File

@@ -56,19 +56,31 @@ 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);
if (world().getBlockState(feet).getBlock() instanceof SlabBlock) {
return feet.up();
}
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
//
// so of course crashing on 2b is horribly bad due to queue times and logout spot
// catch the NPE and ignore it if it does happen
//
// this does not impact performance at all since we're not null checking constantly
// if there is an exception, the only overhead is Java generating the exception object... so we can ignore it
try {
if (world().getBlockState(feet).getBlock() instanceof SlabBlock) {
return feet.up();
}
} catch (NullPointerException ignored) {}
return feet;
}
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,13 +20,13 @@ 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;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameType;
import net.minecraft.world.World;
@@ -36,21 +36,27 @@ import net.minecraft.world.World;
*/
public interface IPlayerController {
void syncHeldItem();
boolean hasBrokenBlock();
boolean onPlayerDamageBlock(BlockPos pos, Direction side);
void resetBlockRemoving();
ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, PlayerEntity player);
void setGameType(GameType type);
GameType getGameType();
default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : 4.5F;
}
ActionResultType processRightClickBlock(ClientPlayerEntity player, World world, Hand hand, BlockRayTraceResult result);
ActionResultType processRightClick(ClientPlayerEntity player, World world, Hand hand);
boolean clickBlock(BlockPos loc, Direction face);
void setHittingBlock(boolean hittingBlock);
default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : BaritoneAPI.getSettings().blockReachDistance.value;
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
@@ -36,7 +37,6 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
@@ -44,9 +44,11 @@ import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SettingsUtil {
private static final Path SETTINGS_PATH = Minecraft.getInstance().gameDir.toPath().resolve("baritone").resolve("settings.txt");
private static final Pattern SETTING_PATTERN = Pattern.compile("^(?<setting>[^ ]+) +(?<value>.+)"); // key and value split by the first space
@@ -122,15 +124,54 @@ public class SettingsUtil {
return modified;
}
/**
* Gets the type of a setting and returns it as a string, with package names stripped.
* <p>
* For example, if the setting type is {@code java.util.List<java.lang.String>}, this function returns
* {@code List<String>}.
*
* @param setting The setting
* @return The type
*/
public static String settingTypeToString(Settings.Setting setting) {
return setting.getType().getTypeName()
.replaceAll("(?:\\w+\\.)+(\\w+)", "$1");
}
public static <T> String settingValueToString(Settings.Setting<T> setting, T value) throws IllegalArgumentException {
Parser io = Parser.getParser(setting.getType());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
return io.toString(new ParserContext(setting), value);
}
public static String settingValueToString(Settings.Setting setting) throws IllegalArgumentException {
//noinspection unchecked
return settingValueToString(setting, setting.value);
}
public static String settingDefaultToString(Settings.Setting setting) throws IllegalArgumentException {
//noinspection unchecked
return settingValueToString(setting, setting.defaultValue);
}
public static String maybeCensor(int coord) {
if (BaritoneAPI.getSettings().censorCoordinates.value) {
return "<censored>";
}
return Integer.toString(coord);
}
public static String settingToString(Settings.Setting setting) throws IllegalStateException {
if (setting.getName().equals("logger")) {
return "logger";
}
Parser io = Parser.getParser(setting.getType());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
return setting.getName() + " " + io.toString(new ParserContext(setting), setting.value);
return setting.getName() + " " + settingValueToString(setting);
}
public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException {
@@ -176,7 +217,8 @@ public class SettingsUtil {
INTEGER(Integer.class, Integer::parseInt),
FLOAT(Float.class, Float::parseFloat),
LONG(Long.class, Long::parseLong),
ENUMFACING(Direction.class, Direction::byName),
STRING(String.class, String::new),
DIRECTION(Direction.class, Direction::byName),
COLOR(
Color.class,
str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])),
@@ -202,7 +244,7 @@ public class SettingsUtil {
public Object parse(ParserContext context, String raw) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type);
return Arrays.stream(raw.split(","))
return Stream.of(raw.split(","))
.map(s -> parser.parse(context, s))
.collect(Collectors.toList());
}
@@ -223,22 +265,22 @@ public class SettingsUtil {
}
};
private final Class<?> klass;
private final Class<?> cla$$;
private final Function<String, Object> parser;
private final Function<Object, String> toString;
Parser() {
this.klass = null;
this.cla$$ = null;
this.parser = null;
this.toString = null;
}
<T> Parser(Class<T> klass, Function<String, T> parser) {
this(klass, parser, Object::toString);
<T> Parser(Class<T> cla$$, Function<String, T> parser) {
this(cla$$, parser, Object::toString);
}
<T> Parser(Class<T> klass, Function<String, T> parser, Function<T, String> toString) {
this.klass = klass;
<T> Parser(Class<T> cla$$, Function<String, T> parser, Function<T, String> toString) {
this.cla$$ = cla$$;
this.parser = parser::apply;
this.toString = x -> toString.apply((T) x);
}
@@ -257,11 +299,11 @@ public class SettingsUtil {
@Override
public boolean accepts(Type type) {
return type instanceof Class && this.klass.isAssignableFrom((Class) type);
return type instanceof Class && this.cla$$.isAssignableFrom((Class) type);
}
public static Parser getParser(Type type) {
return Arrays.stream(values())
return Stream.of(values())
.filter(parser -> parser.accepts(type))
.findFirst().orElse(null);
}

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);
}
}

Some files were not shown because too many files have changed in this diff Show More