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

CyclopsMC / IntegratedCrafting / #479011757

21 Aug 2024 03:39PM UTC coverage: 29.168% (-0.05%) from 29.22%
#479011757

push

github

rubensworks
Bump mod version

824 of 2825 relevant lines covered (29.17%)

0.29 hits per line

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

0.53
/src/main/java/org/cyclops/integratedcrafting/part/PartTypeInterfaceCrafting.java
1
package org.cyclops.integratedcrafting.part;
2

3
import com.google.common.collect.Lists;
4
import com.google.common.collect.MapMaker;
5
import it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap;
6
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
7
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
8
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
9
import it.unimi.dsi.fastutil.ints.IntArraySet;
10
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
11
import it.unimi.dsi.fastutil.ints.IntSet;
12
import net.minecraft.core.Direction;
13
import net.minecraft.nbt.CompoundTag;
14
import net.minecraft.nbt.ListTag;
15
import net.minecraft.nbt.Tag;
16
import net.minecraft.network.RegistryFriendlyByteBuf;
17
import net.minecraft.network.chat.Component;
18
import net.minecraft.network.chat.MutableComponent;
19
import net.minecraft.resources.ResourceLocation;
20
import net.minecraft.server.level.ServerPlayer;
21
import net.minecraft.world.MenuProvider;
22
import net.minecraft.world.SimpleContainer;
23
import net.minecraft.world.entity.player.Inventory;
24
import net.minecraft.world.entity.player.Player;
25
import net.minecraft.world.inventory.AbstractContainerMenu;
26
import net.minecraft.world.item.ItemStack;
27
import net.neoforged.neoforge.common.NeoForge;
28
import org.apache.commons.lang3.tuple.Triple;
29
import org.apache.logging.log4j.Level;
30
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
31
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeHandler;
32
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
33
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
34
import org.cyclops.commoncapabilities.api.ingredient.IPrototypedIngredient;
35
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
36
import org.cyclops.commoncapabilities.api.ingredient.IngredientInstanceWrapper;
37
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
38
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
39
import org.cyclops.cyclopscore.datastructure.DimPos;
40
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
41
import org.cyclops.cyclopscore.inventory.SimpleInventory;
42
import org.cyclops.cyclopscore.persist.nbt.NBTClassType;
43
import org.cyclops.integratedcrafting.Capabilities;
44
import org.cyclops.integratedcrafting.GeneralConfig;
45
import org.cyclops.integratedcrafting.IntegratedCrafting;
46
import org.cyclops.integratedcrafting.api.crafting.CraftingJob;
47
import org.cyclops.integratedcrafting.api.crafting.CraftingJobStatus;
48
import org.cyclops.integratedcrafting.api.crafting.ICraftingInterface;
49
import org.cyclops.integratedcrafting.api.crafting.ICraftingResultsSink;
50
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
51
import org.cyclops.integratedcrafting.core.CraftingHelpers;
52
import org.cyclops.integratedcrafting.core.CraftingJobHandler;
53
import org.cyclops.integratedcrafting.core.CraftingProcessOverrides;
54
import org.cyclops.integratedcrafting.core.part.PartTypeCraftingBase;
55
import org.cyclops.integratedcrafting.ingredient.storage.IngredientComponentStorageSlottedInsertProxy;
56
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCrafting;
57
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCraftingSettings;
58
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
59
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
60
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
61
import org.cyclops.integrateddynamics.api.evaluate.variable.ValueDeseralizationContext;
62
import org.cyclops.integrateddynamics.api.network.INetwork;
63
import org.cyclops.integrateddynamics.api.network.INetworkIngredientsChannel;
64
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
65
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
66
import org.cyclops.integrateddynamics.api.network.NetworkCapability;
67
import org.cyclops.integrateddynamics.api.part.IPartContainer;
68
import org.cyclops.integrateddynamics.api.part.PartCapability;
69
import org.cyclops.integrateddynamics.api.part.PartPos;
70
import org.cyclops.integrateddynamics.api.part.PartTarget;
71
import org.cyclops.integrateddynamics.api.part.PrioritizedPartPos;
72
import org.cyclops.integrateddynamics.core.evaluate.InventoryVariableEvaluator;
73
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeRecipe;
74
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
75
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
76
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
77
import org.cyclops.integrateddynamics.core.part.PartStateBase;
78
import org.cyclops.integrateddynamics.core.part.PartTypeBase;
79
import org.cyclops.integrateddynamics.core.part.event.PartVariableDrivenVariableContentsUpdatedEvent;
80

81
import javax.annotation.Nullable;
82
import java.util.Collection;
83
import java.util.Iterator;
84
import java.util.List;
85
import java.util.ListIterator;
86
import java.util.Map;
87
import java.util.Optional;
88

89
/**
90
 * Interface for item handlers.
91
 * @author rubensworks
92
 */
