• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

CyclopsMC / IntegratedCrafting / #479011729

10 Jun 2024 03:02PM UTC coverage: 25.044% (+0.1%) from 24.947%
#479011729

push

github

rubensworks
Update to NeoForge 1.20.4

0 of 52 new or added lines in 14 files covered. (0.0%)

3 existing lines in 3 files now uncovered.

706 of 2819 relevant lines covered (25.04%)

0.25 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.28
/src/main/java/org/cyclops/integratedcrafting/core/CraftingHelpers.java
1
package org.cyclops.integratedcrafting.core;
2

3
import com.google.common.collect.Lists;
4
import com.google.common.collect.Maps;
5
import com.google.common.collect.Sets;
6
import net.minecraft.core.Direction;
7
import net.minecraft.world.level.block.Block;
8
import net.minecraft.world.level.block.entity.BlockEntity;
9
import org.apache.commons.lang3.tuple.Pair;
10
import org.apache.logging.log4j.Level;
11
import org.cyclops.commoncapabilities.api.capability.recipehandler.IPrototypedIngredientAlternatives;
12
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
13
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
14
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
15
import org.cyclops.commoncapabilities.api.ingredient.IPrototypedIngredient;
16
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
17
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
18
import org.cyclops.commoncapabilities.api.ingredient.PrototypedIngredient;
19
import org.cyclops.commoncapabilities.api.ingredient.capability.ICapabilityGetter;
20
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
21
import org.cyclops.commoncapabilities.api.ingredient.storage.IngredientComponentStorageEmpty;
22
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
23
import org.cyclops.cyclopscore.ingredient.collection.IIngredientCollectionMutable;
24
import org.cyclops.cyclopscore.ingredient.collection.IngredientArrayList;
25
import org.cyclops.cyclopscore.ingredient.collection.IngredientCollectionPrototypeMap;
26
import org.cyclops.cyclopscore.ingredient.collection.IngredientCollectionQuantitativeGrouper;
27
import org.cyclops.cyclopscore.ingredient.collection.IngredientHashSet;
28
import org.cyclops.integratedcrafting.Capabilities;
29
import org.cyclops.integratedcrafting.IntegratedCrafting;
30
import org.cyclops.integratedcrafting.api.crafting.CraftingJob;
31
import org.cyclops.integratedcrafting.api.crafting.CraftingJobDependencyGraph;
32
import org.cyclops.integratedcrafting.api.crafting.FailedCraftingRecipeException;
33
import org.cyclops.integratedcrafting.api.crafting.RecursiveCraftingRecipeException;
34
import org.cyclops.integratedcrafting.api.crafting.UnavailableCraftingInterfacesException;
35
import org.cyclops.integratedcrafting.api.crafting.UnknownCraftingRecipeException;
36
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
37
import org.cyclops.integratedcrafting.api.recipe.IRecipeIndex;
38
import org.cyclops.integrateddynamics.IntegratedDynamics;
39
import org.cyclops.integrateddynamics.api.PartStateException;
40
import org.cyclops.integrateddynamics.api.ingredient.capability.IPositionedAddonsNetworkIngredientsHandler;
41
import org.cyclops.integrateddynamics.api.network.INetwork;
42
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
43
import org.cyclops.integrateddynamics.api.part.PartPos;
44
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
45
import org.cyclops.integrateddynamics.core.network.IngredientChannelAdapter;
46
import org.cyclops.integrateddynamics.core.network.IngredientChannelIndexed;
47

48
import javax.annotation.Nullable;
49
import java.util.Collection;
50
import java.util.Collections;
51
import java.util.Iterator;
52
import java.util.List;
53
import java.util.ListIterator;
54
import java.util.Map;
55
import java.util.Optional;
56
import java.util.Set;
57
import java.util.UUID;
58
import java.util.function.Function;
59
import java.util.stream.Collectors;
60
import java.util.stream.IntStream;
61

62
/**
63
 * Helpers related to handling crafting jobs.
64
 * @author rubensworks
65
 */
66
public class CraftingHelpers {
×
67

68
    /**
69
     * Get the network at the given position,
70
     * or throw a PartStateException if it is null.
71
     * @param pos A position.
72
     * @return A network.
73
     * @throws PartStateException If the network could not be found.
74
     */
75
    public static INetwork getNetworkChecked(PartPos pos) throws PartStateException {
76
        INetwork network = NetworkHelpers.getNetwork(pos.getPos().getLevel(true), pos.getPos().getBlockPos(), pos.getSide()).orElse(null);
×
77
        if (network == null) {
×
78
            IntegratedDynamics.clog(Level.ERROR, "Could not get the network for transfer as no network was found.");
×
79
            throw new PartStateException(pos.getPos(), pos.getSide());
×
80
        }
81
        return network;
×
82
    }
83

84
    /**
85
     * Get the crafting network in the given network.
86
     * @param network A network.
87
     * @return The crafting network.
88
     */
89
    public static Optional<ICraftingNetwork> getCraftingNetwork(@Nullable INetwork network) {
90
        if (network != null) {
×
NEW
91
            return network.getCapability(Capabilities.CraftingNetwork.NETWORK);
×
92
        }
NEW
93
        return Optional.empty();
×
94
    }
95

96
    /**
97
     * Get the crafting network in the given network.
98
     * @param network A network.
99
     * @return The crafting network.
100
     */
101
    public static ICraftingNetwork getCraftingNetworkChecked(@Nullable INetwork network) {
102
        return getCraftingNetwork(network)
×
103
                .orElseThrow(() -> new IllegalStateException("Could not find a crafting network"));
×
104
    }
105

106
    /**
107
     * Get the storage network of the given type in the given network.
108
     * @param network A network.
109
     * @param ingredientComponent The ingredient component type of the network.
110
     * @param <T> The instance type.
111
     * @param <M> The matching condition parameter.
112
     * @return The storage network.
113
     */
114
    public static <T, M> Optional<IPositionedAddonsNetworkIngredients<T, M>> getIngredientsNetwork(INetwork network,
115
                                                                                                       IngredientComponent<T, M> ingredientComponent) {
NEW
116
        return ingredientComponent
×
NEW
117
                .getCapability(org.cyclops.integrateddynamics.Capabilities.PositionedAddonsNetworkIngredientsHandler.INGREDIENT)
×
NEW
118
                .flatMap(ingredientsHandler -> ((IPositionedAddonsNetworkIngredientsHandler<T, M>) ingredientsHandler).getStorage(network));
×
119
    }
120

121
    /**
122
     * Get the storage network of the given type in the given network.
123
     * @param network A network.
124
     * @param ingredientComponent The ingredient component type of the network.
125
     * @param <T> The instance type.
126
     * @param <M> The matching condition parameter.
127
     * @return The storage network.
128
     */
129
    public static <T, M> IPositionedAddonsNetworkIngredients<T, M> getIngredientsNetworkChecked(INetwork network,
130
                                                                                                IngredientComponent<T, M> ingredientComponent) {
131
        return getIngredientsNetwork(network, ingredientComponent)
×
132
                .orElseThrow(() -> new IllegalStateException("Could not find an ingredients network"));
×
133
    }
134

135
    /**
136
     * Get the storage of the given ingredient component type from the network.
137
     * @param network The network.
138
     * @param channel A network channel.
139
     * @param ingredientComponent The ingredient component type of the network.
140
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
141
     * @param <T> The instance type.
142
     * @param <M> The matching condition parameter.
143
     * @return The storage.
144
     */
145
    public static <T, M> IIngredientComponentStorage<T, M> getNetworkStorage(INetwork network, int channel,
146
                                                                             IngredientComponent<T, M> ingredientComponent,
147
                                                                             boolean scheduleObservation) {
148
        IPositionedAddonsNetworkIngredients<T, M> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
149
        if (ingredientsNetwork != null) {
×
150
            if (scheduleObservation) {
×
151
                ingredientsNetwork.scheduleObservation();
×
152
            }
153
            return ingredientsNetwork.getChannel(channel);
×
154
        }
155
        return new IngredientComponentStorageEmpty<>(ingredientComponent);
×
156
    }
157

158
    /**
159
     * If the network is guaranteed to have uncommitted changes (such as the one in #48),
160
     * forcefully run observers synchronously, so that we can calculate the job in a consistent network state.
161
     * @param network The network.
162
     * @param channel A network channel.
163
     */
164
    public static void beforeCalculateCraftingJobs(INetwork network, int channel) {
NEW
165
        for (IngredientComponent<?, ?> ingredientComponent : IngredientComponent.REGISTRY.stream().toList()) {
×
166
            IPositionedAddonsNetworkIngredients<?, ?> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
167
            if (ingredientsNetwork != null && (ingredientsNetwork.isObservationForcedPending(channel))) {
×
168
                ingredientsNetwork.runObserverSync();
×
169
            }
170
        }
×
171
    }
×
172

173
    /**
174
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
175
     * @param network The target network.
176
     * @param channel The target channel.
177
     * @param ingredientComponent The ingredient component type of the instance.
178
     * @param instance The instance to craft.
179
     * @param matchCondition The match condition of the instance.
180
     * @param craftMissing If the missing required ingredients should also be crafted.
181
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
182
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
183
     * @param collectMissingRecipes If the missing recipes should be collected inside
184
     *                              {@link UnknownCraftingRecipeException}.
185
     *                              This may slow down calculation for deeply nested recipe graphs.
186
     * @param <T> The instance type.
187
     * @param <M> The matching condition parameter.
188
     * @return The crafting job for the given instance.
189
     * @throws UnknownCraftingRecipeException If the recipe for a (sub)ingredient is unavailable.
190
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
191
     */
192
    public static <T, M> CraftingJob calculateCraftingJobs(INetwork network, int channel,
193
                                                           IngredientComponent<T, M> ingredientComponent,
194
                                                           T instance, M matchCondition, boolean craftMissing,
195
                                                           IIdentifierGenerator identifierGenerator,
196
                                                           CraftingJobDependencyGraph craftingJobsGraph,
197
                                                           boolean collectMissingRecipes)
198
            throws UnknownCraftingRecipeException, RecursiveCraftingRecipeException {
199
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
200
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
201
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
202
        beforeCalculateCraftingJobs(network, channel);
×
203

204
        CraftingJob craftingJob = calculateCraftingJobs(recipeIndex, channel, storageGetter, ingredientComponent, instance, matchCondition,
×
205
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
206
                collectMissingRecipes);
207
        craftingJobsGraph.addCraftingJobId(craftingJob);
×
208
        return craftingJob;
×
209
    }
210

211
    /**
212
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
213
     * @param network The target network.
214
     * @param channel The target channel.
215
     * @param recipe The recipe to calculate a job for.
216
     * @param amount The amount of times the recipe should be crafted.
217
     * @param craftMissing If the missing required ingredients should also be crafted.
218
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
219
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
220
     * @param collectMissingRecipes If the missing recipes should be collected inside
221
     *                              {@link FailedCraftingRecipeException}.
222
     *                              This may slow down calculation for deeply nested recipe graphs.
223
     * @return The crafting job for the given instance.
224
     * @throws FailedCraftingRecipeException If the recipe could not be crafted due to missing sub-dependencies.
225
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
226
     */
227
    public static CraftingJob calculateCraftingJobs(INetwork network, int channel,
228
                                                    IRecipeDefinition recipe, int amount, boolean craftMissing,
229
                                                    IIdentifierGenerator identifierGenerator,
230
                                                    CraftingJobDependencyGraph craftingJobsGraph,
231
                                                    boolean collectMissingRecipes)
232
            throws FailedCraftingRecipeException, RecursiveCraftingRecipeException {
233
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
234
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
235
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
236
        beforeCalculateCraftingJobs(network, channel);
×
237

238
        PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel, storageGetter, recipe, amount,
×
239
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
240
                collectMissingRecipes);
241
        if (result.getCraftingJob() == null) {
×
242
            throw new FailedCraftingRecipeException(recipe, amount, result.getMissingDependencies(),
×
243
                    compressMixedIngredients(new MixedIngredients(result.getIngredientsStorage())), result.getPartialCraftingJobs());
×
244
        } else {
245
            craftingJobsGraph.addCraftingJobId(result.getCraftingJob());
×
246
            return result.getCraftingJob();
×
247
        }
248
    }
