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

CyclopsMC / IntegratedCrafting / #479011824

30 Dec 2025 07:13AM UTC coverage: 24.402% (+0.2%) from 24.214%
#479011824

push

github

rubensworks
Fix split jobs having incorrect buffer storage

0 of 3 new or added lines in 2 files covered. (0.0%)

1 existing line in 1 file now uncovered.

755 of 3094 relevant lines covered (24.4%)

0.24 hits per line

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

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

3
import com.google.common.collect.Iterables;
4
import com.google.common.collect.Lists;
5
import com.google.common.collect.Maps;
6
import com.google.common.collect.Sets;
7
import net.minecraft.core.Direction;
8
import net.minecraft.world.level.block.entity.BlockEntity;
9
import net.minecraftforge.common.capabilities.ICapabilityProvider;
10
import net.minecraftforge.common.util.LazyOptional;
11
import org.apache.commons.lang3.tuple.Pair;
12
import org.apache.logging.log4j.Level;
13
import org.cyclops.commoncapabilities.api.capability.recipehandler.IPrototypedIngredientAlternatives;
14
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
15
import org.cyclops.commoncapabilities.api.ingredient.*;
16
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
17
import org.cyclops.commoncapabilities.api.ingredient.storage.IngredientComponentStorageEmpty;
18
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
19
import org.cyclops.cyclopscore.ingredient.collection.*;
20
import org.cyclops.cyclopscore.ingredient.storage.IngredientComponentStorageSlottedCollectionWrapper;
21
import org.cyclops.integratedcrafting.Capabilities;
22
import org.cyclops.integratedcrafting.IntegratedCrafting;
23
import org.cyclops.integratedcrafting.api.crafting.*;
24
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
25
import org.cyclops.integratedcrafting.api.recipe.IRecipeIndex;
26
import org.cyclops.integratedcrafting.capability.network.CraftingNetworkConfig;
27
import org.cyclops.integrateddynamics.IntegratedDynamics;
28
import org.cyclops.integrateddynamics.api.PartStateException;
29
import org.cyclops.integrateddynamics.api.ingredient.capability.IPositionedAddonsNetworkIngredientsHandler;
30
import org.cyclops.integrateddynamics.api.network.INetwork;
31
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
32
import org.cyclops.integrateddynamics.api.part.PartPos;
33
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
34
import org.cyclops.integrateddynamics.core.network.IngredientChannelAdapter;
35
import org.cyclops.integrateddynamics.core.network.IngredientChannelIndexed;
36

37
import javax.annotation.Nullable;
38
import java.util.*;
39
import java.util.function.Function;
40
import java.util.stream.Collectors;
41
import java.util.stream.IntStream;
42

43
/**
44
 * Helpers related to handling crafting jobs.
45
 * @author rubensworks
46
 */
47
public class CraftingHelpers {
×
48

49
    /**
50
     * Get the network at the given position,
51
     * or throw a PartStateException if it is null.
52
     * @param pos A position.
53
     * @return A network.
54
     * @throws PartStateException If the network could not be found.
55
     */
56
    public static INetwork getNetworkChecked(PartPos pos) throws PartStateException {
57
        INetwork network = NetworkHelpers.getNetwork(pos.getPos().getLevel(true), pos.getPos().getBlockPos(), pos.getSide()).orElse(null);
×
58
        if (network == null) {
×
59
            IntegratedDynamics.clog(Level.ERROR, "Could not get the network for transfer as no network was found.");
×
60
            throw new PartStateException(pos.getPos(), pos.getSide());
×
61
        }
62
        return network;
×
63
    }
64

65
    /**
66
     * Get the crafting network in the given network.
67
     * @param network A network.
68
     * @return The crafting network.
69
     */
70
    public static LazyOptional<ICraftingNetwork> getCraftingNetwork(@Nullable INetwork network) {
71
        if (network != null) {
×
72
            return network.getCapability(CraftingNetworkConfig.CAPABILITY);
×
73
        }
74
        return null;
×
75
    }
76

77
    /**
78
     * Get the crafting network in the given network.
79
     * @param network A network.
80
     * @return The crafting network.
81
     */
82
    public static ICraftingNetwork getCraftingNetworkChecked(@Nullable INetwork network) {
83
        return getCraftingNetwork(network)
×
84
                .orElseThrow(() -> new IllegalStateException("Could not find a crafting network"));
×
85
    }
86

87
    /**
88
     * Get the storage network of the given type in the given network.
89
     * @param network A network.
90
     * @param ingredientComponent The ingredient component type of the network.
91
     * @param <T> The instance type.
92
     * @param <M> The matching condition parameter.
93
     * @return The storage network.
94
     */
95
    public static <T, M> LazyOptional<IPositionedAddonsNetworkIngredients<T, M>> getIngredientsNetwork(INetwork network,
96
                                                                                                       IngredientComponent<T, M> ingredientComponent) {
97
        IPositionedAddonsNetworkIngredientsHandler<T, M> ingredientsHandler = ingredientComponent.getCapability(Capabilities.POSITIONED_ADDONS_NETWORK_INGREDIENTS_HANDLER).orElse(null);
×
98
        if (ingredientsHandler != null) {
×
99
            return ingredientsHandler.getStorage(network);
×
100
        }
101
        return LazyOptional.empty();
×
102
    }
103

104
    /**
105
     * Get the storage network of the given type in the given network.
106
     * @param network A network.
107
     * @param ingredientComponent The ingredient component type of the network.
108
     * @param <T> The instance type.
109
     * @param <M> The matching condition parameter.
110
     * @return The storage network.
111
     */
112
    public static <T, M> IPositionedAddonsNetworkIngredients<T, M> getIngredientsNetworkChecked(INetwork network,
113
                                                                                                IngredientComponent<T, M> ingredientComponent) {
114
        return getIngredientsNetwork(network, ingredientComponent)
×
115
                .orElseThrow(() -> new IllegalStateException("Could not find an ingredients network"));
×
116
    }
117

118
    /**
119
     * Get the storage of the given ingredient component type from the network.
120
     * @param network The network.
121
     * @param channel A network channel.
122
     * @param ingredientComponent The ingredient component type of the network.
123
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
124
     * @param <T> The instance type.
125
     * @param <M> The matching condition parameter.
126
     * @return The storage.
127
     */
128
    public static <T, M> IIngredientComponentStorage<T, M> getNetworkStorage(INetwork network, int channel,
129
                                                                             IngredientComponent<T, M> ingredientComponent,
130
                                                                             boolean scheduleObservation) {
131
        IPositionedAddonsNetworkIngredients<T, M> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
132
        if (ingredientsNetwork != null) {
×
133
            if (scheduleObservation) {
×
134
                ingredientsNetwork.scheduleObservation();
×
135
            }
136
            return ingredientsNetwork.getChannel(channel);
×
137
        }
138
        return new IngredientComponentStorageEmpty<>(ingredientComponent);
×
139
    }
140

141
    /**
142
     * If the network is guaranteed to have uncommitted changes (such as the one in #48),
143
     * forcefully run observers synchronously, so that we can calculate the job in a consistent network state.
144
     * @param network The network.
145
     * @param channel A network channel.
146
     */
147
    public static void beforeCalculateCraftingJobs(INetwork network, int channel) {
148
        for (IngredientComponent<?, ?> ingredientComponent : IngredientComponent.REGISTRY.getValues()) {
×
149
            IPositionedAddonsNetworkIngredients<?, ?> ingredientsNetwork = getIngredientsNetwork(network, ingredientComponent).orElse(null);
×
150
            if (ingredientsNetwork != null && (ingredientsNetwork.isObservationForcedPending(channel))) {
×
151
                ingredientsNetwork.runObserverSync();
×
152
            }
153
        }
×
154
    }
×
155

156
    /**
157
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
158
     * @param network The target network.
159
     * @param channel The target channel.
160
     * @param ingredientComponent The ingredient component type of the instance.
161
     * @param instance The instance to craft.
162
     * @param matchCondition The match condition of the instance.
163
     * @param craftMissing If the missing required ingredients should also be crafted.
164
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
165
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
166
     * @param collectMissingRecipes If the missing recipes should be collected inside
167
     *                              {@link UnknownCraftingRecipeException}.
168
     *                              This may slow down calculation for deeply nested recipe graphs.
169
     * @param <T> The instance type.
170
     * @param <M> The matching condition parameter.
171
     * @return The crafting job for the given instance.
172
     * @throws UnknownCraftingRecipeException If the recipe for a (sub)ingredient is unavailable.
173
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
174
     */
175
    public static <T, M> CraftingJob calculateCraftingJobs(INetwork network, int channel,
176
                                                           IngredientComponent<T, M> ingredientComponent,
177
                                                           T instance, M matchCondition, boolean craftMissing,
178
                                                           IIdentifierGenerator identifierGenerator,
179
                                                           CraftingJobDependencyGraph craftingJobsGraph,
180
                                                           boolean collectMissingRecipes)
181
            throws UnknownCraftingRecipeException, RecursiveCraftingRecipeException {
182
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
183
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
184
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
185
        beforeCalculateCraftingJobs(network, channel);
×
186

187
        CraftingJob craftingJob = calculateCraftingJobs(recipeIndex, channel, storageGetter, ingredientComponent, instance, matchCondition,
×
188
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
189
                collectMissingRecipes);
190
        craftingJobsGraph.addCraftingJobId(craftingJob);
×
191
        return craftingJob;
×
192
    }
193

194
    /**
195
     * Calculate the required crafting jobs and their dependencies for the given instance in the given network.
196
     * @param network The target network.
197
     * @param channel The target channel.
198
     * @param recipe The recipe to calculate a job for.
199
     * @param amount The amount of times the recipe should be crafted.
200
     * @param craftMissing If the missing required ingredients should also be crafted.
201
     * @param identifierGenerator identifierGenerator An ID generator for crafting jobs.
202
     * @param craftingJobsGraph The target graph where all dependencies will be stored.
203
     * @param collectMissingRecipes If the missing recipes should be collected inside
204
     *                              {@link FailedCraftingRecipeException}.
205
     *                              This may slow down calculation for deeply nested recipe graphs.
206
     * @return The crafting job for the given instance.
207
     * @throws FailedCraftingRecipeException If the recipe could not be crafted due to missing sub-dependencies.
208
     * @throws RecursiveCraftingRecipeException If an infinite recursive recipe was detected.
209
     */
210
    public static CraftingJob calculateCraftingJobs(INetwork network, int channel,
211
                                                    IRecipeDefinition recipe, int amount, boolean craftMissing,
212
                                                    IIdentifierGenerator identifierGenerator,
213
                                                    CraftingJobDependencyGraph craftingJobsGraph,
214
                                                    boolean collectMissingRecipes)
215
            throws FailedCraftingRecipeException, RecursiveCraftingRecipeException {
216
        ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
217
        IRecipeIndex recipeIndex = craftingNetwork.getRecipeIndex(channel);
×
218
        Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter = getNetworkStorageGetter(network, channel, true);
×
219
        beforeCalculateCraftingJobs(network, channel);
×
220

221
        PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel, storageGetter, recipe, amount,
×
222
                craftMissing, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), identifierGenerator, craftingJobsGraph, Sets.newHashSet(),
×
223
                collectMissingRecipes);