93
public class PartTypeInterfaceCrafting extends PartTypeCraftingBase<PartTypeInterfaceCrafting, PartTypeInterfaceCrafting.State> {
94

95
    public PartTypeInterfaceCrafting(String name) {
96
        super(name);
1✔
97
    }
1✔
98

99
    @Override
100
    public int getConsumptionRate(State state) {
101
        return state.getCraftingJobHandler().getProcessingCraftingJobs().size() * GeneralConfig.interfaceCraftingBaseConsumption;
×
102
    }
103

104
    @Override
105
    public Optional<MenuProvider> getContainerProvider(PartPos pos) {
106
        return Optional.of(new MenuProvider() {
×
107

108
            @Override
109
            public MutableComponent getDisplayName() {
110
                return Component.translatable(getTranslationKey());
×
111
            }
112

113
            @Override
114
            public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player playerEntity) {
115
                Triple<IPartContainer, PartTypeBase, PartTarget> data = PartHelpers.getContainerPartConstructionData(pos);
×
116
                PartTypeInterfaceCrafting.State partState = (PartTypeInterfaceCrafting.State) data.getLeft().getPartState(data.getRight().getCenter().getSide());
×
117
                return new ContainerPartInterfaceCrafting(id, playerInventory, partState.getInventoryVariables(),
×
118
                        Optional.of(data.getRight()), Optional.of(data.getLeft()), (PartTypeInterfaceCrafting) data.getMiddle());
×
119
            }
120
        });
121
    }
122

123
    @Override
124
    public void writeExtraGuiData(RegistryFriendlyByteBuf packetBuffer, PartPos pos, ServerPlayer player) {
125
        // Write inventory size
126
        IPartContainer partContainer = PartHelpers.getPartContainerChecked(pos);
×
127
        PartTypeInterfaceCrafting.State partState = (PartTypeInterfaceCrafting.State) partContainer.getPartState(pos.getSide());
×
128
        packetBuffer.writeInt(partState.getInventoryVariables().getContainerSize());
×
129

130
        super.writeExtraGuiData(packetBuffer, pos, player);
×
131
    }
×
132

133
    @Override
134
    public Optional<MenuProvider> getContainerProviderSettings(PartPos pos) {
135
        return Optional.of(new MenuProvider() {
×
136

137
            @Override
138
            public MutableComponent getDisplayName() {
139
                return Component.translatable(getTranslationKey());
×
140
            }
141

142
            @Override
143
            public AbstractContainerMenu createMenu(int id, Inventory playerInventory, Player playerEntity) {
144
                Triple<IPartContainer, PartTypeBase, PartTarget> data = PartHelpers.getContainerPartConstructionData(pos);
×
145
                return new ContainerPartInterfaceCraftingSettings(id, playerInventory, new SimpleContainer(0),
×
146
                        data.getRight(), Optional.of(data.getLeft()), data.getMiddle());
×
147
            }
148
        });
149
    }
150

151
    @Override
152
    protected PartTypeInterfaceCrafting.State constructDefaultState() {
153
        return new PartTypeInterfaceCrafting.State();
×
154
    }
155

156
    @Override
157
    public void afterNetworkReAlive(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
158
        super.afterNetworkReAlive(network, partNetwork, target, state);
×
159
        addTargetToNetwork(network, target, state, true);
×
160
    }
×
161

162
    @Override
163
    public void onNetworkRemoval(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
164
        super.onNetworkRemoval(network, partNetwork, target, state);
×
165
        removeTargetFromNetwork(network, target.getTarget(), state);
×
166
    }
×
167

168
    @Override
169
    public void onNetworkAddition(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
170
        super.onNetworkAddition(network, partNetwork, target, state);
×
171
        addTargetToNetwork(network, target, state, true);
×
172
    }
×
173

174
    @Override
175
    public void setPriorityAndChannel(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state, int priority, int channel) {
176
        // We need to do this because the crafting network is not automagically aware of the priority changes,
177
        // so we have to re-add it.
178
        removeTargetFromNetwork(network, target.getTarget(), state);
×
179
        super.setPriorityAndChannel(network, partNetwork, target, state, priority, channel);
×
180
        addTargetToNetwork(network, target, state, false);
×
181
    }
×
182

183
    protected NetworkCapability<ICraftingNetwork> getNetworkCapability() {
184
        return Capabilities.CraftingNetwork.NETWORK;
×
185
    }
186

187
    protected void addTargetToNetwork(INetwork network, PartTarget pos, PartTypeInterfaceCrafting.State state, boolean initialize) {
188
        network.getCapability(getNetworkCapability())
×
189
                .ifPresent(craftingNetwork -> {
×
190
                    int channelCrafting = state.getChannelCrafting();
×
191
                    state.setTarget(pos);
×
192
                    state.setNetworks(network, craftingNetwork, NetworkHelpers.getPartNetworkChecked(network), channelCrafting, ValueDeseralizationContext.of(pos.getCenter().getPos().getLevel(true)), initialize);
×
193
                    state.setShouldAddToCraftingNetwork(true);
×
194
                });
×
195
    }
×
196

197
    protected void removeTargetFromNetwork(INetwork network, PartPos pos, PartTypeInterfaceCrafting.State state) {
198
        ICraftingNetwork craftingNetwork = state.getCraftingNetwork();
×
199
        if (craftingNetwork != null) {
×
200
            network.getCapability(getNetworkCapability())
×
201
                    .ifPresent(n -> n.removeCraftingInterface(state.getChannelCrafting(), state));
×
202
        }
203
        state.setNetworks(null, null, null, -1, null, false);
×
204
        state.setTarget(null);
×
205
    }
