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

CyclopsMC / IntegratedCrafting / #479011755

21 Aug 2024 03:37PM UTC coverage: 24.903% (-0.04%) from 24.947%
#479011755

push

github

rubensworks
Bump mod version

706 of 2835 relevant lines covered (24.9%)

0.25 hits per line

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

0.0
/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.FriendlyByteBuf;
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.minecraft.world.level.block.state.BlockState;
28
import net.minecraftforge.common.MinecraftForge;
29
import net.minecraftforge.common.capabilities.Capability;
30
import net.minecraftforge.common.util.LazyOptional;
31
import org.apache.commons.lang3.tuple.Triple;
32
import org.apache.logging.log4j.Level;
33
import org.cyclops.commoncapabilities.api.capability.block.BlockCapabilities;
34
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeDefinition;
35
import org.cyclops.commoncapabilities.api.capability.recipehandler.IRecipeHandler;
36
import org.cyclops.commoncapabilities.api.ingredient.IIngredientMatcher;
37
import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
38
import org.cyclops.commoncapabilities.api.ingredient.IPrototypedIngredient;
39
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
40
import org.cyclops.commoncapabilities.api.ingredient.IngredientInstanceWrapper;
41
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredients;
42
import org.cyclops.commoncapabilities.api.ingredient.storage.IIngredientComponentStorage;
43
import org.cyclops.cyclopscore.datastructure.DimPos;
44
import org.cyclops.cyclopscore.helper.BlockEntityHelpers;
45
import org.cyclops.cyclopscore.inventory.SimpleInventory;
46
import org.cyclops.cyclopscore.persist.nbt.NBTClassType;
47
import org.cyclops.integratedcrafting.Capabilities;
48
import org.cyclops.integratedcrafting.GeneralConfig;
49
import org.cyclops.integratedcrafting.IntegratedCrafting;
50
import org.cyclops.integratedcrafting.api.crafting.CraftingJob;
51
import org.cyclops.integratedcrafting.api.crafting.CraftingJobStatus;
52
import org.cyclops.integratedcrafting.api.crafting.ICraftingInterface;
53
import org.cyclops.integratedcrafting.api.crafting.ICraftingResultsSink;
54
import org.cyclops.integratedcrafting.api.network.ICraftingNetwork;
55
import org.cyclops.integratedcrafting.capability.network.CraftingInterfaceConfig;
56
import org.cyclops.integratedcrafting.capability.network.CraftingNetworkConfig;
57
import org.cyclops.integratedcrafting.core.CraftingHelpers;
58
import org.cyclops.integratedcrafting.core.CraftingJobHandler;
59
import org.cyclops.integratedcrafting.core.CraftingProcessOverrides;
60
import org.cyclops.integratedcrafting.core.part.PartTypeCraftingBase;
61
import org.cyclops.integratedcrafting.ingredient.storage.IngredientComponentStorageSlottedInsertProxy;
62
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCrafting;
63
import org.cyclops.integratedcrafting.inventory.container.ContainerPartInterfaceCraftingSettings;
64
import org.cyclops.integrateddynamics.api.evaluate.EvaluationException;
65
import org.cyclops.integrateddynamics.api.evaluate.variable.IValue;
66
import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable;
67
import org.cyclops.integrateddynamics.api.evaluate.variable.ValueDeseralizationContext;
68
import org.cyclops.integrateddynamics.api.network.INetwork;
69
import org.cyclops.integrateddynamics.api.network.INetworkIngredientsChannel;
70
import org.cyclops.integrateddynamics.api.network.IPartNetwork;
71
import org.cyclops.integrateddynamics.api.network.IPositionedAddonsNetworkIngredients;
72
import org.cyclops.integrateddynamics.api.part.IPartContainer;
73
import org.cyclops.integrateddynamics.api.part.PartPos;
74
import org.cyclops.integrateddynamics.api.part.PartTarget;
75
import org.cyclops.integrateddynamics.api.part.PrioritizedPartPos;
76
import org.cyclops.integrateddynamics.capability.network.PositionedAddonsNetworkIngredientsHandlerConfig;
77
import org.cyclops.integrateddynamics.core.evaluate.InventoryVariableEvaluator;
78
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueObjectTypeRecipe;
79
import org.cyclops.integrateddynamics.core.evaluate.variable.ValueTypes;
80
import org.cyclops.integrateddynamics.core.helper.NetworkHelpers;
81
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
82
import org.cyclops.integrateddynamics.core.part.PartStateBase;
83
import org.cyclops.integrateddynamics.core.part.PartTypeBase;
84
import org.cyclops.integrateddynamics.core.part.event.PartVariableDrivenVariableContentsUpdatedEvent;
85