249

250
    /**
251
     * @return An identifier generator for crafting jobs.
252
     */
253
    public static IIdentifierGenerator getGlobalCraftingJobIdentifier() {
254
        return () -> IntegratedCrafting.globalCounters.getNext("craftingJob");
×
255
    }
256

257
    /**
258
     * Calculate the effective quantity for the given instance in the output of the given recipe.
259
     * @param recipe A recipe.
260
     * @param ingredientComponent The ingredient component.
261
     * @param instance An instance.
262
     * @param matchCondition A match condition.
263
     * @param <T> The instance type.
264
     * @param <M> The matching condition parameter.
265
     * @return The effective quantity.
266
     */
267
    public static <T, M> long getOutputQuantityForRecipe(IRecipeDefinition recipe,
268
                                                         IngredientComponent<T, M> ingredientComponent,
269
                                                         T instance, M matchCondition) {
270
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
271
        return recipe.getOutput().getInstances(ingredientComponent)
1✔
272
                .stream()
1✔
273
                .filter(i -> matcher.matches(i, instance, matchCondition))
1✔
274
                .mapToLong(matcher::getQuantity)
1✔
275
                .sum();
1✔
276
    }
277

278
    /**
279
     * Calculate a crafting job for the given instance.
280
     *
281
     * This method is merely an easily-stubbable implementation for the method above,
282
     * to simplify unit testing.
283
     *
284
     * @param recipeIndex The recipe index.
285
     * @param channel The target channel that will be stored in created crafting jobs.
286
     * @param storageGetter A callback function to get a storage for the given ingredient component.
287
     * @param ingredientComponent The ingredient component type of the instance.
288
     * @param instance The instance to craft.
289
     * @param matchCondition The match condition of the instance.
290
     * @param craftMissing If the missing required ingredients should also be crafted.
291
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
292
     *                                  This is to make sure that instances can not be extracted multiple times
293
     *                                  when simulating.
294
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
295
     * @param identifierGenerator An ID generator for crafting jobs.
296
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
297
     * @param parentDependencies A set of parent recipe dependencies that are pending.
298
     *                           This is used to check for infinite recursion in recipes.
299
     * @param collectMissingRecipes If the missing recipes should be collected inside
300
     *                              {@link UnknownCraftingRecipeException}.
301
     *                              This may slow down calculation for deeply nested recipe graphs.
302
     * @param <T> The instance type.
303
     * @param <M> The matching condition parameter.
304
     * @return The crafting job for the given instance.
305
     * @throws UnknownCraftingRecipeException If the recipe for a (sub)ingredient is unavailable.
306
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
307
     */
308
    protected static <T, M> CraftingJob calculateCraftingJobs(IRecipeIndex recipeIndex, int channel,
309
                                                              Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
310
                                                              IngredientComponent<T, M> ingredientComponent,
311
                                                              T instance, M matchCondition, boolean craftMissing,
312
                                                              Map<IngredientComponent<?, ?>,
313
                                                                      IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
314
                                                              Map<IngredientComponent<?, ?>,
315
                                                                      IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
316
                                                              IIdentifierGenerator identifierGenerator,
317
                                                              CraftingJobDependencyGraph craftingJobsGraph,
318
                                                              Set<IPrototypedIngredient> parentDependencies,
319
                                                              boolean collectMissingRecipes)
320
            throws UnknownCraftingRecipeException, RecursiveCraftingRecipeException {
321
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
322
        // This matching condition makes it so that the recipe output does not have to match with the requested input by quantity.
323
        M quantifierlessCondition = matcher.withoutCondition(matchCondition,
1✔
324
                ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
325
        long instanceQuantity = matcher.getQuantity(instance);
1✔
326

327
        // Loop over all available recipes, and return the first valid one.
328
        Iterator<IRecipeDefinition> recipes = recipeIndex.getRecipes(ingredientComponent, instance, quantifierlessCondition);
1✔
329
        List<UnknownCraftingRecipeException> firstMissingDependencies = Lists.newArrayList();
1✔
330
        Map<IngredientComponent<?, ?>, List<?>> firstIngredientsStorage = Collections.emptyMap();
1✔
331
        List<CraftingJob> firstPartialCraftingJobs = Lists.newArrayList();
1✔
332
        while (recipes.hasNext()) {
1✔
333
            IRecipeDefinition recipe = recipes.next();
1✔
334

335
            // Calculate the quantity for the given instance that the recipe outputs
336
            long recipeOutputQuantity = getOutputQuantityForRecipe(recipe, ingredientComponent, instance, quantifierlessCondition);
1✔
337
            // Based on the quantity of the recipe output, calculate the amount of required recipe jobs.
338
            int amount = (int) Math.ceil(((float) instanceQuantity) / (float) recipeOutputQuantity);
1✔
339

340
            // Calculate jobs for the given recipe
341
            PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel,
1✔
342
                    storageGetter, recipe, amount, craftMissing,
343
                    simulatedExtractionMemory, extractionMemoryReusable, identifierGenerator, craftingJobsGraph, parentDependencies,
344
                    collectMissingRecipes && firstMissingDependencies.isEmpty());
1✔
345
            if (result.getCraftingJob() == null) {
1✔
346
                firstMissingDependencies = result.getMissingDependencies();
1✔
347
                firstIngredientsStorage = result.getIngredientsStorage();
1✔
348
                if (result.getPartialCraftingJobs() != null) {
1✔
349
                    firstPartialCraftingJobs = result.getPartialCraftingJobs();
1✔
350
                }
351
            } else {
352
                return result.getCraftingJob();
1✔
353
            }
354
        }
1✔
355

356
        // No valid recipes were available, so we error or collect the missing instance.
357
        throw new UnknownCraftingRecipeException(new PrototypedIngredient<>(ingredientComponent, instance, matchCondition),
1✔
358
                matcher.getQuantity(instance), firstMissingDependencies, compressMixedIngredients(new MixedIngredients(firstIngredientsStorage)),
1✔
359
                firstPartialCraftingJobs);
360
    }
361

362
    /**
363
     * Calculate a crafting job for the given recipe.
364
     *
365
     * This method is merely an easily-stubbable implementation for the method above,
366
     * to simplify unit testing.
367
     *
368
     * @param recipeIndex The recipe index.
369
     * @param channel The target channel that will be stored in created crafting jobs.
370
     * @param storageGetter A callback function to get a storage for the given ingredient component.
371
     * @param recipe The recipe to calculate a job for.
372
     * @param amount The amount of times the recipe should be crafted.
373
     * @param craftMissing If the missing required ingredients should also be crafted.
374
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
375
     *                                  This is to make sure that instances can not be extracted multiple times
376
     *                                  when simulating.
377
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
378
     * @param identifierGenerator An ID generator for crafting jobs.
379
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
380
     * @param parentDependencies A set of parent recipe dependencies that are pending.
381
     *                           This is used to check for infinite recursion in recipes.
382
     * @param collectMissingRecipes If the missing recipes should be collected inside
383
     *                              {@link UnknownCraftingRecipeException}.
384
     *                              This may slow down calculation for deeply nested recipe graphs.
385
     * @return The crafting job for the given instance.
386
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
387
     */
388
    protected static PartialCraftingJobCalculation calculateCraftingJobs(
389
            IRecipeIndex recipeIndex, int channel,
390
            Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
391
            IRecipeDefinition recipe, int amount, boolean craftMissing,
392
            Map<IngredientComponent<?, ?>,
393
                    IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
394
            Map<IngredientComponent<?, ?>,
395
                    IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
396
            IIdentifierGenerator identifierGenerator,
397
            CraftingJobDependencyGraph craftingJobsGraph,
398
            Set<IPrototypedIngredient> parentDependencies,
399
            boolean collectMissingRecipes)
400
            throws RecursiveCraftingRecipeException {
401
        List<UnknownCraftingRecipeException> missingDependencies = Lists.newArrayList();
1✔
402
        List<CraftingJob> partialCraftingJobs = Lists.newArrayList();
1✔
403

404
        // Check if all requirements are met for this recipe, if so return directly (don't schedule yet)
405
        Pair<Map<IngredientComponent<?, ?>, List<?>>, Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>>> simulation =
1✔
406
                getRecipeInputs(storageGetter, recipe, true, simulatedExtractionMemory, extractionMemoryReusable,
1✔
407
                        true, amount);
408
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> missingIngredients = simulation.getRight();
1✔
409
        if (!craftMissing && !missingIngredients.isEmpty()) {
1✔
410
            if (collectMissingRecipes) {
1✔
411
                // Collect missing ingredients as missing recipes when we don't want to craft sub-components,
412
                // but they are missing.
413
                for (Map.Entry<IngredientComponent<?, ?>, MissingIngredients<?, ?>> entry : missingIngredients.entrySet()) {
1✔
414
                    for (MissingIngredients.Element<?, ?> element : entry.getValue().getElements()) {
1✔
415
                        MissingIngredients.PrototypedWithRequested<?, ?> alternative = element.getAlternatives().get(0);
1✔
416

417
                        // Calculate the instance that was available in storage
418
                        IngredientComponent<?, ?> component = alternative.getRequestedPrototype().getComponent();
1✔
419
                        IIngredientMatcher matcher = component.getMatcher();
1✔
420
                        long storedQuantity = matcher.getQuantity(alternative.getRequestedPrototype().getPrototype()) - alternative.getQuantityMissing();
1✔
421
                        Map<IngredientComponent<?, ?>, List<?>> storageMap;
422
                        if (storedQuantity > 0) {
1✔
423
                            storageMap = Maps.newIdentityHashMap();
×
424
                            storageMap.put(component, Collections.singletonList(
×
425
                                    matcher.withQuantity(alternative.getRequestedPrototype().getPrototype(), storedQuantity)
×
426
                            ));
427
                        } else {
428
                            storageMap = Collections.emptyMap();
1✔
429
                        }
430

431
                        missingDependencies.add(new UnknownCraftingRecipeException(
1✔
432
                                alternative.getRequestedPrototype(), alternative.getQuantityMissing(),
1✔
433
                                Collections.emptyList(), compressMixedIngredients(new MixedIngredients(storageMap)), Lists.newArrayList()));
1✔
434
                    }
1✔
435
                }
1✔
436
            }
437
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), null);
1✔
438
        }