×
206

207
    @Override
208
    public boolean isUpdate(State state) {
209
        return true;
×
210
    }
211

212
    @Override
213
    public int getMinimumUpdateInterval(State state) {
214
        return state.getDefaultUpdateInterval();
×
215
    }
216

217
    @Override
218
    public void update(INetwork network, IPartNetwork partNetwork, PartTarget target, State state) {
219
        super.update(network, partNetwork, target, state);
×
220

221
        // Init network data in part state if it has not been done yet.
222
        // This can occur when the part chunk is being reloaded.
223
        if (state.getCraftingNetwork() == null) {
×
224
            addTargetToNetwork(network, target, state, false);
×
225
        }
226

227
        int channel = state.getChannelCrafting();
×
228

229
        // Update the network data in the part state
230
        if (state.shouldAddToCraftingNetwork()) {
×
231
            ICraftingNetwork craftingNetwork = network.getCapability(getNetworkCapability()).orElse(null);
×
232
            craftingNetwork.addCraftingInterface(channel, state);
×
233
            state.setShouldAddToCraftingNetwork(false);
×
234
        }
235

236
        // Push any pending output ingredients into the network
237
        state.flushInventoryOutputBuffer(network);
×
238

239
        // Block job ticking if there still are outputs in our crafting result buffer.
240
        if (state.getInventoryOutputBuffer().isEmpty()) {
×
241
            // Tick the job handler
242
            PartPos targetPos = state.getTarget().getTarget();
×
243
            state.getCraftingJobHandler().update(network, channel, targetPos);
×
244
        }
245

246
        // Reload recipes if needed
247
        IntSet slots = state.getDelayedRecipeReloads();
×
248
        if (!slots.isEmpty()) {
×
249
            ICraftingNetwork craftingNetwork = network.getCapability(getNetworkCapability()).orElse(null);
×
250
            if (craftingNetwork != null) {
×
251
                IntSet slotsCopy = new IntOpenHashSet(slots); // Create a copy, to allow insertion into slots during this loop
×
252
                slots.clear();
×
253
                for (Integer slot : slotsCopy) {
×
254
                    // Remove the old recipe from the network
255
                    Int2ObjectMap<IRecipeDefinition> recipes = state.getRecipesIndexed();
×
256
                    IRecipeDefinition oldRecipe = recipes.get(slot);
×
257
                    if (oldRecipe != null) {
×
258
                        craftingNetwork.removeCraftingInterfaceRecipe(channel, state, oldRecipe);
×
259
                    }
260

261
                    // Reload the recipe in the slot
262
                    // We simulate initialization for the first two ticks, as dependency variables may still be loading,
263
                    // and errored may only go away after these dependencies are fully loaded.
264
                    // Related to CyclopsMC/IntegratedCrafting#110
265
                    state.reloadRecipe(slot, state.ticksAfterReload <= 1);
×
266

267
                    // Add the new recipe to the network
268
                    IRecipeDefinition newRecipe = recipes.get(slot);
×
269
                    if (newRecipe != null) {
×
270
                        craftingNetwork.addCraftingInterfaceRecipe(channel, state, newRecipe);
×
271
                    }
272
                }
×
273
            }
274
        }
275

276
        // Internal tick counter
277
        state.ticksAfterReload++;
×
278
    }
×
279

280
    @Nullable
281
    protected static <T, M> IngredientInstanceWrapper<T, M> insertIntoNetwork(IngredientInstanceWrapper<T, M> wrapper,
282
                                                                              INetwork network, int channel) {
283
        IPositionedAddonsNetworkIngredients<T, M> storageNetwork = wrapper.getComponent()
×
284
                .getCapability(org.cyclops.integrateddynamics.Capabilities.PositionedAddonsNetworkIngredientsHandler.INGREDIENT)
×
285
                .map(n -> (IPositionedAddonsNetworkIngredients<T, M>) n.getStorage(network).orElse(null))
×
286
                .orElse(null);
×
287
        if (storageNetwork != null) {
×
288
            IIngredientComponentStorage<T, M> storage = storageNetwork.getChannel(channel);
×
289
            T remaining = storage.insert(wrapper.getInstance(), false);
×
290
            if (wrapper.getComponent().getMatcher().isEmpty(remaining)) {
×
291
                return null;
×
292
            } else {
293
                return new IngredientInstanceWrapper<>(wrapper.getComponent(), remaining);
×
294
            }
295
        }
296
        return wrapper;
×
297
    }
298

299
    @Override
300
    public void addDrops(PartTarget target, State state, List<ItemStack> itemStacks, boolean dropMainElement, boolean saveState) {
301
        // Drop any remaining output ingredients (only items)
302
        for (IngredientInstanceWrapper<?, ?> ingredientInstanceWrapper : state.getInventoryOutputBuffer()) {
×
303
            if (ingredientInstanceWrapper.getComponent() == IngredientComponent.ITEMSTACK) {
×
304
                itemStacks.add((ItemStack) ingredientInstanceWrapper.getInstance());
×
305
            }
306
        }
×
307
        state.getInventoryOutputBuffer().clear();
×
308

309
        // Drop the stored variables
310
        for(int i = 0; i < state.getInventoryVariables().getContainerSize(); i++) {
×
311
            ItemStack itemStack = state.getInventoryVariables().getItem(i);
×
312
            if(!itemStack.isEmpty()) {
×
313
                itemStacks.add(itemStack);
×
314
            }
315
        }
316
        state.getInventoryVariables().clearContent();
×
317

318
        super.addDrops(target, state, itemStacks, dropMainElement, saveState);
×
319
    }