224
        if (result.getCraftingJob() == null) {
×
225
            throw new FailedCraftingRecipeException(recipe, amount, result.getMissingDependencies(),
×
226
                    compressMixedIngredients(new MixedIngredients(result.getIngredientsStorage())), result.getPartialCraftingJobs());
×
227
        } else {
228
            craftingJobsGraph.addCraftingJobId(result.getCraftingJob());
×
229
            return result.getCraftingJob();
×
230
        }
231
    }
232

233
    /**
234
     * @return An identifier generator for crafting jobs.
235
     */
236
    public static IIdentifierGenerator getGlobalCraftingJobIdentifier() {
237
        return () -> IntegratedCrafting.globalCounters.getNext("craftingJob");
×
238
    }
239

240
    /**
241
     * Calculate the effective quantity for the given instance in the output of the given recipe.
242
     * @param recipe A recipe.
243
     * @param ingredientComponent The ingredient component.
244
     * @param instance An instance.
245
     * @param matchCondition A match condition.
246
     * @param <T> The instance type.
247
     * @param <M> The matching condition parameter.
248
     * @return The effective quantity.
249
     */
250
    public static <T, M> long getOutputQuantityForRecipe(IRecipeDefinition recipe,
251
                                                         IngredientComponent<T, M> ingredientComponent,
252
                                                         T instance, M matchCondition) {
253
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
254
        return recipe.getOutput().getInstances(ingredientComponent)
1✔
255
                .stream()
1✔
256
                .filter(i -> matcher.matches(i, instance, matchCondition))
1✔
257
                .mapToLong(matcher::getQuantity)
1✔
258
                .sum();
1✔
259
    }
260

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

310
        // Loop over all available recipes, and return the first valid one.
311
        Iterator<IRecipeDefinition> recipes = recipeIndex.getRecipes(ingredientComponent, instance, quantifierlessCondition);
1✔
312
        List<UnknownCraftingRecipeException> firstMissingDependencies = Lists.newArrayList();
1✔
313
        Map<IngredientComponent<?, ?>, List<?>> firstIngredientsStorage = Collections.emptyMap();
1✔
314
        List<CraftingJob> firstPartialCraftingJobs = Lists.newArrayList();
1✔
315
        RecursiveCraftingRecipeException firstRecursiveException = null;
1✔
316
        while (recipes.hasNext()) {
1✔
317
            IRecipeDefinition recipe = recipes.next();
1✔
318

319
            // Calculate the quantity for the given instance that the recipe outputs
320
            long recipeOutputQuantity = getOutputQuantityForRecipe(recipe, ingredientComponent, instance, quantifierlessCondition);
1✔
321
            // Based on the quantity of the recipe output, calculate the amount of required recipe jobs.
322
            int amount = (int) Math.ceil(((float) instanceQuantity) / (float) recipeOutputQuantity);
1✔
323

324
            // Calculate jobs for the given recipe
325
            try {
326
                PartialCraftingJobCalculation result = calculateCraftingJobs(recipeIndex, channel,
1✔
327
                        storageGetter, recipe, amount, craftMissing,
328
                        simulatedExtractionMemory, extractionMemoryReusable, identifierGenerator, craftingJobsGraph, parentDependencies,
329
                        collectMissingRecipes && firstMissingDependencies.isEmpty());
1✔
330
                if (result.getCraftingJob() == null) {
1✔
331
                    firstMissingDependencies = result.getMissingDependencies();
1✔
332
                    firstIngredientsStorage = result.getIngredientsStorage();
1✔
333
                    if (result.getPartialCraftingJobs() != null) {
1✔
334
                        firstPartialCraftingJobs = result.getPartialCraftingJobs();
1✔
335
                    }
336
                } else {
337
                    return result.getCraftingJob();
1✔
338
                }
339
            } catch (RecursiveCraftingRecipeException e) {
1✔
340
                if (firstRecursiveException == null) {
1✔
341
                    firstRecursiveException = e;
1✔
342
                }
343
                continue;
1✔
344
            }
1✔
345
        }
1✔
346

347
        if (firstRecursiveException != null) {
1✔
348
            throw firstRecursiveException;
1✔
349
        }
350

351
        // No valid recipes were available, so we error or collect the missing instance.
352
        throw new UnknownCraftingRecipeException(new PrototypedIngredient<>(ingredientComponent, instance, matchCondition),
1✔
353
                matcher.getQuantity(instance), firstMissingDependencies, compressMixedIngredients(new MixedIngredients(firstIngredientsStorage)),
1✔
354
                firstPartialCraftingJobs);
355
    }
356

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

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

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

426
                        missingDependencies.add(new UnknownCraftingRecipeException(
1✔
427
                                alternative.getRequestedPrototype(), alternative.getQuantityMissing(),
1✔
428
                                Collections.emptyList(), compressMixedIngredients(new MixedIngredients(storageMap)), Lists.newArrayList()));
1✔
429
                    }
1✔
430
                }
1✔
431
            }
432
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), null);
1✔
433
        }
434

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

477
        // If at least one of our dependencies does not have a valid recipe or is not available,
478
        // go check the next recipe.
479
        if (!missingDependencies.isEmpty()) {
1✔
480
            return new PartialCraftingJobCalculation(null, missingDependencies, simulation.getLeft(), partialCraftingJobs);
1✔
481
        }
482

483
        CraftingJob craftingJob = new CraftingJob(identifierGenerator.getNext(), channel, recipe, amount,
1✔
484
                compressMixedIngredients(new MixedIngredients(simulation.getLeft())));
1✔
485
        for (CraftingJob dependency : dependencies.values()) {
1✔
486
            craftingJob.addDependency(dependency);
1✔
487
            craftingJobsGraph.addDependency(craftingJob, dependency);
1✔
488
        }
1✔
489
        return new PartialCraftingJobCalculation(craftingJob, null, simulation.getLeft(), null);
1✔
490
    }
491

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

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

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

573
                            // Nothing has to be crafted anymore, jump to next dependency
574
                            skipDependency = true;
×
575
                            break;
×
576
                        } else {
577
                            // Partial availability, other part needs to be crafted still.
578
                            prototype = new PrototypedIngredient<>(dependencyComponent,
1✔
579
                                    dependencyMatcher.withQuantity(prototype.getPrototype(), remainingQuantity),
1✔
580
                                    prototype.getCondition());
1✔
581
                        }
582
                    }
583
                }
584

585
                // Try to craft the given prototype
586
                try {
587
                    Set<IPrototypedIngredient> childDependencies = Sets.newHashSet(parentDependencies);
1✔
588
                    IPrototypedIngredient<T, M> dependencyPrototype = prototype;
1✔
589
                    if (dependencyMatcher.getQuantity(dependencyPrototype.getPrototype()) != 1) {
1✔
590
                        // Ensure 1-quantity is stored, for proper comparisons in future calls.
591
                        dependencyPrototype = new PrototypedIngredient<>(dependencyComponent,
1✔
592
                                dependencyMatcher.withQuantity(prototype.getPrototype(), 1),
1✔
593
                                prototype.getCondition());
1✔
594
                    }
595
                    if (!childDependencies.add(dependencyPrototype)) {
1✔
596
                        throw new RecursiveCraftingRecipeException(prototype);
1✔
597
                    }
598

599
                    dependency = calculateCraftingJobs(recipeIndex, channel, storageGetter,
1✔
600
                            dependencyComponent, prototype.getPrototype(),
1✔
601
                            prototype.getCondition(), true, simulatedExtractionMemory, extractionMemoryReusable,
1✔
602
                            identifierGenerator, craftingJobsGraph, childDependencies, collectMissingRecipes);
603
                    dependencyInstance = prototype.getPrototype();
1✔
604

605
                    // The prototype is valid,
606
                    // so we can finally store our temporary surplus
607
                    if (dependencyComponentSurplus != null) {
1✔
608
                        dependenciesOutputSurplus.put(dependencyComponent, dependencyComponentSurplus);
1✔
609
                    }
610

611
                    // Add the auxiliary recipe outputs that are not requested to the surplus
612
                    Object dependencyQuantifierlessCondition = dependencyMatcher.withoutCondition(prototype.getCondition(),
1✔
613
                            dependencyComponent.getPrimaryQuantifier().getMatchCondition());
1✔
614
                    long requestedQuantity = dependencyMatcher.getQuantity(prototype.getPrototype());
1✔
615
                    for (IngredientComponent outputComponent : dependency.getRecipe().getOutput().getComponents()) {
1✔
616
                        IngredientCollectionPrototypeMap<?, ?> componentSurplus = dependenciesOutputSurplus.get(outputComponent);
1✔
617
                        if (componentSurplus == null) {
1✔
618
                            componentSurplus = new IngredientCollectionPrototypeMap<>(outputComponent, true);
1✔
619
                            dependenciesOutputSurplus.put(outputComponent, componentSurplus);
1✔
620
                        }
621
                        List<Object> instances = dependency.getRecipe().getOutput().getInstances(outputComponent);
1✔
622
                        long recipeAmount = dependency.getAmount();
1✔
623
                        if (recipeAmount > 1) {
1✔
624
                            IIngredientMatcher matcher = outputComponent.getMatcher();
1✔
625
                            // If more than one recipe amount was crafted, correctly multiply the outputs to calculate the effective surplus.
626
                            instances = instances
1✔
627
                                    .stream()
1✔
628
                                    .map(instance -> matcher.withQuantity(instance, matcher.getQuantity(instance) * recipeAmount))
1✔
629
                                    .collect(Collectors.toList());
1✔
630
                        }
631
                        addRemainderAsSurplusForComponent(outputComponent, (List) instances, componentSurplus,
1✔
632
                                (IngredientComponent) prototype.getComponent(), prototype.getPrototype(), dependencyQuantifierlessCondition,
1✔
633
                                requestedQuantity);
634
                    }
1✔
635

636
                    break;
1✔
637
                } catch (UnknownCraftingRecipeException e) {
1✔
638
                    // Save the first error, and check the next prototype
639
                    if (firstError == null) {
1✔
640
                        // Modify the error so that the correct missing quantity is stored
641
                        firstError = new UnknownCraftingRecipeException(
1✔
642
                                e.getIngredient(), prototypedAlternative.getQuantityMissing(),
1✔
643
                                e.getMissingChildRecipes(), compressMixedIngredients(e.getIngredientsStorage()), e.getPartialCraftingJobs());
1✔
644
                    }
645
                }