439

440
        // For all missing ingredients, recursively call this method for all missing items, and add as dependencies
441
        // We store dependencies as a mapping from recipe to job,
442
        // so that only one job exist per unique recipe,
443
        // so that a job amount can be incremented once another equal recipe is found.
444
        Map<IRecipeDefinition, CraftingJob> dependencies = Maps.newHashMapWithExpectedSize(missingIngredients.size());
1✔
445
        Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> dependenciesOutputSurplus = Maps.newIdentityHashMap();
1✔
446
        // We must be able to find crafting jobs for all dependencies
447
        for (IngredientComponent dependencyComponent : missingIngredients.keySet()) {
1✔
448
            try {
449
                // TODO: if we run into weird simulated extraction bugs, we may have to scope simulatedExtractionMemory, but I'm not sure about this (yet)
450
                PartialCraftingJobCalculationDependency resultDependency = calculateCraftingJobDependencyComponent(
1✔
451
                        dependencyComponent, dependenciesOutputSurplus, missingIngredients.get(dependencyComponent), parentDependencies,
1✔
452
                        dependencies, recipeIndex, channel, storageGetter, simulatedExtractionMemory, extractionMemoryReusable,
453
                        identifierGenerator, craftingJobsGraph, collectMissingRecipes);
454
                // Don't check the other components once we have an invalid dependency.
455
                if (!resultDependency.isValid()) {
1✔
456
                    missingDependencies.addAll(resultDependency.getUnknownCrafingRecipes());
1✔
457
                    partialCraftingJobs.addAll(resultDependency.getPartialCraftingJobs());
1✔
458
                    if (!collectMissingRecipes) {
1✔
459
                        break;
1✔
460
                    }
461
                }
462
            } catch (RecursiveCraftingRecipeException e) {
1✔
463
                e.addRecipe(recipe);
1✔
464
                throw e;
1✔
465
            }
1✔
466
        }
1✔
467

468
        // If at least one of our dependencies does not have a valid recipe or is not available,
469
        // go check the next recipe.
470
        if (!missingDependencies.isEmpty()) {
1✔
471
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), partialCraftingJobs);
1✔
472
        }
473

474
        CraftingJob craftingJob = new CraftingJob(identifierGenerator.getNext(), channel, recipe, amount,
1✔
475
                compressMixedIngredients(new MixedIngredients(simulation.getLeft())));
1✔
476
        for (CraftingJob dependency : dependencies.values()) {
1✔
477
            craftingJob.addDependency(dependency);
1✔
478
            craftingJobsGraph.addDependency(craftingJob, dependency);
1✔
479
        }
1✔
480
        return new PartialCraftingJobCalculation(craftingJob, null, simulation.getLeft(), null);
1✔
481
    }
482

483
    // Helper function for calculateCraftingJobs, returns a list of non-craftable ingredients and craftable ingredients.
484
    protected static <T, M> PartialCraftingJobCalculationDependency calculateCraftingJobDependencyComponent(
485
            IngredientComponent<T, M> dependencyComponent,
486
            Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> dependenciesOutputSurplus,
487
            MissingIngredients<T, M> missingIngredients,
488
            Set<IPrototypedIngredient> parentDependencies,
489
            Map<IRecipeDefinition, CraftingJob> dependencies,
490
            IRecipeIndex recipeIndex,
491
            int channel,
492
            Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
493
            Map<IngredientComponent<?, ?>,
494
                    IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemory,
495
            Map<IngredientComponent<?, ?>,
496
                    IIngredientCollectionMutable<?, ?>> extractionMemoryReusable,
497
            IIdentifierGenerator identifierGenerator,
498
            CraftingJobDependencyGraph craftingJobsGraph,
499
            boolean collectMissingRecipes)
500
            throws RecursiveCraftingRecipeException {
501
        IIngredientMatcher<T, M> dependencyMatcher = dependencyComponent.getMatcher();
1✔
502
        List<UnknownCraftingRecipeException> missingDependencies = Lists.newArrayList();
1✔
503
        for (MissingIngredients.Element<T, M> missingElement : missingIngredients.getElements()) {
1✔
504
            CraftingJob dependency = null;
1✔
505
            T dependencyInstance = null;
1✔
506
            boolean skipDependency = false;
1✔
507
            UnknownCraftingRecipeException firstError = null;
1✔
508
            // Loop over all prototype alternatives, at least one has to match.
509
            for (MissingIngredients.PrototypedWithRequested<T, M> prototypedAlternative : missingElement.getAlternatives()) {
1✔
510
                // Check if the missing element is reusable, and was triggered for craft earlier.
511
                if (missingElement.isInputReusable() && ((IIngredientCollectionMutable<T, M>) extractionMemoryReusable.get(dependencyComponent))
1✔
512
                        .contains(prototypedAlternative.getRequestedPrototype().getPrototype())) {
1✔
513
                    // Nothing has to be crafted anymore, jump to next dependency
514
                    skipDependency = true;
1✔
515
                    break;
1✔
516
                }
517

518
                IPrototypedIngredient<T, M> prototype = new PrototypedIngredient<>(
1✔
519
                        dependencyComponent,
520
                        dependencyMatcher.withQuantity(prototypedAlternative.getRequestedPrototype().getPrototype(), prototypedAlternative.getQuantityMissing()),
1✔
521
                        prototypedAlternative.getRequestedPrototype().getCondition()
1✔
522
                );
523
                // First check if we can grab it from previous surplus
524
                IngredientCollectionPrototypeMap<T, M> dependencyComponentSurplusOld = (IngredientCollectionPrototypeMap<T, M>) dependenciesOutputSurplus.get(dependencyComponent);
1✔
525
                IngredientCollectionPrototypeMap<T, M> dependencyComponentSurplus = null;
1✔
526
                if (dependencyComponentSurplusOld != null) {
1✔
527
                    // First create a copy of the given surplus store,
528
                    // and only once we see that the prototype is valid,
529
                    // save this copy again.
530
                    // This is because if this prototype is invalid,
531
                    // then we don't want these invalid surpluses.
532
                    dependencyComponentSurplus = new IngredientCollectionPrototypeMap<>(dependencyComponentSurplusOld.getComponent(), true);
1✔
533
                    dependencyComponentSurplus.addAll(dependencyComponentSurplusOld);
1✔
534

535
                    long remainingQuantity = dependencyMatcher.getQuantity(prototype.getPrototype());
1✔
536
                    IIngredientMatcher<T, M> prototypeMatcher = prototype.getComponent().getMatcher();
1✔
537
                    // Check all instances in the surplus that match with the given prototype
538
                    // For each match, we subtract its quantity from the required quantity.
539
                    Iterator<T> surplusIt = dependencyComponentSurplus.iterator(prototype.getPrototype(),
1✔
540
                            prototypeMatcher.withoutCondition(prototype.getCondition(), prototype.getComponent().getPrimaryQuantifier().getMatchCondition()));
1✔
541
                    boolean updatedRemainingQuantity = false;
1✔
542
                    while (remainingQuantity > 0 && surplusIt.hasNext()) {
1✔
543
                        updatedRemainingQuantity = true;
1✔
544
                        T matchingInstance = surplusIt.next();
1✔
545
                        long matchingInstanceQuantity = dependencyMatcher.getQuantity(matchingInstance);
1✔
546
                        if (matchingInstanceQuantity <= remainingQuantity) {
1✔
547
                            // This whole surplus instance can be consumed
548
                            remainingQuantity -= matchingInstanceQuantity;
1✔
549
                            surplusIt.remove();
1✔
550
                        } else {
551
                            // Only part of this surplus instance can be consumed.
552
                            matchingInstanceQuantity -= remainingQuantity;
1✔
553
                            remainingQuantity = 0;
1✔
554
                            surplusIt.remove();
1✔
555
                            dependencyComponentSurplus.setQuantity(matchingInstance, matchingInstanceQuantity);
1✔
556
                        }
557
                    }
1✔
558
                    if (updatedRemainingQuantity) {
1✔
559
                        if (remainingQuantity == 0) {
1✔
560
                            // The prototype is valid,
561
                            // so we can finally store our temporary surplus
562
                            dependenciesOutputSurplus.put(dependencyComponent, dependencyComponentSurplus);
1✔
563

564
                            // Nothing has to be crafted anymore, jump to next dependency
565
                            skipDependency = true;
1✔
566
                            break;
1✔
567
                        } else {
568
                            // Partial availability, other part needs to be crafted still.
569
                            prototype = new PrototypedIngredient<>(dependencyComponent,
1✔
570
                                    dependencyMatcher.withQuantity(prototype.getPrototype(), remainingQuantity),
1✔
571
                                    prototype.getCondition());
1✔
572
                        }
573
                    }
574
                }
575

576
                // Try to craft the given prototype
577
                try {
578
                    Set<IPrototypedIngredient> childDependencies = Sets.newHashSet(parentDependencies);
1✔
579
                    if (!childDependencies.add(prototype)) {
1✔
580
                        throw new RecursiveCraftingRecipeException(prototype);
1✔
581
                    }
582

583
                    dependency = calculateCraftingJobs(recipeIndex, channel, storageGetter,
1✔
584
                            dependencyComponent, prototype.getPrototype(),
1✔
585
                            prototype.getCondition(), true, simulatedExtractionMemory, extractionMemoryReusable,
1✔
586
                            identifierGenerator, craftingJobsGraph, childDependencies, collectMissingRecipes);
587
                    dependencyInstance = prototype.getPrototype();
1✔
588

589
                    // The prototype is valid,
590
                    // so we can finally store our temporary surplus
591
                    if (dependencyComponentSurplus != null) {
1✔
592
                        dependenciesOutputSurplus.put(dependencyComponent, dependencyComponentSurplus);
1✔
593
                    }
594

595
                    // Add the auxiliary recipe outputs that are not requested to the surplus
596
                    Object dependencyQuantifierlessCondition = dependencyMatcher.withoutCondition(prototype.getCondition(),
1✔
597
                            dependencyComponent.getPrimaryQuantifier().getMatchCondition());
1✔
598
                    long requestedQuantity = dependencyMatcher.getQuantity(prototype.getPrototype());
1✔
599
                    for (IngredientComponent outputComponent : dependency.getRecipe().getOutput().getComponents()) {
1✔
600
                        IngredientCollectionPrototypeMap<?, ?> componentSurplus = dependenciesOutputSurplus.get(outputComponent);
1✔
601
                        if (componentSurplus == null) {
1✔
602
                            componentSurplus = new IngredientCollectionPrototypeMap<>(outputComponent, true);
1✔
603
                            dependenciesOutputSurplus.put(outputComponent, componentSurplus);
1✔
604
                        }
605
                        List<Object> instances = dependency.getRecipe().getOutput().getInstances(outputComponent);
1✔
606
                        long recipeAmount = dependency.getAmount();
1✔
607
                        if (recipeAmount > 1) {
1✔
608
                            IIngredientMatcher matcher = outputComponent.getMatcher();
1✔
609
                            // If more than one recipe amount was crafted, correctly multiply the outputs to calculate the effective surplus.
610
                            instances = instances
1✔
611
                                    .stream()
1✔
612
                                    .map(instance -> matcher.withQuantity(instance, matcher.getQuantity(instance) * recipeAmount))
1✔
613
                                    .collect(Collectors.toList());
1✔
614
                        }
615
                        addRemainderAsSurplusForComponent(outputComponent, (List) instances, componentSurplus,
1✔
616
                                (IngredientComponent) prototype.getComponent(), prototype.getPrototype(), dependencyQuantifierlessCondition,
1✔
617
                                requestedQuantity);
618
                    }
1✔
619

620
                    break;
1✔
621
                } catch (UnknownCraftingRecipeException e) {
1✔
622
                    // Save the first error, and check the next prototype
623
                    if (firstError == null) {
1✔
624
                        // Modify the error so that the correct missing quantity is stored
625
                        firstError = new UnknownCraftingRecipeException(
1✔
626
                                e.getIngredient(), prototypedAlternative.getQuantityMissing(),
1✔
627
                                e.getMissingChildRecipes(), compressMixedIngredients(e.getIngredientsStorage()), e.getPartialCraftingJobs());
1✔
628
                    }
629
                }
630
            }
1✔
631

632
            // Check if this dependency can be skipped
633
            if (skipDependency) {
1✔
634
                continue;
1✔
635
            }
636

637
            // If no valid crafting recipe was found for the current sub-instance, re-throw its error
638
            if (dependency == null) {
1✔
639
                missingDependencies.add(firstError);
1✔
640
                if (collectMissingRecipes) {
1✔
641
                    continue;
1✔
642
                } else {
643
                    break;
644
                }
645
            }
646

647
            // --- When we reach this point, a valid sub-recipe was found ---
648

649
            // Update our simulatedExtractionMemory to indicate that the dependency's
650
            // instance should not be extracted anymore.
651
            ((IngredientCollectionPrototypeMap<T, M>) simulatedExtractionMemory.get(dependencyComponent))
1✔
652
                    .remove(dependencyInstance);
1✔
653

654
            // If the dependency instance is reusable, mark it as available in our reusable extraction memory
655
            if (missingElement.isInputReusable()) {
1✔
656
                ((IIngredientCollectionMutable<T, M>) extractionMemoryReusable.get(dependencyComponent)).add(dependencyInstance);
1✔
657
            }
658

659
            // Add the valid sub-recipe it to our dependencies
660
            // If the recipe was already present at this level, just increment the amount of the existing job.
661
            CraftingJob existingJob = dependencies.get(dependency.getRecipe());
1✔
662
            if (existingJob == null) {
1✔
663
                dependencies.put(dependency.getRecipe(), dependency);
1✔
664
            } else {
665
                // Remove the standalone dependency job by merging it into the existing job
666
                craftingJobsGraph.mergeCraftingJobs(existingJob, dependency, true);
1✔
667
            }
668
        }
1✔
669

670
        return new PartialCraftingJobCalculationDependency(missingDependencies, dependencies.values());
1✔
671
    }