×
320

321
    public static class State extends PartStateBase<PartTypeInterfaceCrafting>
322
            implements ICraftingInterface, ICraftingResultsSink {
323

324
        protected int ticksAfterReload = 0;
×
325

326
        private final CraftingJobHandler craftingJobHandler;
327
        private final SimpleInventory inventoryVariables;
328
        private final List<InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe>> variableEvaluators;
329
        private final List<IngredientInstanceWrapper<?, ?>> inventoryOutputBuffer;
330
        private final Int2ObjectMap<MutableComponent> recipeSlotMessages;
331
        private final Int2BooleanMap recipeSlotValidated;
332
        private final IntSet delayedRecipeReloads;
333
        private final Map<IVariable, Boolean> variableListeners;
334
        private int channelCrafting = 0;
×
335
        private boolean disableCraftingCheck = false;
×
336

337
        private final Int2ObjectMap<IRecipeDefinition> currentRecipes;
338
        private PartTarget target = null;
×
339
        private INetwork network = null;
×
340
        private ICraftingNetwork craftingNetwork = null;
×
341
        private IPartNetwork partNetwork = null;
×
342
        private int channel = -1;
×
343
        private ValueDeseralizationContext valueDeseralizationContext;
344
        private boolean shouldAddToCraftingNetwork = false;
×
345
        private Player lastPlayer;
346

347
        public State() {
×
348
            this.craftingJobHandler = new CraftingJobHandler(1, true,
×
349
                    CraftingProcessOverrides.REGISTRY.getCraftingProcessOverrides(), this);
×
350
            this.inventoryVariables = new SimpleInventory(9, 1);
×
351
            this.inventoryVariables.addDirtyMarkListener(this);
×
352
            this.variableEvaluators = Lists.newArrayList();
×
353
            this.inventoryOutputBuffer = Lists.newArrayList();
×
354
            this.recipeSlotMessages = new Int2ObjectArrayMap<>();
×
355
            this.recipeSlotValidated = new Int2BooleanArrayMap();
×
356
            this.delayedRecipeReloads = new IntArraySet();
×
357
            this.variableListeners = new MapMaker().weakKeys().makeMap();
×
358
            this.currentRecipes = new Int2ObjectArrayMap<>();
×
359
        }
×
360

361
        @Override
362
        protected int getDefaultUpdateInterval() {
363
            return GeneralConfig.minCraftingInterfaceUpdateFreq;
×
364
        }
365

366
        /**
367
         * @return The inner variables inventory
368
         */
369
        public SimpleInventory getInventoryVariables() {
370
            return this.inventoryVariables;
×
371
        }
372

373
        @Override
374
        public void writeToNBT(ValueDeseralizationContext valueDeseralizationContext, CompoundTag tag) {
375
            super.writeToNBT(valueDeseralizationContext, tag);
×
376
            inventoryVariables.writeToNBT(valueDeseralizationContext.holderLookupProvider(), tag, "variables");
×
377

378
            ListTag instanceTags = new ListTag();
×
379
            for (IngredientInstanceWrapper instanceWrapper : inventoryOutputBuffer) {
×
380
                CompoundTag instanceTag = new CompoundTag();
×
381
                instanceTag.putString("component", IngredientComponent.REGISTRY.getKey(instanceWrapper.getComponent()).toString());
×
382
                instanceTag.put("instance", instanceWrapper.getComponent().getSerializer().serializeInstance(valueDeseralizationContext.holderLookupProvider(), instanceWrapper.getInstance()));
×
383
                instanceTags.add(instanceTag);
×
384
            }
×
385
            tag.put("inventoryOutputBuffer", instanceTags);
×
386

387
            this.craftingJobHandler.writeToNBT(valueDeseralizationContext.holderLookupProvider(), tag);
×
388
            tag.putInt("channelCrafting", channelCrafting);
×
389

390
            CompoundTag recipeSlotErrorsTag = new CompoundTag();
×
391
            for (Int2ObjectMap.Entry<MutableComponent> entry : this.recipeSlotMessages.int2ObjectEntrySet()) {
×
392
                NBTClassType.writeNbt(MutableComponent.class, String.valueOf(entry.getIntKey()), entry.getValue(), recipeSlotErrorsTag, valueDeseralizationContext.holderLookupProvider());
×
393
            }
×
394
            tag.put("recipeSlotMessages", recipeSlotErrorsTag);
×
395

396
            CompoundTag recipeSlotValidatedTag = new CompoundTag();
×
397
            for (Int2BooleanMap.Entry entry : this.recipeSlotValidated.int2BooleanEntrySet()) {
×
398
                recipeSlotValidatedTag.putBoolean(String.valueOf(entry.getIntKey()), entry.getBooleanValue());
×
399
            }
×
400
            tag.put("recipeSlotValidated", recipeSlotValidatedTag);
×
401

402
            tag.putBoolean("disableCraftingCheck", disableCraftingCheck);
×
403
        }
×
404

405
        @Override
406
        public void readFromNBT(ValueDeseralizationContext valueDeseralizationContext, CompoundTag tag) {
407
            super.readFromNBT(valueDeseralizationContext, tag);
×
408
            inventoryVariables.readFromNBT(valueDeseralizationContext.holderLookupProvider(), tag, "variables");
×
409

410
            this.inventoryOutputBuffer.clear();
×
411
            for (Tag instanceTagRaw : tag.getList("inventoryOutputBuffer", Tag.TAG_COMPOUND)) {
×
412
                CompoundTag instanceTag = (CompoundTag) instanceTagRaw;
×
413
                String componentName = instanceTag.getString("component");
×
414
                IngredientComponent<?, ?> component = IngredientComponent.REGISTRY.get(ResourceLocation.parse(componentName));
×
415
                this.inventoryOutputBuffer.add(new IngredientInstanceWrapper(component,
×
416
                        component.getSerializer().deserializeInstance(valueDeseralizationContext.holderLookupProvider(), instanceTag.get("instance"))));
×
417
            }
×
418

419
            this.craftingJobHandler.readFromNBT(valueDeseralizationContext.holderLookupProvider(), tag);
×
420
            this.channelCrafting = tag.getInt("channelCrafting");
×
421

422
            this.recipeSlotMessages.clear();
×
423
            CompoundTag recipeSlotErrorsTag = tag.getCompound("recipeSlotMessages");
×
424
            for (String slot : recipeSlotErrorsTag.getAllKeys()) {
×
425
                MutableComponent unlocalizedString = NBTClassType.readNbt(MutableComponent.class, slot, recipeSlotErrorsTag, valueDeseralizationContext.holderLookupProvider());
×
426
                this.recipeSlotMessages.put(Integer.parseInt(slot), unlocalizedString);
×
427
            }
×
428

429
            this.recipeSlotValidated.clear();
×
430
            CompoundTag recipeSlotValidatedTag = tag.getCompound("recipeSlotValidated");
×
431
            for (String slot : recipeSlotValidatedTag.getAllKeys()) {
×
432
                this.recipeSlotValidated.put(Integer.parseInt(slot), recipeSlotValidatedTag.getBoolean(slot));
×
433
            }
×
434

435
            this.disableCraftingCheck = tag.getBoolean("disableCraftingCheck");
×
436
        }
×
437

438
        public void setChannelCrafting(int channelCrafting) {
439
            if (this.channelCrafting != channelCrafting) {
×
440
                // Unregister from the network
441
                if (craftingNetwork != null) {
×
442
                    craftingNetwork.removeCraftingInterface(this.channelCrafting, this);
×
443
                }
444

445
                // Update the channel
446
                this.channelCrafting = channelCrafting;
×
447

448
                // Re-register to the network
449
                if (craftingNetwork != null) {
×
450
                    craftingNetwork.addCraftingInterface(this.channelCrafting, this);
×
451
                }
452

453
                sendUpdate();
×
454
            }
455
        }
×
456

457
        public int getChannelCrafting() {
458
            return channelCrafting;
×
459
        }
460

461
        public void reloadRecipes(boolean initialize) {
462
            this.currentRecipes.clear();
×
463
            this.recipeSlotMessages.clear();
×
464
            this.recipeSlotValidated.clear();
×
465
            variableEvaluators.clear();
×
466
            for (int i = 0; i < getInventoryVariables().getContainerSize(); i++) {
×
467
                int slot = i;
×
468
                variableEvaluators.add(new InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe>(
×
469
                        getInventoryVariables(), slot, valueDeseralizationContext, ValueTypes.OBJECT_RECIPE) {
×
470
                    @Override
471
                    public void onErrorsChanged() {
472
                        super.onErrorsChanged();
×
473
                        setLocalErrors(slot, getErrors());
×
474
                    }
×
475
                });
476
            }
477
            if (this.partNetwork != null) {
×
478
                for (int i = 0; i < getInventoryVariables().getContainerSize(); i++) {
×
479
                    reloadRecipe(i, initialize);
×
480
                }
481
            }
482
        }
×
483

484
        private void setLocalErrors(int slot, List<MutableComponent> errors) {
485
            if (errors.isEmpty()) {
×
486
                if (this.recipeSlotMessages.size() > slot) {
×
487
                    this.recipeSlotMessages.remove(slot);
×
488
                }
489
            } else {
490
                this.recipeSlotMessages.put(slot, errors.get(0));
×
491
            }
492
        }
×
493

494
        protected void reloadRecipe(int slot, boolean initialize) {
495
            this.currentRecipes.remove(slot);
×
496
            if (this.recipeSlotMessages.size() > slot) {
×
497
                this.recipeSlotMessages.remove(slot);
×
498
            }
499
            if (this.recipeSlotValidated.size() > slot) {
×
500
                this.recipeSlotValidated.remove(slot);
×
501
            }
502
            if (this.partNetwork != null) {
×
503
                InventoryVariableEvaluator<ValueObjectTypeRecipe.ValueRecipe> evaluator = variableEvaluators.get(slot);
×
504
                evaluator.refreshVariable(network, false);
×
505
                IVariable<ValueObjectTypeRecipe.ValueRecipe> variable = evaluator.getVariable(network);
×
506
                if (variable != null) {
×
507
                    try {
508
                        // Refresh the recipe if variable is changed
509
                        // The map is needed because we only want to register the listener once for each variable
510
                        if (!this.variableListeners.containsKey(variable)) {
×
511
                            variable.addInvalidationListener(() -> {
×
512
                                this.variableListeners.remove(variable);
×
513
                                delayedReloadRecipe(slot);
×
514
                            });
×
515
                            this.variableListeners.put(variable, true);
×
516
                        }
517

518
                        IValue value = variable.getValue();
×
519
                        if (value.getType() == ValueTypes.OBJECT_RECIPE) {
×
520
                            Optional<IRecipeDefinition> recipeWrapper = ((ValueObjectTypeRecipe.ValueRecipe) value).getRawValue();
×
521
                            if (recipeWrapper.isPresent()) {
×
522
                                IRecipeDefinition recipe = recipeWrapper.get();
×
523
                                if (!GeneralConfig.validateRecipesCraftingInterface || this.disableCraftingCheck || isValid(recipe)) {
×
524
                                    this.currentRecipes.put(slot, recipe);
×
525
                                    this.recipeSlotValidated.put(slot, true);
×
526
                                    this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.valid"));
×
527
                                } else {
528
                                    this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.invalid"));
×
529
                                }
530
                            }
531
                        } else {
×
532
                            this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.norecipe"));
×
533
                        }
534
                    } catch (EvaluationException e) {
×
535
                        this.recipeSlotMessages.put(slot, e.getErrorMessage());
×
536
                    }
×
537
                } else {
538
                    // If we're initializing, the variable might be referencing other variables that are not yet loaded.
539
                    // So let's retry once in the next tick.
540
                    if (initialize && evaluator.hasVariable()) {
×
541
                        this.delayedReloadRecipe(slot);
×
542
                    } else {
543
                        this.recipeSlotMessages.put(slot, Component.translatable("gui.integratedcrafting.partinterface.slot.message.norecipe"));
×
544
                    }
545
                }
546

547
                try {
548
                    IPartNetwork partNetwork = NetworkHelpers.getPartNetworkChecked(network);
×
549
                    NeoForge.EVENT_BUS.post(new PartVariableDrivenVariableContentsUpdatedEvent<>(network,
×
550
                            partNetwork, getTarget(),
×
551
                            PartTypes.INTERFACE_CRAFTING, this, lastPlayer, variable,
552
                            variable != null ? variable.getValue() : null));
×
553
                } catch (EvaluationException e) {
×
554
                    // Ignore error
555
                }
×
556
            }
557
            sendUpdate();
×
558
        }
×
559

560
        public void setLastPlayer(Player lastPlayer) {
561
            this.lastPlayer = lastPlayer;
×
562
        }
×
563

564
        private void delayedReloadRecipe(int slot) {
565
            this.delayedRecipeReloads.add(slot);
×
566
        }
×
567

568

569
        private boolean isValid(IRecipeDefinition recipe) {
570
            DimPos dimPos = getTarget().getTarget().getPos();
×
571
            Direction side = getTarget().getTarget().getSide();
×
572
            IRecipeHandler recipeHandler = BlockEntityHelpers.getCapability(dimPos.getLevel(true), dimPos.getBlockPos(), side, org.cyclops.commoncapabilities.api.capability.Capabilities.RecipeHandler.BLOCK).orElse(null);
×
573
            if (recipeHandler != null) {
×
574
                IMixedIngredients simulatedOutput = recipeHandler.simulate(MixedIngredients.fromRecipeInput(recipe));
×
575
                if (simulatedOutput != null && !simulatedOutput.isEmpty()) {
×
576
                    if (recipe.getOutput().containsAll(simulatedOutput)) {
×
577
                        return true;
×
578
                    } else {
579
                        if (GeneralConfig.logRecipeValidationFailures) {
×
580
                            IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: incompatible recipe output and simulated output:\nRecipe output: " + recipe.getOutput() + "\nSimulated output: " + simulatedOutput);
×
581
                        }
582
                        return false;
×
583
                    }
584
                }
585
                if (GeneralConfig.logRecipeValidationFailures) {
×
586
                    IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: No output was obtained when simulating a recipe\n" + recipe);
×
587
                }
588
                return false;
×
589
            }
590
            return true; // No recipe handler capability is present, so we can't confirm that the recipe will work.
×
591
        }
592

593
        @Override
594
        public void onDirty() {
595
            super.onDirty();
×
596

597
            // Unregister from the network, when all old recipes are still in place
598
            if (craftingNetwork != null) {
×
599
                craftingNetwork.removeCraftingInterface(channelCrafting, this);
×
600
            }
601

602
            // Recalculate recipes
603
            if (getTarget() != null && !getTarget().getCenter().getPos().getLevel(true).isClientSide) {
×
604
                reloadRecipes(false);
×
605
            }
606

607
            // Re-register to the network, to force an update for all new recipes
608
            if (craftingNetwork != null) {
×
609
                craftingNetwork.addCraftingInterface(channelCrafting, this);
×
610
            }
611
        }
×
612

613
        public void setTarget(PartTarget target) {
614
            this.target = target;
×
615
        }
×
616

617
        public PartTarget getTarget() {
618
            return target;
×
619
        }
620

621
        public void setNetworks(@Nullable INetwork network, @Nullable ICraftingNetwork craftingNetwork,
622
                                @Nullable IPartNetwork partNetwork, int channel,
623
                                @Nullable ValueDeseralizationContext valueDeseralizationContext,
624
                                boolean initialize) {
625
            this.network = network;
×
626
            this.craftingNetwork = craftingNetwork;
×
627
            this.partNetwork = partNetwork;
×
628
            this.channel = channel;
×
629
            this.valueDeseralizationContext = valueDeseralizationContext;
×
630
            reloadRecipes(initialize);
×
631
            if (network != null) {
×
632
                this.getCraftingJobHandler().reRegisterObservers(network);
×
633
            }
634
        }
×
635

636
        public ICraftingNetwork getCraftingNetwork() {
637
            return craftingNetwork;
×
638
        }
639

640
        @Override
641
        public int getChannel() {
642
            return channel;
×
643
        }
644

645
        @Override
646
        public Collection<IRecipeDefinition> getRecipes() {
647
            return this.currentRecipes.values();
×
648
        }
649

650
        public Int2ObjectMap<IRecipeDefinition> getRecipesIndexed() {
651
            return currentRecipes;
×
652
        }
653

654
        @Override
655
        public boolean canScheduleCraftingJobs() {
656
            return getCraftingJobHandler().canScheduleCraftingJobs();
×
657
        }
658

659
        @Override
660
        public void scheduleCraftingJob(CraftingJob craftingJob) {
661
            getCraftingJobHandler().scheduleCraftingJob(craftingJob);
×
662
        }
×
663

664
        @Override
665
        public int getCraftingJobsCount() {
666
            return this.craftingJobHandler.getAllCraftingJobs().size();
×
667
        }
668

669
        @Override
670
        public Iterator<CraftingJob> getCraftingJobs() {
671
            return this.craftingJobHandler.getAllCraftingJobs().values().iterator();
×
672
        }
673

674
        @Override
675
        public List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> getPendingCraftingJobOutputs(int craftingJobId) {
676
            List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> pending = this.craftingJobHandler.getProcessingCraftingJobsPendingIngredients().get(craftingJobId);
×
677
            if (pending == null) {
×
678
                pending = Lists.newArrayList();
×
679
            }
680
            return pending;
×
681
        }
682

683
        @Override
684
        public CraftingJobStatus getCraftingJobStatus(ICraftingNetwork network, int channel, int craftingJobId) {
685
            return craftingJobHandler.getCraftingJobStatus(network, channel, craftingJobId);
×
686
        }
687

688
        @Override
689
        public void cancelCraftingJob(int channel, int craftingJobId) {
690
            craftingJobHandler.markCraftingJobFinished(craftingJobId);
×
691
        }
×
692

693
        @Override
694
        public PrioritizedPartPos getPosition() {
695
            return PrioritizedPartPos.of(getTarget().getCenter(), getPriority());
×
696
        }
697

698
        public CraftingJobHandler getCraftingJobHandler() {
699
            return craftingJobHandler;
×
700
        }
701

702
        public boolean shouldAddToCraftingNetwork() {
703
            return shouldAddToCraftingNetwork;
×
704
        }
705

706
        public void setShouldAddToCraftingNetwork(boolean shouldAddToCraftingNetwork) {
707
            this.shouldAddToCraftingNetwork = shouldAddToCraftingNetwork;
×
708
        }
×
709

710
        public List<IngredientInstanceWrapper<?, ?>> getInventoryOutputBuffer() {
711
            return inventoryOutputBuffer;
×
712
        }
713

714
        @Override
715
        public <T> Optional<T> getCapability(PartTypeInterfaceCrafting partType, PartCapability<T> capability, INetwork network, IPartNetwork partNetwork, PartTarget target) {
716
            if (capability == Capabilities.CraftingInterface.PART) {
×
717
                return Optional.of((T) this);
×
718
            }
719

720
            // Expose the whole storage
721
            if (this.network != null) {
×
722
                IngredientComponent<?, ?> ingredientComponent = IngredientComponent.getIngredientComponentForStorageCapability(capability);
×
723
                if (ingredientComponent != null) {
×
724
                    T cap = wrapStorageCapability(capability, ingredientComponent);
×
725
                    if (cap != null) {
×
726
                        return Optional.of(cap);
×
727
                    }
728
                }
729
            }
730

731
            return super.getCapability(partType, capability, network, partNetwork, target);
×
732
        }
733

734
        protected <C, T, M> C wrapStorageCapability(PartCapability<C> capability, IngredientComponent<T, M> ingredientComponent) {
735
            IIngredientComponentStorage<T, M> storage = CraftingHelpers.getNetworkStorage(this.network, this.channelCrafting,
×
736
                    ingredientComponent, false);
737

738
            // Don't allow extraction, only insertion
739
            storage = new IngredientComponentStorageSlottedInsertProxy<>(storage);
×
740

741
            return ingredientComponent.getStorageWrapperHandler(capability).wrapStorage(storage);
×
742
        }
743

744
        @Override
745
        public <T, M> void addResult(IngredientComponent<T, M> ingredientComponent, T instance) {
746
            this.getInventoryOutputBuffer().add(new IngredientInstanceWrapper<>(ingredientComponent, instance));
×
747

748
            // Try to flush buffer immediately
749
            if (this.network != null) {
×
750
                this.flushInventoryOutputBuffer(this.network);
×
751
            }
752
        }
×
753

754
        public void setIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent, Direction side) {
755
            if (getTarget().getTarget().getSide() == side) {
×
756
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, null);
×
757
            } else {
758
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, side);
×
759
            }