646
            }
1✔
647

648
            // Check if this dependency can be skipped
649
            if (skipDependency) {
1✔
650
                continue;
×
651
            }
652

653
            // If no valid crafting recipe was found for the current sub-instance, re-throw its error
654
            if (dependency == null) {
1✔
655
                missingDependencies.add(firstError);
1✔
656
                if (collectMissingRecipes) {
1✔
657
                    continue;
1✔
658
                } else {
659
                    break;
660
                }
661
            }
662

663
            // --- When we reach this point, a valid sub-recipe was found ---
664

665
            // Update our simulatedExtractionMemory to indicate that the dependency's
666
            // instance should not be extracted anymore.
667
            ((IngredientCollectionPrototypeMap<T, M>) simulatedExtractionMemory.get(dependencyComponent))
1✔
668
                    .remove(dependencyInstance);
1✔
669

670
            // If the dependency instance is reusable, mark it as available in our reusable extraction memory
671
            if (missingElement.isInputReusable()) {
1✔
672
                ((IIngredientCollectionMutable<T, M>) extractionMemoryReusable.get(dependencyComponent)).add(dependencyInstance);
1✔
673
            }
674

675
            // Add the valid sub-recipe it to our dependencies
676
            // If the recipe was already present at this level, just increment the amount of the existing job.
677
            CraftingJob existingJob = dependencies.get(dependency.getRecipe());
1✔
678
            if (existingJob == null) {
1✔
679
                dependencies.put(dependency.getRecipe(), dependency);
1✔
680
            } else {
681
                // Remove the standalone dependency job by merging it into the existing job
682
                craftingJobsGraph.mergeCraftingJobs(existingJob, dependency, true);
1✔
683
            }
684
        }
1✔
685

686
        return new PartialCraftingJobCalculationDependency(missingDependencies, dependencies.values());
1✔
687
    }
688

689
    // Helper function for calculateCraftingJobDependencyComponent
690
    protected static <T1, M1, T2, M2> void addRemainderAsSurplusForComponent(IngredientComponent<T1, M1> ingredientComponent,
691
                                                                             List<T1> instances,
692
                                                                             IngredientCollectionPrototypeMap<T1, M1> simulatedExtractionMemory,
693
                                                                             IngredientComponent<T2, M2> blackListComponent,
694
                                                                             T2 blacklistInstance, M2 blacklistCondition,
695
                                                                             long blacklistQuantity) {
696
        IIngredientMatcher<T2, M2> blacklistMatcher = blackListComponent.getMatcher();
1✔
697
        for (T1 instance : instances) {
1✔
698
            IIngredientMatcher<T1, M1> outputMatcher = ingredientComponent.getMatcher();
1✔
699
            long reduceQuantity = 0;
1✔
700
            if (blackListComponent == ingredientComponent
1✔
701
                    && blacklistMatcher.matches(blacklistInstance, (T2) instance, blacklistCondition)) {
1✔
702
                reduceQuantity = blacklistQuantity;
1✔
703
            }
704
            long quantity = simulatedExtractionMemory.getQuantity(instance) + (outputMatcher.getQuantity(instance) - reduceQuantity);
1✔
705
            if (quantity > 0) {
1✔
706
                simulatedExtractionMemory.setQuantity(instance, quantity);
1✔
707
            }
708
        }
1✔
709
    }
1✔
710

711
    /**
712
     * Schedule all crafting jobs in the given dependency graph in the given network.
713
     *
714
     * @param craftingNetwork            The target crafting network.
715
     * @param storageGetter              The storage getter.
716
     * @param craftingJobDependencyGraph The crafting job dependency graph.
717
     * @param allowDistribution          If the crafting jobs are allowed to be split over multiple crafting interfaces.
718
     * @param initiator                  Optional UUID of the initiator.
719
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
720
     */
721
    public static void scheduleCraftingJobs(ICraftingNetwork craftingNetwork,
722
                                            Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
723
                                            CraftingJobDependencyGraph craftingJobDependencyGraph,
724
                                            boolean allowDistribution,
725
                                            @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
726
        List<CraftingJob> startedJobs = Lists.newArrayList();
×
727
        craftingNetwork.getCraftingJobDependencyGraph().importDependencies(craftingJobDependencyGraph);
×
728
        for (CraftingJob craftingJob : craftingJobDependencyGraph.getCraftingJobs()) {
×
729
            try {
730
                craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution, storageGetter);
×
NEW
731
            } catch (UnavailableCraftingInterfacesException e) {
×
732
                // First, cancel all jobs that were already started
733
                for (CraftingJob startedJob : startedJobs) {
×
734
                    CraftingHelpers.insertIngredientsGuaranteed(startedJob.getIngredientsStorageBuffer(), storageGetter, (ICraftingResultsSink) Iterables.getFirst(craftingNetwork.getCraftingInterfaces(startedJob.getChannel()), null));
×
735
                    craftingNetwork.cancelCraftingJob(startedJob.getChannel(), startedJob.getId());
×
736
                }
×
737

738
                // Then, throw an exception for all jobs in this dependency graph
739
                throw new UnavailableCraftingInterfacesException(craftingJobDependencyGraph.getCraftingJobs());
×
740
            }
×
741
            startedJobs.add(craftingJob);
×
742
            if (initiator != null) {
×
743
                craftingJob.setInitiatorUuid(initiator.toString());
×
744
            }
745
        }
×
746
    }
×
747

748
    /**
749
     * Schedule the given crafting job  in the given network.
750
     *
751
     * @param craftingNetwork   The target crafting network.
752
     * @param storageGetter     The storage getter.
753
     * @param craftingJob       The crafting job to schedule.
754
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
755
     * @param initiator         Optional UUID of the initiator.
756
     * @return The scheduled crafting job.
757
     * @throws UnavailableCraftingInterfacesException If no crafting interfaces were available.
758
     */
759
    public static CraftingJob scheduleCraftingJob(ICraftingNetwork craftingNetwork,
760
                                                  Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
761
                                                  CraftingJob craftingJob,
762
                                                  boolean allowDistribution,
763
                                                  @Nullable UUID initiator) throws UnavailableCraftingInterfacesException {
764
        craftingNetwork.scheduleCraftingJob(craftingJob, allowDistribution, storageGetter);
×
765
        if (initiator != null) {
×
766
            craftingJob.setInitiatorUuid(initiator.toString());
×
767
        }
768
        return craftingJob;
×
769
    }
770

771
    /**
772
     * Schedule a crafting job for the given instance in the given network.
773
     * @param network The target network.
774
     * @param channel The target channel.
775
     * @param ingredientComponent The ingredient component type of the instance.
776
     * @param instance The instance to craft.
777
     * @param matchCondition The match condition of the instance.
778
     * @param craftMissing If the missing required ingredients should also be crafted.
779
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
780
     * @param identifierGenerator An ID generator for crafting jobs.
781
     * @param initiator Optional UUID of the initiator.
782
     * @param <T> The instance type.
783
     * @param <M> The matching condition parameter.
784
     * @return The scheduled crafting job, or null if no recipe was found.
785
     */
786
    @Nullable
787
    public static <T, M> CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
788
                                                                     IngredientComponent<T, M> ingredientComponent,
789
                                                                     T instance, M matchCondition,
790
                                                                     boolean craftMissing, boolean allowDistribution,
791
                                                                     IIdentifierGenerator identifierGenerator,
792
                                                                     @Nullable UUID initiator) {
793
        try {
794
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
795
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, ingredientComponent, instance,
×
796
                    matchCondition, craftMissing, identifierGenerator, dependencyGraph, false);
797

798
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
799

800
            scheduleCraftingJobs(craftingNetwork, getNetworkStorageGetter(network, channel, false), dependencyGraph, allowDistribution, initiator);
×
801

802
            return craftingJob;
×
803
        } catch (UnknownCraftingRecipeException | RecursiveCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
804
            return null;
×
805
        }
806
    }
807

808
    /**
809
     * Schedule a crafting job for the given recipe in the given network.
810
     * @param network The target network.
811
     * @param channel The target channel.
812
     * @param recipe The recipe to craft.
813
     * @param amount The amount to craft.
814
     * @param craftMissing If the missing required ingredients should also be crafted.
815
     * @param allowDistribution If the crafting job is allowed to be split over multiple crafting interfaces.
816
     * @param identifierGenerator An ID generator for crafting jobs.
817
     * @param initiator Optional UUID of the initiator.
818
     * @return The scheduled crafting job, or null if no recipe was found.
819
     */
820
    @Nullable
821
    public static CraftingJob calculateAndScheduleCraftingJob(INetwork network, int channel,
822
                                                              IRecipeDefinition recipe, int amount,
823
                                                              boolean craftMissing, boolean allowDistribution,
824
                                                              IIdentifierGenerator identifierGenerator,
825
                                                              @Nullable UUID initiator) {
826
        try {
827
            CraftingJobDependencyGraph dependencyGraph = new CraftingJobDependencyGraph();
×
828
            CraftingJob craftingJob = calculateCraftingJobs(network, channel, recipe, amount, craftMissing,
×
829
                    identifierGenerator, dependencyGraph, false);
830

831
            ICraftingNetwork craftingNetwork = getCraftingNetworkChecked(network);
×
832

833
            scheduleCraftingJobs(craftingNetwork, getNetworkStorageGetter(network, channel, false), dependencyGraph, allowDistribution, initiator);
×
834

835
            return craftingJob;
×
836
        } catch (RecursiveCraftingRecipeException | FailedCraftingRecipeException | UnavailableCraftingInterfacesException e) {
×
837
            return null;
×
838
        }
839
    }