672

673
    // Helper function for calculateCraftingJobDependencyComponent
674
    protected static <T1, M1, T2, M2> void addRemainderAsSurplusForComponent(IngredientComponent<T1, M1> ingredientComponent,
675
                                                                             List<T1> instances,
676
                                                                             IngredientCollectionPrototypeMap<T1, M1> simulatedExtractionMemory,
677
                                                                             IngredientComponent<T2, M2> blackListComponent,
678
                                                                             T2 blacklistInstance, M2 blacklistCondition,
679
                                                                             long blacklistQuantity) {
680
        IIngredientMatcher<T2, M2> blacklistMatcher = blackListComponent.getMatcher();
1✔
681
        for (T1 instance : instances) {
1✔
682
            IIngredientMatcher<T1, M1> outputMatcher = ingredientComponent.getMatcher();
1✔
683
            long reduceQuantity = 0;
1✔
684
            if (blackListComponent == ingredientComponent
1✔
685
                    && blacklistMatcher.matches(blacklistInstance, (T2) instance, blacklistCondition)) {
1✔
686
                reduceQuantity = blacklistQuantity;
1✔
687
            }
688
            long quantity = simulatedExtractionMemory.getQuantity(instance) + (outputMatcher.getQuantity(instance) - reduceQuantity);
1✔
689
            if (quantity > 0) {
1✔
690
                simulatedExtractionMemory.setQuantity(instance, quantity);
1✔
691
            }
692
        }
1✔
693
    }
1✔
694

695
    /**
696
     * Schedule all crafting jobs in the given dependency graph in the given network.
697
     * @param craftingNetwork The target crafting network.
698
     * @param craftingJobDependencyGraph The crafting job dependency graph.
699
     * @param allowDistribution If the crafting jobs are allowed to be split over multiple crafting interfaces.
700
     * @param initiator Optional UUID of the initiator.
701
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
702
     */
703
    public static void scheduleCraftingJobs(ICraftingNetwork craftingNetwork,
704
                                            CraftingJobDependencyGraph craftingJobDependencyGraph,
705
                                            boolean allowDistribution,
706
                                            @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
707
        List<CraftingJob> startedJobs = Lists.newArrayList();
×
708
        craftingNetwork.getCraftingJobDependencyGraph().importDependencies(craftingJobDependencyGraph);
×
709
        for (CraftingJob craftingJob : craftingJobDependencyGraph.getCraftingJobs()) {
×
710
            try {
711
                craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution);
×
712
            } catch (UnavailableCraftingInterfacesException e) {
×
713
                // First, cancel all jobs that were already started
714
                for (CraftingJob startedJob : startedJobs) {
×
715
                    craftingNetwork.cancelCraftingJob(startedJob.getChannel(), startedJob.getId());
×
716
                }
×
717

718
                // Then, throw an exception for all jobs in this dependency graph
719
                throw new UnavailableCraftingInterfacesException(craftingJobDependencyGraph.getCraftingJobs());
×
720
            }
×
721
            startedJobs.add(craftingJob);
×
722
            if (initiator != null) {
×
723
                craftingJob.setInitiatorUuid(initiator.toString());
×
724
            }
725
        }
×
726
    }
×
727

728
    /**
729
     * Schedule the given crafting job  in the given network.
730
     * @param craftingNetwork The target crafting network.
731
     * @param craftingJob The crafting job to schedule.
732
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
733
     * @param initiator Optional UUID of the initiator.
734
     * @return The scheduled crafting job.
735
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
736
     */
737
    public static CraftingJob scheduleCraftingJob(ICraftingNetwork craftingNetwork,
738
                                                  CraftingJob craftingJob,
739
                                                  boolean allowDistribution,
740
                                                  @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
741
        craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution);
×
742
        if (initiator != null) {
×
743
            craftingJob.setInitiatorUuid(initiator.toString());
×
744
        }
745
        return craftingJob;
×
746
    }
747

748
    /**
749
     * Schedule a crafting job for the given instance in the given network.
750
     * @param network The target network.
751
     * @param channel The target channel.
752
     * @param ingredientComponent The ingredient component type of the instance.
753
     * @param instance The instance to craft.
754
     * @param matchCondition The match condition of the instance.
755
     * @param craftMissing If the missing required ingredients should also be crafted.
756
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
757
     * @param identifierGenerator An ID generator for crafting jobs.
758
     * @param initiator Optional UUID of the initiator.
759
     * @param <T> The instance type.
760
     * @param <M> The matching condition parameter.
761
     * @return The scheduled crafting job, or null if no recipe was found.
762
     */
763
    @Nullable
764
    public static <T, M> CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
765
                                                                     IngredientComponent<T, M> ingredientComponent,
766
                                                                     T instance, M matchCondition,
767
                                                                     boolean craftMissing, boolean allowDistribution,
768
                                                                     IIdentifierGenerator identifierGenerator,
769
                                                                     @Nullable UUID initiator) {
770
        try {
771
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
772
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, ingredientComponent, instance,
×
773
                    matchCondition, craftMissing, identifierGenerator, dependencyGraph, false);
774

775
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
776

777
            scheduleCraftingJobs(craftingNetwork, dependencyGraph, allowDistribution, initiator);
×
778

779
            return craftingJob;
×
780
        } catch (UnknownCraftingRecipeException | RecursiveCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
781
            return null;
×
782
        }
783
    }
784

785
    /**
786
     * Schedule a crafting job for the given recipe in the given network.
787
     * @param network The target network.
788
     * @param channel The target channel.
789
     * @param recipe The recipe to craft.
790
     * @param amount The amount to craft.
791
     * @param craftMissing If the missing required ingredients should also be crafted.
792
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
793
     * @param identifierGenerator An ID generator for crafting jobs.
794
     * @param initiator Optional UUID of the initiator.
795
     * @return The scheduled crafting job, or null if no recipe was found.
796
     */
797
    @Nullable
798
    public static CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
799
                                                              IRecipeDefinition recipe, int amount,
800
                                                              boolean craftMissing, boolean allowDistribution,
801
                                                              IIdentifierGenerator identifierGenerator,
802
                                                              @Nullable UUID initiator) {
803
        try {
804
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
805
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, recipe, amount, craftMissing,
×
806
                    identifierGenerator, dependencyGraph, false);
807

808
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
809

810
            scheduleCraftingJobs(craftingNetwork, dependencyGraph, allowDistribution, initiator);
×
811

812
            return craftingJob;
×
813
        } catch (RecursiveCraftingRecipeException | FailedCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
814
            return null;
×
815
        }
816
    }
817