760
            sendUpdate();
×
761
        }
×
762

763
        public Direction getIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent) {
764
            Direction side = craftingJobHandler.getIngredientComponentTarget(ingredientComponent);
×
765
            if (side == null) {
×
766
                side = getTarget().getTarget().getSide();
×
767
            }
768
            return side;
×
769
        }
770

771
        public boolean isRecipeSlotValid(int slot) {
772
            return this.recipeSlotValidated.containsKey(slot);
×
773
        }
774

775
        @Nullable
776
        public MutableComponent getRecipeSlotUnlocalizedMessage(int slot) {
777
            return this.recipeSlotMessages.get(slot);
×
778
        }
779

780
        public IntSet getDelayedRecipeReloads() {
781
            return delayedRecipeReloads;
×
782
        }
783

784
        public void setDisableCraftingCheck(boolean disableCraftingCheck) {
785
            if (disableCraftingCheck != this.disableCraftingCheck) {
×
786
                this.disableCraftingCheck = disableCraftingCheck;
×
787

788
                this.sendUpdate();
×
789
            }
790
        }
×
791

792
        public boolean isDisableCraftingCheck() {
793
            return disableCraftingCheck;
×
794
        }
795

796
        public void flushInventoryOutputBuffer(INetwork network) {
797
            // Try to insert each ingredient in the buffer into the network.
798
            boolean changed = false;
×
799
            ListIterator<IngredientInstanceWrapper<?, ?>> outputBufferIt = this.getInventoryOutputBuffer().listIterator();
×
800
            while (outputBufferIt.hasNext()) {
×
801
                IngredientInstanceWrapper<?, ?> oldWrapper = outputBufferIt.next();
×
802

803
                // Force observation before insertion (see #98 on why this is necessary)
804
                this.forceObservationOnInsertable(oldWrapper);
×
805

806
                IngredientInstanceWrapper<?, ?> newWrapper = insertIntoNetwork(oldWrapper,
×
807
                        network, this.getChannelCrafting());
×
808
                if (newWrapper != oldWrapper) {
×
809
                    changed = true;
×
810
                }
811
                if (newWrapper == null) {
×
812
                    outputBufferIt.remove();
×
813
                } else {
814
                    outputBufferIt.set(newWrapper);
×
815
                }
816
            }
×
817

818
            // If at least one ingredient was inserted, force a sync observer update in the network.
819
            if (changed) {
×
820
                CraftingHelpers.beforeCalculateCraftingJobs(network, getChannelCrafting());
×
821
            }
822
        }
