4646import static top .offsetmonkey538 .monkeylib538 .common .api .command .CommandAbstractionApi .sendText ;
4747
4848public final class LootTableModifierCommon {
49- public static final String MOD_ID = "loot-table-modifier" ;
50- public static final MonkeyLibLogger LOGGER = MonkeyLibLogger .create (MOD_ID );
51-
52- public static final boolean IS_DEV ;
53- static {
54- final String isDev = System .getProperty ("lootTableModifierDev" , "" );
55- if (isDev .equalsIgnoreCase ("true" )) IS_DEV = true ;
56- else if (isDev .equalsIgnoreCase ("false" )) IS_DEV = false ; // This way it can be disabled in devenv too.
57- else IS_DEV = LoaderUtil .isDevelopmentEnvironment ();
58- }
49+ public static final String MOD_ID = "loot-table-modifier" ;
50+ public static final MonkeyLibLogger LOGGER = MonkeyLibLogger .create (MOD_ID );
51+
52+ public static final boolean IS_DEV ;
53+ static {
54+ final String isDev = System .getProperty ("lootTableModifierDev" , "" );
55+ if (isDev .equalsIgnoreCase ("true" )) IS_DEV = true ;
56+ else if (isDev .equalsIgnoreCase ("false" )) IS_DEV = false ; // This way it can be disabled in devenv too.
57+ else IS_DEV = LoaderUtil .isDevelopmentEnvironment ();
58+ }
5959
60- // Only used when IS_DEV is true
61- private static final List <Identifier > MODIFIED_TABLE_IDs ;
62- static {
63- if (IS_DEV ) MODIFIED_TABLE_IDs = Collections .synchronizedList (new ArrayList <>(0 ));
64- else MODIFIED_TABLE_IDs = null ;
65- }
60+ // Only used when IS_DEV is true
61+ private static final List <Identifier > MODIFIED_TABLE_IDs ;
62+ static {
63+ if (IS_DEV ) MODIFIED_TABLE_IDs = Collections .synchronizedList (new ArrayList <>(0 ));
64+ else MODIFIED_TABLE_IDs = null ;
65+ }
6666
67- public static void initialize () {
68- TelemetryRegistry .register (MOD_ID );
67+ public static void initialize () {
68+ TelemetryRegistry .register (MOD_ID );
6969
70- LootModifierActionTypes .register ();
71- LootModifierPredicateTypes .register ();
70+ LootModifierActionTypes .register ();
71+ LootModifierPredicateTypes .register ();
7272
73- if (IS_DEV ) enableDebug ();
74- }
73+ if (IS_DEV ) enableDebug ();
74+ }
7575
76- public static void runModification (ResourceManager resourceManager , Stream <Pair <Identifier , LootTable >> lootRegistry , DynamicOps <JsonElement > registryOps ) {
77- LOGGER .info ("Gathering loot tables..." );
78- final Stopwatch stopwatch = Stopwatch .createStarted ();
76+ public static void runModification (ResourceManager resourceManager , Stream <Pair <Identifier , LootTable >> lootRegistry , DynamicOps <JsonElement > registryOps ) {
77+ LOGGER .info ("Gathering loot tables..." );
78+ final Stopwatch stopwatch = Stopwatch .createStarted ();
7979
80- // Streams are lazy so calling toList here means all the intermediary steps will only now be executed and counted between the stopwatch.
81- final List <Pair <Identifier , LootTable >> tables = lootRegistry .toList ();
80+ // Streams are lazy so calling toList here means all the intermediary steps will only now be executed and counted between the stopwatch.
81+ final List <Pair <Identifier , LootTable >> tables = lootRegistry .toList ();
8282
83- LOGGER .info ("Gathered %s loot tables in %s" , tables .size (), stopwatch .stop ());
83+ LOGGER .info ("Gathered %s loot tables in %s" , tables .size (), stopwatch .stop ());
8484
85- LootTableModifierCommon .runModification (loadModifiers (resourceManager , registryOps ), tables );
86- }
85+ LootTableModifierCommon .runModificationInternal (loadModifiers (resourceManager , registryOps ), tables );
86+ }
8787
88- private static Map <Identifier , LootModifier > loadModifiers (ResourceManager resourceManager , DynamicOps <JsonElement > registryOps ) {
89- LOGGER .info ("Loading loot table modifiers..." );
90- final Stopwatch stopwatch = Stopwatch .createStarted ();
88+ private static Map <Identifier , LootModifier > loadModifiers (ResourceManager resourceManager , DynamicOps <JsonElement > registryOps ) {
89+ LOGGER .info ("Loading loot table modifiers..." );
90+ final Stopwatch stopwatch = Stopwatch .createStarted ();
9191
92- final Map <Identifier , LootModifier > result = new HashMap <>();
92+ final Map <Identifier , LootModifier > result = new HashMap <>();
9393
94- resourceManager .listResources (MOD_ID + "/loot_modifier" , path -> path .endsWith (".json" )).forEach (resource -> {
95- final Identifier id = resource .left ();
94+ resourceManager .listResources (MOD_ID + "/loot_modifier" , path -> path .endsWith (".json" )).forEach (resource -> {
95+ final Identifier id = resource .left ();
9696
97- try {
98- LOGGER .debug ("Loading load loot table modifier from '%s'" , id );
99- result .put (
100- id ,
101- // Can't just use orElseThrow cause 1.20.1 don't have that
102- LootModifier .CODEC .decode (registryOps , JsonParser .parseReader (resource .right ().get ())).map (com .mojang .datafixers .util .Pair ::getFirst ).resultOrPartial (error -> { throw new RuntimeException (error ); }).orElseThrow ()
103- );
104- } catch (Exception e ) {
105- LOGGER .error ("Failed to load loot table modifier from '%s'!" , e , id );
106- }
107- });
97+ try {
98+ LOGGER .debug ("Loading load loot table modifier from '%s'" , id );
99+ result .put (
100+ id ,
101+ // Can't just use orElseThrow cause 1.20.1 don't have that
102+ LootModifier .CODEC .decode (registryOps , JsonParser .parseReader (resource .right ().get ())).map (com .mojang .datafixers .util .Pair ::getFirst ).resultOrPartial (error -> {
103+ throw new RuntimeException (error );
104+ }).orElseThrow ()
105+ );
106+ } catch (Exception e ) {
107+ LOGGER .error ("Failed to load loot table modifier from '%s'!" , e , id );
108+ }
109+ });
108110
109- LOGGER .info ("Loaded %s loot modifiers in %s!" , result .size (), stopwatch .stop ());
111+ LOGGER .info ("Loaded %s loot modifiers in %s!" , result .size (), stopwatch .stop ());
110112
111- return result ;
112- }
113+ return result ;
114+ }
113115
114- //public static void runModification(ResourceManager resourceManager, Registry<LootTable> lootRegistry, RegistryOps<JsonElement> registryOps) {
115- private static void runModification (Map <Identifier , LootModifier > modifiers , @ Unmodifiable List <Pair <Identifier , LootTable >> tables ) {
116- final List <Identifier > modifiedTableIds = new ArrayList <>(); // Used for exporting modified ones
117- int poolsModified = 0 , entriesModified = 0 ;
118- boolean tableModified , poolModified ;
116+ private static void runModificationInternal (Map <Identifier , LootModifier > modifiers , @ Unmodifiable List <Pair <Identifier , LootTable >> tables ) {
117+ final List <Identifier > modifiedTableIds = new ArrayList <>(); // Used for exporting modified ones
118+ int poolsModified = 0 ;
119+ int entriesModified = 0 ;
120+ boolean tableModified ;
121+ boolean poolModified ;
119122
120- LOGGER .info ("Modifying loot tables..." );
121- final Stopwatch stopwatch = Stopwatch .createStarted ();
123+ LOGGER .info ("Modifying loot tables..." );
124+ final Stopwatch stopwatch = Stopwatch .createStarted ();
122125
123- for (Pair <Identifier , LootTable > tableEntry : tables ) {
124- final Identifier tableId = tableEntry .left ();
125- final LootTable table = tableEntry .right ();
126+ for (Pair <Identifier , LootTable > tableEntry : tables ) {
127+ final Identifier tableId = tableEntry .left ();
128+ final LootTable table = tableEntry .right ();
126129
127- tableModified = false ;
130+ tableModified = false ;
128131
129132 final LootPool [] poolsCopy = table .getPools ().toArray (LootPool []::new );
130- int poolsSize = Math .max (1 , poolsCopy .length ); // Run loop at least once
131- for (int i = 0 ; i < poolsSize ; i ++) {
132- final LootPool pool = poolsCopy .length == 0 ? null : poolsCopy [i ];
133- poolModified = false ;
133+ int poolsSize = Math .max (1 , poolsCopy .length ); // Run loop at least once
134+ for (int i = 0 ; i < poolsSize ; i ++) {
135+ final LootPool pool = poolsCopy .length == 0 ? null : poolsCopy [i ];
136+ poolModified = false ;
134137
135- final LootPoolEntry [] entriesCopy = pool == null ? new LootPoolEntry []{} : pool .getEntries ().toArray (LootPoolEntry []::new );
136- int entriesSize = Math .max (1 , entriesCopy .length ); // Run loop at least once
137- for (int j = 0 ; j < entriesSize ; j ++) {
138- final LootPoolEntry entry = entriesCopy .length == 0 ? null : entriesCopy [j ];
138+ final LootPoolEntry [] entriesCopy = pool == null ? new LootPoolEntry []{} : pool .getEntries ().toArray (LootPoolEntry []::new );
139+ int entriesSize = Math .max (1 , entriesCopy .length ); // Run loop at least once
140+ for (int j = 0 ; j < entriesSize ; j ++) {
141+ final LootPoolEntry entry = entriesCopy .length == 0 ? null : entriesCopy [j ];
139142
140- for (Map .Entry <Identifier , LootModifier > modifierEntry : modifiers .entrySet ()) {
141- final LootModifierContext context = new LootModifierContext (table , tableId , pool , entry , tableModified , poolModified );
143+ for (Map .Entry <Identifier , LootModifier > modifierEntry : modifiers .entrySet ()) {
144+ final LootModifierContext context = new LootModifierContext (table , tableId , pool , entry , tableModified , poolModified );
142145
143- final LootModifier modifier = modifierEntry .getValue ();
144- if (!modifier .test (context )) continue ;
146+ final LootModifier modifier = modifierEntry .getValue ();
147+ if (!modifier .test (context )) continue ;
145148
146- if (IS_DEV ) LOGGER .warn ("Modifier %s can modify table %s" , modifierEntry .getKey (), tableId );
149+ if (IS_DEV ) LOGGER .warn ("Modifier %s can modify table %s" , modifierEntry .getKey (), tableId );
147150
148151
149- int result = modifier .apply (context );
152+ int result = modifier .apply (context );
150153
151- if (IS_DEV && result != LootModifierAction .MODIFIED_NONE ) LOGGER .warn ("Modifier %s modified table %s with modified mask %s" , modifierEntry .getKey (), tableId , Integer .toUnsignedString (result , 2 ));
154+ if (IS_DEV && result != LootModifierAction .MODIFIED_NONE ) LOGGER .warn ("Modifier %s modified table %s with modified mask %s" , modifierEntry .getKey (), tableId , Integer .toUnsignedString (result , 2 ));
152155
153- if ((result & LootModifierAction .MODIFIED_TABLE ) == LootModifierAction .MODIFIED_TABLE ) tableModified = true ;
154- if ((result & LootModifierAction .MODIFIED_POOL ) == LootModifierAction .MODIFIED_POOL ) poolModified = true ;
155- if ((result & LootModifierAction .MODIFIED_ENTRY ) == LootModifierAction .MODIFIED_ENTRY ) entriesModified ++;
156- }
157- }
156+ if ((result & LootModifierAction .MODIFIED_TABLE ) == LootModifierAction .MODIFIED_TABLE ) tableModified = true ;
157+ if ((result & LootModifierAction .MODIFIED_POOL ) == LootModifierAction .MODIFIED_POOL ) poolModified = true ;
158+ if ((result & LootModifierAction .MODIFIED_ENTRY ) == LootModifierAction .MODIFIED_ENTRY ) entriesModified ++;
159+ }
160+ }
158161
159- poolsModified += poolModified ? 1 : 0 ;
160- }
161- if (tableModified ) modifiedTableIds .add (tableId );
162- }
162+ poolsModified += poolModified ? 1 : 0 ;
163+ }
164+ if (tableModified ) modifiedTableIds .add (tableId );
165+ }
163166
164167
165- LOGGER .info ("Applied %s modifiers and modified %s entries, %s pools and %s loot tables in %s!" , modifiers .size (), entriesModified , poolsModified , modifiedTableIds .size (), stopwatch .stop ());
168+ LOGGER .info ("Applied %s modifiers and modified %s entries, %s pools and %s loot tables in %s!" , modifiers .size (), entriesModified , poolsModified , modifiedTableIds .size (), stopwatch .stop ());
166169
167- if (!IS_DEV ) return ;
170+ if (!IS_DEV ) return ;
168171
169- LOGGER .warn ("Dev mode enabled, modified loot tables can be exported using the '/loot-table-modifier debug export' command" );
170- synchronized (MODIFIED_TABLE_IDs ) {
171- MODIFIED_TABLE_IDs .clear ();
172- MODIFIED_TABLE_IDs .addAll (modifiedTableIds );
173- }
172+ LOGGER .warn ("Dev mode enabled, modified loot tables can be exported using the '/loot-table-modifier debug export' command" );
173+ synchronized (MODIFIED_TABLE_IDs ) {
174+ MODIFIED_TABLE_IDs .clear ();
175+ MODIFIED_TABLE_IDs .addAll (modifiedTableIds );
176+ }
174177 }
175178
176- private static void enableDebug () {
179+ private static void enableDebug () {
177180 CommandRegistrationApi .registerCommand (
178181 literal (MOD_ID )
179182 .then (
@@ -186,64 +189,64 @@ private static void enableDebug() {
186189 )
187190 )
188191 );
189- }
190-
191- private static int executeExportCommand (CommandContext <Object > context ) {
192- synchronized (MODIFIED_TABLE_IDs ) {
193- final DynamicOps <JsonElement > ops = PlatformCommandUtils .getRegistryOps (context );
194-
195- try {
196- final Path exportDir = LoaderUtil .getGameDir ().resolve (".loot-table-modifier" ).resolve ("export" );
197- if (Files .exists (exportDir )) PathUtils .deleteDirectory (exportDir );
198-
199- sendText (
200- context ,
201- MonkeyLibText
202- .of ("Exporting modified tables to " )
203- .append (MonkeyLibText .of (exportDir .toString ()).setStyle (
204- MonkeyLibStyle .empty ()
205- .withUnderline (true )
206- .withColor (MonkeyLibStyle .Color .WHITE )
207- .withShowText (MonkeyLibText .of ("Click to copy" ))
208- .withCopyToClipboard (exportDir .toAbsolutePath ().toString ())
209- ))
210- );
211- final Stopwatch stopwatch = Stopwatch .createStarted ();
212-
213- for (Identifier id : MODIFIED_TABLE_IDs ) {
214- final LootTable table = PlatformCommandUtils .getTableForId (context , id );
215- final Path file = exportDir .resolve (id .getNamespace ()).resolve (id .getPath () + ".json" );
216- Files .createDirectories (file .getParent ());
217-
218- LOGGER .warn ("Exporting loot table to %s" , file );
219- DataResult <JsonElement > dataResult = LootTable .CODEC_PROVIDER .get ().encodeStart (ops , table );
220- final Optional <JsonElement > optionalResult = dataResult .resultOrPartial (LOGGER ::error );
221- final JsonElement result = optionalResult .orElseThrow ();
222-
223- LOGGER .warn ("Writing loot table to %s" , file );
224-
225- try (JsonWriter jsonWriter = new JsonWriter (Files .newBufferedWriter (file , StandardCharsets .UTF_8 ))) {
226- jsonWriter .setSerializeNulls (false );
227- jsonWriter .setIndent (" " );
228- PlatformMain .writeSorted (jsonWriter , result );
229- }
230- }
231- sendMessage (context , "Exported %s modified tables in %s" .formatted (MODIFIED_TABLE_IDs .size (), stopwatch .stop ()));
232- } catch (IOException e ) {
233- throw new RuntimeException ("Failed to export modified tables!" , e );
234- }
235-
236- return 1 ;
237- }
238- }
192+ }
193+
194+ private static int executeExportCommand (CommandContext <Object > context ) {
195+ synchronized (MODIFIED_TABLE_IDs ) {
196+ final DynamicOps <JsonElement > ops = PlatformCommandUtils .getRegistryOps (context );
197+
198+ try {
199+ final Path exportDir = LoaderUtil .getGameDir ().resolve (".loot-table-modifier" ).resolve ("export" );
200+ if (Files .exists (exportDir )) PathUtils .deleteDirectory (exportDir );
201+
202+ sendText (
203+ context ,
204+ MonkeyLibText
205+ .of ("Exporting modified tables to " )
206+ .append (MonkeyLibText .of (exportDir .toString ()).setStyle (
207+ MonkeyLibStyle .empty ()
208+ .withUnderline (true )
209+ .withColor (MonkeyLibStyle .Color .WHITE )
210+ .withShowText (MonkeyLibText .of ("Click to copy" ))
211+ .withCopyToClipboard (exportDir .toAbsolutePath ().toString ())
212+ ))
213+ );
214+ final Stopwatch stopwatch = Stopwatch .createStarted ();
215+
216+ for (Identifier id : MODIFIED_TABLE_IDs ) {
217+ final LootTable table = PlatformCommandUtils .getTableForId (context , id );
218+ final Path file = exportDir .resolve (id .getNamespace ()).resolve (id .getPath () + ".json" );
219+ Files .createDirectories (file .getParent ());
220+
221+ LOGGER .warn ("Exporting loot table to %s" , file );
222+ DataResult <JsonElement > dataResult = LootTable .CODEC_PROVIDER .get ().encodeStart (ops , table );
223+ final Optional <JsonElement > optionalResult = dataResult .resultOrPartial (LOGGER ::error );
224+ final JsonElement result = optionalResult .orElseThrow ();
225+
226+ LOGGER .warn ("Writing loot table to %s" , file );
227+
228+ try (JsonWriter jsonWriter = new JsonWriter (Files .newBufferedWriter (file , StandardCharsets .UTF_8 ))) {
229+ jsonWriter .setSerializeNulls (false );
230+ jsonWriter .setIndent (" " );
231+ PlatformMain .writeSorted (jsonWriter , result );
232+ }
233+ }
234+ sendMessage (context , "Exported %s modified tables in %s" .formatted (MODIFIED_TABLE_IDs .size (), stopwatch .stop ()));
235+ } catch (IOException e ) {
236+ throw new RuntimeException ("Failed to export modified tables!" , e );
237+ }
238+
239+ return 1 ;
240+ }
241+ }
239242
240243 public static <T > T load (Class <T > clazz ) {
241244 return java .util .ServiceLoader .load (clazz , LootTableModifierCommon .class .getClassLoader ())
242245 .findFirst ()
243246 .orElseThrow (() -> new RuntimeException ("Failed to load service for " + clazz .getName ()));
244247 }
245248
246- public static Identifier id (String path ) {
247- return Identifier .of (MOD_ID , path );
248- }
249+ public static Identifier id (String path ) {
250+ return Identifier .of (MOD_ID , path );
251+ }
249252}
0 commit comments