818
    /**
819
     * Check if the given network contains the given instance in any of its storages.
820
     * @param network The target network.
821
     * @param channel The target channel.
822
     * @param ingredientComponent The ingredient component type of the instance.
823
     * @param instance The instance to check.
824
     * @param matchCondition The match condition of the instance.
825
     * @param <T> The instance type.
826
     * @param <M> The matching condition parameter.
827
     * @return If the instance is present in the network.
828
     */
829
    public static <T, M> boolean hasStorageInstance(INetwork network, int channel,
830
                                                    IngredientComponent<T, M> ingredientComponent,
831
                                                    T instance, M matchCondition) {
832
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
833
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
834
        boolean contains;
835
        if (storage instanceof IngredientChannelIndexed) {
×
836
            IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
837
            long quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
838
            contains = matcher.hasCondition(matchCondition, ingredientComponent.getPrimaryQuantifier().getMatchCondition()) ? quantityPresent >= matcher.getQuantity(instance) : quantityPresent > 0;
×
839
        } else {
×
840
            contains = !ingredientComponent.getMatcher().isEmpty(storage.extract(instance, matchCondition, true));
×
841
        }
842
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
843
        return contains;
×
844
    }
845

846
    /**
847
     * Check the quantity of the given instance in the network.
848
     * @param network The target network.
849
     * @param channel The target channel.
850
     * @param ingredientComponent The ingredient component type of the instance.
851
     * @param instance The instance to check.
852
     * @param matchCondition The match condition of the instance.
853
     * @param <T> The instance type.
854
     * @param <M> The matching condition parameter.
855
     * @return The quantity in the network.
856
     */
857
    public static <T, M> long getStorageInstanceQuantity(INetwork network, int channel,
858
                                                         IngredientComponent<T, M> ingredientComponent,
859
                                                         T instance, M matchCondition) {
860
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
861
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
862
        long quantityPresent;
863
        if (storage instanceof IngredientChannelIndexed) {
×
864
            quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
865
        } else {
866
            quantityPresent = ingredientComponent.getMatcher().getQuantity(storage.extract(instance, matchCondition, true));
×
867
        }
868
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
869
        return quantityPresent;
×
870
    }
871

872
    /**
873
     * Check if there is a scheduled crafting job for the given instance.
874
     * @param craftingNetwork The target crafting network.
875
     * @param channel The target channel.
876
     * @param ingredientComponent The ingredient component type of the instance.
877
     * @param instance The instance to check.
878
     * @param matchCondition The match condition of the instance.
879
     * @param <T> The instance type.
880
     * @param <M> The matching condition parameter.
881
     * @return If the instance has a crafting job.
882
     */
883
    public static <T, M> boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
884
                                            IngredientComponent<T, M> ingredientComponent,
885
                                            T instance, M matchCondition) {
886
        Iterator<CraftingJob> craftingJobs = craftingNetwork.getCraftingJobs(channel, ingredientComponent,
×
887
                instance, matchCondition);
888
        return craftingJobs.hasNext();
×
889
    }
890

891
    /**
892
     * Check if there is a scheduled crafting job for the given recipe.
893
     * @param craftingNetwork The target crafting network.
894
     * @param channel The target channel.
895
     * @param recipe The recipe to check.
896
     * @return If the instance has a crafting job.
897
     */
898
    public static boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
899
                                     IRecipeDefinition recipe) {
900
        Iterator<CraftingJob> it = craftingNetwork.getCraftingJobs(channel);
×
901
        while (it.hasNext()) {
×
902
            if (it.next().getRecipe().equals(recipe)) {
×
903
                return true;
×
904
            }
905
        }
906
        return false;
×
907
    }
908

909
    /**
910
     * Get all required recipe input ingredients from the network for the given ingredient component.
911
     *
912
     * If multiple alternative inputs are possible,
913
     * then only the first possible match will be taken.
914
     *
915
     * Note: Make sure that you first call in simulation-mode
916
     * to see if the ingredients are available.
917
     * If you immediately call this non-simulated,
918
     * then there might be a chance that ingredients are lost
919
     * from the network.
920
     *
921
     * @param storage The target storage.
922
     * @param ingredientComponent The ingredient component to get the ingredients for.
923
     * @param recipe The recipe to get the inputs from.
924
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
925
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
926
     * @param <T> The instance type.
927
     * @param <M> The matching condition parameter, may be Void.
928
     * @return A list of slot-based ingredients, or null if no valid inputs could be found.
929
     */
930
    @Nullable
931
    public static <T, M> List<T> getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage,
932
                                                           IngredientComponent<T, M> ingredientComponent,
933
                                                           IRecipeDefinition recipe, boolean simulate,
934
                                                           long recipeOutputQuantity) {
935
        return getIngredientRecipeInputs(storage, ingredientComponent, recipe, simulate,
1✔
936
                simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null,
1✔
937
                new IngredientHashSet<>(ingredientComponent),
938
                false, recipeOutputQuantity).getLeft();
1✔
939
    }
940

941
    /**
942
     * Get all required recipe input ingredients from the network for the given ingredient component,
943
     * and optionally, explicitly calculate the missing ingredients.
944
     *
945
     * If multiple alternative inputs are possible,
946
     * then only the first possible match will be taken.
947
     *
948
     * Note: Make sure that you first call in simulation-mode
949
     * to see if the ingredients are available.
950
     * If you immediately call this non-simulated,
951
     * then there might be a chance that ingredients are lost
952
     * from the network.
953
     *
954
     * @param storage The target storage.
955
     * @param ingredientComponent The ingredient component to get the ingredients for.
956
     * @param recipe The recipe to get the inputs from.
957
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
958
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
959
     *                                  This is to make sure that instances can not be extracted multiple times
960
     *                                  when simulating.
961
     *                                  The quantities can also go negatives,
962
     *                                  which means that a surplus of the given instance is present,
963
     *                                  which will be used up first before a call to the storage.
964
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
965
     * @param collectMissingIngredients If missing ingredients should be collected.
966
     *                                  If false, then the first returned list may be null
967
     *                                  if no valid matches can be found,
968
     *                                  and the second returned list is always null,
969
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
970
     * @param <T> The instance type.
971
     * @param <M> The matching condition parameter, may be Void.
972
     * @return A pair with two lists:
973
     *           1. A list of available slot-based ingredients.
974
     *           2. A missing ingredients object.
975
     */
976
    public static <T, M> Pair<List<T>, MissingIngredients<T, M>>
977
    getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage, IngredientComponent<T, M> ingredientComponent,
978
                              IRecipeDefinition recipe, boolean simulate,
979
                              IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemory,
980
                              IIngredientCollectionMutable<T, M> extractionMemoryReusable,