×
823

824
        /**
825
         * Iterate over all positions that *could* accept the given instance,
826
         * and force an observation over them.
827
         *
828
         * This is necessary to ensure that we have the latest state indexed right before insertion.
829
         * This allows us to force another observation right after the insertion,
830
         * which will guarantee that we will track the expected diff events as result.
831
         *
832
         * @param oldWrapper The ingredient to attempt to insert (simulated).
833
         * @param <T> Ingredient type.
834
         * @param <M> Match flags.
835
         */
836
        protected <T, M> void forceObservationOnInsertable(IngredientInstanceWrapper<T, M> oldWrapper) {
837
            IIngredientMatcher<T, M> matcher = oldWrapper.getComponent().getMatcher();
×
838
            IPositionedAddonsNetworkIngredients<T, M> ingredientsNetwork = CraftingHelpers.getIngredientsNetwork(network, oldWrapper.getComponent()).orElse(null);
×
839
            if (ingredientsNetwork != null) {
×
840
                boolean marked = false;
×
841
                INetworkIngredientsChannel<?, ?> ingredientsNetworkChannel = ingredientsNetwork.getChannel(this.getChannelCrafting());
×
842
                T instance = oldWrapper.getInstance();
×
843
                for (PartPos position : ingredientsNetworkChannel.findNonFullPositions()) {
×
844
                    T instanceOut = ingredientsNetwork.getPositionedStorage(position).insert(instance, true);
×
845
                    if (!matcher.matchesExactly(instanceOut, instance)) {
×
846
                        marked = true;
×
847
                        instance = instanceOut;
×
848
                        ingredientsNetwork.scheduleObservationForced(this.getChannelCrafting(), position);
×
849
                        if (matcher.isEmpty(instance)) {
×
850
                            break;
×
851
                        }
852
                    }
853
                }
×
854

855
                if (marked || ingredientsNetwork.isObservationForcedPending(channel)) {
×
856
                    ingredientsNetwork.runObserverSync();
×
857
                }
858
            }
859
        }
×
860
    }
861
}
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

© 2026 Coveralls, Inc