840

841
    /**
842
     * Check if the given network contains the given instance in any of its storages.
843
     * @param network The target network.
844
     * @param channel The target channel.
845
     * @param ingredientComponent The ingredient component type of the instance.
846
     * @param instance The instance to check.
847
     * @param matchCondition The match condition of the instance.
848
     * @param <T> The instance type.
849
     * @param <M> The matching condition parameter.
850
     * @return If the instance is present in the network.
851
     */
852
    public static <T, M> boolean hasStorageInstance(INetwork network, int channel,
853
                                                    IngredientComponent<T, M> ingredientComponent,
854
                                                    T instance, M matchCondition) {
855
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
856
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
857
        boolean contains;
858
        if (storage instanceof IngredientChannelIndexed) {
×
859
            IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
860
            long quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
861
            contains = matcher.hasCondition(matchCondition, ingredientComponent.getPrimaryQuantifier().getMatchCondition()) ? quantityPresent >= matcher.getQuantity(instance) : quantityPresent > 0;
×
862
        } else {
×
863
            contains = !ingredientComponent.getMatcher().isEmpty(storage.extract(instance, matchCondition, true));
×
864
        }
865
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
866
        return contains;
×
867
    }
868

869
    /**
870
     * Check the quantity of the given instance in the network.
871
     * @param network The target network.
872
     * @param channel The target channel.
873
     * @param ingredientComponent The ingredient component type of the instance.
874
     * @param instance The instance to check.
875
     * @param matchCondition The match condition of the instance.
876
     * @param <T> The instance type.
877
     * @param <M> The matching condition parameter.
878
     * @return The quantity in the network.
879
     */
880
    public static <T, M> long getStorageInstanceQuantity(INetwork network, int channel,
881
                                                         IngredientComponent<T, M> ingredientComponent,
882
                                                         T instance, M matchCondition) {
883
        IIngredientComponentStorage<T, M> storage = getNetworkStorage(network, channel, ingredientComponent, true);
×
884
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).disableLimits();
×
885
        long quantityPresent;
886
        if (storage instanceof IngredientChannelIndexed) {
×
887
            quantityPresent = ((IngredientChannelIndexed<T, M>) storage).getIndex().getQuantity(instance);
×
888
        } else {
889
            quantityPresent = ingredientComponent.getMatcher().getQuantity(storage.extract(instance, matchCondition, true));
×
890
        }
891
        if (storage instanceof IngredientChannelAdapter) ((IngredientChannelAdapter) storage).enableLimits();
×
892
        return quantityPresent;
×
893
    }
894

895
    /**
896
     * Check if there is a scheduled crafting job for the given instance.
897
     * @param craftingNetwork The target crafting network.
898
     * @param channel The target channel.
899
     * @param ingredientComponent The ingredient component type of the instance.
900
     * @param instance The instance to check.
901
     * @param matchCondition The match condition of the instance.
902
     * @param <T> The instance type.
903
     * @param <M> The matching condition parameter.
904
     * @return If the instance has a crafting job.
905
     */
906
    public static <T, M> boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
907
                                            IngredientComponent<T, M> ingredientComponent,
908
                                            T instance, M matchCondition) {
909
        Iterator<CraftingJob> craftingJobs = craftingNetwork.getCraftingJobs(channel, ingredientComponent,
×
910
                instance, matchCondition);
911
        return craftingJobs.hasNext();
×
912
    }
913

914
    /**
915
     * Check if there is a scheduled crafting job for the given recipe.
916
     * @param craftingNetwork The target crafting network.
917
     * @param channel The target channel.
918
     * @param recipe The recipe to check.
919
     * @return If the instance has a crafting job.
920
     */
921
    public static boolean isCrafting(ICraftingNetwork craftingNetwork, int channel,
922
                                     IRecipeDefinition recipe) {
923
        Iterator<CraftingJob> it = craftingNetwork.getCraftingJobs(channel);
×
924
        while (it.hasNext()) {
×
925
            if (it.next().getRecipe().equals(recipe)) {
×
926
                return true;
×
927
            }
928
        }
929
        return false;
×
930
    }
931

932
    /**
933
     * Get all required recipe input ingredients from the network for the given ingredient component.
934
     *
935
     * If multiple alternative inputs are possible,
936
     * then only the first possible match will be taken.
937
     *
938
     * Note: Make sure that you first call in simulation-mode
939
     * to see if the ingredients are available.
940
     * If you immediately call this non-simulated,
941
     * then there might be a chance that ingredients are lost
942
     * from the network.
943
     *
944
     * @param storage The target storage.
945
     * @param ingredientComponent The ingredient component to get the ingredients for.
946
     * @param recipe The recipe to get the inputs from.
947
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
948
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
949
     * @param <T> The instance type.
950
     * @param <M> The matching condition parameter, may be Void.
951
     * @return A list of slot-based ingredients, or null if no valid inputs could be found.
952
     */
953
    @Nullable
954
    public static <T, M> List<T> getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage,
955
                                                           IngredientComponent<T, M> ingredientComponent,
956
                                                           IRecipeDefinition recipe, boolean simulate,
957
                                                           long recipeOutputQuantity) {
958
        return getIngredientRecipeInputs(storage, ingredientComponent, recipe, simulate,
1✔
959
                simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null,
1✔
960
                new IngredientHashSet<>(ingredientComponent),
961
                false, recipeOutputQuantity).getLeft();
1✔
962
    }
963

964
    /**
965
     * Get all required recipe input ingredients from the network for the given ingredient component,
966
     * and optionally, explicitly calculate the missing ingredients.
967
     *
968
     * If multiple alternative inputs are possible,
969
     * then only the first possible match will be taken.
970
     *
971
     * Note: Make sure that you first call in simulation-mode
972
     * to see if the ingredients are available.
973
     * If you immediately call this non-simulated,
974
     * then there might be a chance that ingredients are lost
975
     * from the network.
976
     *
977
     * @param storage The target storage.
978
     * @param ingredientComponent The ingredient component to get the ingredients for.
979
     * @param recipe The recipe to get the inputs from.
980
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
981
     * @param simulatedExtractionMemory This map remembers all extracted instances in simulation mode.
982
     *                                  This is to make sure that instances can not be extracted multiple times
983
     *                                  when simulating.
984
     *                                  The quantities can also go negatives,
985
     *                                  which means that a surplus of the given instance is present,
986
     *                                  which will be used up first before a call to the storage.
987
     * @param extractionMemoryReusable Like simulatedExtractionMemory, but it stores the reusable ingredients.
988
     * @param collectMissingIngredients If missing ingredients should be collected.
989
     *                                  If false, then the first returned list may be null
990
     *                                  if no valid matches can be found,
991
     *                                  and the second returned list is always null,
992
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
993
     * @param <T> The instance type.
994
     * @param <M> The matching condition parameter, may be Void.
995
     * @return A pair with two lists:
996
     *           1. A list of available slot-based ingredients.
997
     *           2. A missing ingredients object.
998
     */
999
    public static <T, M> Pair<List<T>, MissingIngredients<T, M>>