981
                              boolean collectMissingIngredients, long recipeOutputQuantity) {
982
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
983

984
        // Quickly return if the storage is empty
985
        // We can't take this shortcut if we have a reusable ingredient AND extractionMemoryReusable is not empty
986
        if (storage.getMaxQuantity() == 0 &&
1✔
987
                extractionMemoryReusable.isEmpty() &&
1✔
988
                IntStream.range(0, recipe.getInputs(ingredientComponent).size())
1✔
989
                        .noneMatch(i -> recipe.isInputReusable(ingredientComponent, i))) {
1✔
990
            if (collectMissingIngredients) {
1✔
991
                List<IPrototypedIngredientAlternatives<T, M>> recipeInputs = recipe.getInputs(ingredientComponent);
1✔
992
                MissingIngredients<T, M> missing = new MissingIngredients<>(recipeInputs.stream().map(IPrototypedIngredientAlternatives::getAlternatives)
1✔
993
                        .map(l -> multiplyPrototypedIngredients(l, recipeOutputQuantity)) // If the input is reusable, don't multiply the expected input quantity
1✔
994
                        .map(ps -> new MissingIngredients.Element<>(ps
1✔
995
                                .stream()
1✔
996
                                .map(p -> new MissingIngredients.PrototypedWithRequested<>(p, matcher.getQuantity(p.getPrototype())))
1✔
997
                                .collect(Collectors.toList()), false)
1✔
998
                        )
999
                        .collect(Collectors.toList()));
1✔
1000
                return Pair.of(
1✔
1001
                        Lists.newArrayList(Collections.nCopies(recipe.getInputs(ingredientComponent).size(),
1✔
1002
                                ingredientComponent.getMatcher().getEmptyInstance())),
1✔
1003
                        missing);
1004
            } else {
1005
                return Pair.of(null, null);
1✔
1006
            }
1007
        }
1008

1009
        // Iterate over all input slots
1010
        List<IPrototypedIngredientAlternatives<T, M>> inputAlternativePrototypes = recipe.getInputs(ingredientComponent);
1✔
1011
        List<T> inputInstances = Lists.newArrayList();
1✔
1012
        List<MissingIngredients.Element<T, M>> missingElements =
1013
                collectMissingIngredients ? Lists.newArrayList() : null;
1✔
1014
        for (int inputIndex = 0; inputIndex < inputAlternativePrototypes.size(); inputIndex++) {
1✔
1015
            IPrototypedIngredientAlternatives<T, M> inputPrototypes = inputAlternativePrototypes.get(inputIndex);
1✔
1016
            T firstInputInstance = null;
1✔
1017
            boolean setFirstInputInstance = false;
1✔
1018
            T inputInstance = null;
1✔
1019
            boolean hasInputInstance = false;
1✔
1020
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBufferFirst = null;
1✔
1021
            IIngredientCollectionMutable<T, M> extractionMemoryReusableBufferFirst = null;
1✔
1022

1023
            // Iterate over all alternatives for this input slot, and take the first matching ingredient.
1024
            List<MissingIngredients.PrototypedWithRequested<T, M>> missingAlternatives = Lists.newArrayList();
1✔
1025
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryAlternative = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1026
            if (simulate) {
1✔
1027
                simulatedExtractionMemoryAlternative.addAll(simulatedExtractionMemory);
1✔
1028
            }
1029
            for (IPrototypedIngredient<T, M> inputPrototype : inputPrototypes.getAlternatives()) {
1✔
1030
                boolean inputReusable = recipe.isInputReusable(ingredientComponent, inputIndex);
1✔
1031
                IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBuffer = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1032
                IIngredientCollectionMutable<T, M> extractionMemoryReusableBuffer = inputReusable ? new IngredientHashSet<>(ingredientComponent) : null;
1✔
1033
                boolean shouldBreak = false;
1✔
1034

1035
                // Multiply required prototype if recipe quantity is higher than one, AND if the input is NOT reusable.
1036
                if (recipeOutputQuantity > 1 && !inputReusable) {
1✔
1037
                    inputPrototype = multiplyPrototypedIngredient(inputPrototype, recipeOutputQuantity);
1✔
1038
                }
1039

1040
                // If the prototype is empty, we can skip network extraction
1041
                if (matcher.isEmpty(inputPrototype.getPrototype())) {
1✔
1042
                    inputInstance = inputPrototype.getPrototype();
1✔
1043
                    hasInputInstance = true;
1✔
1044
                    break;
1✔
1045
                }
1046

1047
                long prototypeQuantity = matcher.getQuantity(inputPrototype.getPrototype());
1✔
1048
                if (inputReusable && extractionMemoryReusable.contains(inputPrototype.getPrototype())) {
1✔
1049
                    // If the reusable item has been extracted before, mark as valid, and don't extract again.
1050
                    inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1051
                    hasInputInstance = true;
1✔
1052
                    shouldBreak = true;
1✔
1053
                } else {
1054
                    long memoryQuantity;
1055
                    if (simulate && (memoryQuantity = simulatedExtractionMemoryAlternative
1✔
1056
                            .getQuantity(inputPrototype.getPrototype())) != 0) {
1✔
1057
                        long newQuantity = memoryQuantity + prototypeQuantity;
1✔
1058
                        if (newQuantity > 0) {
1✔
1059
                            // Part of our quantity can be provided via simulatedExtractionMemory,
1060
                            // but not all of it,
1061
                            // so we need to extract from storage as well.
1062
                            T newInstance = matcher.withQuantity(inputPrototype.getPrototype(), newQuantity);
1✔
1063
                            M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1064
                                    ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1065
                            if (storage instanceof IngredientChannelAdapter)
1✔
1066
                                ((IngredientChannelAdapter) storage).disableLimits();
×
1067
                            T extracted = storage.extract(newInstance, matchCondition, true);
1✔
1068
                            if (storage instanceof IngredientChannelAdapter)
1✔
1069
                                ((IngredientChannelAdapter) storage).enableLimits();
×
1070
                            long quantityExtracted = matcher.getQuantity(extracted);
1✔
1071
                            if (quantityExtracted == newQuantity) {
1✔
1072
                                // All remaining could be extracted from storage, all is fine now
1073
                                inputInstance = inputPrototype.getPrototype();
1✔
1074
                                simulatedExtractionMemoryAlternative.add(inputInstance);
1✔
1075
                                simulatedExtractionMemoryBuffer.add(inputInstance);
1✔
1076
                                if (inputReusable) {
1✔
1077
                                    extractionMemoryReusableBuffer.add(inputInstance);
1✔
1078
                                }
1079
                                hasInputInstance = true;
1✔
1080
                                shouldBreak = true;
1✔
1081
                            } else if (collectMissingIngredients) {
1✔
1082
                                // Not everything could be extracted from storage, we *miss* the remaining ingredient.
1083
                                long quantityMissingPrevious = Math.max(0, memoryQuantity - quantityExtracted);
1✔
1084
                                long quantityMissingTotal = newQuantity - quantityExtracted;
1✔
1085
                                long quantityMissingRelative = quantityMissingTotal - quantityMissingPrevious;
1✔
1086

1087
                                missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissingRelative));
1✔
1088
                                inputInstance = matcher.withQuantity(inputPrototype.getPrototype(), prototypeQuantity - quantityMissingRelative);
1✔
1089
                                simulatedExtractionMemoryAlternative.setQuantity(inputPrototype.getPrototype(), quantityMissingTotal);
1✔
1090
                                simulatedExtractionMemoryBuffer.add(matcher.withQuantity(inputPrototype.getPrototype(), quantityMissingRelative));
1✔
1091
                            }
1092
                        } else {
1✔
1093
                            // All of our quantity can be provided via our surplus in simulatedExtractionMemory
1094
                            simulatedExtractionMemoryAlternative.add(inputPrototype.getPrototype());
1✔
1095
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1096
                            if (inputReusable) {
1✔
1097
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1098
                            }
1099
                            inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1100
                            hasInputInstance = true;
1✔
1101
                            shouldBreak = true;
1✔
1102
                        }
1103
                    } else {
1✔
1104
                        M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1105
                                ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1106
                        if (storage instanceof IngredientChannelAdapter)
1✔
1107
                            ((IngredientChannelAdapter) storage).disableLimits();
×
1108
                        T extracted = storage.extract(inputPrototype.getPrototype(), matchCondition, simulate);
1✔
1109
                        if (storage instanceof IngredientChannelAdapter)
1✔
1110
                            ((IngredientChannelAdapter) storage).enableLimits();
×
1111
                        long quantityExtracted = matcher.getQuantity(extracted);
1✔
1112
                        inputInstance = extracted;
1✔
1113
                        if (simulate) {
1✔
1114
                            simulatedExtractionMemoryAlternative.add(extracted);
1✔
1115
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1116
                        }
1117
                        if (prototypeQuantity == quantityExtracted) {
1✔
1118
                            hasInputInstance = true;
1✔
1119
                            shouldBreak = true;
1✔
1120
                            if (inputReusable) {
1✔
1121
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1122
                            }
1123
                        } else if (collectMissingIngredients) {
1✔
1124
                            long quantityMissing = prototypeQuantity - quantityExtracted;
1✔
1125
                            missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissing));
1✔
1126
                        }
1127
                    }
1128
                }
1129

1130
                if (!setFirstInputInstance || shouldBreak) {
1✔
1131
                    setFirstInputInstance = true;
1✔
1132
                    firstInputInstance = inputInstance;
1✔
1133
                    simulatedExtractionMemoryBufferFirst = simulatedExtractionMemoryBuffer;
1✔
1134
                    if (inputReusable) {
1✔
1135
                        extractionMemoryReusableBufferFirst = extractionMemoryReusableBuffer;
1✔
1136
                    } else {
1137
                        extractionMemoryReusableBufferFirst = null;
1✔
1138
                    }
1139
                }
1140

1141
                if (shouldBreak) {
1✔
1142
                    break;
1✔
1143
                }
1144
            }
1✔
1145

1146
            if (simulatedExtractionMemoryBufferFirst != null) {
1✔
1147
                for (T instance : simulatedExtractionMemoryBufferFirst) {
1✔
1148
                    simulatedExtractionMemory.add(instance);
1✔
1149
                }
1✔
1150
            }
1151
            if (extractionMemoryReusableBufferFirst != null) {
1✔
1152
                for (T instance : extractionMemoryReusableBufferFirst) {
1✔
1153
                    extractionMemoryReusable.add(instance);
1✔
1154
                }
1✔
1155
            }
1156

1157
            // If none of the alternatives were found, fail immediately
1158
            if (!hasInputInstance) {
1✔
1159
                if (!simulate) {
1✔
1160
                    // But first, re-insert all already-extracted instances
1161
                    for (T instance : inputInstances) {
1✔
1162
                        T remaining = storage.insert(instance, false);
1✔
1163
                        if (!matcher.isEmpty(remaining)) {
1✔
1164
                            throw new IllegalStateException("Extraction for a crafting recipe failed" +
×
1165
                                    "due to inconsistent insertion behaviour by destination in simulation " +
1166
                                    "and non-simulation: " + storage + ". Lost: " + remaining);
1167
                        }
1168
                    }
1✔
1169
                }
1170

1171
                if (!collectMissingIngredients) {
1✔
1172
                    // This input failed, return immediately
1173
                    return Pair.of(null, null);
1✔
1174
                } else {
1175
                    // Multiply missing collection if recipe quantity is higher than one
1176
                    if (missingAlternatives.size() > 0) {
1✔
1177
                        missingElements.add(new MissingIngredients.Element<>(missingAlternatives, recipe.isInputReusable(ingredientComponent, inputIndex)));
1✔
1178
                    }
1179
                }
1180
            }
1181

1182
            // Otherwise, append it to the list and carry on.
1183
            // If none of the instances were valid, we add the first partially valid instance.
1184
            if (hasInputInstance) {
1✔
1185
                inputInstances.add(inputInstance);
1✔
1186
            } else if (setFirstInputInstance && !matcher.isEmpty(firstInputInstance)) {
1✔
1187
                inputInstances.add(firstInputInstance);
1✔
1188
            }
1189
        }
1190

1191
        return Pair.of(
1✔
1192
                inputInstances,
1193
                collectMissingIngredients ? new MissingIngredients<>(missingElements) : null
1✔
1194
        );
1195
    }
1196

1197
    /**
1198
     * Get all required recipe input ingredients from the network.
1199
     *
1200
     * If multiple alternative inputs are possible,
1201
     * then only the first possible match will be taken.
1202
     *
1203
     * Note: Make sure that you first call in simulation-mode
1204
     * to see if the ingredients are available.
1205
     * If you immediately call this non-simulated,
1206
     * then there might be a chance that ingredients are lost
1207
     * from the network.
1208
     *
1209
     * @param network The target network.
1210
     * @param channel The target channel.
1211
     * @param recipe The recipe to get the inputs from.
1212
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1213
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1214
     * @return The found ingredients or null.
1215
     */
1216
    @Nullable
1217
    public static IMixedIngredients getRecipeInputs(INetwork network, int channel,
1218
                                                    IRecipeDefinition recipe, boolean simulate,
1219
                                                    long recipeOutputQuantity) {
1220
        Map<IngredientComponent<?, ?>, List<?>> inputs = getRecipeInputs(getNetworkStorageGetter(network, channel, true),
×
1221
                recipe, simulate, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), false, recipeOutputQuantity).getLeft();
×
1222
        return inputs == null ? null : new MixedIngredients(inputs);
×
1223
    }
1224

1225
    /**
1226
     * Create a callback function for getting a storage for an ingredient component from the given network channel.
1227
     * @param network The target network.
1228
     * @param channel The target channel.
1229
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
1230
     * @return A callback function for getting a storage for an ingredient component.
1231
     */
1232
    public static Function<IngredientComponent<?, ?>, IIngredientComponentStorage> getNetworkStorageGetter(INetwork network, int channel, boolean scheduleObservation) {
1233
        return ingredientComponent -> getNetworkStorage(network, channel, ingredientComponent, scheduleObservation);
×
1234
    }
1235

1236
    /**
1237
     * Get all required recipe input ingredients based on a given storage callback.
1238
     *
1239
     * If multiple alternative inputs are possible,
1240
     * then only the first possible match will be taken.
1241
     *
1242
     * Note: Make sure that you first call in simulation-mode
1243
     * to see if the ingredients are available.
1244
     * If you immediately call this non-simulated,
1245
     * then there might be a chance that ingredients are lost
1246
     * from the network.
1247
     *
1248
     * @param storageGetter A callback function to get a storage for the given ingredient component.
1249
     * @param recipe The recipe to get the inputs from.
1250
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1251
     * @param simulatedExtractionMemories This map remembers all extracted instances in simulation mode.
1252
     *                                    This is to make sure that instances can not be extracted multiple times
1253
     *                                    when simulating.
1254
     * @param extractionMemoriesReusable Like simulatedExtractionMemories, but it stores the reusable ingredients.
1255
     * @param collectMissingIngredients If missing ingredients should be collected.
1256
     *                                  If false, then the first returned mixed ingredients may be null
1257
     *                                  if no valid matches can be found,
1258
     *                                  and the second returned list is always null,
1259
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1260
     * @return A pair with two objects:
1261
     *           1. The found ingredients or null.
1262
     *           2. A mapping from ingredient component to missing ingredients (non-slot-based).
1263
     */