86
import javax.annotation.Nullable;
87
import java.util.Collection;
88
import java.util.Iterator;
89
import java.util.List;
90
import java.util.ListIterator;
91
import java.util.Map;
92
import java.util.Optional;
93

94
/**
95
 * Interface for item handlers.
96
 * @author rubensworks
97
 */
98
public class PartTypeInterfaceCrafting extends PartTypeCraftingBase<PartTypeInterfaceCrafting, PartTypeInterfaceCrafting.State> {
99

100
    public PartTypeInterfaceCrafting(String name) {
101
        super(name);
×
102
    }
×
103

104
    @Override
105
    public int getConsumptionRate(State state) {
106
        return state.getCraftingJobHandler().getProcessingCraftingJobs().size() * GeneralConfig.interfaceCraftingBaseConsumption;
×
107
    }
108

109
    @Override
110
    public Optional<MenuProvider> getContainerProvider(PartPos pos) {
111
        return Optional.of(new MenuProvider() {
×
112

113
            @Override
114
            public MutableComponent getDisplayName() {
115
                return Component.translatable(getTranslationKey());
×
116
            }
117

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

128
    @Override
129
    public void writeExtraGuiData(FriendlyByteBuf packetBuffer, PartPos pos, ServerPlayer player) {
130
        // Write inventory size
131
        IPartContainer partContainer = PartHelpers.getPartContainerChecked(pos);
×
132
        PartTypeInterfaceCrafting.State partState = (PartTypeInterfaceCrafting.State) partContainer.getPartState(pos.getSide());
×
133
        packetBuffer.writeInt(partState.getInventoryVariables().getContainerSize());
×
134

135
        super.writeExtraGuiData(packetBuffer, pos, player);
×
136
    }
×
137

138
    @Override
139
    public Optional<MenuProvider> getContainerProviderSettings(PartPos pos) {
140
        return Optional.of(new MenuProvider() {
×
141

142
            @Override
143
            public MutableComponent getDisplayName() {
144
                return Component.translatable(getTranslationKey());
×
145
            }
146

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

156
    @Override
157
    protected PartTypeInterfaceCrafting.State constructDefaultState() {
158
        return new PartTypeInterfaceCrafting.State();
×
159
    }
160

161
    @Override
162
    public void afterNetworkReAlive(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
163
        super.afterNetworkReAlive(network, partNetwork, target, state);
×
164
        addTargetToNetwork(network, target, state, true);
×
165
    }
×
166

167
    @Override
168
    public void onNetworkRemoval(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
169
        super.onNetworkRemoval(network, partNetwork, target, state);
×
170
        removeTargetFromNetwork(network, target.getTarget(), state);
×
171
    }
×
172

173
    @Override
174
    public void onNetworkAddition(INetwork network, IPartNetwork partNetwork, PartTarget target, PartTypeInterfaceCrafting.State state) {
175
        super.onNetworkAddition(network, partNetwork, target, state);
×
176
        addTargetToNetwork(network, target, state, true);
×
177
    }
×
178

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

188
    protected Capability<ICraftingNetwork> getNetworkCapability() {
189
        return CraftingNetworkConfig.CAPABILITY;
×
190
    }
191

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

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

212
    @Override
213
    public boolean isUpdate(State state) {
214
        return true;
×
215
    }
216

217
    @Override
218
    public int getMinimumUpdateInterval(State state) {
219
        return state.getDefaultUpdateInterval();
×
220
    }
221

222
    @Override
223
    public void update(INetwork network, IPartNetwork partNetwork, PartTarget target, State state) {
224
        super.update(network, partNetwork, target, state);
×
225

226
        // Init network data in part state if it has not been done yet.
227
        // This can occur when the part chunk is being reloaded.
228
        if (state.getCraftingNetwork() == null) {
×
229
            addTargetToNetwork(network, target, state, false);
×
230
        }
231

232
        int channel = state.getChannelCrafting();
×
233

234
        // Update the network data in the part state
235
        if (state.shouldAddToCraftingNetwork()) {
×
236
            ICraftingNetwork craftingNetwork = network.getCapability(getNetworkCapability()).orElse(null);
×
237
            craftingNetwork.addCraftingInterface(channel, state);
×
238
            state.setShouldAddToCraftingNetwork(false);
×
239
        }
240

241
        // Push any pending output ingredients into the network
242
        state.flushInventoryOutputBuffer(network);
×
243

244
        // Block job ticking if there still are outputs in our crafting result buffer.
245
        if (state.getInventoryOutputBuffer().isEmpty()) {
×
246
            // Tick the job handler
247
            PartPos targetPos = state.getTarget().getTarget();
×
248
            state.getCraftingJobHandler().update(network, channel, targetPos);
×
249
        }
250

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

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

272
                    // Add the new recipe to the network
273
                    IRecipeDefinition newRecipe = recipes.get(slot);
×
274
                    if (newRecipe != null) {
×
275
                        craftingNetwork.addCraftingInterfaceRecipe(channel, state, newRecipe);
×
276
                    }
277
                }
×
278
            }
279
        }
280

281
        // Internal tick counter
282
        state.ticksAfterReload++;
×
283
    }
×
284

285
    @Nullable
286
    protected static <T, M> IngredientInstanceWrapper<T, M> insertIntoNetwork(IngredientInstanceWrapper<T, M> wrapper,
287
                                                                              INetwork network, int channel) {
288
        IPositionedAddonsNetworkIngredients<T, M> storageNetwork = wrapper.getComponent()
×
289
                .getCapability(PositionedAddonsNetworkIngredientsHandlerConfig.CAPABILITY)
×
290
                .map(n -> (IPositionedAddonsNetworkIngredients<T, M>) n.getStorage(network).orElse(null))
×
291
                .orElse(null);
×
292
        if (storageNetwork != null) {
×
293
            IIngredientComponentStorage<T, M> storage = storageNetwork.getChannel(channel);
×
294
            T remaining = storage.insert(wrapper.getInstance(), false);
×
295
            if (wrapper.getComponent().getMatcher().isEmpty(remaining)) {
×
296
                return null;
×
297
            } else {
298
                return new IngredientInstanceWrapper<>(wrapper.getComponent(), remaining);
×
299
            }
300
        }
301
        return wrapper;
×
302
    }
303

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

314
        // Drop the stored variables
315
        for(int i = 0; i < state.getInventoryVariables().getContainerSize(); i++) {
×
316
            ItemStack itemStack = state.getInventoryVariables().getItem(i);
×
317
            if(!itemStack.isEmpty()) {
×
318
                itemStacks.add(itemStack);
×
319
            }
320
        }
321
        state.getInventoryVariables().clearContent();
×
322

323
        super.addDrops(target, state, itemStacks, dropMainElement, saveState);
×
324
    }
×
325

326
    public static class State extends PartStateBase<PartTypeInterfaceCrafting>
327
            implements ICraftingInterface, ICraftingResultsSink {
328

329
        protected int ticksAfterReload = 0;
×
330

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

342
        private final Int2ObjectMap<IRecipeDefinition> currentRecipes;
343
        private PartTarget target = null;
×
344
        private INetwork network = null;
×
345
        private ICraftingNetwork craftingNetwork = null;
×
346
        private IPartNetwork partNetwork = null;
×
347
        private int channel = -1;
×
348
        private ValueDeseralizationContext valueDeseralizationContext;
349
        private boolean shouldAddToCraftingNetwork = false;
×
350
        private Player lastPlayer;
351

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

366
        @Override
367
        protected int getDefaultUpdateInterval() {
368
            return GeneralConfig.minCraftingInterfaceUpdateFreq;
×
369
        }
370

371
        /**
372
         * @return The inner variables inventory
373
         */
374
        public SimpleInventory getInventoryVariables() {
375
            return this.inventoryVariables;
×
376
        }
377

378
        @Override
379
        public void writeToNBT(CompoundTag tag) {
380
            super.writeToNBT(tag);
×
381
            inventoryVariables.writeToNBT(tag, "variables");
×
382

383
            ListTag instanceTags = new ListTag();
×
384
            for (IngredientInstanceWrapper instanceWrapper : inventoryOutputBuffer) {
×
385
                CompoundTag instanceTag = new CompoundTag();
×
386
                instanceTag.putString("component", IngredientComponent.REGISTRY.getKey(instanceWrapper.getComponent()).toString());
×
387
                instanceTag.put("instance", instanceWrapper.getComponent().getSerializer().serializeInstance(instanceWrapper.getInstance()));
×
388
                instanceTags.add(instanceTag);
×
389
            }
×
390
            tag.put("inventoryOutputBuffer", instanceTags);
×
391

392
            this.craftingJobHandler.writeToNBT(tag);
×
393
            tag.putInt("channelCrafting", channelCrafting);
×
394

395
            CompoundTag recipeSlotErrorsTag = new CompoundTag();
×
396
            for (Int2ObjectMap.Entry<MutableComponent> entry : this.recipeSlotMessages.int2ObjectEntrySet()) {
×
397
                NBTClassType.writeNbt(MutableComponent.class, String.valueOf(entry.getIntKey()), entry.getValue(), recipeSlotErrorsTag);
×
398
            }
×
399
            tag.put("recipeSlotMessages", recipeSlotErrorsTag);
×
400

401
            CompoundTag recipeSlotValidatedTag = new CompoundTag();
×
402
            for (Int2BooleanMap.Entry entry : this.recipeSlotValidated.int2BooleanEntrySet()) {
×
403
                recipeSlotValidatedTag.putBoolean(String.valueOf(entry.getIntKey()), entry.getBooleanValue());
×
404
            }
×
405
            tag.put("recipeSlotValidated", recipeSlotValidatedTag);
×
406

407
            tag.putBoolean("disableCraftingCheck", disableCraftingCheck);
×
408
        }
×
409

410
        @Override
411
        public void readFromNBT(ValueDeseralizationContext valueDeseralizationContext, CompoundTag tag) {
412
            super.readFromNBT(valueDeseralizationContext, tag);
×
413
            inventoryVariables.readFromNBT(tag, "variables");
×
414

415
            this.inventoryOutputBuffer.clear();
×
416
            for (Tag instanceTagRaw : tag.getList("inventoryOutputBuffer", Tag.TAG_COMPOUND)) {
×
417
                CompoundTag instanceTag = (CompoundTag) instanceTagRaw;
×
418
                String componentName = instanceTag.getString("component");
×
419
                IngredientComponent<?, ?> component = IngredientComponent.REGISTRY.getValue(new ResourceLocation(componentName));
×
420
                this.inventoryOutputBuffer.add(new IngredientInstanceWrapper(component,
×
421
                        component.getSerializer().deserializeInstance(instanceTag.get("instance"))));
×
422
            }
×
423

424
            this.craftingJobHandler.readFromNBT(tag);
×
425
            this.channelCrafting = tag.getInt("channelCrafting");
×
426

427
            this.recipeSlotMessages.clear();
×
428
            CompoundTag recipeSlotErrorsTag = tag.getCompound("recipeSlotMessages");
×
429
            for (String slot : recipeSlotErrorsTag.getAllKeys()) {
×
430
                MutableComponent unlocalizedString = NBTClassType.readNbt(MutableComponent.class, slot, recipeSlotErrorsTag);
×
431
                this.recipeSlotMessages.put(Integer.parseInt(slot), unlocalizedString);
×
432
            }
×
433

434
            this.recipeSlotValidated.clear();
×
435
            CompoundTag recipeSlotValidatedTag = tag.getCompound("recipeSlotValidated");
×
436
            for (String slot : recipeSlotValidatedTag.getAllKeys()) {
×
437
                this.recipeSlotValidated.put(Integer.parseInt(slot), recipeSlotValidatedTag.getBoolean(slot));
×
438
            }
×
439

440
            this.disableCraftingCheck = tag.getBoolean("disableCraftingCheck");
×
441
        }
×
442

443
        public void setChannelCrafting(int channelCrafting) {
444
            if (this.channelCrafting != channelCrafting) {
×
445
                // Unregister from the network
446
                if (craftingNetwork != null) {
×
447
                    craftingNetwork.removeCraftingInterface(this.channelCrafting, this);
×
448
                }
449

450
                // Update the channel
451
                this.channelCrafting = channelCrafting;
×
452

453
                // Re-register to the network
454
                if (craftingNetwork != null) {
×
455
                    craftingNetwork.addCraftingInterface(this.channelCrafting, this);
×
456
                }
457

458
                sendUpdate();
×
459
            }
460
        }
×
461

462
        public int getChannelCrafting() {
463
            return channelCrafting;
×
464
        }
465

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

489
        private void setLocalErrors(int slot, List<MutableComponent> errors) {
490
            if (errors.isEmpty()) {
×
491
                if (this.recipeSlotMessages.size() > slot) {
×
492
                    this.recipeSlotMessages.remove(slot);
×
493
                }
494
            } else {
495
                this.recipeSlotMessages.put(slot, errors.get(0));
×
496
            }
497
        }
×
498

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

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

552
                try {
553
                    IPartNetwork partNetwork = NetworkHelpers.getPartNetworkChecked(network);
×
554
                    MinecraftForge.EVENT_BUS.post(new PartVariableDrivenVariableContentsUpdatedEvent<>(network,
×
555
                            partNetwork, getTarget(),
×
556
                            PartTypes.INTERFACE_CRAFTING, this, lastPlayer, variable,
557
                            variable != null ? variable.getValue() : null));
×
558
                } catch (EvaluationException e) {
×
559
                    // Ignore error
560
                }
×
561
            }
562
            sendUpdate();
×
563
        }
×
564

565
        public void setLastPlayer(Player lastPlayer) {
566
            this.lastPlayer = lastPlayer;
×
567
        }
×
568

569
        private void delayedReloadRecipe(int slot) {
570
            this.delayedRecipeReloads.add(slot);
×
571
        }
×
572

573

574
        private boolean isValid(IRecipeDefinition recipe) {
575
            DimPos dimPos = getTarget().getTarget().getPos();
×
576
            Direction side = getTarget().getTarget().getSide();
×
577
            IRecipeHandler recipeHandler = BlockEntityHelpers.getCapability(dimPos.getLevel(true), dimPos.getBlockPos(), side, Capabilities.RECIPE_HANDLER).orElse(null);
×
578
            if (recipeHandler == null) {
×
579
                BlockState blockState = dimPos.getLevel(true).getBlockState(dimPos.getBlockPos());
×
580
                recipeHandler = BlockCapabilities.getInstance().getCapability(blockState, Capabilities.RECIPE_HANDLER,
×
581
                        dimPos.getLevel(true), dimPos.getBlockPos(), side)
×
582
                .orElse(null);
×
583
            }
584
            if (recipeHandler != null) {
×
585
                IMixedIngredients simulatedOutput = recipeHandler.simulate(MixedIngredients.fromRecipeInput(recipe));
×
586
                if (simulatedOutput != null && !simulatedOutput.isEmpty()) {
×
587
                    if (recipe.getOutput().containsAll(simulatedOutput)) {
×
588
                        return true;
×
589
                    } else {
590
                        if (GeneralConfig.logRecipeValidationFailures) {
×
591
                            IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: incompatible recipe output and simulated output:\nRecipe output: " + recipe.getOutput() + "\nSimulated output: " + simulatedOutput);
×
592
                        }
593
                        return false;
×
594
                    }
595
                }
596
                if (GeneralConfig.logRecipeValidationFailures) {
×
597
                    IntegratedCrafting.clog(Level.INFO, "Recipe validation failure: No output was obtained when simulating a recipe\n" + recipe);
×
598
                }
599
                return false;
×
600
            }
601
            return true; // No recipe handler capability is present, so we can't confirm that the recipe will work.
×
602
        }
603

604
        @Override
605
        public void onDirty() {
606
            super.onDirty();
×
607

608
            // Unregister from the network, when all old recipes are still in place
609
            if (craftingNetwork != null) {
×
610
                craftingNetwork.removeCraftingInterface(channelCrafting, this);
×
611
            }
612

613
            // Recalculate recipes
614
            if (getTarget() != null && !getTarget().getCenter().getPos().getLevel(true).isClientSide) {
×
615
                reloadRecipes(false);
×
616
            }
617

618
            // Re-register to the network, to force an update for all new recipes
619
            if (craftingNetwork != null) {
×
620
                craftingNetwork.addCraftingInterface(channelCrafting, this);
×
621
            }
622
        }
×
623

624
        public void setTarget(PartTarget target) {
625
            this.target = target;
×
626
        }
×
627

628
        public PartTarget getTarget() {
629
            return target;
×
630
        }
631

632
        public void setNetworks(@Nullable INetwork network, @Nullable ICraftingNetwork craftingNetwork,
633
                                @Nullable IPartNetwork partNetwork, int channel,
634
                                @Nullable ValueDeseralizationContext valueDeseralizationContext,
635
                                boolean initialize) {
636
            this.network = network;
×
637
            this.craftingNetwork = craftingNetwork;
×
638
            this.partNetwork = partNetwork;
×
639
            this.channel = channel;
×
640
            this.valueDeseralizationContext = valueDeseralizationContext;
×
641
            reloadRecipes(initialize);
×
642
            if (network != null) {
×
643
                this.getCraftingJobHandler().reRegisterObservers(network);
×
644
            }
645
        }
×
646

647
        public ICraftingNetwork getCraftingNetwork() {
648
            return craftingNetwork;
×
649
        }
650

651
        @Override
652
        public int getChannel() {
653
            return channel;
×
654
        }
655

656
        @Override
657
        public Collection<IRecipeDefinition> getRecipes() {
658
            return this.currentRecipes.values();
×
659
        }
660

661
        public Int2ObjectMap<IRecipeDefinition> getRecipesIndexed() {
662
            return currentRecipes;
×
663
        }
664

665
        @Override
666
        public boolean canScheduleCraftingJobs() {
667
            return getCraftingJobHandler().canScheduleCraftingJobs();
×
668
        }
669

670
        @Override
671
        public void scheduleCraftingJob(CraftingJob craftingJob) {
672
            getCraftingJobHandler().scheduleCraftingJob(craftingJob);
×
673
        }
×
674

675
        @Override
676
        public int getCraftingJobsCount() {
677
            return this.craftingJobHandler.getAllCraftingJobs().size();
×
678
        }
679

680
        @Override
681
        public Iterator<CraftingJob> getCraftingJobs() {
682
            return this.craftingJobHandler.getAllCraftingJobs().values().iterator();
×
683
        }
684

685
        @Override
686
        public List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> getPendingCraftingJobOutputs(int craftingJobId) {
687
            List<Map<IngredientComponent<?, ?>, List<IPrototypedIngredient<?, ?>>>> pending = this.craftingJobHandler.getProcessingCraftingJobsPendingIngredients().get(craftingJobId);
×
688
            if (pending == null) {
×
689
                pending = Lists.newArrayList();
×
690
            }
691
            return pending;
×
692
        }
693

694
        @Override
695
        public CraftingJobStatus getCraftingJobStatus(ICraftingNetwork network, int channel, int craftingJobId) {
696
            return craftingJobHandler.getCraftingJobStatus(network, channel, craftingJobId);
×
697
        }
698

699
        @Override
700
        public void cancelCraftingJob(int channel, int craftingJobId) {
701
            craftingJobHandler.markCraftingJobFinished(craftingJobId);
×
702
        }
×
703

704
        @Override
705
        public PrioritizedPartPos getPosition() {
706
            return PrioritizedPartPos.of(getTarget().getCenter(), getPriority());
×
707
        }
708

709
        public CraftingJobHandler getCraftingJobHandler() {
710
            return craftingJobHandler;
×
711
        }
712

713
        public boolean shouldAddToCraftingNetwork() {
714
            return shouldAddToCraftingNetwork;
×
715
        }
716

717
        public void setShouldAddToCraftingNetwork(boolean shouldAddToCraftingNetwork) {
718
            this.shouldAddToCraftingNetwork = shouldAddToCraftingNetwork;
×
719
        }
×
720

721
        public List<IngredientInstanceWrapper<?, ?>> getInventoryOutputBuffer() {
722
            return inventoryOutputBuffer;
×
723
        }
724

725
        @Override
726
        public <T> LazyOptional<T> getCapability(Capability<T> capability, INetwork network, IPartNetwork partNetwork, PartTarget target) {
727
            if (capability == CraftingInterfaceConfig.CAPABILITY) {
×
728
                return LazyOptional.of(() -> this).cast();
×
729
            }
730

731
            // Expose the whole storage
732
            if (this.network != null) {
×
733
                IngredientComponent<?, ?> ingredientComponent = IngredientComponent.getIngredientComponentForStorageCapability(capability);
×
734
                if (ingredientComponent != null) {
×
735
                    T cap = wrapStorageCapability(capability, ingredientComponent);
×
736
                    if (cap != null) {
×
737
                        return LazyOptional.of(() -> cap);
×
738
                    }
739
                }
740
            }
741

742
            return super.getCapability(capability, network, partNetwork, target);
×
743
        }
744

745
        protected <C, T, M> C wrapStorageCapability(Capability<C> capability, IngredientComponent<T, M> ingredientComponent) {
746
            IIngredientComponentStorage<T, M> storage = CraftingHelpers.getNetworkStorage(this.network, this.channelCrafting,
×
747
                    ingredientComponent, false);
748

749
            // Don't allow extraction, only insertion
750
            storage = new IngredientComponentStorageSlottedInsertProxy<>(storage);
×
751

752
            return ingredientComponent.getStorageWrapperHandler(capability).wrapStorage(storage);
×
753
        }
754

755
        @Override
756
        public <T, M> void addResult(IngredientComponent<T, M> ingredientComponent, T instance) {
757
            this.getInventoryOutputBuffer().add(new IngredientInstanceWrapper<>(ingredientComponent, instance));
×
758

759
            // Try to flush buffer immediately
760
            if (this.network != null) {
×
761
                this.flushInventoryOutputBuffer(this.network);
×
762
            }
763
        }
×
764

765
        public void setIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent, Direction side) {
766
            if (getTarget().getTarget().getSide() == side) {
×
767
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, null);
×
768
            } else {
769
                craftingJobHandler.setIngredientComponentTarget(ingredientComponent, side);
×
770
            }
771
            sendUpdate();
×
772
        }
×
773

774
        public Direction getIngredientComponentTargetSideOverride(IngredientComponent<?, ?> ingredientComponent) {
775
            Direction side = craftingJobHandler.getIngredientComponentTarget(ingredientComponent);
×
776
            if (side == null) {
×
777
                side = getTarget().getTarget().getSide();
×
778
            }
779
            return side;
×
780
        }
781

782
        public boolean isRecipeSlotValid(int slot) {
783
            return this.recipeSlotValidated.containsKey(slot);
×
784
        }
785

786
        @Nullable
787
        public MutableComponent getRecipeSlotUnlocalizedMessage(int slot) {
788
            return this.recipeSlotMessages.get(slot);
×
789
        }
790

791
        public IntSet getDelayedRecipeReloads() {
792
            return delayedRecipeReloads;
×
793
        }
794

795
        public void setDisableCraftingCheck(boolean disableCraftingCheck) {
796
            if (disableCraftingCheck != this.disableCraftingCheck) {
×
797
                this.disableCraftingCheck = disableCraftingCheck;
×
798

799
                this.sendUpdate();
×
800
            }
801
        }
×
802

803
        public boolean isDisableCraftingCheck() {
804
            return disableCraftingCheck;
×
805
        }
806

807
        public void flushInventoryOutputBuffer(INetwork network) {
808
            // Try to insert each ingredient in the buffer into the network.
809
            boolean changed = false;
×
810
            ListIterator<IngredientInstanceWrapper<?, ?>> outputBufferIt = this.getInventoryOutputBuffer().listIterator();
×
811
            while (outputBufferIt.hasNext()) {
×
812
                IngredientInstanceWrapper<?, ?> oldWrapper = outputBufferIt.next();
×
813

814
                // Force observation before insertion (see #98 on why this is necessary)
815
                this.forceObservationOnInsertable(oldWrapper);
×
816

817
                IngredientInstanceWrapper<?, ?> newWrapper = insertIntoNetwork(oldWrapper,
×
818
                        network, this.getChannelCrafting());
×
819
                if (newWrapper != oldWrapper) {
×
820
                    changed = true;
×
821
                }
822
                if (newWrapper == null) {
×
823
                    outputBufferIt.remove();
×
824
                } else {
825
                    outputBufferIt.set(newWrapper);
×
826
                }
827
            }
×
828

829
            // If at least one ingredient was inserted, force a sync observer update in the network.
830
            if (changed) {
×
831
                CraftingHelpers.beforeCalculateCraftingJobs(network, getChannelCrafting());
×
832
            }
833
        }
×
834

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

866
                if (marked || ingredientsNetwork.isObservationForcedPending(channel)) {
×
867
                    ingredientsNetwork.runObserverSync();
×
868
                }
869
            }
870
        }
×
871
    }
872
}
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