1000
    getIngredientRecipeInputs(IIngredientComponentStorage<T, M> storage, IngredientComponent<T, M> ingredientComponent,
1001
                              IRecipeDefinition recipe, boolean simulate,
1002
                              IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemory,
1003
                              IIngredientCollectionMutable<T, M> extractionMemoryReusable,
1004
                              boolean collectMissingIngredients, long recipeOutputQuantity) {
1005
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
1006

1007
        // Quickly return if the storage is empty
1008
        // We can't take this shortcut if we have a reusable ingredient AND extractionMemoryReusable is not empty
1009
        if (storage.getMaxQuantity() == 0 &&
1✔
1010
                extractionMemoryReusable.isEmpty() &&
1✔
1011
                IntStream.range(0, recipe.getInputs(ingredientComponent).size())
1✔
1012
                        .noneMatch(i -> recipe.isInputReusable(ingredientComponent, i))) {
1✔
1013
            if (collectMissingIngredients) {
1✔
1014
                List<IPrototypedIngredientAlternatives<T, M>> recipeInputs = recipe.getInputs(ingredientComponent);
1✔
1015
                MissingIngredients<T, M> missing = new MissingIngredients<>(recipeInputs.stream().map(IPrototypedIngredientAlternatives::getAlternatives)
1✔
1016
                        .map(l -> multiplyPrototypedIngredients(l, recipeOutputQuantity)) // If the input is reusable, don't multiply the expected input quantity
1✔
1017
                        .map(ps -> new MissingIngredients.Element<>(ps
1✔
1018
                                .stream()
1✔
1019
                                .map(p -> new MissingIngredients.PrototypedWithRequested<>(p, matcher.getQuantity(p.getPrototype())))
1✔
1020
                                .collect(Collectors.toList()), false)
1✔
1021
                        )
1022
                        .collect(Collectors.toList()));
1✔
1023
                return Pair.of(
1✔
1024
                        Lists.newArrayList(Collections.nCopies(recipe.getInputs(ingredientComponent).size(),
1✔
1025
                                ingredientComponent.getMatcher().getEmptyInstance())),
1✔
1026
                        missing);
1027
            } else {
1028
                return Pair.of(null, null);
1✔
1029
            }
1030
        }
1031

1032
        // Iterate over all input slots
1033
        List<IPrototypedIngredientAlternatives<T, M>> inputAlternativePrototypes = recipe.getInputs(ingredientComponent);
1✔
1034
        List<T> inputInstances = Lists.newArrayList();
1✔
1035
        List<MissingIngredients.Element<T, M>> missingElements =
1036
                collectMissingIngredients ? Lists.newArrayList() : null;
1✔
1037
        for (int inputIndex = 0; inputIndex < inputAlternativePrototypes.size(); inputIndex++) {
1✔
1038
            IPrototypedIngredientAlternatives<T, M> inputPrototypes = inputAlternativePrototypes.get(inputIndex);
1✔
1039
            T firstInputInstance = null;
1✔
1040
            boolean setFirstInputInstance = false;
1✔
1041
            T inputInstance = null;
1✔
1042
            boolean hasInputInstance = false;
1✔
1043
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBufferFirst = null;
1✔
1044
            IIngredientCollectionMutable<T, M> extractionMemoryReusableBufferFirst = null;
1✔
1045

1046
            // Iterate over all alternatives for this input slot, and take the first matching ingredient.
1047
            List<MissingIngredients.PrototypedWithRequested<T, M>> missingAlternatives = Lists.newArrayList();
1✔
1048
            IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryAlternative = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1049
            if (simulate) {
1✔
1050
                simulatedExtractionMemoryAlternative.addAll(simulatedExtractionMemory);
1✔
1051
            }
1052
            for (IPrototypedIngredient<T, M> inputPrototype : inputPrototypes.getAlternatives()) {
1✔
1053
                boolean inputReusable = recipe.isInputReusable(ingredientComponent, inputIndex);
1✔
1054
                IngredientCollectionPrototypeMap<T, M> simulatedExtractionMemoryBuffer = simulate ? new IngredientCollectionPrototypeMap<>(ingredientComponent, true) : null;
1✔
1055
                IIngredientCollectionMutable<T, M> extractionMemoryReusableBuffer = inputReusable ? new IngredientHashSet<>(ingredientComponent) : null;
1✔
1056
                boolean shouldBreak = false;
1✔
1057

1058
                // Multiply required prototype if recipe quantity is higher than one, AND if the input is NOT reusable.
1059
                if (recipeOutputQuantity > 1 && !inputReusable) {
1✔
1060
                    inputPrototype = multiplyPrototypedIngredient(inputPrototype, recipeOutputQuantity);
1✔
1061
                }
1062

1063
                // If the prototype is empty, we can skip network extraction
1064
                if (matcher.isEmpty(inputPrototype.getPrototype())) {
1✔
1065
                    inputInstance = inputPrototype.getPrototype();
1✔
1066
                    hasInputInstance = true;
1✔
1067
                    break;
1✔
1068
                }
1069

1070
                long prototypeQuantity = matcher.getQuantity(inputPrototype.getPrototype());
1✔
1071
                if (inputReusable && extractionMemoryReusable.contains(inputPrototype.getPrototype())) {
1✔
1072
                    // If the reusable item has been extracted before, mark as valid, and don't extract again.
1073
                    inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1074
                    hasInputInstance = true;
1✔
1075
                    shouldBreak = true;
1✔
1076
                } else {
1077
                    long memoryQuantity;
1078
                    if (simulate && (memoryQuantity = simulatedExtractionMemoryAlternative
1✔
1079
                            .getQuantity(inputPrototype.getPrototype())) != 0) {
1✔
1080
                        long newQuantity = memoryQuantity + prototypeQuantity;
1✔
1081
                        if (newQuantity > 0) {
1✔
1082
                            // Part of our quantity can be provided via simulatedExtractionMemory,
1083
                            // but not all of it,
1084
                            // so we need to extract from storage as well.
1085
                            T newInstance = matcher.withQuantity(inputPrototype.getPrototype(), newQuantity);
1✔
1086
                            M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1087
                                    ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1088
                            if (storage instanceof IngredientChannelAdapter)
1✔
1089
                                ((IngredientChannelAdapter) storage).disableLimits();
×
1090
                            T extracted = storage.extract(newInstance, matchCondition, true);
1✔
1091
                            if (storage instanceof IngredientChannelAdapter)
1✔
1092
                                ((IngredientChannelAdapter) storage).enableLimits();
×
1093
                            long quantityExtracted = matcher.getQuantity(extracted);
1✔
1094
                            if (quantityExtracted == newQuantity) {
1✔
1095
                                // All remaining could be extracted from storage, all is fine now
1096
                                inputInstance = inputPrototype.getPrototype();
1✔
1097
                                simulatedExtractionMemoryAlternative.add(inputInstance);
1✔
1098
                                simulatedExtractionMemoryBuffer.add(inputInstance);
1✔
1099
                                if (inputReusable) {
1✔
1100
                                    extractionMemoryReusableBuffer.add(inputInstance);
1✔
1101
                                }
1102
                                hasInputInstance = true;
1✔
1103
                                shouldBreak = true;
1✔
1104
                            } else if (collectMissingIngredients) {
1✔
1105
                                // Not everything could be extracted from storage, we *miss* the remaining ingredient.
1106
                                long quantityMissingPrevious = Math.max(0, memoryQuantity - quantityExtracted);
1✔
1107
                                long quantityMissingTotal = newQuantity - quantityExtracted;
1✔
1108
                                long quantityMissingRelative = quantityMissingTotal - quantityMissingPrevious;
1✔
1109

1110
                                missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissingRelative));
1✔
1111
                                inputInstance = matcher.withQuantity(inputPrototype.getPrototype(), prototypeQuantity - quantityMissingRelative);
1✔
1112
                                simulatedExtractionMemoryAlternative.setQuantity(inputPrototype.getPrototype(), quantityMissingTotal);
1✔
1113
                                // Original prototype quantity because we what can be extracted from storage and what could NOT be extracted from storage should be added to the simulation extraction memory.
1114
                                // The part that could NOT be extracted will be removed later when crafting jobs are calculated for the missing elements. (not doing so would lead to over-estimation of what is in storage)
1115
                                simulatedExtractionMemoryBuffer.add(matcher.withQuantity(inputPrototype.getPrototype(), prototypeQuantity));
1✔
1116
                            }
1117
                        } else {
1✔
1118
                            // All of our quantity can be provided via our surplus in simulatedExtractionMemory
1119
                            simulatedExtractionMemoryAlternative.add(inputPrototype.getPrototype());
1✔
1120
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1121
                            if (inputReusable) {
1✔
1122
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1123
                            }
1124
                            inputInstance = inputPrototype.getComponent().getMatcher().getEmptyInstance();
1✔
1125
                            hasInputInstance = true;
1✔
1126
                            shouldBreak = true;
1✔
1127
                        }
1128
                    } else {
1✔
1129
                        M matchCondition = matcher.withoutCondition(inputPrototype.getCondition(),
1✔
1130
                                ingredientComponent.getPrimaryQuantifier().getMatchCondition());
1✔
1131
                        if (storage instanceof IngredientChannelAdapter)
1✔
1132
                            ((IngredientChannelAdapter) storage).disableLimits();
×
1133
                        T extracted = storage.extract(inputPrototype.getPrototype(), matchCondition, simulate);
1✔
1134
                        if (storage instanceof IngredientChannelAdapter)
1✔
1135
                            ((IngredientChannelAdapter) storage).enableLimits();
×
1136
                        long quantityExtracted = matcher.getQuantity(extracted);
1✔
1137
                        inputInstance = extracted;
1✔
1138
                        if (simulate) {
1✔
1139
                            simulatedExtractionMemoryAlternative.add(extracted);
1✔
1140
                            simulatedExtractionMemoryBuffer.add(inputPrototype.getPrototype());
1✔
1141
                        }
1142
                        if (prototypeQuantity == quantityExtracted) {
1✔
1143
                            hasInputInstance = true;
1✔
1144
                            shouldBreak = true;
1✔
1145
                            if (inputReusable) {
1✔
1146
                                extractionMemoryReusableBuffer.add(inputPrototype.getPrototype());
1✔
1147
                            }
1148
                        } else if (collectMissingIngredients) {
1✔
1149
                            long quantityMissing = prototypeQuantity - quantityExtracted;
1✔
1150
                            missingAlternatives.add(new MissingIngredients.PrototypedWithRequested<>(inputPrototype, quantityMissing));
1✔
1151
                        }
1152
                    }
1153
                }
1154

1155
                if (!setFirstInputInstance || shouldBreak) {
1✔
1156
                    setFirstInputInstance = true;
1✔
1157
                    firstInputInstance = inputInstance;
1✔
1158
                    simulatedExtractionMemoryBufferFirst = simulatedExtractionMemoryBuffer;
1✔
1159
                    if (inputReusable) {
1✔
1160
                        extractionMemoryReusableBufferFirst = extractionMemoryReusableBuffer;
1✔
1161
                    } else {
1162
                        extractionMemoryReusableBufferFirst = null;
1✔
1163
                    }
1164
                }
1165

1166
                if (shouldBreak) {
1✔
1167
                    break;
1✔
1168
                }
1169
            }
1✔
1170

1171
            if (simulatedExtractionMemoryBufferFirst != null) {
1✔
1172
                for (T instance : simulatedExtractionMemoryBufferFirst) {
1✔
1173
                    simulatedExtractionMemory.add(instance);
1✔
1174
                }
1✔
1175
            }
1176
            if (extractionMemoryReusableBufferFirst != null) {
1✔
1177
                for (T instance : extractionMemoryReusableBufferFirst) {
1✔
1178
                    extractionMemoryReusable.add(instance);
1✔
1179
                }
1✔
1180
            }
1181

1182
            // If none of the alternatives were found, fail immediately
1183
            if (!hasInputInstance) {
1✔
1184
                if (!simulate) {
1✔
1185
                    // But first, re-insert all already-extracted instances
1186
                    for (T instance : inputInstances) {
1✔
1187
                        T remaining = storage.insert(instance, false);
1✔
1188
                        if (!matcher.isEmpty(remaining)) {
1✔
1189
                            throw new IllegalStateException("Extraction for a crafting recipe failed" +
×
1190
                                    "due to inconsistent insertion behaviour by destination in simulation " +
1191
                                    "and non-simulation: " + storage + ". Lost: " + remaining);
1192
                        }
1193
                    }
1✔
1194
                }
1195

1196
                if (!collectMissingIngredients) {
1✔
1197
                    // This input failed, return immediately
1198
                    return Pair.of(null, null);
1✔
1199
                } else {
1200
                    // Multiply missing collection if recipe quantity is higher than one
1201
                    if (missingAlternatives.size() > 0) {
1✔
1202
                        missingElements.add(new MissingIngredients.Element<>(missingAlternatives, recipe.isInputReusable(ingredientComponent, inputIndex)));
1✔
1203
                    }
1204
                }
1205
            }
1206

1207
            // Otherwise, append it to the list and carry on.
1208
            // If none of the instances were valid, we add the first partially valid instance.
1209
            if (hasInputInstance) {
1✔
1210
                inputInstances.add(inputInstance);
1✔
1211
            } else if (setFirstInputInstance && !matcher.isEmpty(firstInputInstance)) {
1✔
1212
                inputInstances.add(firstInputInstance);
1✔
1213
            }
1214
        }
1215

1216
        return Pair.of(
1✔
1217
                inputInstances,
1218
                collectMissingIngredients ? new MissingIngredients<>(missingElements) : null
1✔
1219
        );
1220
    }
1221