1264
    public static Pair<Map<IngredientComponent<?, ?>, List<?>>, Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>>>
1265
    getRecipeInputs(Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter, IRecipeDefinition recipe, boolean simulate,
1266
                    Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemories,
1267
                    Map<IngredientComponent<?, ?>, IIngredientCollectionMutable<?, ?>> extractionMemoriesReusable,
1268
                    boolean collectMissingIngredients, long recipeOutputQuantity) {
1269
        Map<IngredientComponent<?, ?>, List<?>> ingredientsAvailable = Maps.newIdentityHashMap();
1✔
1270
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> ingredientsMissing = Maps.newIdentityHashMap();
1✔
1271
        for (IngredientComponent<?, ?> ingredientComponent : recipe.getInputComponents()) {
1✔
1272
            IIngredientComponentStorage storage = storageGetter.apply(ingredientComponent);
1✔
1273
            IngredientCollectionPrototypeMap<?, ?> simulatedExtractionMemory = simulatedExtractionMemories.get(ingredientComponent);
1✔
1274
            if (simulatedExtractionMemory == null) {
1✔
1275
                simulatedExtractionMemory = new IngredientCollectionPrototypeMap<>(ingredientComponent, true);
1✔
1276
                simulatedExtractionMemories.put(ingredientComponent, simulatedExtractionMemory);
1✔
1277
            }
1278
            IIngredientCollectionMutable extractionMemoryReusable = extractionMemoriesReusable.get(ingredientComponent);
1✔
1279
            if (extractionMemoryReusable == null) {
1✔
1280
                extractionMemoryReusable = new IngredientHashSet<>(ingredientComponent);
1✔
1281
                extractionMemoriesReusable.put(ingredientComponent, extractionMemoryReusable);
1✔
1282
            }
1283
            Pair<List<?>, MissingIngredients<?, ?>> subIngredients = getIngredientRecipeInputs(storage,
1✔
1284
                    (IngredientComponent) ingredientComponent, recipe, simulate, simulatedExtractionMemory, extractionMemoryReusable,
1285
                    collectMissingIngredients, recipeOutputQuantity);
1286
            List<?> subIngredientAvailable = subIngredients.getLeft();
1✔
1287
            MissingIngredients<?, ?> subIngredientsMissing = subIngredients.getRight();
1✔
1288
            if (subIngredientAvailable == null && !collectMissingIngredients) {
1✔
1289
                return Pair.of(null, null);
×
1290
            } else {
1291
                if (subIngredientAvailable != null && !subIngredientAvailable.isEmpty()) {
1✔
1292
                    ingredientsAvailable.put(ingredientComponent, subIngredientAvailable);
1✔
1293
                }
1294
                if (collectMissingIngredients && !subIngredientsMissing.getElements().isEmpty()) {
1✔
1295
                    ingredientsMissing.put(ingredientComponent, subIngredientsMissing);
1✔
1296
                }
1297
            }
1298
        }
1✔
1299
        return Pair.of(ingredientsAvailable, ingredientsMissing);
1✔
1300
    }
1301

1302
    /**
1303
     * Create a list of prototyped ingredients from the instances
1304
     * of the given ingredient component type in the given mixed ingredients.
1305
     *
1306
     * Equal prototypes will be stacked.
1307
     *
1308
     * @param ingredientComponent The ingredient component type.
1309
     * @param mixedIngredients The mixed ingredients.
1310
     * @param <T> The instance type.
1311
     * @param <M> The matching condition parameter.
1312
     * @return A list of prototypes.
1313
     */
1314
    public static <T, M> List<IPrototypedIngredient<T, M>> getCompressedIngredients(IngredientComponent<T, M> ingredientComponent,
1315
                                                                                    IMixedIngredients mixedIngredients) {
1316
        List<IPrototypedIngredient<T, M>> outputs = Lists.newArrayList();
1✔
1317

1318
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
1319
        for (T instance : mixedIngredients.getInstances(ingredientComponent)) {
1✔
1320
            // Try to stack this instance with an existing prototype
1321
            boolean stacked = false;
1✔
1322
            ListIterator<IPrototypedIngredient<T, M>> existingIt = outputs.listIterator();
1✔
1323
            while(existingIt.hasNext()) {
1✔
1324
                IPrototypedIngredient<T, M> prototypedIngredient = existingIt.next();
1✔
1325
                if (matcher.matches(instance, prototypedIngredient.getPrototype(),
1✔
1326
                        prototypedIngredient.getCondition())) {
1✔
1327
                    T stackedInstance = matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1328
                            matcher.getQuantity(prototypedIngredient.getPrototype())
1✔
1329
                                    + matcher.getQuantity(instance));
1✔
1330
                    existingIt.set(new PrototypedIngredient<>(ingredientComponent, stackedInstance,
1✔
1331
                            prototypedIngredient.getCondition()));
1✔
1332
                    stacked = true;
1✔
1333
                    break;
1✔
1334
                }
1335
            }
1✔
1336

1337
            // If not possible, just append it to the list
1338
            if (!stacked) {
1✔
1339
                outputs.add(new PrototypedIngredient<>(ingredientComponent, instance,
1✔
1340
                        matcher.getExactMatchNoQuantityCondition()));
1✔
1341
            }
1342
        }
1✔
1343

1344
        return outputs;
1✔
1345
    }
1346

1347
    /**
1348
     * Create a collection of prototypes from the given recipe's outputs.
1349
     *
1350
     * Equal prototypes will be stacked.
1351
     *
1352
     * @param recipe A recipe.
1353
     * @return A map from ingredient component types to their list of prototypes.
1354
     */
1355
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> getRecipeOutputs(IRecipeDefinition recipe) {
1356
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> outputs = Maps.newHashMap();
1✔
1357

1358
        IMixedIngredients mixedIngredients = recipe.getOutput();
1✔
1359
        for (IngredientComponent ingredientComponent : mixedIngredients.getComponents()) {
1✔
1360
            outputs.put(ingredientComponent, getCompressedIngredients(ingredientComponent, mixedIngredients));
1✔
1361
        }
1✔
1362

1363
        return outputs;
1✔
1364
    }
1365

1366
    /**
1367
     * Creates a new recipe outputs object with all ingredient quantities multiplied by the given amount.
1368
     * @param recipeOutputs A recipe objects holder.
1369
     * @param amount An amount to multiply all instances by.
1370
     * @return A new recipe objects holder.
1371
     */
1372
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> multiplyRecipeOutputs(
1373
            Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> recipeOutputs, int amount) {
1374
        if (amount == 1) {
1✔
1375
            return recipeOutputs;
1✔
1376
        }
1377

1378
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> newRecipeOutputs = Maps.newIdentityHashMap();
1✔
1379
        for (Map.Entry<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> entry : recipeOutputs.entrySet()) {
1✔
1380
            newRecipeOutputs.put(entry.getKey(), multiplyPrototypedIngredients((List) entry.getValue(), amount));
1✔
1381
        }
1✔
1382
        return newRecipeOutputs;
1✔
1383
    }
1384

1385
    /**
1386
     * Multiply the quantity of a given prototyped ingredient list with the given amount.
1387
     * @param prototypedIngredients A prototyped ingredient list.
1388
     * @param amount An amount to multiply by.
1389
     * @param <T> The instance type.
1390
     * @param <M> The matching condition parameter.
1391
     * @return A multiplied prototyped ingredient list.
1392
     */
1393
    public static <T, M> List<IPrototypedIngredient<T, M>> multiplyPrototypedIngredients(Collection<IPrototypedIngredient<T, M>> prototypedIngredients,
1394
                                                                                         long amount) {
1395
        return prototypedIngredients
1✔
1396
                .stream()
1✔
1397
                .map(p -> multiplyPrototypedIngredient(p, amount))
1✔
1398
                .collect(Collectors.toList());
1✔
1399
    }
1400

1401
    /**
1402
     * Multiply the quantity of a given prototyped ingredient with the given amount.
1403
     * @param prototypedIngredient A prototyped ingredient.
1404
     * @param amount An amount to multiply by.
1405
     * @param <T> The instance type.
1406
     * @param <M> The matching condition parameter.
1407
     * @return A multiplied prototyped ingredient.
1408
     */
1409
    public static <T, M> IPrototypedIngredient<T, M> multiplyPrototypedIngredient(IPrototypedIngredient<T, M> prototypedIngredient,
1410
                                                                                  long amount) {
1411
        IIngredientMatcher<T, M> matcher = prototypedIngredient.getComponent().getMatcher();
1✔
1412
        return new PrototypedIngredient<>(prototypedIngredient.getComponent(),
1✔
1413
                matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1414
                        matcher.getQuantity(prototypedIngredient.getPrototype()) * amount),
1✔
1415
                prototypedIngredient.getCondition());
1✔
1416
    }
1417

1418
    /**
1419
     * Merge two mixed ingredients in a new mixed ingredients object.
1420
     * Instances will be stacked.
1421
     * @param a A first mixed ingredients object.
1422
     * @param b A second mixed ingredients object.
1423
     * @return A merged mixed ingredients object.
1424
     */
1425
    public static IMixedIngredients mergeMixedIngredients(IMixedIngredients a, IMixedIngredients b) {
1426
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1427
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1428
        for (IngredientComponent<?, ?> component : a.getComponents()) {
1✔
1429
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1430
            groupings.put(component, grouping);
1✔
1431
            grouping.addAll(a.getInstances(component));
1✔
1432
        }
1✔
1433
        for (IngredientComponent<?, ?> component : b.getComponents()) {
1✔
1434
            IngredientCollectionQuantitativeGrouper grouping = groupings.get(component);
1✔
1435
            if (grouping == null) {
1✔
1436
                grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1437
                groupings.put(component, grouping);
1✔
1438
            }
1439
            grouping.addAll(b.getInstances(component));
1✔
1440
        }
1✔
1441

1442
        // Convert IngredientCollectionPrototypeMaps to lists
1443
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1444
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1445
            ingredients.put(entry.getKey(), Lists.newArrayList(entry.getValue()));
1✔
1446
        }
1✔
1447
        return new MixedIngredients(ingredients);
1✔
1448
    }
1449

1450
    /**
1451
     * Stack all ingredients in the given mixed ingredients object.
1452
     * @param mixedIngredients A mixed ingredients object.
1453
     * @return A new mixed ingredients object.
1454
     */
