aboutsummaryrefslogtreecommitdiff
path: root/runtime/src/main/java/me/shedaniel/rei/impl/EntryRegistryImpl.java
blob: d5ff03c285af741e2dc1bac71ed999bbcc5bd51a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
 * This file is licensed under the MIT License, part of Roughly Enough Items.
 * Copyright (c) 2018, 2019, 2020 shedaniel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package me.shedaniel.rei.impl;

import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import me.shedaniel.rei.RoughlyEnoughItemsCore;
import me.shedaniel.rei.api.ConfigObject;
import me.shedaniel.rei.api.EntryRegistry;
import me.shedaniel.rei.api.ingredient.EntryStack;
import me.shedaniel.rei.api.ingredient.util.EntryStacks;
import me.shedaniel.rei.impl.filtering.FilteringContextImpl;
import me.shedaniel.rei.impl.filtering.FilteringContextType;
import me.shedaniel.rei.impl.filtering.FilteringRule;
import me.shedaniel.rei.api.util.CollectionUtils;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.core.NonNullList;
import net.minecraft.core.Registry;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@ApiStatus.Internal
@Environment(EnvType.CLIENT)
public class EntryRegistryImpl implements EntryRegistry {
    private final List<EntryStack<?>> preFilteredList = Lists.newCopyOnWriteArrayList();
    private final List<EntryStack<?>> entries = Lists.newCopyOnWriteArrayList();
    @Nullable
    private List<AmountIgnoredEntryStackWrapper> reloadingRegistry;
    private boolean reloading;
    
    public void finishReload() {
        reloading = false;
        preFilteredList.clear();
        reloadingRegistry.removeIf(AmountIgnoredEntryStackWrapper::isEmpty);
        entries.clear();
        entries.addAll(CollectionUtils.map(reloadingRegistry, AmountIgnoredEntryStackWrapper::unwrap));
        reloadingRegistry = null;
    }
    
    @Override
    @NotNull
    public Stream<EntryStack<?>> getEntryStacks() {
        return reloading ? reloadingRegistry.stream().map(AmountIgnoredEntryStackWrapper::unwrap) : entries.stream();
    }
    
    @Override
    @NotNull
    public List<EntryStack<?>> getPreFilteredList() {
        return preFilteredList;
    }
    
    @Override
    @ApiStatus.Experimental
    public void refilter() {
        Stopwatch stopwatch = Stopwatch.createStarted();
        
        FilteringContextImpl context = new FilteringContextImpl(entries);
        List<FilteringRule<?>> rules = ((ConfigObjectImpl) ConfigObject.getInstance()).getFilteringRules();
        Stopwatch innerStopwatch = Stopwatch.createStarted();
        for (int i = rules.size() - 1; i >= 0; i--) {
            innerStopwatch.reset().start();
            FilteringRule<?> rule = rules.get(i);
            context.handleResult(rule.processFilteredStacks(context));
            RoughlyEnoughItemsCore.LOGGER.debug("Refiltered rule [%s] in %s.", FilteringRule.REGISTRY.getKey(rule).toString(), innerStopwatch.stop().toString());
        }
        
        Set<AmountIgnoredEntryStackWrapper> hiddenStacks = context.stacks.get(FilteringContextType.HIDDEN);
        if (hiddenStacks.isEmpty()) {
            preFilteredList.clear();
            preFilteredList.addAll(entries);
        } else {
            preFilteredList.clear();
            preFilteredList.addAll(entries.parallelStream()
                    .map(AmountIgnoredEntryStackWrapper::new)
                    .filter(not(hiddenStacks::contains))
                    .map(AmountIgnoredEntryStackWrapper::unwrap)
                    .collect(Collectors.toList()));
        }
        
        RoughlyEnoughItemsCore.LOGGER.debug("Refiltered %d entries with %d rules in %s.", entries.size() - preFilteredList.size(), rules.size(), stopwatch.stop().toString());
    }
    
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>) target.negate();
    }
    
    public void resetToReloadStart() {
        entries.clear();
        if (reloadingRegistry != null)
            reloadingRegistry.clear();
        reloadingRegistry = Lists.newArrayListWithCapacity(Registry.ITEM.keySet().size() + 100);
        preFilteredList.clear();
        reloading = true;
    }
    
    @NotNull
    @Override
    public List<ItemStack> appendStacksForItem(@NotNull Item item) {
        NonNullList<ItemStack> list = NonNullList.create();
        item.fillItemCategory(item.getItemCategory(), list);
        if (list.isEmpty())
            return Collections.singletonList(item.getDefaultInstance());
        return list;
    }
    
    @NotNull
    @Override
    public ItemStack[] getAllStacksFromItem(@NotNull Item item) {
        List<ItemStack> list = appendStacksForItem(item);
        ItemStack[] array = list.toArray(new ItemStack[0]);
        Arrays.sort(array, (a, b) -> ItemStack.matches(a, b) ? 0 : 1);
        return array;
    }
    
    @Override
    public void registerEntryAfter(@Nullable EntryStack<?> afterEntry, @NotNull EntryStack<?> stack) {
        if (reloading) {
            int index = afterEntry != null ? reloadingRegistry.lastIndexOf(new AmountIgnoredEntryStackWrapper(afterEntry)) : -1;
            if (index >= 0) {
                reloadingRegistry.add(index, new AmountIgnoredEntryStackWrapper(stack));
            } else reloadingRegistry.add(new AmountIgnoredEntryStackWrapper(stack));
        } else {
            if (afterEntry != null) {
                int index = entries.lastIndexOf(afterEntry);
                entries.add(index, stack);
            } else entries.add(stack);
        }
    }
    
    @Override
    public void registerEntriesAfter(@Nullable EntryStack<?> afterEntry, @NotNull Collection<@NotNull ? extends EntryStack<?>> stacks) {
        if (reloading) {
            int index = afterEntry != null ? reloadingRegistry.lastIndexOf(new AmountIgnoredEntryStackWrapper(afterEntry)) : -1;
            if (index >= 0) {
                reloadingRegistry.addAll(index, CollectionUtils.map(stacks, AmountIgnoredEntryStackWrapper::new));
            } else reloadingRegistry.addAll(CollectionUtils.map(stacks, AmountIgnoredEntryStackWrapper::new));
        } else {
            if (afterEntry != null) {
                int index = entries.lastIndexOf(afterEntry);
                entries.addAll(index, stacks);
            } else entries.addAll(stacks);
        }
    }
    
    @Override
    public boolean alreadyContain(EntryStack<?> stack) {
        if (reloading) {
            return reloadingRegistry.parallelStream().anyMatch(s -> EntryStacks.equalsExact(s.unwrap(), stack));
        }
        return entries.parallelStream().anyMatch(s -> EntryStacks.equalsExact(s, stack));
    }
    
    @Override
    public void removeEntry(EntryStack<?> stack) {
        if (reloading) {
            reloadingRegistry.remove(new AmountIgnoredEntryStackWrapper(stack));
        } else {
            entries.remove(stack);
        }
    }
    
    @Override
    public void removeEntryIf(Predicate<EntryStack<?>> stackPredicate) {
        if (reloading) {
            reloadingRegistry.removeIf(wrapper -> stackPredicate.test(wrapper.unwrap()));
        } else {
            entries.removeIf(stackPredicate);
        }
    }
}