1222
    /**
1223
     * Get all required recipe input ingredients from the network.
1224
     *
1225
     * If multiple alternative inputs are possible,
1226
     * then only the first possible match will be taken.
1227
     *
1228
     * Note: Make sure that you first call in simulation-mode
1229
     * to see if the ingredients are available.
1230
     * If you immediately call this non-simulated,
1231
     * then there might be a chance that ingredients are lost
1232
     * from the network.
1233
     *
1234
     * @param network The target network.
1235
     * @param channel The target channel.
1236
     * @param recipe The recipe to get the inputs from.
1237
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1238
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1239
     * @return The found ingredients or null.
1240
     */
1241
    @Nullable
1242
    public static IMixedIngredients getRecipeInputs(INetwork network, int channel,
1243
                                                    IRecipeDefinition recipe, boolean simulate,
1244
                                                    long recipeOutputQuantity) {
1245
        Map<IngredientComponent<?, ?>, List<?>> inputs = getRecipeInputs(getNetworkStorageGetter(network, channel, true),
×
1246
                recipe, simulate, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), false, recipeOutputQuantity).getLeft();
×
1247
        return inputs == null ? null : new MixedIngredients(inputs);
×
1248
    }
1249

1250
    /**
1251
     * Get all required recipe input ingredients from the crafting job's buffer.
1252
     *
1253
     * If multiple alternative inputs are possible,
1254
     * then only the first possible match will be taken.
1255
     *
1256
     * Note: Make sure that you first call in simulation-mode
1257
     * to see if the ingredients are available.
1258
     * If you immediately call this non-simulated,
1259
     * then there might be a chance that ingredients are lost
1260
     * from the buffer.
1261
     *
1262
     * @param craftingJob The crafting job.
1263
     * @param recipe The recipe to get the inputs from.
1264
     * @param simulate If true, then the ingredients will effectively be removed from the buffer, not when false.
1265
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1266
     * @return The found ingredients or null.
1267
     */
1268
    @Nullable
1269
    public static IMixedIngredients getRecipeInputsFromCraftingJobBuffer(CraftingJob craftingJob,
1270
                                                    IRecipeDefinition recipe, boolean simulate,
1271
                                                    long recipeOutputQuantity) {
1272
        Map<IngredientComponent<?, ?>, List<?>> inputs = getRecipeInputs(getCraftingJobBufferStorageGetter(craftingJob),
×
1273
                recipe, simulate, Maps.newIdentityHashMap(), Maps.newIdentityHashMap(), false, recipeOutputQuantity).getLeft();
×
1274
        return inputs == null ? null : new MixedIngredients(inputs);
×
1275
    }
1276

1277
    /**
1278
     * Create a callback function for getting a storage for an ingredient component from the given network channel.
1279
     * @param network The target network.
1280
     * @param channel The target channel.
1281
     * @param scheduleObservation If an observation inside the ingredients network should be scheduled.
1282
     * @return A callback function for getting a storage for an ingredient component.
1283
     */
1284
    public static Function<IngredientComponent<?, ?>, IIngredientComponentStorage> getNetworkStorageGetter(INetwork network, int channel, boolean scheduleObservation) {
1285
        return ingredientComponent -> getNetworkStorage(network, channel, ingredientComponent, scheduleObservation);
×
1286
    }
1287

1288
    /**
1289
     * Create a callback function for getting a storage for an ingredient component from the given crafting job buffer.
1290
     * @param craftingJob The crafting job.
1291
     * @return A callback function for getting a storage for an ingredient component.
1292
     */
1293
    public static Function<IngredientComponent<?, ?>, IIngredientComponentStorage> getCraftingJobBufferStorageGetter(CraftingJob craftingJob) {
1294
        return ingredientComponent -> {
×
1295
            List<?> list = craftingJob.getIngredientsStorageBuffer().getInstances(ingredientComponent);
×
1296
            return new IngredientComponentStorageSlottedCollectionWrapper<>(new IngredientList(ingredientComponent, list), Long.MAX_VALUE, Long.MAX_VALUE);
×
1297
        };
1298
    }
1299

1300
    /**
1301
     * Get all required recipe input ingredients based on a given storage callback.
1302
     *
1303
     * If multiple alternative inputs are possible,
1304
     * then only the first possible match will be taken.
1305
     *
1306
     * Note: Make sure that you first call in simulation-mode
1307
     * to see if the ingredients are available.
1308
     * If you immediately call this non-simulated,
1309
     * then there might be a chance that ingredients are lost
1310
     * from the network.
1311
     *
1312
     * @param storageGetter A callback function to get a storage for the given ingredient component.
1313
     * @param recipe The recipe to get the inputs from.
1314
     * @param simulate If true, then the ingredients will effectively be removed from the network, not when false.
1315
     * @param simulatedExtractionMemories This map remembers all extracted instances in simulation mode.
1316
     *                                    This is to make sure that instances can not be extracted multiple times
1317
     *                                    when simulating.
1318
     * @param extractionMemoriesReusable Like simulatedExtractionMemories, but it stores the reusable ingredients.
1319
     * @param collectMissingIngredients If missing ingredients should be collected.
1320
     *                                  If false, then the first returned mixed ingredients may be null
1321
     *                                  if no valid matches can be found,
1322
     *                                  and the second returned list is always null,
1323
     * @param recipeOutputQuantity The number of times the given recipe should be applied.
1324
     * @return A pair with two objects:
1325
     *           1. The found ingredients or null.
1326
     *           2. A mapping from ingredient component to missing ingredients (non-slot-based).
1327
     */
1328
    public static Pair<Map<IngredientComponent<?, ?>, List<?>>, Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>>>
1329
    getRecipeInputs(Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter, IRecipeDefinition recipe, boolean simulate,
1330
                    Map<IngredientComponent<?, ?>, IngredientCollectionPrototypeMap<?, ?>> simulatedExtractionMemories,
1331
                    Map<IngredientComponent<?, ?>, IIngredientCollectionMutable<?, ?>> extractionMemoriesReusable,
1332
                    boolean collectMissingIngredients, long recipeOutputQuantity) {
1333
        // Determine available and missing ingredients
1334
        Map<IngredientComponent<?, ?>, List<?>> ingredientsAvailable = Maps.newIdentityHashMap();
1✔
1335
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> ingredientsMissing = Maps.newIdentityHashMap();
1✔
1336
        for (IngredientComponent<?, ?> ingredientComponent : recipe.getInputComponents()) {
1✔
1337
            IIngredientComponentStorage storage = storageGetter.apply(ingredientComponent);
1✔
1338
            IngredientCollectionPrototypeMap<?, ?> simulatedExtractionMemory = simulatedExtractionMemories.get(ingredientComponent);
1✔
1339
            if (simulatedExtractionMemory == null) {
1✔
1340
                simulatedExtractionMemory = new IngredientCollectionPrototypeMap<>(ingredientComponent, true);
1✔
1341
                simulatedExtractionMemories.put(ingredientComponent, simulatedExtractionMemory);
1✔
1342
            }
1343
            IIngredientCollectionMutable extractionMemoryReusable = extractionMemoriesReusable.get(ingredientComponent);
1✔
1344
            if (extractionMemoryReusable == null) {
1✔
1345
                extractionMemoryReusable = new IngredientHashSet<>(ingredientComponent);
1✔
1346
                extractionMemoriesReusable.put(ingredientComponent, extractionMemoryReusable);
1✔
1347
            }
1348
            Pair<List<?>, MissingIngredients<?, ?>> subIngredients = getIngredientRecipeInputs(storage,
1✔
1349
                    (IngredientComponent) ingredientComponent, recipe, simulate, simulatedExtractionMemory, extractionMemoryReusable,
1350
                    collectMissingIngredients, recipeOutputQuantity);
1351
            List<?> subIngredientAvailable = subIngredients.getLeft();
1✔
1352
            MissingIngredients<?, ?> subIngredientsMissing = subIngredients.getRight();
1✔
1353
            if (subIngredientAvailable == null && !collectMissingIngredients) {
1✔
1354
                return Pair.of(null, null);
×
1355
            } else {
1356
                if (subIngredientAvailable != null && !subIngredientAvailable.isEmpty()) {
1✔
1357
                    ingredientsAvailable.put(ingredientComponent, subIngredientAvailable);
1✔
1358
                }
1359
                if (collectMissingIngredients && !subIngredientsMissing.getElements().isEmpty()) {
1✔
1360
                    ingredientsMissing.put(ingredientComponent, subIngredientsMissing);
1✔
1361
                }
1362
            }
1363
        }
1✔
1364

1365
        // Compress missing ingredients
1366
        // We do this to ensure that instances missing multiple times can be easily combined
1367
        // when triggering a crafting job for them.
1368
        Map<IngredientComponent<?, ?>, MissingIngredients<?, ?>> ingredientsMissingCompressed = Maps.newIdentityHashMap();
1✔
1369
        for (IngredientComponent<?, ?> ingredientComponent : ingredientsMissing.keySet()) {
1✔
1370
            ingredientsMissingCompressed.put(ingredientComponent, compressMissingIngredients(ingredientsMissing.get(ingredientComponent)));
1✔
1371
        }
1✔
1372

1373
        return Pair.of(ingredientsAvailable, ingredientsMissingCompressed);
1✔
1374
    }
1375

1376
    /**
1377
     * Create a list of prototyped ingredients from the instances
1378
     * of the given ingredient component type in the given mixed ingredients.
1379
     *
1380
     * Equal prototypes will be stacked.
1381
     *
1382
     * @param ingredientComponent The ingredient component type.
1383
     * @param mixedIngredients The mixed ingredients.
1384
     * @param <T> The instance type.
1385
     * @param <M> The matching condition parameter.
1386
     * @return A list of prototypes.
1387
     */