1455
    protected static IMixedIngredients compressMixedIngredients(IMixedIngredients mixedIngredients) {
1456
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1457
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1458
        for (IngredientComponent<?, ?> component : mixedIngredients.getComponents()) {
1✔
1459
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1460
            groupings.put(component, grouping);
1✔
1461
            grouping.addAll(mixedIngredients.getInstances(component));
1✔
1462
        }
1✔
1463

1464
        // Convert IngredientCollectionPrototypeMaps to lists
1465
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1466
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1467
            IIngredientMatcher matcher = entry.getKey().getMatcher();
1✔
1468
            List<?> values = entry.getValue()
1✔
1469
                    .stream()
1✔
1470
                    .filter(i -> !matcher.isEmpty(i))
1✔
1471
                    .collect(Collectors.toList());
1✔
1472
            if (!values.isEmpty()) {
1✔
1473
                ingredients.put(entry.getKey(), values);
1✔
1474
            }
1475
        }
1✔
1476
        return new MixedIngredients(ingredients);
1✔
1477
    }
1478

1479
    /**
1480
     * Insert the ingredients of the given ingredient component type into the target to make it start crafting.
1481
     *
1482
     * If insertion in non-simulation mode fails,
1483
     * ingredients will be re-inserted into the network.
1484
     *
1485
     * @param ingredientComponent The ingredient component type.
1486
     * @param capabilityType capabilityType The type of capability, usually Block.class, Item.class, or Entity.class.
1487
     * @param capabilityGetter A capability provider.
1488
     * @param capabilityTarget The capability target for error reporting.
1489
     * @param side The target side.
1490
     * @param ingredients The ingredients to insert.
1491
     * @param storageFallback The storage to insert any failed ingredients back into. Can be null in simulation mode.
1492
     * @param simulate If insertion should be simulated.
1493
     * @param <T> The instance type.
1494
     * @param <M> The matching condition parameter.
1495
     * @return If all instances could be inserted.
1496
     */
1497
    public static <T, M, C> boolean insertIngredientCrafting(IngredientComponent<T, M> ingredientComponent,
1498
                                                          Class<?> capabilityType,
1499
                                                          ICapabilityGetter<Direction> capabilityGetter,
1500
                                                          Object capabilityTarget,
1501
                                                          @Nullable Direction side,
1502
                                                          IMixedIngredients ingredients,
1503
                                                          IIngredientComponentStorage<T, M> storageFallback,
1504
                                                          boolean simulate) {
1505
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
NEW
1506
        IIngredientComponentStorage<T, M> storage = ingredientComponent.getStorage(capabilityType, capabilityGetter, side);
×
1507
        List<T> instances = ingredients.getInstances(ingredientComponent);
×
1508
        List<T> failedInstances = Lists.newArrayList();
×
1509
        boolean ok = true;
×
1510
        for (T instance : instances) {
×
1511
            T remaining = storage.insert(instance, simulate);
×
1512
            if (!matcher.isEmpty(remaining)) {
×
1513
                ok = false;
×
1514
                if (!simulate) {
×
1515
                    failedInstances.add(remaining);
×
1516
                }
1517
            }
1518
        }
×
1519

1520
        // If we had failed insertions, try to insert them back into the network.
1521
        for (T instance : failedInstances) {
×
1522
            T remaining = storageFallback.insert(instance, false);
×
1523
            if (!matcher.isEmpty(remaining)) {
×
1524
                throw new IllegalStateException("Insertion for a crafting recipe failed" +
×
1525
                        "due to inconsistent insertion behaviour by destination in simulation " +
1526
                        "and non-simulation: " + capabilityTarget + ". Lost: " + instances);
1527
            }
1528
        }
×
1529

1530
        return ok;
×
1531
    }
1532

1533
    /**
1534
     * Insert the ingredients of all applicable ingredient component types into the target to make it start crafting.
1535
     *
1536
     * If insertion in non-simulation mode fails,
1537
     * ingredients will be re-inserted into the network.
1538
     *
1539
     * @param targetGetter A function to get the target position.
1540
     * @param ingredients The ingredients to insert.
1541
     * @param network The network.
1542
     * @param channel The channel.
1543
     * @param simulate If insertion should be simulated.
1544
     * @return If all instances could be inserted.
1545
     */
1546
    public static boolean insertCrafting(Function<IngredientComponent<?, ?>, PartPos> targetGetter,
1547
                                         IMixedIngredients ingredients,
1548
                                         INetwork network, int channel,
1549
                                         boolean simulate) {
1550
        Map<IngredientComponent<?, ?>, BlockEntity> tileMap = Maps.newIdentityHashMap();
×
1551

1552
        // First, check if we can find valid tiles for all ingredient components
1553
        for (IngredientComponent<?, ?> ingredientComponent : ingredients.getComponents()) {
×
1554
            BlockEntity tile = BlockEntityHelpers.get(targetGetter.apply(ingredientComponent).getPos(), BlockEntity.class).orElse(null);
×
1555
            if (tile != null) {
×
1556
                tileMap.put(ingredientComponent, tile);
×
1557
            } else {
1558
                return false;
×
1559
            }
1560
        }
×
1561

1562
        // Next, insert the instances into the respective tiles
1563
        boolean ok = true;
×
1564
        for (Map.Entry<IngredientComponent<?, ?>, BlockEntity> entry : tileMap.entrySet()) {
×
1565
            IIngredientComponentStorage<?, ?> storageNetwork = simulate ? null : getNetworkStorage(network, channel, entry.getKey(), false);
×
NEW
1566
            if (!insertIngredientCrafting((IngredientComponent) entry.getKey(),
×
NEW
1567
                    Block.class, ICapabilityGetter.forBlockEntity(entry.getValue()), entry.getValue(),
×
UNCOV
1568
                    targetGetter.apply(entry.getKey()).getSide(), ingredients,
×
1569
                    storageNetwork, simulate)) {
1570
                ok = false;
×
1571
            }
1572
        }
×
1573

1574
        return ok;
×
1575
    }
1576

1577
    /**
1578
     * Split the given crafting job amount into new jobs with a given split factor.
1579
     * @param craftingJob A crafting job to split.
1580
     * @param splitFactor The number of jobs to split the job over.
1581
     * @param dependencyGraph The dependency graph that will be updated if there are dependencies in the original job.
1582
     * @param identifierGenerator An identifier generator for the crafting jobs ids.
1583
     * @return The newly created crafting jobs.
1584
     */
1585
    public static List<CraftingJob> splitCraftingJobs(CraftingJob craftingJob, int splitFactor,
1586
                                                      CraftingJobDependencyGraph dependencyGraph,
1587
                                                      IIdentifierGenerator identifierGenerator) {
1588
        splitFactor = Math.min(splitFactor, craftingJob.getAmount());
1✔
1589
        int division = craftingJob.getAmount() / splitFactor;
1✔
1590
        int modulus = craftingJob.getAmount() % splitFactor;
1✔
1591

1592
        // Clone original job into splitFactor jobs
1593
        List<CraftingJob> newCraftingJobs = Lists.newArrayList();
1✔
1594
        for (int i = 0; i < splitFactor; i++) {
1✔
1595
            CraftingJob clonedJob = craftingJob.clone(identifierGenerator);
1✔
1596
            newCraftingJobs.add(clonedJob);
1✔
1597

1598
            // Update amount
1599
            int newAmount = division;
1✔
1600
            if (modulus > 0) {
1✔
1601
                // No amounts will be lost, as modulus is guaranteed to be smaller than splitFactor
1602
                newAmount++;
1✔
1603
                modulus--;
1✔
1604
            }
1605
            clonedJob.setAmount(newAmount);
1✔
1606
        }
1607

1608
        // Collect dependency links
1609
        Collection<CraftingJob> originalDependencies = dependencyGraph.getDependencies(craftingJob);
1✔
1610
        Collection<CraftingJob> originalDependents = dependencyGraph.getDependents(craftingJob);
1✔
1611

1612
        // Remove dependency links to and from the original jobs
1613
        for (CraftingJob dependency : originalDependencies) {
1✔
1614
            craftingJob.removeDependency(dependency);
1✔
1615
            dependencyGraph.removeDependency(craftingJob.getId(), dependency.getId());
1✔
1616
        }
1✔
1617
        for (CraftingJob dependent : originalDependents) {
1✔
1618
            dependent.removeDependency(craftingJob);
1✔
1619
            dependencyGraph.removeDependency(dependent.getId(), craftingJob.getId());
1✔
1620
        }
1✔
1621

1622
        // Create dependency links to and from the new crafting jobs
1623
        for (CraftingJob dependency : originalDependencies) {
1✔
1624
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1625
                newCraftingJob.addDependency(dependency);
1✔
1626
                dependencyGraph.addDependency(newCraftingJob, dependency);
1✔
1627
            }
1✔
1628
        }
1✔
1629
        for (CraftingJob originalDependent : originalDependents) {
1✔
1630
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1631
                originalDependent.addDependency(newCraftingJob);
1✔
1632
                dependencyGraph.addDependency(originalDependent, newCraftingJob);
1✔
1633
            }
1✔
1634
        }
1✔
1635

1636
        return newCraftingJobs;
1✔
1637
    }
1638

1639
    /**
1640
     * Insert the given ingredients into the given storage networks.
1641
     * @param ingredients A collection of ingredients.
1642
     * @param storageGetter A storage network getter.
1643
     * @param simulate If insertion should be simulated.
1644
     * @return The remaining ingredients that were not inserted.
1645
     */
1646
    public static IMixedIngredients insertIngredients(IMixedIngredients ingredients,
1647
                                                      Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
1648
                                                      boolean simulate) {
1649
        Map<IngredientComponent<?, ?>, List<?>> remainingIngredients = Maps.newIdentityHashMap();
×
1650
        for (IngredientComponent<?, ?> component : ingredients.getComponents()) {
×
1651
            IIngredientComponentStorage storage = storageGetter.apply(component);
×
1652
            IIngredientMatcher matcher = component.getMatcher();
×
1653
            for (Object instance : ingredients.getInstances(component)) {
×
1654
                Object remainder = storage.insert(instance, simulate);
×
1655
                if (!matcher.isEmpty(remainder)) {
×
1656
                    List remainingInstances = remainingIngredients.get(component);
×
1657
                    if (remainingInstances == null) {
×
1658
                        remainingInstances = Lists.newArrayList();
×
1659
                        remainingIngredients.put(component, remainingInstances);
×
1660
                    }
1661
                    remainingInstances.add(instance);
×
1662
                }
1663
            }
×
1664
        }
×
1665
        return new MixedIngredients(remainingIngredients);
×
1666
    }
1667

1668
    /**
1669
     * Generates semi-unique IDs.
1670
     */
1671
    public static interface IIdentifierGenerator {
1672
        public int getNext();
1673
    }
1674

1675
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc