aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/kubatech/api/EIGDynamicInventory.java
blob: 0d4c7d2ec6a3f46e340e614e2b8c677659e51055 (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package kubatech.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;

import org.lwjgl.opengl.GL11;

import com.gtnewhorizons.modularui.api.GlStateManager;
import com.gtnewhorizons.modularui.api.ModularUITextures;
import com.gtnewhorizons.modularui.api.drawable.IDrawable;
import com.gtnewhorizons.modularui.api.drawable.ItemDrawable;
import com.gtnewhorizons.modularui.api.drawable.UITexture;
import com.gtnewhorizons.modularui.api.math.Alignment;
import com.gtnewhorizons.modularui.api.math.Color;
import com.gtnewhorizons.modularui.api.screen.ModularWindow;
import com.gtnewhorizons.modularui.api.screen.UIBuildContext;
import com.gtnewhorizons.modularui.api.widget.Widget;
import com.gtnewhorizons.modularui.common.internal.Theme;
import com.gtnewhorizons.modularui.common.internal.wrapper.ModularGui;
import com.gtnewhorizons.modularui.common.widget.ButtonWidget;
import com.gtnewhorizons.modularui.common.widget.ChangeableWidget;
import com.gtnewhorizons.modularui.common.widget.DynamicPositionedRow;
import com.gtnewhorizons.modularui.common.widget.FakeSyncWidget;
import com.gtnewhorizons.modularui.common.widget.Scrollable;

import kubatech.api.gui.AutoScalingStackSizeText;
import kubatech.api.helpers.GTHelper;
import kubatech.api.utils.ModUtils;

public class EIGDynamicInventory<T> {

    int width, height;
    Supplier<Integer> maxSeedCountGetter;
    Supplier<Integer> maxSeedTypeGetter;
    Supplier<Integer> usedSeedCountGetter;
    Supplier<Integer> usedSeedTypesGetter;
    private int maxSeedTypes = 0;
    private int maxSeedCount = 0;
    private int usedSeedTypes = 0;
    private int usedSeedCount = 0;
    List<T> inventory;
    TInventoryGetter<T> inventoryGetter;
    TInventoryInjector inventoryInjector = null;
    TInventoryExtractor<T> inventoryExtractor = null;
    TInventoryReplacerOrMerger inventoryReplacer = null;
    Supplier<Boolean> isEnabledGetter = null;
    boolean isEnabled = true;

    public EIGDynamicInventory(int width, int height, Supplier<Integer> maxSeedTypeGetter,
        Supplier<Integer> maxSeedCountGetter, Supplier<Integer> usedSeedTypesGetter,
        Supplier<Integer> usedSeedCountGetter, List<T> inventory, TInventoryGetter<T> inventoryGetter) {
        this.width = width;
        this.height = height;
        this.maxSeedTypeGetter = maxSeedTypeGetter;
        this.maxSeedCountGetter = maxSeedCountGetter;
        this.usedSeedTypesGetter = usedSeedTypesGetter;
        this.usedSeedCountGetter = usedSeedCountGetter;
        this.inventory = inventory;
        this.inventoryGetter = inventoryGetter;
    }

    public EIGDynamicInventory<T> allowInventoryInjection(TInventoryInjector inventoryInjector) {
        this.inventoryInjector = inventoryInjector;
        return this;
    }

    public EIGDynamicInventory<T> allowInventoryExtraction(TInventoryExtractor<T> inventoryExtractor) {
        this.inventoryExtractor = inventoryExtractor;
        return this;
    }

    public EIGDynamicInventory<T> allowInventoryReplace(TInventoryReplacerOrMerger inventoryReplacer) {
        this.inventoryReplacer = inventoryReplacer;
        return this;
    }

    public EIGDynamicInventory<T> setEnabled(Supplier<Boolean> isEnabled) {
        this.isEnabledGetter = isEnabled;
        return this;
    }

    public UITexture getItemSlot() {
        return ModularUITextures.ITEM_SLOT;
    }

    @SuppressWarnings("UnstableApiUsage")
    public Widget asWidget(ModularWindow.Builder builder, UIBuildContext buildContext) {
        ChangeableWidget container = new ChangeableWidget(() -> createWidget(buildContext.getPlayer()));
        // TODO: Only reset the widget when there are more slot stacks, otherwise just refresh them somehow

        container
            // max seed types
            .attachSyncer(new FakeSyncWidget.IntegerSyncer(() -> {
                int i = this.maxSeedTypeGetter.get();
                if (this.maxSeedTypes != i) {
                    this.maxSeedTypes = i;
                    container.notifyChangeNoSync();
                }
                return i;
            }, i -> {
                if (this.maxSeedTypes != i) {
                    this.maxSeedTypes = i;
                    container.notifyChangeNoSync();
                }
            }), builder)
            // used seed types
            .attachSyncer(new FakeSyncWidget.IntegerSyncer(() -> {
                int i = this.usedSeedTypesGetter.get();
                if (this.usedSeedTypes != i) {
                    this.usedSeedTypes = i;
                    container.notifyChangeNoSync();
                }
                return i;
            }, i -> {
                if (this.usedSeedTypes != i) {
                    this.usedSeedTypes = i;
                    container.notifyChangeNoSync();
                }
            }), builder)
            // max seed count
            .attachSyncer(new FakeSyncWidget.IntegerSyncer(() -> {
                int i = this.maxSeedCountGetter.get();
                if (this.maxSeedCount != i) {
                    this.maxSeedCount = i;
                    container.notifyChangeNoSync();
                }
                return i;
            }, i -> {
                if (this.maxSeedCount != i) {
                    this.maxSeedCount = i;
                    container.notifyChangeNoSync();
                }
            }), builder)
            // used seed count
            .attachSyncer(new FakeSyncWidget.IntegerSyncer(() -> {
                int i = this.usedSeedCountGetter.get();
                if (this.usedSeedCount != i) {
                    this.usedSeedCount = i;
                    container.notifyChangeNoSync();
                }
                return i;
            }, i -> {
                if (this.usedSeedCount != i) {
                    this.usedSeedCount = i;
                    container.notifyChangeNoSync();
                }
            }), builder)

            .attachSyncer(new FakeSyncWidget.ListSyncer<>(() -> {
                List<GTHelper.StackableItemSlot> newDrawables = new ArrayList<>();
                for (int i = 0, mStorageSize = inventory.size(); i < mStorageSize; i++) {
                    T slot = inventory.get(i);
                    if (slot == null) {
                        continue;
                    }
                    ItemStack stack = inventoryGetter.get(slot);
                    newDrawables
                        .add(new GTHelper.StackableItemSlot(1, stack, new ArrayList<>(Collections.singletonList(i))));
                }
                if (!Objects.equals(newDrawables, drawables)) {
                    drawables = newDrawables;
                    container.notifyChangeNoSync();
                }
                return drawables;
            }, l -> {
                drawables.clear();
                drawables.addAll(l);
                container.notifyChangeNoSync();
            }, (buffer, i) -> {
                try {
                    i.write(buffer);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }, buffer -> {
                try {
                    return GTHelper.StackableItemSlot.read(buffer);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }), builder);
        if (isEnabledGetter != null) {
            container.attachSyncer(new FakeSyncWidget.BooleanSyncer(isEnabledGetter, i -> isEnabled = i), builder);
        }
        return container;
    }

    List<GTHelper.StackableItemSlot> drawables = new ArrayList<>();

    private Widget createWidget(EntityPlayer player) {
        Scrollable dynamicInventoryWidget = new Scrollable().setVerticalScroll();

        ArrayList<Widget> buttons = new ArrayList<>();

        if (!ModUtils.isClientThreaded()) {
            drawables = new ArrayList<>();
            for (int i = 0, inventorySize = inventory.size(); i < inventorySize; i++) {
                T slot = inventory.get(i);
                if (slot == null) {
                    continue;
                }
                ItemStack stack = inventoryGetter.get(slot);
                drawables.add(new GTHelper.StackableItemSlot(1, stack, new ArrayList<>(Collections.singleton(i))));
            }
        }

        for (int ID = 0; ID < drawables.size(); ID++) {
            final int finalID = ID;

            buttons.add(new ButtonWidget() {

                @Override
                public void drawBackground(float partialTicks) {
                    super.drawBackground(partialTicks);
                    if (!isEnabled) {
                        GL11.glDisable(GL11.GL_LIGHTING);
                        GL11.glEnable(GL11.GL_BLEND);
                        GlStateManager.colorMask(true, true, true, false);
                        ModularGui.drawSolidRect(1, 1, 16, 16, Color.withAlpha(Color.BLACK.normal, 0x80));
                        GlStateManager.colorMask(true, true, true, true);
                        GL11.glDisable(GL11.GL_BLEND);
                    }
                    // Copied from SlotWidget#draw
                    else if (isHovering() && !getContext().getCursor()
                        .hasDraggable()) {
                            GL11.glDisable(GL11.GL_LIGHTING);
                            GL11.glEnable(GL11.GL_BLEND);
                            GlStateManager.colorMask(true, true, true, false);
                            ModularGui.drawSolidRect(1, 1, 16, 16, Theme.INSTANCE.getSlotHighlight());
                            GlStateManager.colorMask(true, true, true, true);
                            GL11.glDisable(GL11.GL_BLEND);
                        }
                }
            }.setPlayClickSound(false)
                .setOnClick((clickData, widget) -> {
                    if (!(player instanceof EntityPlayerMP)) return;
                    if (!isEnabledGetter.get()) return;

                    if (clickData.mouseButton == 2) {
                        // special button handler goes here
                        if (drawables.size() <= finalID) return;
                        if (player.capabilities.isCreativeMode && player.inventory.getItemStack() == null) {
                            int realID = drawables.get(finalID).realSlots.get(0);
                            ItemStack stack = inventoryGetter.get(inventory.get(realID))
                                .copy();
                            stack.stackSize = stack.getMaxStackSize();
                            player.inventory.setItemStack(stack);
                            ((EntityPlayerMP) player).isChangingQuantityOnly = false;
                            ((EntityPlayerMP) player).updateHeldItem();
                            return;
                        }
                    } else if (clickData.shift) {
                        if (inventoryExtractor == null) return;
                        if (drawables.size() <= finalID) return;
                        int realID = drawables.get(finalID).realSlots.get(0);
                        T toRemoveFrom = this.inventory.get(realID);
                        ItemStack removed = this.inventoryExtractor.extract(toRemoveFrom, (EntityPlayerMP) player);
                        if (removed != null) {
                            if (player.inventory.addItemStackToInventory(removed))
                                player.inventoryContainer.detectAndSendChanges();
                            else player.entityDropItem(removed, 0.f);
                            return;
                        }
                    } else {
                        ItemStack input = player.inventory.getItemStack();
                        if (input != null) {
                            if (inventoryInjector == null) return;
                            if (clickData.mouseButton == 1) {
                                ItemStack copy = input.copy();
                                copy.stackSize = 1;
                                inventoryInjector.inject(copy);
                                if (copy.stackSize == 1) return;
                                input.stackSize--;
                            } else {
                                inventoryInjector.inject(input);
                            }
                            if (input.stackSize > 0) {
                                // clearing and updating the held item value like this is the only
                                // way I found to be able to reliably update the item count in the UI.
                                player.inventory.setItemStack(null);
                                ((EntityPlayerMP) player).updateHeldItem();
                                player.inventory.setItemStack(input);
                                ((EntityPlayerMP) player).updateHeldItem();
                                return;
                            } else player.inventory.setItemStack(null);
                            ((EntityPlayerMP) player).isChangingQuantityOnly = false;
                            ((EntityPlayerMP) player).updateHeldItem();
                            return;
                        }
                        if (drawables.size() > finalID) {
                            if (inventoryExtractor == null) return;
                            int realID = drawables.get(finalID).realSlots.get(0);
                            T toRemoveFrom = this.inventory.get(realID);
                            ItemStack removed = this.inventoryExtractor.extract(toRemoveFrom, (EntityPlayerMP) player);
                            if (removed != null) {
                                player.inventory.setItemStack(removed);
                                ((EntityPlayerMP) player).isChangingQuantityOnly = false;
                                ((EntityPlayerMP) player).updateHeldItem();
                                return;
                            }
                        }
                    }
                })
                .setBackground(() -> {
                    ItemStack stack = drawables.get(finalID).stack;
                    float slotSize = 16.0f;
                    IDrawable itemDrawable = new ItemDrawable(stack).withFixedSize(slotSize, slotSize, 1, 1);
                    IDrawable stackSizeText = new AutoScalingStackSizeText(stack.stackSize).color(Color.WHITE.normal)
                        .shadow()
                        .alignment(Alignment.BottomRight)
                        .measure();

                    return new IDrawable[] { getItemSlot(), itemDrawable, stackSizeText };
                })
                .dynamicTooltip(() -> {
                    if (drawables.size() > finalID) {
                        ItemStack stack = drawables.get(finalID).stack;
                        List<String> tip = new LinkedList<>();
                        for (Object o : stack.getTooltip(player, false)) {
                            tip.add(o.toString());
                        }
                        if (!tip.isEmpty() && tip.get(0) != null) {
                            tip.set(0, stack.stackSize + " x " + tip.get(0));
                        }
                        return tip;
                    }
                    return Collections.emptyList();
                })
                .setSize(18, 18));
        }

        // only add the extra slot if we are still able to insert
        if (this.usedSeedCount < this.maxSeedCount) {
            buttons.add(new ButtonWidget() {

                @Override
                public void drawBackground(float partialTicks) {
                    super.drawBackground(partialTicks);
                    if (!isEnabled) {
                        GL11.glDisable(GL11.GL_LIGHTING);
                        GL11.glEnable(GL11.GL_BLEND);
                        GlStateManager.colorMask(true, true, true, false);
                        ModularGui.drawSolidRect(1, 1, 16, 16, Color.withAlpha(Color.BLACK.normal, 0x80));
                        GlStateManager.colorMask(true, true, true, true);
                        GL11.glDisable(GL11.GL_BLEND);
                    }
                    // Copied from SlotWidget#draw
                    else if (isHovering() && !getContext().getCursor()
                        .hasDraggable()) {
                            GL11.glDisable(GL11.GL_LIGHTING);
                            GL11.glEnable(GL11.GL_BLEND);
                            GlStateManager.colorMask(true, true, true, false);
                            ModularGui.drawSolidRect(1, 1, 16, 16, Theme.INSTANCE.getSlotHighlight());
                            GlStateManager.colorMask(true, true, true, true);
                            GL11.glDisable(GL11.GL_BLEND);
                        }
                }
            }.setPlayClickSound(false)
                .setOnClick((clickData, widget) -> {
                    if (!(player instanceof EntityPlayerMP)) return;
                    if (!isEnabledGetter.get()) return;
                    ItemStack input = player.inventory.getItemStack();
                    if (input != null) {
                        if (clickData.mouseButton == 1) {
                            ItemStack copy = input.copy();
                            copy.stackSize = 1;
                            inventoryInjector.inject(copy);
                            if (copy.stackSize == 1) return;

                            input.stackSize--;
                        } else {
                            inventoryInjector.inject(input);
                        }
                        if (input.stackSize > 0) {
                            // clearing and updating the held item value like this is the only
                            // way i found to be able to reliably update the item count in the UI.
                            player.inventory.setItemStack(null);
                            ((EntityPlayerMP) player).updateHeldItem();
                            player.inventory.setItemStack(input);
                            ((EntityPlayerMP) player).updateHeldItem();
                            return;
                        } else player.inventory.setItemStack(null);
                        ((EntityPlayerMP) player).isChangingQuantityOnly = false;
                        ((EntityPlayerMP) player).updateHeldItem();
                        return;
                    }
                })
                .setBackground(() -> {
                    IDrawable itemSlot = getItemSlot();

                    IDrawable stackSizeText = new AutoScalingStackSizeText(this.maxSeedCount - this.usedSeedCount)
                        .color(Color.WHITE.normal)
                        .shadow()
                        .alignment(Alignment.BottomRight)
                        .measure();

                    return new IDrawable[] { itemSlot, stackSizeText };
                })
                .dynamicTooltip(() -> {
                    // TODO: all l10n for insertion slot tooltip.
                    List<String> tip = new ArrayList<>();
                    tip.add(
                        EnumChatFormatting.DARK_PURPLE + "Remaining seed types: "
                            + (this.maxSeedTypes - this.usedSeedTypes));
                    tip.add(
                        EnumChatFormatting.DARK_GREEN + "Remaining seed capacity: "
                            + (this.maxSeedCount - this.usedSeedCount));
                    return tip;
                })
                .setSize(18, 18));
        }

        final int perRow = width / 18;
        for (int i = 0, imax = ((buttons.size() - 1) / perRow); i <= imax; i++) {
            DynamicPositionedRow row = new DynamicPositionedRow().setSynced(false);
            for (int j = 0, jmax = (i == imax ? (buttons.size() - 1) % perRow : (perRow - 1)); j <= jmax; j++) {
                final int finalI = i * perRow;
                final int ID = finalI + j;
                row.widget(buttons.get(ID));
            }
            dynamicInventoryWidget.widget(row.setPos(0, i * 18));
        }
        dynamicInventoryWidget.setSize(width, height);
        return dynamicInventoryWidget;
    }

    @FunctionalInterface
    public interface TInventoryGetter<T> {

        /**
         * Allows to get an ItemStack from the dynamic inventory
         *
         * @param from Dynamic inventory item from which we want to take an item out
         * @return ItemStack or null if inaccessible
         */
        ItemStack get(T from);
    }

    @FunctionalInterface
    public interface TInventoryInjector {

        /**
         * Allows to insert an item to the dynamic inventory
         *
         * @param what ItemStack which we are trying to insert
         * @return Leftover ItemStack (stackSize == 0 if everything has been inserted) or null
         */
        ItemStack inject(ItemStack what);
    }

    @FunctionalInterface
    public interface TInventoryExtractor<T> {

        /**
         * Allows to extract an item from the dynamic inventory
         *
         * @return Item that we took out or null
         */
        ItemStack extract(T container, EntityPlayerMP player);
    }

    @FunctionalInterface
    public interface TInventoryReplacerOrMerger {

        /**
         * Allows to replace an item in Dynamic Inventory
         *
         * @param where which index we want to replace
         * @param stack what stack we want to replace it with
         * @return Stack that we are left with or null
         */
        ItemStack replaceOrMerge(int where, ItemStack stack);
    }

}