1388
    public static <T, M> List<IPrototypedIngredient<T, M>> getCompressedIngredients(IngredientComponent<T, M> ingredientComponent,
1389
                                                                                    IMixedIngredients mixedIngredients) {
1390
        List<IPrototypedIngredient<T, M>> outputs = Lists.newArrayList();
1✔
1391

1392
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
1✔
1393
        for (T instance : mixedIngredients.getInstances(ingredientComponent)) {
1✔
1394
            // Try to stack this instance with an existing prototype
1395
            boolean stacked = false;
1✔
1396
            ListIterator<IPrototypedIngredient<T, M>> existingIt = outputs.listIterator();
1✔
1397
            while(existingIt.hasNext()) {
1✔
1398
                IPrototypedIngredient<T, M> prototypedIngredient = existingIt.next();
1✔
1399
                if (matcher.matches(instance, prototypedIngredient.getPrototype(),
1✔
1400
                        prototypedIngredient.getCondition())) {
1✔
1401
                    T stackedInstance = matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1402
                            matcher.getQuantity(prototypedIngredient.getPrototype())
1✔
1403
                                    + matcher.getQuantity(instance));
1✔
1404
                    existingIt.set(new PrototypedIngredient<>(ingredientComponent, stackedInstance,
1✔
1405
                            prototypedIngredient.getCondition()));
1✔
1406
                    stacked = true;
1✔
1407
                    break;
1✔
1408
                }
1409
            }
1✔
1410

1411
            // If not possible, just append it to the list
1412
            if (!stacked) {
1✔
1413
                outputs.add(new PrototypedIngredient<>(ingredientComponent, instance,
1✔
1414
                        matcher.getExactMatchNoQuantityCondition()));
1✔
1415
            }
1416
        }
1✔
1417

1418
        return outputs;
1✔
1419
    }
1420

1421
    /**
1422
     * Compress the given missing ingredients so that equal instances just have an incremented quantity.
1423
     *
1424
     * @param missingIngredients The missing ingredients.
1425
     * @param <T> The instance type.
1426
     * @param <M> The matching condition parameter.
1427
     * @return A new missing ingredients object.
1428
     */
1429
    public static <T, M> MissingIngredients<T, M> compressMissingIngredients(MissingIngredients<T, M> missingIngredients) {
1430
        // Index identical missing ingredients in a map, to group them by quantity
1431
        Map<MissingIngredients.Element<T, M>, Long> elementsCompressedMap = Maps.newLinkedHashMap(); // Must be a linked map to maintain our order!!!
1✔
1432
        for (MissingIngredients.Element<T, M> element : missingIngredients.getElements()) {
1✔
1433
            elementsCompressedMap.merge(element, 1L, Long::sum);
1✔
1434
        }
1✔
1435

1436
        // Create a new missing ingredients list where we multiply the missing quantities
1437
        List<MissingIngredients.Element<T, M>> elementsCompressed = Lists.newArrayList();
1✔
1438
        for (Map.Entry<MissingIngredients.Element<T, M>, Long> entry : elementsCompressedMap.entrySet()) {
1✔
1439
            Long quantity = entry.getValue();
1✔
1440
            if (quantity == 1L || entry.getKey().isInputReusable()) {
1✔
1441
                elementsCompressed.add(entry.getKey());
1✔
1442
            } else {
1443
                MissingIngredients.Element<T, M> elementOld = entry.getKey();
1✔
1444
                MissingIngredients.Element<T, M> elementNewQuantity = new MissingIngredients.Element<>(
1✔
1445
                        elementOld.getAlternatives().stream()
1✔
1446
                                .map(alt -> new MissingIngredients.PrototypedWithRequested<>(alt.getRequestedPrototype(), alt.getQuantityMissing() * quantity))
1✔
1447
                                .toList(),
1✔
1448
                        elementOld.isInputReusable()
1✔
1449
                );
1450
                elementsCompressed.add(elementNewQuantity);
1✔
1451
            }
1452
        }
1✔
1453
        return new MissingIngredients<>(elementsCompressed);
1✔
1454
    }
1455

1456
    /**
1457
     * Create a collection of prototypes from the given recipe's outputs.
1458
     *
1459
     * Equal prototypes will be stacked.
1460
     *
1461
     * @param recipe A recipe.
1462
     * @return A map from ingredient component types to their list of prototypes.
1463
     */
1464
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> getRecipeOutputs(IRecipeDefinition recipe) {
1465
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> outputs = Maps.newHashMap();
1✔
1466

1467
        IMixedIngredients mixedIngredients = recipe.getOutput();
1✔
1468
        for (IngredientComponent ingredientComponent : mixedIngredients.getComponents()) {
1✔
1469
            outputs.put(ingredientComponent, getCompressedIngredients(ingredientComponent, mixedIngredients));
1✔
1470
        }
1✔
1471

1472
        return outputs;
1✔
1473
    }
1474

1475
    /**
1476
     * Creates a new recipe outputs object with all ingredient quantities multiplied by the given amount.
1477
     * @param recipeOutputs A recipe objects holder.
1478
     * @param amount An amount to multiply all instances by.
1479
     * @return A new recipe objects holder.
1480
     */
1481
    public static Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> multiplyRecipeOutputs(
1482
            Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> recipeOutputs, int amount) {
1483
        if (amount == 1) {
1✔
1484
            return recipeOutputs;
1✔
1485
        }
1486

1487
        Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> newRecipeOutputs = Maps.newIdentityHashMap();
1✔
1488
        for (Map.Entry<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>> entry : recipeOutputs.entrySet()) {
1✔
1489
            newRecipeOutputs.put(entry.getKey(), multiplyPrototypedIngredients((List) entry.getValue(), amount));
1✔
1490
        }
1✔
1491
        return newRecipeOutputs;
1✔
1492
    }
1493

1494
    /**
1495
     * Multiply the quantity of a given prototyped ingredient list with the given amount.
1496
     * @param prototypedIngredients A prototyped ingredient list.
1497
     * @param amount An amount to multiply by.
1498
     * @param <T> The instance type.
1499
     * @param <M> The matching condition parameter.
1500
     * @return A multiplied prototyped ingredient list.
1501
     */
1502
    public static <T, M> List<IPrototypedIngredient<T, M>> multiplyPrototypedIngredients(Collection<IPrototypedIngredient<T, M>> prototypedIngredients,
1503
                                                                                         long amount) {
1504
        return prototypedIngredients
1✔
1505
                .stream()
1✔
1506
                .map(p -> multiplyPrototypedIngredient(p, amount))
1✔
1507
                .collect(Collectors.toList());
1✔
1508
    }
1509

1510
    /**
1511
     * Multiply the quantity of a given prototyped ingredient with the given amount.
1512
     * @param prototypedIngredient A prototyped ingredient.
1513
     * @param amount An amount to multiply by.
1514
     * @param <T> The instance type.
1515
     * @param <M> The matching condition parameter.
1516
     * @return A multiplied prototyped ingredient.
1517
     */
1518
    public static <T, M> IPrototypedIngredient<T, M> multiplyPrototypedIngredient(IPrototypedIngredient<T, M> prototypedIngredient,
1519
                                                                                  long amount) {
1520
        IIngredientMatcher<T, M> matcher = prototypedIngredient.getComponent().getMatcher();
1✔
1521
        return new PrototypedIngredient<>(prototypedIngredient.getComponent(),
1✔
1522
                matcher.withQuantity(prototypedIngredient.getPrototype(),
1✔
1523
                        matcher.getQuantity(prototypedIngredient.getPrototype()) * amount),
1✔
1524
                prototypedIngredient.getCondition());
1✔
1525
    }
1526

1527
    /**
1528
     * Merge two mixed ingredients in a new mixed ingredients object.
1529
     * Instances will be stacked.
1530
     * @param a A first mixed ingredients object.
1531
     * @param b A second mixed ingredients object.
1532
     * @return A merged mixed ingredients object.
1533
     */
1534
    public static IMixedIngredients mergeMixedIngredients(IMixedIngredients a, IMixedIngredients b) {
1535
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1536
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1537
        for (IngredientComponent<?, ?> component : a.getComponents()) {
1✔
1538
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1539
            groupings.put(component, grouping);
1✔
1540
            grouping.addAll(a.getInstances(component));
1✔
1541
        }
1✔
1542
        for (IngredientComponent<?, ?> component : b.getComponents()) {
1✔
1543
            IngredientCollectionQuantitativeGrouper grouping = groupings.get(component);
1✔
1544
            if (grouping == null) {
1✔
1545
                grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1546
                groupings.put(component, grouping);
1✔
1547
            }
1548
            grouping.addAll(b.getInstances(component));
1✔
1549
        }
1✔
1550

1551
        // Convert IngredientCollectionPrototypeMaps to lists
1552
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1553
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1554
            ingredients.put(entry.getKey(), Lists.newArrayList(entry.getValue()));
1✔
1555
        }
1✔
1556
        return new MixedIngredients(ingredients);
1✔
1557
    }
1558

1559
    /**
1560
     * Stack all ingredients in the given mixed ingredients object.
1561
     * @param mixedIngredients A mixed ingredients object.
1562
     * @return A new mixed ingredients object.
1563
     */
1564
    protected static IMixedIngredients compressMixedIngredients(IMixedIngredients mixedIngredients) {
1565
        // Temporarily store instances in IngredientCollectionPrototypeMaps
1566
        Map<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> groupings = Maps.newIdentityHashMap();
1✔
1567
        for (IngredientComponent<?, ?> component : mixedIngredients.getComponents()) {
1✔
1568
            IngredientCollectionQuantitativeGrouper grouping = new IngredientCollectionQuantitativeGrouper<>(new IngredientArrayList<>(component));
1✔
1569
            groupings.put(component, grouping);
1✔
1570
            grouping.addAll(mixedIngredients.getInstances(component));
1✔
1571
        }
1✔
1572

1573
        // Convert IngredientCollectionPrototypeMaps to lists
1574
        Map<IngredientComponent<?, ?>, List<?>> ingredients = Maps.newIdentityHashMap();
1✔
1575
        for (Map.Entry<IngredientComponent<?, ?>, IngredientCollectionQuantitativeGrouper<?, ?, IngredientArrayList<?, ?>>> entry : groupings.entrySet()) {
1✔
1576
            IIngredientMatcher matcher = entry.getKey().getMatcher();
1✔
1577
            List<?> values = entry.getValue()
1✔
1578
                    .stream()
1✔
1579
                    .filter(i -> !matcher.isEmpty(i))
1✔
1580
                    .collect(Collectors.toList());
1✔
1581
            if (!values.isEmpty()) {
1✔
1582
                ingredients.put(entry.getKey(), values);
1✔
1583
            }
1584
        }
1✔
1585
        return new MixedIngredients(ingredients);
1✔
1586
    }
1587

1588
    /**
1589
     * Insert the ingredients of the given ingredient component type into the target to make it start crafting.
1590
     *
1591
     * If insertion in non-simulation mode fails,
1592
     * ingredients will be re-inserted into the network.
1593
     *
1594
     * @param ingredientComponent The ingredient component type.
1595
     * @param capabilityProvider The target capability provider.
1596
     * @param side The target side.
1597
     * @param ingredients The ingredients to insert.
1598
     * @param storageFallback The storage to insert any failed ingredients back into. Can be null in simulation mode.
1599
     * @param simulate If insertion should be simulated.
1600
     * @param <T> The instance type.
1601
     * @param <M> The matching condition parameter.
1602
     * @return If all instances could be inserted.
1603
     */
1604
    public static <T, M> boolean insertIngredientCrafting(IngredientComponent<T, M> ingredientComponent,
1605
                                                          ICapabilityProvider capabilityProvider,
1606
                                                          @Nullable Direction side,
1607
                                                          IMixedIngredients ingredients,
1608
                                                          IIngredientComponentStorage<T, M> storageFallback,
1609
                                                          boolean simulate) {
1610
        IIngredientMatcher<T, M> matcher = ingredientComponent.getMatcher();
×
1611
        IIngredientComponentStorage<T, M> storage = ingredientComponent.getStorage(capabilityProvider, side);
×
1612
        List<T> instances = ingredients.getInstances(ingredientComponent);
×
1613
        List<T> failedInstances = Lists.newArrayList();
×
1614
        boolean ok = true;
×
1615
        for (T instance : instances) {
×
1616
            T remaining = storage.insert(instance, simulate);
×
1617
            if (!matcher.isEmpty(remaining)) {
×
1618
                ok = false;
×
1619
                if (!simulate) {
×
1620
                    failedInstances.add(remaining);
×
1621
                }
1622
            }
1623
        }
×
1624

1625
        // If we had failed insertions, try to insert them back into the network.
1626
        for (T instance : failedInstances) {
×
1627
            T remaining = storageFallback.insert(instance, false);
×
1628
            if (!matcher.isEmpty(remaining)) {
×
1629
                throw new IllegalStateException("Insertion for a crafting recipe failed" +
×
1630
                        "due to inconsistent insertion behaviour by destination in simulation " +
1631
                        "and non-simulation: " + capabilityProvider + ". Lost: " + instances);
1632
            }
1633
        }
×
1634

1635
        return ok;
×
1636
    }
1637

1638
    /**
1639
     * Insert the ingredients of all applicable ingredient component types into the target to make it start crafting.
1640
     *
1641
     * If insertion in non-simulation mode fails,
1642
     * ingredients will be re-inserted into the network.
1643
     *
1644
     * @param targetGetter A function to get the target position.
1645
     * @param ingredients The ingredients to insert.
1646
     * @param network The network.
1647
     * @param channel The channel.
1648
     * @param simulate If insertion should be simulated.
1649
     * @return If all instances could be inserted.
1650
     */
1651
    public static boolean insertCrafting(Function<IngredientComponent<?, ?>, PartPos> targetGetter,
1652
                                         IMixedIngredients ingredients,
1653
                                         INetwork network, int channel,
1654
                                         boolean simulate) {
1655
        Map<IngredientComponent<?, ?>, BlockEntity> tileMap = Maps.newIdentityHashMap();
×
1656

1657
        // First, check if we can find valid tiles for all ingredient components
1658
        for (IngredientComponent<?, ?> ingredientComponent : ingredients.getComponents()) {
×
1659
            BlockEntity tile = BlockEntityHelpers.get(targetGetter.apply(ingredientComponent).getPos(), BlockEntity.class).orElse(null);
×
1660
            if (tile != null) {
×
1661
                tileMap.put(ingredientComponent, tile);
×
1662
            } else {
1663
                return false;
×
1664
            }
1665
        }
×
1666

1667
        // Next, insert the instances into the respective tiles
1668
        boolean ok = true;
×
1669
        for (Map.Entry<IngredientComponent<?, ?>, BlockEntity> entry : tileMap.entrySet()) {
×
1670
            IIngredientComponentStorage<?, ?> storageNetwork = simulate ? null : getNetworkStorage(network, channel, entry.getKey(), false);
×
1671
            if (!insertIngredientCrafting((IngredientComponent) entry.getKey(), entry.getValue(),
×
1672
                    targetGetter.apply(entry.getKey()).getSide(), ingredients,
×
1673
                    storageNetwork, simulate)) {
1674
                ok = false;
×
1675
            }
1676
        }
×
1677

1678
        return ok;
×
1679
    }
1680

1681
    /**
1682
     * Split the given crafting job amount into new jobs with a given split factor.
1683
     * @param craftingJob A crafting job to split.
1684
     * @param splitFactor The number of jobs to split the job over.
1685
     * @param dependencyGraph The dependency graph that will be updated if there are dependencies in the original job.
1686
     * @param identifierGenerator An identifier generator for the crafting jobs ids.
1687
     * @return The newly created crafting jobs.
1688
     */
1689
    public static List<CraftingJob> splitCraftingJobs(CraftingJob craftingJob, int splitFactor,
1690
                                                      CraftingJobDependencyGraph dependencyGraph,
1691
                                                      IIdentifierGenerator identifierGenerator) {
1692
        splitFactor = Math.min(splitFactor, craftingJob.getAmount());
1✔
1693
        int division = craftingJob.getAmount() / splitFactor;
1✔
1694
        int modulus = craftingJob.getAmount() % splitFactor;
1✔
1695

1696
        // Clone original job into splitFactor jobs
1697
        List<CraftingJob> newCraftingJobs = Lists.newArrayList();
1✔
1698
        for (int i = 0; i < splitFactor; i++) {
1✔
1699
            CraftingJob clonedJob = craftingJob.clone(identifierGenerator);
1✔
1700
            newCraftingJobs.add(clonedJob);
1✔
1701

1702
            // Update amount
1703
            int newAmount = division;
1✔
1704
            if (modulus > 0) {
1✔
1705
                // No amounts will be lost, as modulus is guaranteed to be smaller than splitFactor
1706
                newAmount++;
1✔
1707
                modulus--;
1✔
1708
            }
1709
            clonedJob.setAmount(newAmount);
1✔
1710
        }
1711

1712
        // Collect dependency links
1713
        Collection<CraftingJob> originalDependencies = dependencyGraph.getDependencies(craftingJob);
1✔
1714
        Collection<CraftingJob> originalDependents = dependencyGraph.getDependents(craftingJob);
1✔
1715

1716
        // Remove dependency links to and from the original jobs
1717
        for (CraftingJob dependency : originalDependencies) {
1✔
1718
            craftingJob.removeDependency(dependency);
1✔
1719
            dependencyGraph.removeDependency(craftingJob.getId(), dependency.getId());
1✔
1720
        }
1✔
1721
        for (CraftingJob dependent : originalDependents) {
1✔
1722
            dependent.removeDependency(craftingJob);
1✔
1723
            dependencyGraph.removeDependency(dependent.getId(), craftingJob.getId());
1✔
1724
        }
1✔
1725

1726
        // Create dependency links to and from the new crafting jobs
1727
        for (CraftingJob dependency : originalDependencies) {
1✔
1728
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1729
                newCraftingJob.addDependency(dependency);
1✔
1730
                dependencyGraph.addDependency(newCraftingJob, dependency);
1✔
1731
            }
1✔
1732
        }
1✔
1733
        for (CraftingJob originalDependent : originalDependents) {
1✔
1734
            for (CraftingJob newCraftingJob : newCraftingJobs) {
1✔
1735
                originalDependent.addDependency(newCraftingJob);
1✔
1736
                dependencyGraph.addDependency(originalDependent, newCraftingJob);
1✔
1737
            }
1✔
1738
        }
1✔
1739

1740
        return newCraftingJobs;
1✔
1741
    }
1742

1743
    /**
1744
     * Insert the given ingredients into the given storage networks.
1745
     * @param ingredients A collection of ingredients.
1746
     * @param storageGetter A storage network getter.
1747
     * @param simulate If insertion should be simulated.
1748
     * @return The remaining ingredients that were not inserted.
1749
     */
1750
    public static IMixedIngredients insertIngredients(IMixedIngredients ingredients,
1751
                                                      Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
1752
                                                      boolean simulate) {
1753
        Map<IngredientComponent<?, ?>, List<?>> remainingIngredients = Maps.newIdentityHashMap();
×
1754
        for (IngredientComponent<?, ?> component : ingredients.getComponents()) {
×
1755
            IIngredientComponentStorage storage = storageGetter.apply(component);
×
1756
            IIngredientMatcher matcher = component.getMatcher();
×
1757
            for (Object instance : ingredients.getInstances(component)) {
×
1758
                Object remainder = storage.insert(instance, simulate);
×
1759
                if (!matcher.isEmpty(remainder)) {
×
1760
                    List remainingInstances = remainingIngredients.get(component);
×
1761
                    if (remainingInstances == null) {
×
1762
                        remainingInstances = Lists.newArrayList();
×
1763
                        remainingIngredients.put(component, remainingInstances);
×
1764
                    }
1765
                    remainingInstances.add(instance);
×
1766
                }
1767
            }
×
1768
        }
×
1769
        return new MixedIngredients(remainingIngredients);
×
1770
    }
1771

1772
    /**
1773
     * Insert the given ingredients into the given storage networks.
1774
     * If something fails to be inserted, produce a warning.
1775
     * @param ingredients A collection of ingredients.
1776
     * @param storageGetter A storage network getter.
1777
     * @param failureSink Ingredients that failed to be inserted will be inserted to this sink.
1778
     */
1779
    public static void insertIngredientsGuaranteed(IMixedIngredients ingredients,
1780
                                                   Function<IngredientComponent<?, ?>, IIngredientComponentStorage> storageGetter,
1781
                                                   ICraftingResultsSink failureSink) {
1782
        IMixedIngredients remaining = insertIngredients(ingredients, storageGetter, false);
×
1783
        // If re-insertion into the network fails, insert it into the buffer of the crafting interface,
1784
        // to avoid loss of ingredients.
1785
        if (!remaining.isEmpty()) {
×
1786
            for (IngredientComponent<?, ?> component : remaining.getComponents()) {
×
1787
                for (Object instance : remaining.getInstances(component)) {
×
1788
                    failureSink.addResult((IngredientComponent) component, instance);
×
1789
                }
×
1790
            }
×
1791
        }
1792
    }
×
1793

1794
    /**
1795
     * Generates semi-unique IDs.
1796
     */
1797
    public static interface IIdentifierGenerator {
1798
        public int getNext();
1799
    }
1800

1801
}
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