file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
ContainerRelay.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerRelay.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Quetzi */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.tileentities.tier1.TileRelay; public class ContainerRelay extends Container { private final TileRelay tileRelay; public ContainerRelay(InventoryPlayer invPlayer, TileRelay relay) { this.tileRelay = relay; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { this.addSlotToContainer(new Slot(relay, j + i * 3, 62 + j * 18, 17 + i * 18)); } } bindPlayerInventory(invPlayer); } protected void bindPlayerInventory(InventoryPlayer invPlayer) { // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer player) { return tileRelay.isUseableByPlayer(player); } @Override public ItemStack transferStackInSlot(EntityPlayer player, int par2) { ItemStack itemstack = null; Slot slot = (Slot) inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (par2 < 20) { if (!mergeItemStack(itemstack1, 9, 45, true)) return null; } else if (!mergeItemStack(itemstack1, 0, 9, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize != itemstack.stackSize) { slot.onPickupFromSlot(player, itemstack1); } else { return null; } } return itemstack; } }
2,984
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerSortingMachine.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerSortingMachine.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.ClientProxy; import net.quetzi.bluepower.api.tube.IPneumaticTube.TubeColor; import net.quetzi.bluepower.client.gui.GuiBase; import net.quetzi.bluepower.containers.slots.IPhantomSlot; import net.quetzi.bluepower.containers.slots.SlotPhantom; import net.quetzi.bluepower.tileentities.tier2.TileSortingMachine; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * * @author MineMaarten */ public class ContainerSortingMachine extends Container { private final TileSortingMachine sortingMachine; private int pullMode, sortMode, curColumn; private final int[] colors = new int[9]; public ContainerSortingMachine(InventoryPlayer invPlayer, TileSortingMachine sortingMachine) { this.sortingMachine = sortingMachine; for (int i = 0; i < 5; i++) { for (int j = 0; j < 8; j++) { addSlotToContainer(new SlotPhantom(sortingMachine, i * 8 + j, 26 + j * 18, 18 + i * 18)); } } bindPlayerInventory(invPlayer); } protected void bindPlayerInventory(InventoryPlayer invPlayer) { int offset = 140; // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, offset + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 58 + offset)); } } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack var3 = null; Slot var4 = (Slot) inventorySlots.get(par2); if (var4 != null && var4.getHasStack()) { ItemStack var5 = var4.getStack(); var3 = var5.copy(); if (par2 < 40) { if (!mergeItemStack(var5, 40, 76, false)) return null; var4.onSlotChange(var5, var3); } else { if (!mergeItemStack(var5, 0, 40, false)) return null; var4.onSlotChange(var5, var3); } if (var5.stackSize == 0) { var4.putStack((ItemStack) null); } else { var4.onSlotChanged(); } if (var5.stackSize == var3.stackSize) return null; var4.onPickupFromSlot(par1EntityPlayer, var5); } return var3; } /** * Looks for changes made in the container, sends them to every listener. */ @Override public void detectAndSendChanges() { super.detectAndSendChanges(); for (Object crafter : crafters) { ICrafting icrafting = (ICrafting) crafter; for (int i = 0; i < 9; i++) { if (colors[i] != sortingMachine.colors[i].ordinal()) { icrafting.sendProgressBarUpdate(this, i, sortingMachine.colors[i].ordinal()); } } if (pullMode != sortingMachine.pullMode.ordinal()) { icrafting.sendProgressBarUpdate(this, 9, sortingMachine.pullMode.ordinal()); } if (sortMode != sortingMachine.sortMode.ordinal()) { icrafting.sendProgressBarUpdate(this, 10, sortingMachine.sortMode.ordinal()); } if (curColumn != sortingMachine.curColumn) { icrafting.sendProgressBarUpdate(this, 11, sortingMachine.curColumn); } } pullMode = sortingMachine.pullMode.ordinal(); sortMode = sortingMachine.sortMode.ordinal(); curColumn = sortingMachine.curColumn; for (int i = 0; i < colors.length; i++) { colors[i] = sortingMachine.colors[i].ordinal(); } } @Override @SideOnly(Side.CLIENT) public void updateProgressBar(int id, int value) { if (id < 9) { sortingMachine.colors[id] = TubeColor.values()[value]; } if (id == 9) { sortingMachine.pullMode = TileSortingMachine.PullMode.values()[value]; } if (id == 10) { sortingMachine.sortMode = TileSortingMachine.SortMode.values()[value]; ((GuiBase) ClientProxy.getOpenedGui()).redraw(); } if (id == 11) { sortingMachine.curColumn = value; } } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return sortingMachine.isUseableByPlayer(entityplayer); } /** * This class is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ @Override public ItemStack slotClick(int slotNum, int mouseButton, int modifier, EntityPlayer player) { Slot slot = slotNum < 0 ? null : (Slot) inventorySlots.get(slotNum); if (slot instanceof IPhantomSlot) { return slotClickPhantom(slot, mouseButton, modifier, player); } return super.slotClick(slotNum, mouseButton, modifier, player); } /** * This method is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ private ItemStack slotClickPhantom(Slot slot, int mouseButton, int modifier, EntityPlayer player) { ItemStack stack = null; if (mouseButton == 2) { if (((IPhantomSlot) slot).canAdjust()) { slot.putStack(null); } } else if (mouseButton == 0 || mouseButton == 1) { InventoryPlayer playerInv = player.inventory; slot.onSlotChanged(); ItemStack stackSlot = slot.getStack(); ItemStack stackHeld = playerInv.getItemStack(); if (stackSlot != null) { stack = stackSlot.copy(); } if (stackSlot == null) { if (stackHeld != null && slot.isItemValid(stackHeld)) { fillPhantomSlot(slot, stackHeld, mouseButton, modifier); } } else if (stackHeld == null) { adjustPhantomSlot(slot, mouseButton, modifier); slot.onPickupFromSlot(player, playerInv.getItemStack()); } else if (slot.isItemValid(stackHeld)) { if (canStacksMerge(stackSlot, stackHeld)) { adjustPhantomSlot(slot, mouseButton, modifier); } else { fillPhantomSlot(slot, stackHeld, mouseButton, modifier); } } } return stack; } /** * This method is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ public boolean canStacksMerge(ItemStack stack1, ItemStack stack2) { if (stack1 == null || stack2 == null) return false; if (!stack1.isItemEqual(stack2)) return false; if (!ItemStack.areItemStackTagsEqual(stack1, stack2)) return false; return true; } /** * This method is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ protected void adjustPhantomSlot(Slot slot, int mouseButton, int modifier) { if (!((IPhantomSlot) slot).canAdjust()) { return; } ItemStack stackSlot = slot.getStack(); int stackSize; if (modifier == 1) { stackSize = mouseButton == 0 ? (stackSlot.stackSize + 1) / 2 : stackSlot.stackSize * 2; } else { stackSize = mouseButton == 0 ? stackSlot.stackSize - 1 : stackSlot.stackSize + 1; } if (stackSize > slot.getSlotStackLimit()) { stackSize = slot.getSlotStackLimit(); } stackSlot.stackSize = stackSize; if (stackSlot.stackSize <= 0) { slot.putStack((ItemStack) null); } } /** * This method is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ protected void fillPhantomSlot(Slot slot, ItemStack stackHeld, int mouseButton, int modifier) { if (!((IPhantomSlot) slot).canAdjust()) { return; } int stackSize = mouseButton == 0 ? stackHeld.stackSize : 1; if (stackSize > slot.getSlotStackLimit()) { stackSize = slot.getSlotStackLimit(); } ItemStack phantomStack = stackHeld.copy(); phantomStack.stackSize = stackSize; slot.putStack(phantomStack); } }
10,154
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerIOExpander.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerIOExpander.java
package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.quetzi.bluepower.tileentities.tier3.TileIOExpander; public class ContainerIOExpander extends Container { public ContainerIOExpander(InventoryPlayer inventoryPlayer, TileIOExpander ioExpander) { } @Override public boolean canInteractWith(EntityPlayer var1) { return true; } }
482
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerCanvasBag.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerCanvasBag.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.containers.inventorys.InventoryItem; import net.quetzi.bluepower.containers.slots.SlotExclude; import net.quetzi.bluepower.containers.slots.SlotLocked; import net.quetzi.bluepower.init.BPItems; public class ContainerCanvasBag extends Container { IInventory canvasBagInventory; ItemStack bag; public ContainerCanvasBag(ItemStack bag, IInventory playerInventory, IInventory canvasBagInventory) { this.bag = bag; int i = -1 * 18; canvasBagInventory.openInventory(); for (int j = 0; j < 3; ++j) { for (int k = 0; k < 9; ++k) { addSlotToContainer(new SlotExclude(canvasBagInventory, k + j * 9, 8 + k * 18, 18 + j * 18, BPItems.canvas_bag)); } } for (int j = 0; j < 3; ++j) { for (int k = 0; k < 9; ++k) { addSlotToContainer(new Slot(playerInventory, k + j * 9 + 9, 8 + k * 18, 103 + j * 18 + i)); } } for (int j = 0; j < 9; ++j) { if (playerInventory.getStackInSlot(j) == ((InventoryItem) canvasBagInventory).getItem()) { addSlotToContainer(new SlotLocked(playerInventory, j, 8 + j * 18, 161 + i)); } else { addSlotToContainer(new Slot(playerInventory, j, 8 + j * 18, 161 + i)); } addSlotToContainer(new Slot(playerInventory, j, 8 + j * 18, 161 + i)); } this.canvasBagInventory = canvasBagInventory; } @Override public boolean canInteractWith(EntityPlayer player) { return ItemStack.areItemStacksEqual(player.getCurrentEquippedItem(), bag); } @Override public ItemStack slotClick(int par1, int par2, int par3, EntityPlayer player) { if (par3 != 2 || player.inventory.currentItem != par2) { return super.slotClick(par1, par2, par3, player); } else { return null; } } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack itemstack = null; Slot slot = (Slot) inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (par2 < 27) { if (!mergeItemStack(itemstack1, 27, 63, true)) { return null; } } else if (!mergeItemStack(itemstack1, 0, 27, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(par1EntityPlayer, itemstack1); } return itemstack; } @Override public boolean mergeItemStack(ItemStack par1ItemStack, int par2, int par3, boolean par4) { boolean flag1 = false; int k = par2; if (par4) { k = par3 - 1; } Slot slot; ItemStack itemstack1; if (par1ItemStack.isStackable()) { while (par1ItemStack.stackSize > 0 && (!par4 && k < par3 || par4 && k >= par2)) { slot = (Slot) inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() && (!par1ItemStack.getHasSubtypes() || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1) && slot.isItemValid(par1ItemStack)) { int l = itemstack1.stackSize + par1ItemStack.stackSize; if (l <= par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize = 0; itemstack1.stackSize = l; slot.onSlotChanged(); flag1 = true; } else if (itemstack1.stackSize < par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize -= par1ItemStack.getMaxStackSize() - itemstack1.stackSize; itemstack1.stackSize = par1ItemStack.getMaxStackSize(); slot.onSlotChanged(); flag1 = true; } } if (par4) { --k; } else { ++k; } } } if (par1ItemStack.stackSize > 0) { if (par4) { k = par3 - 1; } else { k = par2; } while (!par4 && k < par3 || par4 && k >= par2) { slot = (Slot) inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 == null && slot.isItemValid(par1ItemStack)) { if (1 < par1ItemStack.stackSize) { ItemStack copy = par1ItemStack.copy(); copy.stackSize = 1; slot.putStack(copy); par1ItemStack.stackSize -= 1; flag1 = true; break; } else { slot.putStack(par1ItemStack.copy()); slot.onSlotChanged(); par1ItemStack.stackSize = 0; flag1 = true; break; } } if (par4) { --k; } else { ++k; } } } return flag1; } }
6,987
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerCPU.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerCPU.java
package net.quetzi.bluepower.containers; import net.quetzi.bluepower.tileentities.tier3.TileCPU; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; public class ContainerCPU extends Container { private final TileCPU cpu; public ContainerCPU(InventoryPlayer invPlayer, TileCPU cpu) { this.cpu = cpu; } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return true; } }
499
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerBuffer.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerBuffer.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.tileentities.tier1.TileBuffer; public class ContainerBuffer extends Container { private final TileBuffer tileBuffer; public ContainerBuffer(InventoryPlayer invPlayer, TileBuffer buffer) { tileBuffer = buffer; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { addSlotToContainer(new Slot(buffer, i * 5 + j, 45 + j * 18, 18 + i * 18)); } } bindPlayerInventory(invPlayer); } protected void bindPlayerInventory(InventoryPlayer invPlayer) { // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 104 + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 162)); } } @Override public boolean canInteractWith(EntityPlayer player) { return tileBuffer.isUseableByPlayer(player); } @Override public ItemStack transferStackInSlot(EntityPlayer player, int par2) { ItemStack itemstack = null; Slot slot = (Slot) inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (par2 < 20) { if (!mergeItemStack(itemstack1, 20, 56, true)) return null; } else if (!mergeItemStack(itemstack1, 0, 20, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize != itemstack.stackSize) { slot.onPickupFromSlot(player, itemstack1); } else { return null; } } return itemstack; } }
3,010
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerRedbusID.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerRedbusID.java
package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.quetzi.bluepower.tileentities.tier3.IRedBusWindow; public class ContainerRedbusID extends Container { private final IRedBusWindow device; public ContainerRedbusID(InventoryPlayer invPlayer, IRedBusWindow device) { this.device = device; } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return true; } }
539
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerSeedBag.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerSeedBag.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.containers.inventorys.InventoryItem; import net.quetzi.bluepower.containers.slots.SlotLocked; import net.quetzi.bluepower.containers.slots.SlotSeedBag; import net.quetzi.bluepower.items.ItemSeedBag; public class ContainerSeedBag extends Container { IInventory seedBagInventory; ItemStack bag; public ContainerSeedBag(ItemStack bag,IInventory playerInventory, IInventory seedBagInventory) { this.seedBagInventory = seedBagInventory; this.bag = bag; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { this.addSlotToContainer(new SlotSeedBag(seedBagInventory, j + i * 3, 62 + j * 18, 17 + i * 18)); } } for (int i = 0; i < 3; ++i) { for (int j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for (int i = 0; i < 9; ++i) { if (playerInventory.getStackInSlot(i) == ((InventoryItem) seedBagInventory).getItem()) { this.addSlotToContainer(new SlotLocked(playerInventory, i, 8 + i * 18, 142)); } else { this.addSlotToContainer(new Slot(playerInventory, i, 8 + i * 18, 142)); } } seedBagInventory.openInventory(); } @Override public boolean canInteractWith(EntityPlayer player) { return player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() instanceof ItemSeedBag; } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack itemstack = null; Slot slot = (Slot) this.inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (par2 < 9) { if (!this.mergeItemStack(itemstack1, 9, 45, true)) { return null; } } else if (!this.mergeItemStack(itemstack1, 0, 9, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(par1EntityPlayer, itemstack1); } return itemstack; } @Override public boolean mergeItemStack(ItemStack par1ItemStack, int par2, int par3, boolean par4) { boolean flag1 = false; int k = par2; if (par4) { k = par3 - 1; } Slot slot; ItemStack itemstack1; if (par1ItemStack.isStackable()) { while (par1ItemStack.stackSize > 0 && (!par4 && k < par3 || par4 && k >= par2)) { slot = (Slot) this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() && (!par1ItemStack.getHasSubtypes() || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1) && slot.isItemValid(par1ItemStack)) { int l = itemstack1.stackSize + par1ItemStack.stackSize; if (l <= par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize = 0; itemstack1.stackSize = l; slot.onSlotChanged(); flag1 = true; } else if (itemstack1.stackSize < par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize -= par1ItemStack.getMaxStackSize() - itemstack1.stackSize; itemstack1.stackSize = par1ItemStack.getMaxStackSize(); slot.onSlotChanged(); flag1 = true; } } if (par4) { --k; } else { ++k; } } } if (par1ItemStack.stackSize > 0) { if (par4) { k = par3 - 1; } else { k = par2; } while (!par4 && k < par3 || par4 && k >= par2) { slot = (Slot) this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 == null && slot.isItemValid(par1ItemStack)) { if (1 < par1ItemStack.stackSize) { ItemStack copy = par1ItemStack.copy(); copy.stackSize = 1; slot.putStack(copy); par1ItemStack.stackSize -= 1; flag1 = true; break; } else { slot.putStack(par1ItemStack.copy()); slot.onSlotChanged(); par1ItemStack.stackSize = 0; flag1 = true; break; } } if (par4) { --k; } else { ++k; } } } return flag1; } }
6,679
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerKinect.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerKinect.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.tileentities.tier1.TileKinectGenerator; public class ContainerKinect extends Container { private final TileKinectGenerator tilekinect; public ContainerKinect(InventoryPlayer invPlayer, TileKinectGenerator kinect) { tilekinect = kinect; //Inventory for Turbines addSlotToContainer(new Slot(kinect, 0, 80, 35)); bindPlayerInventory(invPlayer); } protected void bindPlayerInventory(InventoryPlayer invPlayer) { // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer player) { return tilekinect.isUseableByPlayer(player); } @Override public ItemStack transferStackInSlot(EntityPlayer player, int par2) { return null; } }
2,140
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerMonitor.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerMonitor.java
package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.quetzi.bluepower.tileentities.tier3.TileMonitor; public class ContainerMonitor extends Container { public ContainerMonitor(InventoryPlayer inventoryPlayer, TileMonitor monitor) { } @Override public boolean canInteractWith(EntityPlayer var1) { return true; } }
467
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerDiskDrive.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerDiskDrive.java
package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.quetzi.bluepower.tileentities.tier3.TileDiskDrive; public class ContainerDiskDrive extends Container { private final TileDiskDrive diskDrive; public ContainerDiskDrive(InventoryPlayer invPlayer, TileDiskDrive ent) { this.diskDrive = ent; } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return true; } }
541
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerAlloyFurnace.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerAlloyFurnace.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityFurnace; import net.quetzi.bluepower.containers.slots.SlotMachineInput; import net.quetzi.bluepower.containers.slots.SlotMachineOutput; import net.quetzi.bluepower.tileentities.tier1.TileAlloyFurnace; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ContainerAlloyFurnace extends Container { private final TileAlloyFurnace tileFurnace; private int currentBurnTime; private int maxBurnTime; private int currentProcessTime; public ContainerAlloyFurnace(InventoryPlayer invPlayer, TileAlloyFurnace furnace) { tileFurnace = furnace; addSlotToContainer(new SlotMachineInput(furnace, 0, 21, 35)); addSlotToContainer(new SlotMachineOutput(furnace, 1, 134, 35)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { addSlotToContainer(new SlotMachineInput(furnace, i * 3 + j + 2, 47 + j * 18, 17 + i * 18)); } } bindPlayerInventory(invPlayer); } protected void bindPlayerInventory(InventoryPlayer invPlayer) { // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 142)); } } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack var3 = null; Slot var4 = (Slot) inventorySlots.get(par2); if (var4 != null && var4.getHasStack()) { ItemStack var5 = var4.getStack(); var3 = var5.copy(); if (par2 < 11) { if (!mergeItemStack(var5, 11, 47, false)) return null; var4.onSlotChange(var5, var3); } else { if (TileEntityFurnace.isItemFuel(var5) && mergeItemStack(var5, 0, 1, false)) { } else if (!mergeItemStack(var5, 2, 11, false)) return null; var4.onSlotChange(var5, var3); } if (var5.stackSize == 0) { var4.putStack((ItemStack) null); } else { var4.onSlotChanged(); } if (var5.stackSize == var3.stackSize) return null; var4.onPickupFromSlot(par1EntityPlayer, var5); } return var3; } /** * Looks for changes made in the container, sends them to every listener. */ @Override public void detectAndSendChanges() { super.detectAndSendChanges(); for (Object crafter : crafters) { ICrafting icrafting = (ICrafting) crafter; if (currentBurnTime != tileFurnace.currentBurnTime) { icrafting.sendProgressBarUpdate(this, 0, tileFurnace.currentBurnTime); } if (maxBurnTime != tileFurnace.maxBurnTime) { icrafting.sendProgressBarUpdate(this, 1, tileFurnace.maxBurnTime); } if (currentProcessTime != tileFurnace.currentProcessTime) { icrafting.sendProgressBarUpdate(this, 2, tileFurnace.currentProcessTime); } } currentBurnTime = tileFurnace.currentBurnTime; maxBurnTime = tileFurnace.maxBurnTime; currentProcessTime = tileFurnace.currentProcessTime; } @Override @SideOnly(Side.CLIENT) public void updateProgressBar(int par1, int par2) { if (par1 == 0) { tileFurnace.currentBurnTime = par2; } if (par1 == 1) { tileFurnace.maxBurnTime = par2; } if (par1 == 2) { tileFurnace.currentProcessTime = par2; } } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return tileFurnace.isUseableByPlayer(entityplayer); } }
5,332
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ContainerDeployer.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/ContainerDeployer.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.quetzi.bluepower.tileentities.tier1.TileDeployer; public class ContainerDeployer extends Container { private final TileDeployer tileDeployer; public ContainerDeployer(InventoryPlayer invPlayer, TileDeployer deployer) { bindPlayerInventory(invPlayer); this.tileDeployer= deployer; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { this.addSlotToContainer(new Slot(deployer, j + i * 3, 62 + j * 18, 17 + i * 18)); } } } protected void bindPlayerInventory(InventoryPlayer invPlayer) { // Render inventory for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } // Render hotbar for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(invPlayer, j, 8 + j * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer player) { return tileDeployer.isUseableByPlayer(player); } @Override public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) { ItemStack itemstack = null; Slot slot = (Slot) this.inventorySlots.get(par2); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (par2 < 9) { if (!this.mergeItemStack(itemstack1, 9, 45, true)) { return null; } } else if (!this.mergeItemStack(itemstack1, 0, 9, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(par1EntityPlayer, itemstack1); } return itemstack; } @Override public boolean mergeItemStack(ItemStack par1ItemStack, int par2, int par3, boolean par4) { boolean flag1 = false; int k = par2; if (par4) { k = par3 - 1; } Slot slot; ItemStack itemstack1; if (par1ItemStack.isStackable()) { while (par1ItemStack.stackSize > 0 && (!par4 && k < par3 || par4 && k >= par2)) { slot = (Slot) this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 != null && itemstack1.getItem() == par1ItemStack.getItem() && (!par1ItemStack.getHasSubtypes() || par1ItemStack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(par1ItemStack, itemstack1) && slot.isItemValid(par1ItemStack)) { int l = itemstack1.stackSize + par1ItemStack.stackSize; if (l <= par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize = 0; itemstack1.stackSize = l; slot.onSlotChanged(); flag1 = true; } else if (itemstack1.stackSize < par1ItemStack.getMaxStackSize()) { par1ItemStack.stackSize -= par1ItemStack.getMaxStackSize() - itemstack1.stackSize; itemstack1.stackSize = par1ItemStack.getMaxStackSize(); slot.onSlotChanged(); flag1 = true; } } if (par4) { --k; } else { ++k; } } } if (par1ItemStack.stackSize > 0) { if (par4) { k = par3 - 1; } else { k = par2; } while (!par4 && k < par3 || par4 && k >= par2) { slot = (Slot) this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 == null && slot.isItemValid(par1ItemStack)) { if (1 < par1ItemStack.stackSize) { ItemStack copy = par1ItemStack.copy(); copy.stackSize = 1; slot.putStack(copy); par1ItemStack.stackSize -= 1; flag1 = true; break; } else { slot.putStack(par1ItemStack.copy()); slot.onSlotChanged(); par1ItemStack.stackSize = 0; flag1 = true; break; } } if (par4) { --k; } else { ++k; } } } return flag1; } }
6,193
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotExclude.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotExclude.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers.slots; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class SlotExclude extends Slot { Item filter; public SlotExclude(IInventory par1iInventory, int par2, int par3, int par4, Item filter) { super(par1iInventory, par2, par3, par4); this.filter = filter; } public boolean isItemValid(ItemStack par1ItemStack) { return !(par1ItemStack.getItem() == filter); } }
1,344
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotSeedBag.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotSeedBag.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers.slots; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemStack; public class SlotSeedBag extends Slot { public SlotSeedBag(IInventory par1iInventory, int par2, int par3, int par4) { super(par1iInventory, par2, par3, par4); // TODO Auto-generated constructor stub } public boolean isItemValid(ItemStack itemstack) { itemstack = itemstack.copy(); itemstack.stackSize = 1; if (itemstack.getItem() instanceof ItemSeeds) { ItemStack seedType = null; for (int i = 0; i < this.inventory.getSizeInventory(); i++) { ItemStack is = this.inventory.getStackInSlot(i); if (is != null) { seedType = is.copy(); seedType.stackSize = 1; break; } } if (seedType == null) { return true; } else { return ItemStack.areItemStacksEqual(itemstack, seedType); } } return false; } }
1,991
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotLocked.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotLocked.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers.slots; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; public class SlotLocked extends Slot { public SlotLocked(IInventory par1iInventory, int par2, int par3, int par4) { super(par1iInventory, par2, par3, par4); } @Override public boolean canTakeStack(EntityPlayer par1EntityPlayer) { return false; } }
1,238
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotMachineInput.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotMachineInput.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers.slots; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class SlotMachineInput extends Slot { IInventory inv; public SlotMachineInput(IInventory _inv, int slotNum, int x, int y) { super(_inv, slotNum, x, y); inv = _inv; } @Override public boolean isItemValid(ItemStack itemStack) { return inv.isItemValidForSlot(this.getSlotIndex(), itemStack); } }
1,245
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotMachineOutput.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotMachineOutput.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.containers.slots; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class SlotMachineOutput extends Slot { public SlotMachineOutput(IInventory inv, int slotNum, int x, int y) { super(inv, slotNum, x, y); } /** * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ @Override public boolean isItemValid(ItemStack itemStack) { return false; } }
1,268
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
SlotPhantom.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/SlotPhantom.java
package net.quetzi.bluepower.containers.slots; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; /** * This class is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar <http://www.railcraft.info> */ public class SlotPhantom extends Slot implements IPhantomSlot { // used for filters public SlotPhantom(IInventory par2IInventory, int par3, int par4, int par5) { super(par2IInventory, par3, par4, par5); } @Override public boolean canTakeStack(EntityPlayer par1EntityPlayer) { return false; } @Override public boolean canAdjust() { return true; } }
797
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IPhantomSlot.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/slots/IPhantomSlot.java
package net.quetzi.bluepower.containers.slots; /** * This class is copied from the BuildCraft code, which can be found here: https://github.com/BuildCraft/BuildCraft * @author CovertJaguar */ public interface IPhantomSlot { /* * Phantom Slots don't "use" items, they are used for filters and various * other logic slots. */ boolean canAdjust(); }
379
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
InventoryItem.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/containers/inventorys/InventoryItem.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> * * @author Lumien */ package net.quetzi.bluepower.containers.inventorys; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; public class InventoryItem extends InventoryBasic { private ItemStack item; private EntityPlayer player; private boolean reading = false; public InventoryItem(EntityPlayer player, ItemStack item, String name, boolean customName, int size) { super(name, customName, size); this.player = player; this.item = item; if (!hasInventory()) { createInventory(); } } public static InventoryItem getItemInventory(ItemStack is, String name, int size) { return getItemInventory(null, is, name, size); } public static InventoryItem getItemInventory(EntityPlayer player, ItemStack is, String name, int size) { return new InventoryItem(player, is, name, false, size); } public ItemStack getItem() { return item; } @Override public void openInventory() { loadInventory(); } @Override public void closeInventory() { closeInventory(null); } public void closeInventory(ItemStack is) { saveInventory(is); } private boolean hasInventory() { if (item.stackTagCompound == null) { return false; } return item.stackTagCompound.getTag("Inventory") != null; } private void createInventory() { writeToNBT(); } protected void writeToNBT() { if (item.stackTagCompound == null) { item.stackTagCompound = new NBTTagCompound(); } NBTTagList itemList = new NBTTagList(); for (int i = 0; i < getSizeInventory(); i++) { if (getStackInSlot(i) != null) { NBTTagCompound slotEntry = new NBTTagCompound(); slotEntry.setByte("Slot", (byte) i); getStackInSlot(i).writeToNBT(slotEntry); itemList.appendTag(slotEntry); } } NBTTagCompound inventory = new NBTTagCompound(); inventory.setTag("Items", itemList); item.stackTagCompound.setTag("Inventory", inventory); } public void loadInventory() { readFromNBT(); } @Override public void markDirty() { super.markDirty(); if (!reading) { saveInventory(null); } } protected void setNBT(ItemStack is) { if (is == null && player != null) { is = player.getCurrentEquippedItem(); } if (is != null && is.getItem() == this.item.getItem()) { is.setTagCompound(item.getTagCompound()); } } protected void readFromNBT() { reading = true; NBTTagList itemList = (NBTTagList) ((NBTTagCompound) item.stackTagCompound.getTag("Inventory")).getTag("Items"); for (int i = 0; i < itemList.tagCount(); i++) { NBTTagCompound slotEntry = itemList.getCompoundTagAt(i); int j = slotEntry.getByte("Slot") & 0xff; if (j >= 0 && j < getSizeInventory()) { setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(slotEntry)); } } reading = false; } public void saveInventory(ItemStack is) { writeToNBT(); setNBT(is); } }
4,394
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
Color.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/util/Color.java
/* * This file is part of Blue Power. Blue Power is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Blue Power is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along * with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.util; /** * @author amadornes * */ public enum Color { BLACK("\u00A70"), // DARK_BLUE("\u00A71"), // DARK_GREEN("\u00A72"), // DARK_AQUA("\u00A73"), // DARK_RED("\u00A74"), // DARK_PURPLE("\u00A75"), // GOLD("\u00A76"), // GRAY("\u00A77"), // DARK_GRAY("\u00A78"), // BLUE("\u00A79"), // GREEN("\u00A7a"), // AQUA("\u00A7b"), // RED("\u00A7c"), // LIGHT_PURPLE("\u00A7d"), // YELLOW("\u00A7e"), // WHITE("\u00A7f"), // STRIKE_THROUGH("\u00A7m"), // UNDERLINE("\u00A7n"), // BOLD("\u00A7l"), // RANDOM("\u00A7k"), // ITALIC("\u00A7o"), // RESET("\u00A7r");// public String code = ""; private Color(String code) { this.code = code; } @Override public String toString() { return code; } }
1,544
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
RayTracer.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/util/RayTracer.java
/* * This file is part of Blue Power. Blue Power is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Blue Power is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along * with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.util; import java.util.ArrayList; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; import net.quetzi.bluepower.api.part.BPPart; import net.quetzi.bluepower.api.vec.Vector3; import net.quetzi.bluepower.compat.CompatibilityUtils; import net.quetzi.bluepower.compat.fmp.IMultipartCompat; import net.quetzi.bluepower.references.Dependencies; import codechicken.lib.raytracer.IndexedCuboid6; import codechicken.lib.vec.Cuboid6; import cpw.mods.fml.common.Optional; public class RayTracer { public static final MovingObjectPosition rayTrace(Vector3 start, Vector3 end, List<AxisAlignedBB> aabbs) { return rayTrace(start, end, aabbs, new Vector3(0, 0, 0)); } public static final MovingObjectPosition rayTrace(Vector3 start, Vector3 end, List<AxisAlignedBB> aabbs, int x, int y, int z) { return rayTrace(start, end, aabbs, new Vector3(x, y, z)); } public static final MovingObjectPosition rayTrace(Vector3 start, Vector3 end, List<AxisAlignedBB> aabbs, Vector3 location) { return null; } @Optional.Method(modid = Dependencies.FMP) public static final AxisAlignedBB getSelectedCuboid(MovingObjectPosition mop, EntityPlayer player, ForgeDirection face, Iterable<IndexedCuboid6> boxes, boolean unused) { List<Cuboid6> cuboids = new ArrayList<Cuboid6>(); for (IndexedCuboid6 c : boxes) cuboids.add(c); return getSelectedCuboid(mop, player, face, cuboids); } @Optional.Method(modid = Dependencies.FMP) public static final AxisAlignedBB getSelectedCuboid(MovingObjectPosition mop, EntityPlayer player, ForgeDirection face, Iterable<Cuboid6> boxes) { List<AxisAlignedBB> aabbs = new ArrayList<AxisAlignedBB>(); for (Cuboid6 c : boxes) aabbs.add(c.toAABB()); return getSelectedBox(mop, player, face, aabbs); } public static final AxisAlignedBB getSelectedBox(MovingObjectPosition mop, EntityPlayer player, ForgeDirection face, Iterable<AxisAlignedBB> boxes) { Vector3 hit = new Vector3(mop.hitVec.xCoord - mop.blockX, mop.hitVec.yCoord - mop.blockY, mop.hitVec.zCoord - mop.blockZ); for (AxisAlignedBB c : boxes) { boolean is = false; if (face == ForgeDirection.UP || face == ForgeDirection.DOWN) { boolean is2 = false; if (face == ForgeDirection.UP) { if (c.maxY == hit.getY()) is2 = true; } else { if (c.minY == hit.getY()) is2 = true; } if (is2 && hit.getX() >= c.minX && hit.getX() < c.maxX && hit.getZ() >= c.minZ && hit.getZ() < c.maxZ) is = true; } if (face == ForgeDirection.NORTH || face == ForgeDirection.SOUTH) { boolean is2 = false; if (face == ForgeDirection.SOUTH) { if (c.maxZ == hit.getZ()) is2 = true; } else { if (c.minZ == hit.getZ()) is2 = true; } if (is2 && hit.getX() >= c.minX && hit.getX() < c.maxX && hit.getY() >= c.minY && hit.getY() < c.maxY) is = true; } if (face == ForgeDirection.EAST || face == ForgeDirection.WEST) { boolean is2 = false; if (face == ForgeDirection.EAST) { if (c.maxX == hit.getX()) is2 = true; } else { if (c.minX == hit.getX()) is2 = true; } if (is2 && hit.getY() >= c.minY && hit.getY() < c.maxY && hit.getZ() >= c.minZ && hit.getZ() < c.maxZ) is = true; } if (is) return c; } return null; } /** * @author amadornes * * @return */ public static BPPart getSelectedPart(MovingObjectPosition mop, EntityPlayer player, ForgeDirection face) { return ((IMultipartCompat) CompatibilityUtils.getModule(Dependencies.FMP)).getClickedPart(new Vector3(mop.blockX, mop.blockY, mop.blockZ, player.worldObj), new Vector3(mop.hitVec, player.worldObj).subtract(mop.blockX, mop.blockY, mop.blockZ), null, player); } private static boolean isSameBox(AxisAlignedBB a, AxisAlignedBB b) { if (a.minX == b.minX && a.minY == b.minY && a.minZ == b.minZ && a.maxX == b.maxX && a.maxY == b.maxY && a.maxZ == b.maxZ) return true; return false; } /* * The following methods are from CodeChickenLib, credits to ChickenBones for this. CodeChickenLib can be found here: * http://files.minecraftforge.net/CodeChickenLib/ */ public static Vec3 getCorrectedHeadVec(EntityPlayer player) { Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); if (player.worldObj.isRemote) { v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight();// compatibility with eye height changing mods } else { v.yCoord += player.getEyeHeight(); if (player instanceof EntityPlayerMP && player.isSneaking()) v.yCoord -= 0.08; } return v; } public static Vec3 getStartVec(EntityPlayer player) { return getCorrectedHeadVec(player); } public static Vec3 getEndVec(EntityPlayer player) { Vec3 headVec = getCorrectedHeadVec(player); Vec3 lookVec = player.getLook(1.0F); double reach = player.capabilities.isCreativeMode ? 5 : 4.5; return headVec.addVector(lookVec.xCoord * reach, lookVec.yCoord * reach, lookVec.zCoord * reach); } }
6,702
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ItemStackUtils.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/util/ItemStackUtils.java
/* * This file is part of Blue Power. * * Blue Power is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Blue Power is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Blue Power. If not, see <http://www.gnu.org/licenses/> */ package net.quetzi.bluepower.util; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; /** * * @author MineMaarten */ public class ItemStackUtils { public static boolean isItemFuzzyEqual(ItemStack stack1, ItemStack stack2) { if (stack1.getItem() != stack2.getItem() && !isSameOreDictStack(stack1, stack2)) return false; return stack1.getItemDamage() == stack2.getItemDamage() || stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE; } public static boolean isSameOreDictStack(ItemStack stack1, ItemStack stack2) { int ids[] = OreDictionary.getOreIDs(stack1); for (int id = 0; id < ids.length; id++) { if (id >= 0) { List<ItemStack> oreDictStacks = OreDictionary.getOres(OreDictionary.getOreName(id)); for (ItemStack oreDictStack : oreDictStacks) { if (OreDictionary.itemMatches(oreDictStack, stack2, false)) { return true; } } } } return false; } }
1,876
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ComparatorMOP.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/util/ComparatorMOP.java
package net.quetzi.bluepower.util; import java.util.Comparator; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.quetzi.bluepower.api.vec.Vector3; public class ComparatorMOP implements Comparator<MovingObjectPosition> { private Vec3 start = null; public ComparatorMOP(Vector3 start) { this.start = start.toVec3(); } @Override public int compare(MovingObjectPosition arg0, MovingObjectPosition arg1) { return (int)(((double)((arg0.hitVec.distanceTo(start) - arg1.hitVec.distanceTo(start)) * 1000000))); } }
621
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ForgeDirectionUtils.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/main/java/net/quetzi/bluepower/util/ForgeDirectionUtils.java
package net.quetzi.bluepower.util; import net.minecraftforge.common.util.ForgeDirection; public class ForgeDirectionUtils { public static int getSide(ForgeDirection dir) { for (int i = 0; i < ForgeDirection.VALID_DIRECTIONS.length; i++) { if (ForgeDirection.VALID_DIRECTIONS[i] == dir) return i; } return -1; } }
378
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ComputerCraftAPI.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/ComputerCraftAPI.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api; import dan200.computercraft.api.filesystem.IMount; import dan200.computercraft.api.filesystem.IWritableMount; import dan200.computercraft.api.media.IMediaProvider; import dan200.computercraft.api.peripheral.IPeripheralProvider; import dan200.computercraft.api.redstone.IBundledRedstoneProvider; import dan200.computercraft.api.turtle.ITurtleUpgrade; import net.minecraft.world.World; import java.lang.reflect.Method; /** * The static entry point to the ComputerCraft API. * Members in this class must be called after mod_ComputerCraft has been initialised, * but may be called before it is fully loaded. */ public final class ComputerCraftAPI { /** * Creates a numbered directory in a subfolder of the save directory for a given world, and returns that number.<br> * Use in conjuction with createSaveDirMount() to create a unique place for your peripherals or media items to store files.<br> * @param world The world for which the save dir should be created. This should be the serverside world object. * @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk" * @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason.<br> * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now available for writing. * @see #createSaveDirMount(World, String, long) */ public static int createUniqueNumberedSaveDir( World world, String parentSubPath ) { findCC(); if( computerCraft_createUniqueNumberedSaveDir != null ) { try { return ((Integer)computerCraft_createUniqueNumberedSaveDir.invoke( null, world, parentSubPath )).intValue(); } catch (Exception e){ // It failed } } return -1; } /** * Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it.<br> * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the * users save directory onto a computers file system.<br> * @param world The world for which the save dir can be found. This should be the serverside world object. * @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42".<br> * Use createUniqueNumberedSaveDir() to create a new numbered folder to use. * @param capacity The ammount of data that can be stored in the directory before it fills up, in bytes. * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() * to mount this on a Computers' file system. * @see #createUniqueNumberedSaveDir(World, String) * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) * @see dan200.computercraft.api.filesystem.IMount * @see IWritableMount */ public static IWritableMount createSaveDirMount( World world, String subPath, long capacity ) { findCC(); if( computerCraft_createSaveDirMount != null ) { try { return (IWritableMount)computerCraft_createSaveDirMount.invoke( null, world, subPath, capacity ); } catch (Exception e){ // It failed } } return null; } /** * Creates a file system mount to a resource folder, and returns it.<br> * Use in conjuction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a resource folder onto a computers file system.<br> * The files in this mount will be a combination of files in the specified mod jar, and resource packs that contain resources with the same domain and path.<br> * @param modClass A class in whose jar to look first for the resources to mount. Using your main mod class is recommended. eg: MyMod.class * @param domain The domain under which to look for resources. eg: "mymod" * @param subPath The domain under which to look for resources. eg: "mymod/lua/myfiles" * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() * to mount this on a Computers' file system. * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, dan200.computercraft.api.filesystem.IMount) * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, IWritableMount) * @see dan200.computercraft.api.filesystem.IMount */ public static IMount createResourceMount( Class modClass, String domain, String subPath ) { findCC(); if( computerCraft_createResourceMount != null ) { try { return (IMount)computerCraft_createResourceMount.invoke( null, modClass, domain, subPath ); } catch (Exception e){ // It failed } } return null; } /** * Registers a peripheral handler to convert blocks into IPeripheral implementations. * @see dan200.computercraft.api.peripheral.IPeripheral * @see dan200.computercraft.api.peripheral.IPeripheralProvider */ public static void registerPeripheralProvider( IPeripheralProvider handler ) { findCC(); if ( computerCraft_registerPeripheralProvider != null) { try { computerCraft_registerPeripheralProvider.invoke( null, handler ); } catch (Exception e){ // It failed } } } /** * Registers a new turtle turtle for use in ComputerCraft. After calling this, * users should be able to craft Turtles with your new turtle. It is recommended to call * this during the load() method of your mod. * @see dan200.computercraft.api.turtle.ITurtleUpgrade */ public static void registerTurtleUpgrade( ITurtleUpgrade upgrade ) { if( upgrade != null ) { findCC(); if( computerCraft_registerTurtleUpgrade != null ) { try { computerCraft_registerTurtleUpgrade.invoke( null, upgrade ); } catch( Exception e ) { // It failed } } } } /** * Registers a bundled redstone handler to provide bundled redstone output for blocks * @see dan200.computercraft.api.redstone.IBundledRedstoneProvider */ public static void registerBundledRedstoneProvider( IBundledRedstoneProvider handler ) { findCC(); if( computerCraft_registerBundledRedstoneProvider != null ) { try { computerCraft_registerBundledRedstoneProvider.invoke( null, handler ); } catch (Exception e){ // It failed } } } /** * If there is a Computer or Turtle at a certain position in the world, get it's bundled redstone output. * @see dan200.computercraft.api.redstone.IBundledRedstoneProvider * @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned. * If there is no block capable of emitting bundled redstone at the location, -1 will be returned. */ public static int getBundledRedstoneOutput( World world, int x, int y, int z, int side ) { findCC(); if( computerCraft_getDefaultBundledRedstoneOutput != null ) { try { return ((Integer)computerCraft_getDefaultBundledRedstoneOutput.invoke( null, world, x, y, z, side )).intValue(); } catch (Exception e){ // It failed } } return -1; } /** * Registers a media handler to provide IMedia implementations for Items * @see dan200.computercraft.api.media.IMediaProvider */ public static void registerMediaProvider( IMediaProvider handler ) { findCC(); if( computerCraft_registerMediaProvider != null ) { try { computerCraft_registerMediaProvider.invoke( null, handler ); } catch (Exception e){ // It failed } } } // The functions below here are private, and are used to interface with the non-API ComputerCraft classes. // Reflection is used here so you can develop your mod in MCP without decompiling ComputerCraft and including // it in your solution. private static void findCC() { if( !ccSearched ) { try { computerCraft = Class.forName( "dan200.computercraft.ComputerCraft" ); computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class[]{ World.class, String.class } ); computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class[] { World.class, String.class, Long.TYPE } ); computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class[] { Class.class, String.class, String.class } ); computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class[] { IPeripheralProvider.class } ); computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class[] { ITurtleUpgrade.class } ); computerCraft_registerBundledRedstoneProvider = findCCMethod( "registerBundledRedstoneProvider", new Class[] { IBundledRedstoneProvider.class } ); computerCraft_getDefaultBundledRedstoneOutput = findCCMethod( "getDefaultBundledRedstoneOutput", new Class[] { World.class, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE } ); computerCraft_registerMediaProvider = findCCMethod( "registerMediaProvider", new Class[] { IMediaProvider.class } ); } catch( Exception e ) { System.out.println( "ComputerCraftAPI: ComputerCraft not found." ); } finally { ccSearched = true; } } } private static Method findCCMethod( String name, Class[] args ) { try { return computerCraft.getMethod( name, args ); } catch( NoSuchMethodException e ) { System.out.println( "ComputerCraftAPI: ComputerCraft method " + name + " not found." ); return null; } } private static boolean ccSearched = false; private static Class computerCraft = null; private static Method computerCraft_createUniqueNumberedSaveDir = null; private static Method computerCraft_createSaveDirMount = null; private static Method computerCraft_createResourceMount = null; private static Method computerCraft_registerPeripheralProvider = null; private static Method computerCraft_registerTurtleUpgrade = null; private static Method computerCraft_registerBundledRedstoneProvider = null; private static Method computerCraft_getDefaultBundledRedstoneOutput = null; private static Method computerCraft_registerMediaProvider = null; }
11,324
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ILuaObject.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/lua/ILuaObject.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.lua; /** * An interface for representing custom objects returned by IPeripheral.callMethod() calls. * Return objects implementing this interface to expose objects with methods to lua. */ public interface ILuaObject { /** * Get the names of the methods that this object implements. This works the same as IPeripheral.getMethodNames(). See that method for detailed documentation. * @see dan200.computercraft.api.peripheral.IPeripheral#getMethodNames() */ public String[] getMethodNames(); /** * Called when a user calls one of the methods that this object implements. This works the same as IPeripheral.callMethod(). See that method for detailed documentation. * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod(dan200.computercraft.api.peripheral.IComputerAccess, ILuaContext, int, Object[]) */ public Object[] callMethod( ILuaContext context, int method, Object[] arguments ) throws Exception; }
1,256
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ILuaContext.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/lua/ILuaContext.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.lua; /** * An interface passed to peripherals and ILuaObjects' by computers or turtles, providing methods * that allow the peripheral call to wait for events before returning, just like in lua. * This is very useful if you need to signal work to be performed on the main thread, and don't want to return * until the work has been completed. */ public interface ILuaContext { /** * Wait for an event to occur on the computercraft, suspending the thread until it arises. This method is exactly equivalent to os.pullEvent() in lua. * @param filter A specific event to wait for, or null to wait for any event * @return An object array containing the name of the event that occurred, and any event parameters * @throws Exception If the user presses CTRL+T to terminate the current program while pullEvent() is waiting for an event, a "Terminated" exception will be thrown here. * Do not attempt to common this exception, unless you wish to prevent termination, which is not recommended. * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEvent() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. */ public Object[] pullEvent( String filter ) throws Exception, InterruptedException; /** * The same as pullEvent(), except "terminated" events are ignored. Only use this if you want to prevent program termination, which is not recommended. This method is exactly equivalent to os.pullEventRaw() in lua. * @param filter A specific event to wait for, or null to wait for any event * @return An object array containing the name of the event that occurred, and any event parameters * @throws InterruptedException If the user shuts down or reboots the computercraft while pullEventRaw() is waiting for an event, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. * @see #pullEvent(String) */ public Object[] pullEventRaw( String filter ) throws InterruptedException; /** * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to coroutine.yield() in lua. Use pullEvent() if you wish to wait for events. * @param arguments An object array containing the arguments to pass to coroutine.yield() * @return An object array containing the return values from coroutine.yield() * @throws InterruptedException If the user shuts down or reboots the computercraft the coroutine is suspended, InterruptedException will be thrown. This exception must not be caught or intercepted, or the computercraft will leak memory and end up in a broken state. * @see #pullEvent(String) */ public Object[] yield( Object[] arguments ) throws InterruptedException; }
3,226
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IMedia.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/media/IMedia.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.media; import dan200.computercraft.api.filesystem.IMount; import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * Represents an item that can be placed in a disk drive and used by a Computer. * Implement this interface on your Item class to allow it to be used in the drive. */ public interface IMedia { /** * Get a string representing the label of this item. Will be called vi disk.getLabel() in lua. * @param stack The itemstack to inspect * @return The label. ie: "Dan's Programs" */ public String getLabel( ItemStack stack ); /** * Set a string representing the label of this item. Will be called vi disk.setLabel() in lua. * @param stack The itemstack to modify. * @param label The string to set the label to. * @return true if the label was updated, false if the label may not be modified. */ public boolean setLabel( ItemStack stack, String label ); /** * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathon Coulton - Still Alive" * @param stack The itemstack to inspect. * @return The name, or null if this item does not represent an item with audio. */ public String getAudioTitle( ItemStack stack ); /** * If this disk represents an item with audio (like a record), get the resource name of the audio track to play. * @param stack The itemstack to inspect. * @return The name, or null if this item does not represent an item with audio. */ public String getAudioRecordName( ItemStack stack ); /** * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will be mounted onto the filesystem of the computercraft while the media is in the disk drive. * @param stack The itemstack to inspect. * @param world The world in which the item and disk drive reside. * @return The mount, or null if this item does not represent an item with data. If the IMount returned also implements IWritableMount, it will mounted using mountWritable() * @see dan200.computercraft.api.filesystem.IMount * @see dan200.computercraft.api.filesystem.IWritableMount * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) */ public IMount createDataMount( ItemStack stack, World world ); }
2,733
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IMediaProvider.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/media/IMediaProvider.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.media; import net.minecraft.item.ItemStack; /** * This interface is used to provide IMedia implementations for ItemStack * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) */ public interface IMediaProvider { /** * Produce an IMedia implementation from an ItemStack. * @see dan200.computercraft.api.ComputerCraftAPI#registerMediaProvider(IMediaProvider) * @return an IMedia implementation, or null if the item is not something you wish to handle */ public IMedia getMedia( ItemStack stack ); }
881
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
TurtleAnimation.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/TurtleAnimation.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; public enum TurtleAnimation { None, MoveForward, MoveBack, MoveUp, MoveDown, TurnLeft, TurnRight, SwingLeftTool, SwingRightTool, Wait, }
504
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
TurtleSide.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/TurtleSide.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; /** * An enum representing the two sides of the turtle that a turtle turtle might reside. */ public enum TurtleSide { /** * The turtles left side (where the pickaxe usually is on a Wireless Mining Turtle) */ Left, /** * The turtles right side (where the modem usually is on a Wireless Mining Turtle) */ Right, }
654
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
TurtleUpgradeType.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; /** * An enum representing the two different types of turtle that an ITurtleUpgrade * implementation can add to a turtle. * @see ITurtleUpgrade */ public enum TurtleUpgradeType { /** * A tool is rendered as an item on the side of the turtle, and responds to the turtle.dig() * and turtle.attack() methods (Such as pickaxe or sword on Mining and Melee turtles). */ Tool, /** * A peripheral adds a special peripheral which is attached to the side of the turtle, * and can be interacted with the peripheral API (Such as the modem on Wireless Turtles). */ Peripheral, }
915
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
TurtleVerb.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/TurtleVerb.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; /** * An enum representing the two different actions that an ITurtleUpgrade of type * Tool may be called on to perform by a turtle. * @see ITurtleUpgrade * @see ITurtleUpgrade#useTool */ public enum TurtleVerb { /** * The turtle called turtle.dig(), turtle.digUp() or turtle.digDown() */ Dig, /** * The turtle called turtle.attack(), turtle.attackUp() or turtle.attackDown() */ Attack, }
734
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ITurtleAccess.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/ITurtleAccess.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.peripheral.IPeripheral; import net.minecraft.inventory.IInventory; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.Vec3; import net.minecraft.world.World; /** * The interface passed to turtle by turtles, providing methods that they can call. * This should not be implemented by your classes. Do not interact with turtles except via this interface and ITurtleUpgrade. */ public interface ITurtleAccess { /** * Returns the world in which the turtle resides. * @return the world in which the turtle resides. */ public World getWorld(); /** * Returns a vector containing the integer co-ordinates at which the turtle resides. * @return a vector containing the integer co-ordinates at which the turtle resides. */ public ChunkCoordinates getPosition(); /** * TODO: Document me */ public boolean teleportTo( World world, int x, int y, int z ); /** * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. * This will shift when the turtle is moving. * @param f The subframe fraction * @return a vector containing the floating point co-ordinates at which the turtle resides. */ public Vec3 getVisualPosition( float f ); /** * TODO: Document me */ public float getVisualYaw( float f ); /** * Returns the world direction the turtle is currently facing. * @return the world direction the turtle is currently facing. */ public int getDirection(); /** * TODO: Document me */ public void setDirection( int dir ); /** * TODO: Document me */ public int getSelectedSlot(); /** * TODO: Document me */ public void setSelectedSlot( int slot ); /** * TODO: Document me */ public IInventory getInventory(); /** * TODO: Document me */ public boolean isFuelNeeded(); /** * TODO: Document me */ public int getFuelLevel(); /** * TODO: Document me */ public void setFuelLevel( int fuel ); /** * TODO: Document me */ public int getFuelLimit(); /** * Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle. * @return Whether the turtle was able to consume the ammount of fuel specified. Will return false if you supply a number * greater than the current fuel level of the turtle. */ public boolean consumeFuel( int fuel ); /** * TODO: Document me */ public void addFuel( int fuel ); /** * Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed * on the main thread, so are guaranteed to be able to access Minecraft objects safely, and will be queued up * with the turtles standard movement and tool commands. An issued command will return an unique integer, which will * be supplied as a parameter to a "turtle_response" event issued to the turtle after the command has completed. Look at the * lua source code for "rom/apis/turtle" for how to build a lua wrapper around this functionality. * @param command an object which will execute the custom command when its point in the queue is reached * @return the objects the command returned when executed. you should probably return these to the player * unchanged if called from a peripheral method. * @see ITurtleCommand */ public Object[] executeCommand( ILuaContext context, ITurtleCommand command ) throws Exception; /** * TODO: Document me */ public void playAnimation( TurtleAnimation animation ); /** * Returns the turtle on the specified side of the turtle, if there is one. * @return the turtle on the specified side of the turtle, if there is one. */ public ITurtleUpgrade getUpgrade( TurtleSide side ); /** * TODO: Document me */ public void setUpgrade( TurtleSide side, ITurtleUpgrade upgrade ); /** * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. * @return the peripheral created by the upgrade on the specified side of the turtle, if there is one. */ public IPeripheral getPeripheral( TurtleSide side ); /** * TODO: Document me */ public NBTTagCompound getUpgradeNBTData( TurtleSide side ); /** * TODO: Document me */ public void updateUpgradeNBTData( TurtleSide side ); }
4,905
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ITurtleUpgrade.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; import dan200.computercraft.api.peripheral.IPeripheral; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; /** * The primary interface for defining an turtle for Turtles. A turtle turtle * can either be a new tool, or a new peripheral. * @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade ) */ public interface ITurtleUpgrade { /** * Gets a unique numerical identifier representing this type of turtle turtle. * Like Minecraft common and item IDs, you should strive to make this number unique * among all turtle turtle that have been released for ComputerCraft. * The ID must be in the range 64 to 255, as the ID is stored as an 8-bit value, * and 0-64 is reserved for future use by ComputerCraft. The turtle will * fail registration if an already used ID is specified. * @see dan200.computercraft.api.ComputerCraftAPI#registerTurtleUpgrade( dan200.computercraft.api.turtle.ITurtleUpgrade ) */ public int getUpgradeID(); /** * Return a String to describe this type of turtle in turtle item names. * Examples of built-in adjectives are "Wireless", "Mining" and "Crafty". */ public String getUnlocalisedAdjective(); /** * Return whether this turtle adds a tool or a peripheral to the turtle. * Currently, turtle crafting is restricted to one tool & one peripheral per turtle. * @see TurtleUpgradeType for the differences between the two. */ public TurtleUpgradeType getType(); /** * Return an item stack representing the type of item that a turtle must be crafted * with to create a turtle which holds this turtle. * Currently, turtle crafting is restricted to one tool & one peripheral per turtle. */ public ItemStack getCraftingItem(); /** * Will only be called for Peripheral turtle. Creates a peripheral for a turtle * being placed using this turtle. The peripheral created will be stored * for the lifetime of the turtle, will have update() called once-per-tick, and will be * attach'd detach'd and have methods called in the same manner as a Computer peripheral. * * @param turtle Access to the turtle that the peripheral is being created for. * @param side Which side of the turtle (left or right) that the turtle resides on. * @return The newly created peripheral. You may return null if this turtle is a Tool * and this method is not expected to be called. */ public IPeripheral createPeripheral( ITurtleAccess turtle, TurtleSide side ); /** * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called * by the turtle, and the tool is required to do some work. * @param turtle Access to the turtle that the tool resides on. * @param side Which side of the turtle (left or right) the tool resides on. * @param verb Which action (dig or attack) the turtle is being called on to perform. * @param direction Which world direction the action should be performed in, relative to the turtles * position. This will either be up, down, or the direction the turtle is facing, depending on * whether dig, digUp or digDown was called. * @return Whether the turtle was able to perform the action, and hence whether the turtle.dig() * or turtle.attack() lua method should return true. If true is returned, the tool will perform * a swinging animation. You may return null if this turtle is a Peripheral * and this method is not expected to be called. */ public TurtleCommandResult useTool( ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, int direction ); /** * Called to obtain the IIcon to be used when rendering a turtle peripheral. Needs to be a "common" * type IIcon for now, as there is no way to determine which texture sheet an IIcon is from by the * IIcon itself. * @param turtle Access to the turtle that the peripheral resides on. * @param side Which side of the turtle (left or right) the peripheral resides on. * @return The IIcon that you wish to be used to render your turtle peripheral. */ public IIcon getIcon( ITurtleAccess turtle, TurtleSide side ); /** * TODO: Document me */ public void update( ITurtleAccess turtle, TurtleSide side ); }
4,566
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ITurtleCommand.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/ITurtleCommand.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; /** * An interface for objects executing custom turtle commands, used with ITurtleAccess.issueCommand * @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand) */ public interface ITurtleCommand { /** * Will be called by the turtle on the main thread when it is time to execute the custom command. * The handler should either perform the work of the command, and return success, or return * failure with an error message to indicate the command cannot be executed at this time. * @param turtle access to the turtle for whom the command was issued * @return TurtleCommandResult.success() or TurtleCommandResult.failure( errorMessage ) * @see ITurtleAccess#executeCommand(dan200.computercraft.api.lua.ILuaContext,ITurtleCommand) * @see dan200.computercraft.api.turtle.TurtleCommandResult */ public TurtleCommandResult execute( ITurtleAccess turtle ); }
1,240
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
TurtleCommandResult.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/turtle/TurtleCommandResult.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.turtle; public final class TurtleCommandResult { private static final TurtleCommandResult s_success = new TurtleCommandResult( true, null ); private static final TurtleCommandResult s_emptyFailure = new TurtleCommandResult( false, null ); public static TurtleCommandResult success() { return s_success; } public static TurtleCommandResult failure() { return failure( null ); } public static TurtleCommandResult failure( String errorMessage ) { if( errorMessage != null ) { return new TurtleCommandResult( false, errorMessage ); } else { return s_emptyFailure; } } private final boolean m_success; private final String m_errorMessage; private TurtleCommandResult( boolean success, String errorMessage ) { m_success = success; m_errorMessage = errorMessage; } public boolean isSuccess() { return m_success; } public String getErrorMessage() { return m_errorMessage; } }
1,402
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IComputerAccess.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/peripheral/IComputerAccess.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.peripheral; import dan200.computercraft.api.filesystem.IMount; import dan200.computercraft.api.filesystem.IWritableMount; /** * The interface passed to peripherals by computers or turtles, providing methods * that they can call. This should not be implemented by your classes. Do not interact * with computers except via this interface. */ public interface IComputerAccess { /** * Mount a mount onto the computers' file system in a read only mode.<br> * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount(), ComputerCraftAPI.createResourceMount() or by creating your own objects that implement the IMount interface. * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) * @see #mountWritable(String, dan200.computercraft.api.filesystem.IWritableMount) * @see #unmount(String) * @see dan200.computercraft.api.filesystem.IMount */ public String mount( String desiredLocation, IMount mount ); /** * Mount a mount onto the computers' file system in a writable mode.<br> * @param desiredLocation The location on the computercraft's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computercraft. These can be obtained by calling ComputerCraftAPI.createSaveDirMount() or by creating your own objects that implement the IWritableMount interface. * @return The location on the computercraft's file system where you the mount mounted, or null if there was already a file in the desired location. Store this value if you wish to unmount the mount later. * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) * @see #mount(String, IMount) * @see #unmount(String) * @see IMount */ public String mountWritable( String desiredLocation, IWritableMount mount ); /** * Unmounts a directory previously mounted onto the computers file system by mount() or mountWritable().<br> * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to * access it. All directories mounted by a mount or mountWritable are automatically unmounted when the peripheral * is attached if they have not been explicitly unmounted. * @param location The desired location in the computers file system of the directory to unmount. * This must be the location of a directory previously mounted by mount() or mountWritable(), as * indicated by their return value. * @see #mount(String, IMount) * @see #mountWritable(String, IWritableMount) */ public void unmount( String location ); /** * Returns the numerical ID of this computercraft.<br> * This is the same number obtained by calling os.getComputerID() or running the "id" program from lua, * and is guarunteed unique. This number will be positive. * @return The identifier. */ public int getID(); /** * Causes an event to be raised on this computercraft, which the computercraft can respond to by calling * os.pullEvent(). This can be used to notify the computercraft when things happen in the world or to * this peripheral. * @param event A string identifying the type of event that has occurred, this will be * returned as the first value from os.pullEvent(). It is recommended that you * you choose a name that is unique, and recognisable as originating from your * peripheral. eg: If your peripheral type is "button", a suitable event would be * "button_pressed". * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will * be supplied as extra return values to os.pullEvent(). Objects in the array will be converted * to lua data types in the same fashion as the return values of IPeripheral.callMethod().<br> * You may supply null to indicate that no arguments are to be supplied. * @see dan200.computercraft.api.peripheral.IPeripheral#callMethod */ public void queueEvent( String event, Object[] arguments ); /** * Get a string, unique to the computercraft, by which the computercraft refers to this peripheral. * For directly attached peripherals this will be "left","right","front","back",etc, but * for peripherals attached remotely it will be different. It is good practice to supply * this string when raising events to the computercraft, so that the computercraft knows from * which peripheral the event came. * @return A string unique to the computercraft, but not globally. */ public String getAttachmentName(); }
5,444
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IPeripheral.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/peripheral/IPeripheral.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.peripheral; import dan200.computercraft.api.lua.ILuaContext; /** * The interface that defines a peripheral. This should be implemented by the * TileEntity of any common that you wish to be interacted with by * computercraft or turtle. */ public interface IPeripheral { /** * Should return a string that uniquely identifies this type of peripheral. * This can be queried from lua by calling peripheral.getType() * @return A string identifying the type of peripheral. */ public String getType(); /** * Should return an array of strings that identify the methods that this * peripheral exposes to Lua. This will be called once before each attachment, * and should not change when called multiple times. * @return An array of strings representing method names. * @see #callMethod */ public String[] getMethodNames(); /** * This is called when a lua program on an attached computercraft calls peripheral.call() with * one of the methods exposed by getMethodNames().<br> * <br> * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe * when interacting with minecraft objects. * @param computer The interface to the computercraft that is making the call. Remember that multiple * computers can be attached to a peripheral at once. * @param context The context of the currently running lua thread. This can be used to wait for events * or otherwise yield. * @param method An integer identifying which of the methods from getMethodNames() the computercraft * wishes to call. The integer indicates the index into the getMethodNames() table * that corresponds to the string passed into peripheral.call() * @param arguments An array of objects, representing the arguments passed into peripheral.call().<br> * Lua values of type "string" will be represented by Object type String.<br> * Lua values of type "number" will be represented by Object type Double.<br> * Lua values of type "boolean" will be represented by Object type Boolean.<br> * Lua values of any other type will be represented by a null object.<br> * This array will be empty if no arguments are passed. * @return An array of objects, representing values you wish to return to the lua program.<br> * Integers, Doubles, Floats, Strings, Booleans and null be converted to their corresponding lua type.<br> * All other types will be converted to nil.<br> * You may return null to indicate no values should be returned. * @throws Exception If you throw any exception from this function, a lua error will be raised with the * same message as your exception. Use this to throw appropriate errors if the wrong * arguments are supplied to your method. * @see #getMethodNames */ public Object[] callMethod( IComputerAccess computer, ILuaContext context, int method, Object[] arguments ) throws Exception; /** * Is called when canAttachToSide has returned true, and a computercraft is attaching to the peripheral. * This will occur when a peripheral is placed next to an active computercraft, when a computercraft is turned on next to a peripheral, * or when a turtle travels into a square next to a peripheral. * Between calls to attach() and detach(), the attached computercraft can make method calls on the peripheral using peripheral.call(). * This method can be used to keep track of which computers are attached to the peripheral, or to take action when attachment * occurs.<br> * <br> * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe * when interacting with minecraft objects. * @param computer The interface to the computercraft that is being attached. Remember that multiple * computers can be attached to a peripheral at once. * @see #detach */ public void attach( IComputerAccess computer ); /** * Is called when a computercraft is detaching from the peripheral. * This will occur when a computercraft shuts down, when the peripheral is removed while attached to computers, * or when a turtle moves away from a square attached to a peripheral. * This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment * occurs.<br> * <br> * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe * when interacting with minecraft objects. * @param computer The interface to the computercraft that is being detached. Remember that multiple * computers can be attached to a peripheral at once. * @see #detach */ public void detach( IComputerAccess computer ); /** * TODO: Document me */ public boolean equals( IPeripheral other ); }
5,155
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IPeripheralProvider.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.peripheral; import net.minecraft.world.World; /** * This interface is used to create peripheral implementations for blocks * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) */ public interface IPeripheralProvider { /** * Produce an peripheral implementation from a block location. * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) * @return a peripheral, or null if there is not a peripheral here you'd like to handle. */ public IPeripheral getPeripheral( World world, int x, int y, int z, int side ); }
946
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IWritableMount.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/filesystem/IWritableMount.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.filesystem; import java.io.IOException; import java.io.OutputStream; /** * Represents a part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount() or IComputerAccess.mountWritable(), that can also be written to. * Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount(), or you're free to implement it yourselves! * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) * @see dan200.computercraft.api.peripheral.IComputerAccess#mountWritable(String, dan200.computercraft.api.filesystem.IMount) * @see dan200.computercraft.api.filesystem.IMount */ public interface IWritableMount extends IMount { /** * Creates a directory at a given path inside the virtual file system. * @param path A file path in normalised format, relative to the mount location. ie: "programs/mynewprograms" */ public void makeDirectory( String path ) throws IOException; /** * Deletes a directory at a given path inside the virtual file system. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myoldprograms" */ public void delete( String path ) throws IOException; /** * Opens a file with a given path, and returns an outputstream for writing to it. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" * @return a stream for writing to */ public OutputStream openForWrite( String path ) throws IOException; /** * Opens a file with a given path, and returns an outputstream for appending to it. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" * @return a stream for writing to */ public OutputStream openForAppend( String path ) throws IOException; /** * Get the ammount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail once it reaches zero. * @return The ammount of free space, in bytes. */ public long getRemainingSpace() throws IOException; }
2,450
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IMount.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/filesystem/IMount.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.filesystem; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Represents a read only part of a virtual filesystem that can be mounted onto a computercraft using IComputerAccess.mount(). * Ready made implementations of this interface can be created using ComputerCraftAPI.createSaveDirMount() or ComputerCraftAPI.createResourceMount(), or you're free to implement it yourselves! * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(Class, String, String) * @see dan200.computercraft.api.peripheral.IComputerAccess#mount(String, IMount) * @see IWritableMount */ public interface IMount { /** * Returns whether a file with a given path exists or not. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" * @return true if the file exists, false otherwise */ public boolean exists( String path ) throws IOException; /** * Returns whether a file with a given path is a directory or not. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" * @return true if the file exists and is a directory, false otherwise */ public boolean isDirectory( String path ) throws IOException; /** * Returns the file names of all the files in a directory. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms" * @param contents A list of strings. Add all the file names to this list */ public void list( String path, List<String> contents ) throws IOException; /** * Returns the size of a file with a given path, in bytes * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" * @return the size of the file, in bytes */ public long getSize( String path ) throws IOException; /** * Opens a file with a given path, and returns an inputstream representing it's contents. * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram" * @return a stream representing the contents of the file */ public InputStream openForRead( String path ) throws IOException; }
2,602
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
IBundledRedstoneProvider.java
/FileExtraction/Java_unseen/Quetzi_BluePower/src/api/java/dan200/computercraft/api/redstone/IBundledRedstoneProvider.java
/** * This file is part of the public ComputerCraft API - http://www.computercraft.info * Copyright Daniel Ratcliffe, 2011-2014. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ package dan200.computercraft.api.redstone; import net.minecraft.world.World; /** * This interface is used to provide bundled redstone output for blocks * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) */ public interface IBundledRedstoneProvider { /** * Produce an bundled redstone output from a block location. * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) * @return a number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to handle this block */ public int getBundledRedstoneOutput( World world, int x, int y, int z, int side ); }
1,013
Java
.java
Quetzi/BluePower
33
14
6
2014-05-20T12:41:12Z
2014-08-25T01:35:21Z
ExampleUnitTest.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/test/java/com/herudi/exovideo/ExampleUnitTest.java
package com.herudi.exovideo; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
312
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
PlayerActivity.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/main/java/com/herudi/exovideo/PlayerActivity.java
package com.herudi.exovideo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; /** * Created by herudi-sahimar on 24/04/2017. */ public class PlayerActivity extends Activity { PlayerController playerCtrl; private static final String TAG = "PlayerActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); playerCtrl = new PlayerController(this); playerCtrl.fetchVideo( getIntent().getStringExtra("url"), getIntent().getStringExtra("title"), getIntent().getStringExtra("subtitle") ); setContentView(playerCtrl.getPlayerView()); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @Override protected void onStop() { super.onStop(); Log.v(TAG,"onStop()..."); } @Override protected void onStart() { super.onStart(); Log.v(TAG,"onStart()..."); } @Override protected void onResume() { super.onResume(); Log.v(TAG,"onResume()..."); } @Override protected void onPause() { super.onPause(); Log.v(TAG,"onPause()..."); } @Override protected void onDestroy() { super.onDestroy(); Log.v(TAG,"onDestroy()..."); playerCtrl.getPlayer().release(); } }
1,972
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
ExoPlayerIntentPackage.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/main/java/com/herudi/exovideo/ExoPlayerIntentPackage.java
package com.herudi.exovideo; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by herudi-sahimar on 25/04/2017. */ public class ExoPlayerIntentPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new ExoPlayerIntentModule(reactContext)); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
947
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
PlayerView.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/main/java/com/herudi/exovideo/PlayerView.java
package com.herudi.exovideo; import android.content.Context; import android.graphics.Color; import android.support.v4.content.ContextCompat; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.PlaybackControlView; import com.google.android.exoplayer2.ui.SimpleExoPlayerView; /** * Created by herudi-sahimar on 26/04/2017. */ public class PlayerView extends RelativeLayout { private SimpleExoPlayerView simpleExoPlayerView; private ProgressBar progressBar; private TextView textView; public PlayerView(Context context, SimpleExoPlayer player) { super(context); simpleExoPlayerView = new SimpleExoPlayerView(context); progressBar = new ProgressBar(context); textView = new TextView(context); textView.setX(40); textView.setY(20); textView.setTextColor(Color.parseColor("#FFFFFF")); textView.setTextSize(16); textView.setText("By Herudi"); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,100); params.addRule(RelativeLayout.CENTER_IN_PARENT); simpleExoPlayerView.setLayoutParams(new SimpleExoPlayerView.LayoutParams( SimpleExoPlayerView.LayoutParams.MATCH_PARENT, SimpleExoPlayerView.LayoutParams.MATCH_PARENT )); setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT )); setBackgroundColor(ContextCompat.getColor(context, android.R.color.black)); addView(simpleExoPlayerView); addView(textView); addView(progressBar,params); simpleExoPlayerView.setUseController(true); simpleExoPlayerView.requestFocus(); simpleExoPlayerView.setPlayer(player); simpleExoPlayerView.setControllerVisibilityListener(new PlaybackControlView.VisibilityListener() { @Override public void onVisibilityChange(int visibility) { if (visibility==0){ textView.setVisibility(VISIBLE); }else { textView.setVisibility(GONE); } } }); } public PlayerView(Context context) { super(context); } public ProgressBar getProgressBar() { return progressBar; } public TextView getTextView() { return textView; } }
2,578
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
ExoPlayerIntentModule.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/main/java/com/herudi/exovideo/ExoPlayerIntentModule.java
package com.herudi.exovideo; import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; /** * Created by herudi-sahimar on 25/04/2017. */ public class ExoPlayerIntentModule extends ReactContextBaseJavaModule implements ActivityEventListener { public final int TAG = 1; public ExoPlayerIntentModule(ReactApplicationContext reactContext) { super(reactContext); } @ReactMethod public void showVideoPlayer(String url, String title, String sub) { Activity currentActivity = getCurrentActivity(); if (currentActivity != null) { Intent i = new Intent(this.getReactApplicationContext(),PlayerActivity.class); i.putExtra("url", url); i.putExtra("title", title); i.putExtra("subtitle", sub); currentActivity.startActivityForResult(i, TAG); } } @Override public String getName() { return "ExoPlayerManager"; } @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { if (requestCode == TAG) { getCurrentActivity().finish(); } } @Override public void onNewIntent(Intent intent) { } }
1,466
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
PlayerController.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/main/java/com/herudi/exovideo/PlayerController.java
package com.herudi.exovideo; import android.content.Context; import android.net.Uri; import android.view.View; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.LoadControl; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory; import com.google.android.exoplayer2.extractor.ExtractorsFactory; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.MergingMediaSource; import com.google.android.exoplayer2.source.SingleSampleMediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.upstream.BandwidthMeter; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.TransferListener; import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.Util; /** * Created by herudi-sahimar on 26/04/2017. */ public class PlayerController { private String TAG_NAME = "rnexoplayer"; private Uri videoUri; private Uri subtitleUri; private BandwidthMeter bandwidthMeter; private ExtractorsFactory extractorsFactory; private TrackSelection.Factory trackSelectionFactory; private DataSource.Factory dataSourceFactory; private TrackSelector trackSelector; private LoadControl loadControl; private SimpleExoPlayer player; private PlayerView playerView; public PlayerController(Context context) { this.bandwidthMeter = new DefaultBandwidthMeter(); this.loadControl = new DefaultLoadControl(); this.extractorsFactory = new DefaultExtractorsFactory(); this.trackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter); this.dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context.getApplicationContext(), TAG_NAME), (TransferListener<? super DataSource>) bandwidthMeter); this.trackSelector = new DefaultTrackSelector(trackSelectionFactory); this.player = ExoPlayerFactory.newSimpleInstance(context, this.trackSelector, this.loadControl); this.playerView = new PlayerView(context,this.player); } public PlayerView getPlayerView() { return playerView; } public SimpleExoPlayer getPlayer() { return player; } public void EventListener(){ this.player.addListener(new ExoPlayer.EventListener() { @Override public void onTimelineChanged(Timeline timeline, Object manifest) { } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { } @Override public void onLoadingChanged(boolean isLoading) { } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { switch (playbackState){ case 2:{ playerView.getProgressBar().setVisibility(View.VISIBLE); }break; case 3:{ playerView.getProgressBar().setVisibility(View.GONE); }break; case 4:{ playerView.getProgressBar().setVisibility(View.GONE); }break; } } @Override public void onPlayerError(ExoPlaybackException error) { } @Override public void onPositionDiscontinuity() { } }); this.player.setPlayWhenReady(true); } public void fetchVideo(String uri,String title, String sub) { if (title!=null){ this.playerView.getTextView().setText(title); } this.setVideoUri(Uri.parse(uri)); if (sub!=null){ this.setSubtitleUri(Uri.parse(sub)); this.player.prepare(this.getMergingMediaSource()); }else{ this.player.prepare(this.getMediaSource()); } this.EventListener(); } public Uri getVideoUri() { return videoUri; } public void setVideoUri(Uri videoUri) { this.videoUri = videoUri; } public Uri getSubtitleUri() { return subtitleUri; } public void setSubtitleUri(Uri subtitleUri) { this.subtitleUri = subtitleUri; } public ExtractorsFactory getExtractorsFactory() { return extractorsFactory; } public DataSource.Factory getDataSourceFactory() { return dataSourceFactory; } public MediaSource getMediaSource(){ return new ExtractorMediaSource(this.getVideoUri(),this.getDataSourceFactory(), this.getExtractorsFactory(), null, null); } public MediaSource getMediaSourceSubtitle(){ return new SingleSampleMediaSource(this.getSubtitleUri(),this.getDataSourceFactory(), this.getFormat(), C.TIME_UNSET); } public Format getFormat(){ return Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP,null, Format.NO_VALUE, Format.NO_VALUE, "indonesia", null); } public MergingMediaSource getMergingMediaSource(){ return new MergingMediaSource(this.getMediaSource(), this.getMediaSourceSubtitle()); } }
6,212
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
ApplicationTest.java
/FileExtraction/Java_unseen/herudi_react-native-exoplayer-intent-video/android/src/androidTest/java/com/herudi/exovideo/ApplicationTest.java
package com.herudi.exovideo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
350
Java
.java
herudi/react-native-exoplayer-intent-video
15
4
0
2017-04-25T09:08:39Z
2017-04-27T01:36:34Z
MainActivity.java
/FileExtraction/Java_unseen/xtools-at_Android-PWA-Wrapper/app/src/main/java/at/xtools/pwawrapper/MainActivity.java
package at.xtools.pwawrapper; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import at.xtools.pwawrapper.ui.UIManager; import at.xtools.pwawrapper.webview.WebViewHelper; public class MainActivity extends AppCompatActivity { // Globals private UIManager uiManager; private WebViewHelper webViewHelper; private boolean intentHandled = false; @Override protected void onCreate(Bundle savedInstanceState) { // Setup Theme setTheme(R.style.AppTheme_NoActionBar); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Setup Helpers uiManager = new UIManager(this); webViewHelper = new WebViewHelper(this, uiManager); // Setup App webViewHelper.setupWebView(); uiManager.changeRecentAppsIcon(); // Check for Intents try { Intent i = getIntent(); String intentAction = i.getAction(); // Handle URLs opened in Browser if (!intentHandled && intentAction != null && intentAction.equals(Intent.ACTION_VIEW)){ Uri intentUri = i.getData(); String intentText = ""; if (intentUri != null){ intentText = intentUri.toString(); } // Load up the URL specified in the Intent if (!intentText.equals("")) { intentHandled = true; webViewHelper.loadIntentUrl(intentText); } } else { // Load up the Web App webViewHelper.loadHome(); } } catch (Exception e) { // Load up the Web App webViewHelper.loadHome(); } } @Override protected void onPause() { webViewHelper.onPause(); super.onPause(); } @Override protected void onResume() { webViewHelper.onResume(); // retrieve content from cache primarily if not connected webViewHelper.forceCacheIfOffline(); super.onResume(); } // Handle back-press in browser @Override public void onBackPressed() { if (!webViewHelper.goBack()) { super.onBackPressed(); } } }
2,397
Java
.java
xtools-at/Android-PWA-Wrapper
341
133
14
2017-10-04T16:41:22Z
2021-12-29T22:38:52Z
Constants.java
/FileExtraction/Java_unseen/xtools-at_Android-PWA-Wrapper/app/src/main/java/at/xtools/pwawrapper/Constants.java
package at.xtools.pwawrapper; public class Constants { public Constants(){} // Root page public static String WEBAPP_URL = "https://www.leasingrechnen.at/"; public static String WEBAPP_HOST = "leasingrechnen.at"; // used for checking Intent-URLs // User Agent tweaks public static boolean POSTFIX_USER_AGENT = true; // set to true to append USER_AGENT_POSTFIX to user agent public static boolean OVERRIDE_USER_AGENT = false; // set to true to use USER_AGENT instead of default one public static String USER_AGENT_POSTFIX = "AndroidApp"; // useful for identifying traffic, e.g. in Google Analytics public static String USER_AGENT = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36"; // Constants // window transition duration in ms public static int SLIDE_EFFECT = 2200; // show your app when the page is loaded XX %. // lower it, if you've got server-side rendering (e.g. to 35), // bump it up to ~98 if you don't have SSR or a loading screen in your web app public static int PROGRESS_THRESHOLD = 65; // turn on/off mixed content (both https+http within one page) for API >= 21 public static boolean ENABLE_MIXED_CONTENT = true; }
1,290
Java
.java
xtools-at/Android-PWA-Wrapper
341
133
14
2017-10-04T16:41:22Z
2021-12-29T22:38:52Z
WebViewHelper.java
/FileExtraction/Java_unseen/xtools-at_Android-PWA-Wrapper/app/src/main/java/at/xtools/pwawrapper/webview/WebViewHelper.java
package at.xtools.pwawrapper.webview; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Message; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import at.xtools.pwawrapper.Constants; import at.xtools.pwawrapper.R; import at.xtools.pwawrapper.ui.UIManager; public class WebViewHelper { // Instance variables private Activity activity; private UIManager uiManager; private WebView webView; private WebSettings webSettings; public WebViewHelper(Activity activity, UIManager uiManager) { this.activity = activity; this.uiManager = uiManager; this.webView = (WebView) activity.findViewById(R.id.webView); this.webSettings = webView.getSettings(); } /** * Simple helper method checking if connected to Network. * Doesn't check for actual Internet connection! * @return {boolean} True if connected to Network. */ private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if (networkInfo != null && networkInfo.isConnected()) { // Wifi or Mobile Network is present and connected isAvailable = true; } return isAvailable; } // manipulate cache settings to make sure our PWA gets updated private void useCache(Boolean use) { if (use) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } else { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } } // public method changing cache settings according to network availability. // retrieve content from cache primarily if not connected, // allow fetching from web too otherwise to get updates. public void forceCacheIfOffline() { useCache(!isNetworkAvailable()); } // handles initial setup of webview public void setupWebView() { // accept cookies CookieManager.getInstance().setAcceptCookie(true); // enable JS webSettings.setJavaScriptEnabled(true); // must be set for our js-popup-blocker: webSettings.setSupportMultipleWindows(true); // PWA settings if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { webSettings.setDatabasePath(activity.getApplicationContext().getFilesDir().getAbsolutePath()); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { webSettings.setAppCacheMaxSize(Long.MAX_VALUE); } webSettings.setDomStorageEnabled(true); webSettings.setAppCachePath(activity.getApplicationContext().getCacheDir().getAbsolutePath()); webSettings.setAppCacheEnabled(true); webSettings.setDatabaseEnabled(true); // enable mixed content mode conditionally if (Constants.ENABLE_MIXED_CONTENT && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE); } // retrieve content from cache primarily if not connected forceCacheIfOffline(); // set User Agent if (Constants.OVERRIDE_USER_AGENT || Constants.POSTFIX_USER_AGENT) { String userAgent = webSettings.getUserAgentString(); if (Constants.OVERRIDE_USER_AGENT) { userAgent = Constants.USER_AGENT; } if (Constants.POSTFIX_USER_AGENT) { userAgent = userAgent + " " + Constants.USER_AGENT_POSTFIX; } webSettings.setUserAgentString(userAgent); } // enable HTML5-support webView.setWebChromeClient(new WebChromeClient() { //simple yet effective redirect/popup blocker @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { Message href = view.getHandler().obtainMessage(); view.requestFocusNodeHref(href); final String popupUrl = href.getData().getString("url"); if (popupUrl != null) { //it's null for most rouge browser hijack ads webView.loadUrl(popupUrl); return true; } return false; } // update ProgressBar @Override public void onProgressChanged(WebView view, int newProgress) { uiManager.setLoadingProgress(newProgress); super.onProgressChanged(view, newProgress); } }); // Set up Webview client webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); handleUrlLoad(view, url); } // handle loading error by showing the offline screen @Deprecated @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { handleLoadError(errorCode); } } @TargetApi(Build.VERSION_CODES.M) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // new API method calls this on every error for each resource. // we only want to interfere if the page itself got problems. String url = request.getUrl().toString(); if (view.getUrl().equals(url)) { handleLoadError(error.getErrorCode()); } } } }); } // Lifecycle callbacks public void onPause() { webView.onPause(); } public void onResume() { webView.onResume(); } // show "no app found" dialog private void showNoAppDialog(Activity thisActivity) { new AlertDialog.Builder(thisActivity) .setTitle(R.string.noapp_heading) .setMessage(R.string.noapp_description) .show(); } // handle load errors private void handleLoadError(int errorCode) { if (errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME) { uiManager.setOffline(true); } else { // Unsupported Scheme, recover new Handler().postDelayed(new Runnable() { @Override public void run() { goBack(); } }, 100); } } // handle external urls private boolean handleUrlLoad(WebView view, String url) { // prevent loading content that isn't ours if (!url.startsWith(Constants.WEBAPP_URL)) { // stop loading // stopping only would cause the PWA to freeze, need to reload the app as a workaround view.stopLoading(); view.reload(); // open external URL in Browser/3rd party apps instead try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (intent.resolveActivity(activity.getPackageManager()) != null) { activity.startActivity(intent); } else { showNoAppDialog(activity); } } catch (Exception e) { showNoAppDialog(activity); } // return value for shouldOverrideUrlLoading return true; } else { // let WebView load the page! // activate loading animation screen uiManager.setLoading(true); // return value for shouldOverrideUrlLoading return false; } } // handle back button press public boolean goBack() { if (webView.canGoBack()) { webView.goBack(); return true; } return false; } // load app startpage public void loadHome() { webView.loadUrl(Constants.WEBAPP_URL); } // load URL from intent public void loadIntentUrl(String url) { if (!url.equals("") && url.contains(Constants.WEBAPP_HOST)) { webView.loadUrl(url); } else { // Fallback loadHome(); } } }
9,233
Java
.java
xtools-at/Android-PWA-Wrapper
341
133
14
2017-10-04T16:41:22Z
2021-12-29T22:38:52Z
UIManager.java
/FileExtraction/Java_unseen/xtools-at_Android-PWA-Wrapper/app/src/main/java/at/xtools/pwawrapper/ui/UIManager.java
package at.xtools.pwawrapper.ui; import android.app.Activity; import android.app.ActivityManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.util.TypedValue; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.ProgressBar; import at.xtools.pwawrapper.Constants; import at.xtools.pwawrapper.R; public class UIManager { // Instance variables private Activity activity; private WebView webView; private ProgressBar progressSpinner; private ProgressBar progressBar; private LinearLayout offlineContainer; private boolean pageLoaded = false; public UIManager(Activity activity) { this.activity = activity; this.progressBar = (ProgressBar) activity.findViewById(R.id.progressBarBottom); this.progressSpinner = (ProgressBar) activity.findViewById(R.id.progressSpinner); this.offlineContainer = (LinearLayout) activity.findViewById(R.id.offlineContainer); this.webView = (WebView) activity.findViewById(R.id.webView); // set click listener for offline-screen offlineContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.loadUrl(Constants.WEBAPP_URL); setOffline(false); } }); } // Set Loading Progress for ProgressBar public void setLoadingProgress(int progress) { // set progress in UI if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { progressBar.setProgress(progress, true); } else { progressBar.setProgress(progress); } // hide ProgressBar if not applicable if (progress >= 0 && progress < 100) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.INVISIBLE); } // get app screen back if loading is almost complete if (progress >= Constants.PROGRESS_THRESHOLD && !pageLoaded) { setLoading(false); } } // Show loading animation screen while app is loading/caching the first time public void setLoading(boolean isLoading) { if (isLoading) { progressSpinner.setVisibility(View.VISIBLE); webView.animate().translationX(Constants.SLIDE_EFFECT).alpha(0.5F).setInterpolator(new AccelerateInterpolator()).start(); } else { webView.setTranslationX(Constants.SLIDE_EFFECT * -1); webView.animate().translationX(0).alpha(1F).setInterpolator(new DecelerateInterpolator()).start(); progressSpinner.setVisibility(View.INVISIBLE); } pageLoaded = !isLoading; } // handle visibility of offline screen public void setOffline(boolean offline) { if (offline) { setLoadingProgress(100); webView.setVisibility(View.INVISIBLE); offlineContainer.setVisibility(View.VISIBLE); } else { webView.setVisibility(View.VISIBLE); offlineContainer.setVisibility(View.INVISIBLE); } } // set icon in recent activity view to a white one to be visible in the app bar public void changeRecentAppsIcon() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Bitmap iconWhite = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_appbar); TypedValue typedValue = new TypedValue(); Resources.Theme theme = activity.getTheme(); theme.resolveAttribute(R.attr.colorPrimary, typedValue, true); int color = typedValue.data; ActivityManager.TaskDescription description = new ActivityManager.TaskDescription( activity.getResources().getString(R.string.app_name), iconWhite, color ); activity.setTaskDescription(description); iconWhite.recycle(); } } }
4,223
Java
.java
xtools-at/Android-PWA-Wrapper
341
133
14
2017-10-04T16:41:22Z
2021-12-29T22:38:52Z
Stormlight.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/Stormlight.java
package com.legobmw99.stormlight; import com.legobmw99.stormlight.modules.combat.CombatSetup; import com.legobmw99.stormlight.modules.powers.PowersSetup; import com.legobmw99.stormlight.modules.powers.client.PowersClientSetup; import com.legobmw99.stormlight.modules.powers.command.StormlightCommand; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.network.Network; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.CreativeModeTabEvent; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Mod(Stormlight.MODID) public class Stormlight { public static final String MODID = "stormlight"; public static final Logger LOGGER = LogManager.getLogger(); public static Stormlight instance; public Stormlight() { instance = this; var modBus = FMLJavaModLoadingContext.get().getModEventBus(); modBus.addListener(Stormlight::init); modBus.addListener(Stormlight::clientInit); modBus.addListener(WorldSetup::onEntityAttribute); modBus.addListener(SurgebindingCapability::registerCapability); modBus.addListener(WorldSetup::registerEntityModels); modBus.addListener(WorldSetup::registerEntityRenders); modBus.addListener(Stormlight::registerCreativeTabs); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { modBus.addListener(PowersClientSetup::registerKeyBinding); }); MinecraftForge.EVENT_BUS.addListener(Stormlight::registerCommands); PowersSetup.register(); WorldSetup.register(); CombatSetup.register(); } public static void clientInit(final FMLClientSetupEvent e) { PowersClientSetup.clientInit(e); CombatSetup.clientInit(e); } public static void registerCommands(final RegisterCommandsEvent e) { StormlightCommand.register(e.getDispatcher()); } public static void init(final FMLCommonSetupEvent e) { PowersSetup.init(e); e.enqueueWork(Network::registerPackets); } public static CreativeModeTab stormlight_group; public static void registerCreativeTabs(CreativeModeTabEvent.Register event) { stormlight_group = event.registerCreativeModeTab(new ResourceLocation(MODID, "main_tab"), builder -> builder.icon(() -> { int type = (int) (System.currentTimeMillis() / (1000 * 60)) % 10; return new ItemStack(CombatSetup.SHARDBLADES.get(type).get()); }).title(Component.translatable("tabs.stormlight.main_tab")).displayItems((featureFlags, output) -> { for (var shardblade : CombatSetup.SHARDBLADES) { output.accept(shardblade.get()); } for (var sphere : WorldSetup.DUN_SPHERES) { output.accept(sphere.get()); } for (var sphere : WorldSetup.INFUSED_SPHERES) { output.accept(sphere.get()); } output.accept(WorldSetup.SPREN_SPAWN_EGG.get()); })); } }
3,722
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Languages.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/datagen/Languages.java
package com.legobmw99.stormlight.datagen; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.combat.CombatSetup; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.util.Gemstone; import com.legobmw99.stormlight.util.Order; import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; import net.minecraftforge.common.data.LanguageProvider; public class Languages extends LanguageProvider { public Languages(PackOutput gen) { super(gen, Stormlight.MODID, "en_us"); } private static String toTitleCase(String in) { return in.substring(0, 1).toUpperCase() + in.substring(1); } @Override protected void addTranslations() { add("tabs.stormlight.main_tab", "Stormlight"); for (Order o : Order.values()) { add(CombatSetup.SHARDBLADES.get(o.getIndex()).get(), "Shardblade of the " + toTitleCase(o.getName())); add("orders." + o.getName(), toTitleCase(o.getName())); } for (Gemstone g : Gemstone.values()) { add(WorldSetup.DUN_SPHERES.get(g.getIndex()).get(), "Dun " + toTitleCase(g.getName()) + " Sphere"); add(WorldSetup.INFUSED_SPHERES.get(g.getIndex()).get(), toTitleCase(g.getName()) + " Sphere"); add("gemstone." + g.getName(), toTitleCase(g.getName())); } add(WorldSetup.ADHESION_BLOCK.get(), "Adhesion"); add(WorldSetup.SPREN_SPAWN_EGG.get(), "Spren Spawn Egg"); add("entity.stormlight.spren", "Spren"); add("item.stormlight.shardblade.lore", "This sword seems to glow with strange light"); add("effect.stormlight.stormlight", "Stormlight"); add("effect.stormlight.sticking", "Sticking"); add("effect.stormlight.slicking", "Slicking"); add("effect.stormlight.cohesion", "Cohesion"); add("effect.stormlight.tension", "Tension"); add("effect.stormlight.gravitation", "Gravitation"); add("surge.cohesion.stoneshaping", "Stoneshaping"); add("surge.cohesion.soulcasting", "Soulcasting"); add("commands.stormlight.getorder", "%s has order %s"); add("commands.stormlight.setorder", "%s set to order %s"); add("commands.stormlight.getideal", "%s has ideal %s"); add("commands.stormlight.setideal", "%s set to ideal %s"); add("commands.stormlight.unrecognized_order", "Unrecognized order %s"); add("commands.stormlight.unrecognized_ideal", "Unrecognized ideal %s"); add("key.categories.stormlight", "Stormlight"); add("key.blade", "Summon Shardblade"); add("key.firstSurge", "First Surge"); add("key.secondSurge", "Second Surge"); } @Override public String getName() { return "Stormlight Language"; } }
2,844
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Recipes.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/datagen/Recipes.java
package com.legobmw99.stormlight.datagen; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.world.WorldSetup; import net.minecraft.advancements.critereon.InventoryChangeTrigger; import net.minecraft.data.PackOutput; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.data.recipes.RecipeCategory; import net.minecraft.data.recipes.RecipeProvider; import net.minecraft.data.recipes.ShapedRecipeBuilder; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.ItemLike; import net.minecraftforge.common.Tags; import net.minecraftforge.registries.ForgeRegistries; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Consumer; public class Recipes extends RecipeProvider { private final Map<Character, Ingredient> defaultIngredients = new HashMap<>(); public Recipes(PackOutput generatorIn) { super(generatorIn); add('g', Tags.Items.GLASS); add('d', Items.DIAMOND); add('e', Items.EMERALD); add('q', Items.QUARTZ); } @Override protected void buildRecipes(Consumer<FinishedRecipe> consumer) { buildShaped(consumer, RecipeCategory.MISC, WorldSetup.DUN_SPHERES.get(0).get(), 4, Items.DIAMOND, "ggg", "gdg", "ggg"); buildShaped(consumer, RecipeCategory.MISC, WorldSetup.DUN_SPHERES.get(1).get(), 4, Items.EMERALD, "ggg", "geg", "ggg"); buildShaped(consumer, RecipeCategory.MISC, WorldSetup.DUN_SPHERES.get(2).get(), 4, Items.QUARTZ, "ggg", "gqg", "ggg"); } protected void buildShaped(Consumer<FinishedRecipe> consumer, RecipeCategory cat, ItemLike result, int count, Item criterion, String... lines) { Stormlight.LOGGER.debug("Creating Shaped Recipe for " + ForgeRegistries.ITEMS.getKey(result.asItem())); ShapedRecipeBuilder builder = ShapedRecipeBuilder.shaped(cat, result, count); builder.unlockedBy("has_" + ForgeRegistries.ITEMS.getKey(criterion).getPath(), InventoryChangeTrigger.TriggerInstance.hasItems(criterion)); Set<Character> characters = new HashSet<>(); for (String line : lines) { builder.pattern(line); line.chars().forEach(value -> characters.add((char) value)); } for (Character c : characters) { if (this.defaultIngredients.containsKey(c)) { builder.define(c, this.defaultIngredients.get(c)); } } builder.save(consumer); } protected void add(char c, TagKey<Item> itemTag) { this.defaultIngredients.put(c, Ingredient.of(itemTag)); } protected void add(char c, ItemLike itemProvider) { this.defaultIngredients.put(c, Ingredient.of(itemProvider)); } protected void add(char c, Ingredient ingredient) { this.defaultIngredients.put(c, ingredient); } }
3,022
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
DataGenerators.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/datagen/DataGenerators.java
package com.legobmw99.stormlight.datagen; import net.minecraftforge.data.event.GatherDataEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class DataGenerators { @SubscribeEvent public static void gatherData(GatherDataEvent event) { var generator = event.getGenerator(); var packOutput = generator.getPackOutput(); // var lookup = event.getLookupProvider(); var fileHelper = event.getExistingFileHelper(); generator.addProvider(event.includeServer(), new Recipes(packOutput)); // BlockTags blocktags = new BlockTags(packOutput, lookup, fileHelper); // generator.addProvider(event.includeServer(), blocktags); // generator.addProvider(event.includeServer(), new ItemTags(packOutput, lookup, blocktags, fileHelper)); // generator.addProvider(event.includeServer(), new ForgeAdvancementProvider(packOutput, lookup, fileHelper, List.of(new Advancements()))); generator.addProvider(event.includeClient(), new Languages(packOutput)); generator.addProvider(event.includeClient(), new BlockStates(packOutput, fileHelper)); generator.addProvider(event.includeClient(), new ItemModels(packOutput, fileHelper)); } }
1,338
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
ItemModels.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/datagen/ItemModels.java
package com.legobmw99.stormlight.datagen; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.util.Gemstone; import com.legobmw99.stormlight.util.Order; import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.model.generators.ItemModelProvider; import net.minecraftforge.client.model.generators.ModelFile; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.registries.ForgeRegistries; public class ItemModels extends ItemModelProvider { public ItemModels(PackOutput generator, ExistingFileHelper existingFileHelper) { super(generator, Stormlight.MODID, existingFileHelper); } @Override protected void registerModels() { parentedBlock(WorldSetup.ADHESION_BLOCK.get(), "block/adhesion_light"); for (Order o : Order.values()) { itemShield(o, "item/" + o.getSingularName() + "_shield"); itemShardblade(o, "item/" + o.getSingularName() + "_shardblade"); } for (Gemstone g : Gemstone.values()) { itemGenerated(WorldSetup.DUN_SPHERES.get(g.getIndex()).get(), "item/dun_" + g.getName() + "_sphere"); itemGenerated(WorldSetup.INFUSED_SPHERES.get(g.getIndex()).get(), "item/infused_" + g.getName() + "_sphere"); } getBuilder(ForgeRegistries.ITEMS.getKey(WorldSetup.SPREN_SPAWN_EGG.get()).getPath()).parent(getExistingFile(mcLoc("item/template_spawn_egg"))); } public void itemGenerated(Item item, String texture) { Stormlight.LOGGER.debug("Creating Item Model for " + ForgeRegistries.ITEMS.getKey(item)); getBuilder(ForgeRegistries.ITEMS.getKey(item).getPath()).parent(getExistingFile(mcLoc("item/generated"))).texture("layer0", modLoc(texture)); } public void parentedBlock(Block block, String model) { Stormlight.LOGGER.debug("Creating Item Model for " + ForgeRegistries.BLOCKS.getKey(block)); getBuilder(ForgeRegistries.BLOCKS.getKey(block).getPath()).parent(new ModelFile.UncheckedModelFile(modLoc(model))); } public void itemHandheld(Item item, String texture) { Stormlight.LOGGER.debug("Creating Item Model for " + ForgeRegistries.ITEMS.getKey(item)); getBuilder(ForgeRegistries.ITEMS.getKey(item).getPath()).parent(getExistingFile(mcLoc("item/handheld"))).texture("layer0", modLoc(texture)); } public void itemShardblade(Order order, String texture) { Stormlight.LOGGER.debug("Creating Shardblade Model for " + order.getSingularName()); getBuilder(order.getSingularName() + "_shardblade").parent(getExistingFile(modLoc("item/shardblade"))) .texture("layer0", modLoc(texture)) .override() .predicate(new ResourceLocation(Stormlight.MODID, "shielding"), 1.0F) .model(getExistingFile(modLoc("item/" + order.getSingularName() + "_shield"))); } public void itemShield(Order order, String texture) { Stormlight.LOGGER.debug("Creating Shield Model for " + order.getSingularName()); getBuilder(order.getSingularName() + "_shield").parent(getExistingFile(modLoc("item/shield"))).texture("layer0", modLoc(texture)); } @Override public String getName() { return "Stormlight Item Models"; } }
3,527
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
BlockStates.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/datagen/BlockStates.java
package com.legobmw99.stormlight.datagen; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.powers.block.AdhesionBlock; import com.legobmw99.stormlight.modules.world.WorldSetup; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Direction; import net.minecraft.data.PackOutput; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraftforge.client.model.generators.BlockStateProvider; import net.minecraftforge.client.model.generators.ModelFile; import net.minecraftforge.client.model.generators.VariantBlockStateBuilder; import net.minecraftforge.common.data.ExistingFileHelper; import javax.annotation.Nonnull; public class BlockStates extends BlockStateProvider { public BlockStates(PackOutput gen, ExistingFileHelper exFileHelper) { super(gen, Stormlight.MODID, exFileHelper); } @Override protected void registerStatesAndModels() { createAdhesionLayer(); } private void createAdhesionLayer() { ModelFile layer = models() .withExistingParent("stormlight:adhesion_light", modLoc("block/light")) .texture("texture", modLoc("block/adhesion_light")) .texture("particle", blockTexture(Blocks.SEA_LANTERN)) .renderType("translucent"); VariantBlockStateBuilder builder = getVariantBuilder(WorldSetup.ADHESION_BLOCK.get()); for (AttachFace face : AdhesionBlock.FACE.getPossibleValues()) { int xangle = (face == AttachFace.CEILING) ? 180 : (face == AttachFace.WALL) ? 90 : 0; boolean uvlock = face == AttachFace.WALL; for (Direction dir : AdhesionBlock.FACING.getPossibleValues()) { int yangle = (int) dir.toYRot(); yangle = face != AttachFace.CEILING ? (yangle + 180) % 360 : yangle; builder .partialState() .with(AdhesionBlock.FACE, face) .with(AdhesionBlock.FACING, dir) .modelForState() .modelFile(layer) .uvLock(uvlock) .rotationY(yangle) .rotationX(xangle) .addModel(); } } } @Nonnull @Override public String getName() { return "Stormlight blockstates"; } }
2,479
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Network.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/network/Network.java
package com.legobmw99.stormlight.network; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.api.ISurgebindingData; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.network.packets.SummonBladePacket; import com.legobmw99.stormlight.network.packets.SurgePacket; import com.legobmw99.stormlight.network.packets.SurgebindingDataPacket; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; public class Network { private static final String VERSION = "1.1"; public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Stormlight.MODID, "networking"), () -> VERSION, VERSION::equals, VERSION::equals); private static int index = 0; private static int nextIndex() { return index++; } public static void registerPackets() { INSTANCE.registerMessage(nextIndex(), SurgebindingDataPacket.class, SurgebindingDataPacket::encode, SurgebindingDataPacket::decode, SurgebindingDataPacket::handle); INSTANCE.registerMessage(nextIndex(), SummonBladePacket.class, (self, buf) -> {}, buf -> new SummonBladePacket(), SummonBladePacket::handle); INSTANCE.registerMessage(nextIndex(), SurgePacket.class, SurgePacket::encode, SurgePacket::decode, SurgePacket::handle); } public static void sendToServer(Object msg) { INSTANCE.sendToServer(msg); } public static void sendTo(Object msg, ServerPlayer player) { if (!(player instanceof FakePlayer)) { INSTANCE.sendTo(msg, player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); } } public static void sendTo(Object msg, PacketDistributor.PacketTarget target) { INSTANCE.send(target, msg); } public static void sync(Player player) { player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> sync(data, player)); } public static void sync(ISurgebindingData cap, Player player) { sync(new SurgebindingDataPacket(cap, player), player); } public static void sync(Object msg, Player player) { sendTo(msg, PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player)); } }
2,663
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SurgePacket.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/network/packets/SurgePacket.java
package com.legobmw99.stormlight.network.packets; import com.legobmw99.stormlight.modules.powers.PowersSetup; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.util.Surge; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkDirection; import net.minecraftforge.network.NetworkEvent; import javax.annotation.Nullable; import java.util.function.Supplier; public class SurgePacket { private final Surge surge; private final BlockPos looking; private final boolean shiftHeld; public SurgePacket(Surge surge, @Nullable BlockPos looking, boolean shiftHeld) { this.surge = surge; this.looking = looking; this.shiftHeld = shiftHeld; } public static SurgePacket decode(FriendlyByteBuf buf) { return new SurgePacket(buf.readEnum(Surge.class), buf.readBoolean() ? buf.readBlockPos() : null, buf.readBoolean()); } public void encode(FriendlyByteBuf buf) { buf.writeEnum(surge); boolean hasBlock = looking != null; buf.writeBoolean(hasBlock); if (hasBlock) { buf.writeBlockPos(looking); } buf.writeBoolean(shiftHeld); } public void handle(Supplier<NetworkEvent.Context> ctx) { if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) { ctx.get().enqueueWork(() -> { if (looking != null) { surge.displayEffect(looking, shiftHeld); } }); ctx.get().setPacketHandled(true); } else if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender(); if (player != null) { if (player.getCapability(SurgebindingCapability.PLAYER_CAP).filter(data -> data.isKnight() && data.canUseSurge(surge)).isPresent() && player.hasEffect(PowersSetup.STORMLIGHT.get())) { surge.fire(player, looking, shiftHeld); } } }); ctx.get().setPacketHandled(true); } } }
2,313
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SummonBladePacket.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/network/packets/SummonBladePacket.java
package com.legobmw99.stormlight.network.packets; import com.legobmw99.stormlight.modules.combat.item.ShardbladeItem; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.network.Network; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class SummonBladePacket { public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayer player = ctx.get().getSender(); if (player != null) { player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> { if (data.isBladeStored()) { if (data.earnedBlade()) { data.addBladeToInventory(player); // TODO when spren, hide them } } else if (player.getMainHandItem().getItem() instanceof ShardbladeItem && ((ShardbladeItem) player.getMainHandItem().getItem()).getOrder() == data.getOrder()) { data.storeBlade(player.getMainHandItem()); player.getInventory().setItem(player.getInventory().selected, ItemStack.EMPTY); } Network.sync(data, player); }); } }); ctx.get().setPacketHandled(true); } }
1,530
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SurgebindingDataPacket.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/network/packets/SurgebindingDataPacket.java
package com.legobmw99.stormlight.network.packets; import com.legobmw99.stormlight.api.ISurgebindingData; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.UUID; import java.util.function.Supplier; public class SurgebindingDataPacket { private final CompoundTag nbt; private final UUID uuid; public SurgebindingDataPacket(ISurgebindingData data, Player player) { this.uuid = player.getUUID(); this.nbt = (data != null) ? data.save() : new CompoundTag(); } private SurgebindingDataPacket(CompoundTag data, UUID uuid) { this.nbt = data; this.uuid = uuid; } public static SurgebindingDataPacket decode(FriendlyByteBuf buf) { return new SurgebindingDataPacket(buf.readNbt(), buf.readUUID()); } public void encode(FriendlyByteBuf buf) { buf.writeNbt(this.nbt); buf.writeUUID(this.uuid); } public void handle(Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { Player player = Minecraft.getInstance().level.getPlayerByUUID(this.uuid); if (player != null && SurgebindingCapability.PLAYER_CAP != null) { player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(cap -> cap.load(this.nbt)); } }); ctx.get().setPacketHandled(true); } }
1,603
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
ISurgebindingData.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
package com.legobmw99.stormlight.api; import com.legobmw99.stormlight.util.Ideal; import com.legobmw99.stormlight.util.Order; import com.legobmw99.stormlight.util.Surge; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.UUID; public interface ISurgebindingData { @Nullable Order getOrder(); void setOrder(Order order); Ideal getIdeal(); void setIdeal(Ideal ideal); void storeBlade(@Nonnull ItemStack blade); boolean isBladeStored(); boolean addBladeToInventory(Player player); UUID getSprenID(); void setSprenID(UUID sprenID); default boolean isKnight() { return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR; } default Ideal progressIdeal() { Ideal next = getIdeal().progressIdeal(); setIdeal(next); return next; } default Ideal regressIdeal() { Ideal next = getIdeal().regressIdeal(); setIdeal(next); return next; } default boolean earnedBlade() { Order order = getOrder(); return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0; } default boolean canUseSurge(Surge surge) { Order order = getOrder(); Ideal ideal = getIdeal(); return order != null && ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0)); } void load(CompoundTag nbt); CompoundTag save(); }
1,700
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
CombatSetup.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/combat/CombatSetup.java
package com.legobmw99.stormlight.modules.combat; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.combat.item.ShardbladeItem; import com.legobmw99.stormlight.util.Order; import net.minecraft.client.renderer.item.ItemProperties; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.ArrayList; import java.util.List; public class CombatSetup { public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Stormlight.MODID); public static final List<RegistryObject<ShardbladeItem>> SHARDBLADES = new ArrayList<>(); static { for (Order order : Order.values()) { String name = order.getSingularName(); SHARDBLADES.add(ITEMS.register(name + "_shardblade", () -> new ShardbladeItem(order))); } } public static void register() { ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus()); } @OnlyIn(Dist.CLIENT) public static void clientInit(final FMLClientSetupEvent e) { e.enqueueWork(() -> { for (RegistryObject<ShardbladeItem> shardblade : CombatSetup.SHARDBLADES) { ItemProperties.register(shardblade.get(), new ResourceLocation(Stormlight.MODID, "shielding"), (itemStack, clientWorld, player, seed) -> player != null && player.isUsingItem() && player.getUseItem() == itemStack ? 1.1F : 0.0F); } }); } }
1,907
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
ShardbladeItem.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/combat/item/ShardbladeItem.java
package com.legobmw99.stormlight.modules.combat.item; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.util.Order; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextColor; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraftforge.common.ToolAction; import net.minecraftforge.common.ToolActions; import javax.annotation.Nullable; import java.util.List; public class ShardbladeItem extends SwordItem { private static final int ATTACK_DAMAGE = 12; private static final float ATTACK_SPEED = 10.0f; private static final Tier SHARD = new Tier() { @Override public int getUses() { return -1; } @Override public float getSpeed() { return ATTACK_SPEED; } @Override public float getAttackDamageBonus() { return 0; } @Override public int getLevel() { return 6; } @Override public int getEnchantmentValue() { return 14; } @Override public Ingredient getRepairIngredient() { return Ingredient.of(WorldSetup.INFUSED_SPHERES.stream().map(r -> new ItemStack(r.get()))); } }; private final Order order; public ShardbladeItem(Order order) { super(SHARD, ATTACK_DAMAGE, ATTACK_SPEED, new Properties().stacksTo(1).fireResistant()); this.order = order; } public Order getOrder() { return order; } @Override public float getDestroySpeed(ItemStack stack, BlockState state) { if (state.getMaterial() == Material.STONE) { return 120.0F; } return super.getDestroySpeed(stack, state); } @Override public boolean isCorrectToolForDrops(BlockState state) { return false; } @Override public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) { MutableComponent lore = Component.translatable("item.stormlight.shardblade.lore"); lore.setStyle(lore.getStyle().withColor(TextColor.fromLegacyFormat(ChatFormatting.AQUA))); tooltip.add(lore); } @Override public boolean isEnchantable(ItemStack stack) { return false; } @Override public Rarity getRarity(ItemStack stack) { return Rarity.RARE; } @Override public boolean canPerformAction(ItemStack stack, ToolAction toolAction) { if (ToolActions.DEFAULT_SHIELD_ACTIONS.contains(toolAction) && stack.getUseDuration() > 0) { return true; } return super.canPerformAction(stack, toolAction); } @Override public UseAnim getUseAnimation(ItemStack p_77661_1_) { return UseAnim.BLOCK; } @Override public int getUseDuration(ItemStack p_77626_1_) { return 72000; } @Override public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); player.startUsingItem(hand); return InteractionResultHolder.consume(itemstack); } }
3,690
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PowersEventHandler.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/PowersEventHandler.java
package com.legobmw99.stormlight.modules.powers; import com.legobmw99.stormlight.modules.combat.item.ShardbladeItem; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.modules.powers.data.SurgebindingDataProvider; import com.legobmw99.stormlight.modules.powers.effect.EffectHelper; import com.legobmw99.stormlight.modules.world.item.SphereItem; import com.legobmw99.stormlight.network.Network; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.LevelData; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; public class PowersEventHandler { @SubscribeEvent public static void onAttachCapability(final AttachCapabilitiesEvent<Entity> event) { if (event.getObject() instanceof Player) { SurgebindingDataProvider provider = new SurgebindingDataProvider(); event.addCapability(SurgebindingCapability.IDENTIFIER, provider); } } @SubscribeEvent public static void onJoinWorld(final PlayerEvent.PlayerLoggedInEvent event) { if (!event.getEntity().level.isClientSide()) { if (event.getEntity() instanceof ServerPlayer p) { Network.sync(p); } } } @SubscribeEvent(priority = EventPriority.LOW) public static void onDeath(final LivingDeathEvent event) { if (!event.isCanceled() && event.getEntity() instanceof Player player) { player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> { if (data.isKnight() && !data.isBladeStored()) { player.getInventory().items .stream() .filter(is -> is.getItem() instanceof ShardbladeItem && ((ShardbladeItem) is.getItem()).getOrder() == data.getOrder()) .findFirst() .ifPresent(blade -> { data.storeBlade(blade); blade.setCount(0); }); } }); } } @SubscribeEvent public static void onPlayerClone(final PlayerEvent.Clone event) { if (!event.getEntity().level.isClientSide()) { event.getOriginal().reviveCaps(); Player player = event.getEntity(); player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> event.getOriginal().getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(oldData -> { data.load(oldData.save()); })); event.getOriginal().getCapability(SurgebindingCapability.PLAYER_CAP).invalidate(); event.getOriginal().invalidateCaps(); Network.sync(player); } } @SubscribeEvent public static void onRespawn(final PlayerEvent.PlayerRespawnEvent event) { if (!event.getEntity().level.isClientSide()) { Network.sync(event.getEntity()); } } @SubscribeEvent public static void onChangeDimension(final PlayerEvent.PlayerChangedDimensionEvent event) { if (!event.getEntity().level.isClientSide()) { Network.sync(event.getEntity()); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public static void onLivingDamage(final LivingAttackEvent event) { if (event.getEntity().hasEffect(PowersSetup.STORMLIGHT.get()) && (event.getSource() == event.getEntity().getLevel().damageSources().inWall() || event.getSource() == event.getEntity().getLevel().damageSources().drown())) { if (EffectHelper.drainStormlight(event.getEntity(), 4)) { event.setCanceled(true); } } } @SubscribeEvent public static void onEntityUpdate(LivingEvent.LivingTickEvent event) { var entity = event.getEntity(); if (entity.hasEffect(PowersSetup.STORMLIGHT.get())) { entity.setGlowingTag(!entity.hasEffect(MobEffects.INVISIBILITY)); entity.fallDistance = 0; } else { entity.setGlowingTag(false); entity.setNoGravity(false); } } @SubscribeEvent(priority = EventPriority.NORMAL) public static void onItemToss(ItemTossEvent event) { ItemEntity entity = event.getEntity(); if (entity != null) { // Store dropped shardblades Item item = entity.getItem().getItem(); if (item instanceof ShardbladeItem) { if (event.getPlayer() != null) { event.getPlayer().getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> { if (data.isKnight() && !data.isBladeStored()) { //Only store correct type of blade if (((ShardbladeItem) item).getOrder() == data.getOrder()) { data.storeBlade(entity.getItem()); event.getEntity().kill(); event.setCanceled(true); if (!entity.level.isClientSide()) { Network.sync(event.getPlayer()); } } } }); } } // Transform dropped spheres if (event.getEntity().level.isThundering() && item instanceof SphereItem) { double x, y, z; x = entity.getX(); y = entity.getY(); z = entity.getZ(); if (event.getEntity().isAlive()) { event.getEntity().kill(); for (int i = 0; i < entity.getItem().getCount(); i++) { ItemEntity newEntity = new ItemEntity(event.getEntity().level, x, y, z, new ItemStack(((SphereItem) item).swap(), 1, entity.getItem().getTag())); event.getEntity().level.addFreshEntity(newEntity); } event.setCanceled(true); } } } } @SubscribeEvent(priority = EventPriority.LOWEST) public static void onWorldTick(TickEvent.LevelTickEvent event) { if (event.phase == TickEvent.Phase.END) { LevelData data = event.level.getLevelData(); if (data instanceof ServerLevelData info) { if (info.getGameTime() % 96000 == 0) { info.setClearWeatherTime(0); info.setRainTime(2400); info.setThunderTime(2400); info.setRaining(true); info.setThundering(true); } } } } }
7,571
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Surges.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/Surges.java
package com.legobmw99.stormlight.modules.powers; import com.legobmw99.stormlight.modules.powers.container.PortableCraftingContainer; import com.legobmw99.stormlight.modules.powers.container.PortableStonecutterContainer; import com.legobmw99.stormlight.modules.powers.effect.EffectHelper; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.network.Network; import com.legobmw99.stormlight.network.packets.SurgePacket; import com.legobmw99.stormlight.util.Surge; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.item.FallingBlockEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.LevelData; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraftforge.common.util.ITeleporter; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; public class Surges { private static final Direction[] DIRECTIONS = {Direction.UP, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}; private static final Map<Block, Block> transformableBlocks = buildBlockMap(); private static boolean isBlockSafe(BlockPos pos, Level level) { return pos != null && level.isLoaded(pos) && !level.getBlockState(pos).isAir(); } private static BlockPos findAdjacentBlock(BlockPos pos, ServerPlayer player) { for (Direction d : DIRECTIONS) { BlockPos adj = pos.relative(d); if (!player.level.getBlockState(adj).isSuffocating(player.level, adj)) { return adj; } } return null; } private static Map<Block, Block> buildBlockMap() { Map<Block, Block> map = new HashMap<Block, Block>(); map.put(Blocks.COBBLESTONE, Blocks.STONE); map.put(Blocks.SANDSTONE, Blocks.RED_SANDSTONE); map.put(Blocks.GRASS_BLOCK, Blocks.MYCELIUM); map.put(Blocks.OBSIDIAN, Blocks.LAVA); map.put(Blocks.STONE, Blocks.HAY_BLOCK); map.put(Blocks.MELON, Blocks.PUMPKIN); map.put(Blocks.PUMPKIN, Blocks.MELON); map.put(Blocks.WHITE_WOOL, Blocks.COBWEB); return map; } public static void adhesion(ServerPlayer player, BlockPos pos, boolean shiftHeld) { if (shiftHeld) { if (player.hasEffect(PowersSetup.TENSION.get())) { ItemStack stack = player.getMainHandItem(); if (stack.isDamaged()) { if (EffectHelper.drainStormlight(player, 1000)) { stack.setDamageValue((int) (stack.getDamageValue() - 20 * stack.getXpRepairRatio())); } else if (EffectHelper.drainStormlight(player, 200)) { stack.setDamageValue((int) (stack.getDamageValue() - 2 * stack.getXpRepairRatio())); } } } } else if (isBlockSafe(pos, player.level)) { if (player.getEffect(PowersSetup.STORMLIGHT.get()).getDuration() > 200) { if (WorldSetup.ADHESION_BLOCK.get().coat(player.getLevel(), pos) > 0) { EffectHelper.drainStormlight(player, 200); Network.sendTo(new SurgePacket(Surge.ADHESION, pos, shiftHeld), player); } } } } public static void abrasion(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (shiftHeld) {// Allow climbing EffectHelper.toggleEffect(player, PowersSetup.STICKING.get()); player.removeEffect(PowersSetup.SLICKING.get()); } else { // Allow sliding EffectHelper.toggleEffect(player, PowersSetup.SLICKING.get()); player.removeEffect(PowersSetup.STICKING.get()); } } public static void cohesion(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (shiftHeld) { player.openMenu(new SimpleMenuProvider((i, inv, oplayer) -> new PortableStonecutterContainer(i, inv), Component.translatable("surge.cohesion.stoneshaping"))); } else { EffectHelper.toggleEffect(player, PowersSetup.COHESION.get()); } } public static void tension(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { // todo shift held - haste? EffectHelper.toggleEffect(player, PowersSetup.TENSION.get()); } public static void division(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { // TODO config to disable breaking, give haste instead if (isBlockSafe(pos, player.level)) { if (EffectHelper.drainStormlight(player, 400)) { player .getLevel() .explode(player, player.level.damageSources().magic(), null, pos.getX(), pos.getY(), pos.getZ(), 1.5F, true, shiftHeld ? Level.ExplosionInteraction.BLOCK : Level.ExplosionInteraction.NONE); } } } public static void gravitation(ServerPlayer player, @Nullable BlockPos l, boolean shiftHeld) { if (player.isOnGround() && shiftHeld) { // reverse lashing double range = 10; Vec3 pvec = player.position().add(0D, player.getEyeHeight() / 2.0, 0D); List<ItemEntity> items = player.level.getEntitiesOfClass(ItemEntity.class, new AABB(pvec.subtract(range, range, range), pvec.add(range, range, range))); for (ItemEntity e : items) { Vec3 vec = pvec.subtract(e.position()); e.setDeltaMovement(e.getDeltaMovement().add(vec.normalize().scale(vec.lengthSqr() * 0.1D))); } } else { // Basic lashing // TODO set nogravity, store a vector (? where) and accelerate in that direction. // accelerate based on effect level // will also let you yeet other entities? // - if shift held and entity hit is a living entitiy? // - mark entity (give effect and glowing) // - on next click, set vector // TODO look into ENTITY_GRAVITY // if (!shiftHeld) { // EffectHelper.increasePermanentEffect(player, PowersSetup.GRAVITATION.get(), 6); // } else { // EffectHelper.decreasePermanentEffect(player, PowersSetup.GRAVITATION.get()); // } if (player.getXRot() < -70) { if (player.isNoGravity() || player.isOnGround()) { player.setNoGravity(true); player.setDeltaMovement(player.getDeltaMovement().add(0D, 0.5, 0D)); player.hurtMarked = true; } else { player.setNoGravity(true); player.setDeltaMovement(player.getDeltaMovement().multiply(1D, 0D, 1D)); player.hurtMarked = true; } } else if (player.getXRot() > 70) { if (player.isNoGravity()) { if (player.getDeltaMovement().y > 0.1) { player.setDeltaMovement(player.getDeltaMovement().multiply(1D, 0D, 1D)); player.hurtMarked = true; } else { player.setNoGravity(false); } } } else { double facing = Math.toRadians(Mth.wrapDegrees(player.yHeadRot)); player.setDeltaMovement(player.getDeltaMovement().add(-Math.sin(facing), 0, Math.cos(facing))); player.hurtMarked = true; } } } public static void illumination(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (pos != null && player.level.isLoaded(pos)) { if (shiftHeld) { if (EffectHelper.drainStormlight(player, 300)) { player.addEffect(new MobEffectInstance(MobEffects.INVISIBILITY, 600, 0, true, false, true)); } } else { // Spawn ghost blocks if (player.getMainHandItem().getItem() instanceof BlockItem) { // Allow rudimentary 'building' if (!player.level.getBlockState(pos).isAir()) { pos = pos.relative(Direction.orderedByNearest(player)[0].getOpposite()); } while (!player.level.getEntitiesOfClass(FallingBlockEntity.class, new AABB(pos)).isEmpty()) { pos = pos.relative(Direction.orderedByNearest(player)[0].getOpposite()); } if (!player.level.getBlockState(pos).isAir()) { return; } if (EffectHelper.drainStormlight(player, 20)) { // TODO consider using DisplayBlock? FallingBlockEntity entity = FallingBlockEntity.fall(player.getLevel(), pos, ((BlockItem) player.getMainHandItem().getItem()).getBlock().defaultBlockState()); entity.dropItem = false; entity.noPhysics = true; entity.setNoGravity(true); entity.noPhysics = true; entity.time = -1200; entity.setDeltaMovement(Vec3.ZERO); entity.setPos(Vec3.atBottomCenterOf(pos)); entity.hurtMarked = true; } } else if (player.getMainHandItem().isEmpty()) { // remove entity if there List<FallingBlockEntity> fallings = player.level.getEntitiesOfClass(FallingBlockEntity.class, new AABB(pos)); if (!fallings.isEmpty()) { fallings.forEach(Entity::kill); } } } } } public static void progression(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (shiftHeld) { // Regen if (EffectHelper.drainStormlight(player, 600)) { player.addEffect(new MobEffectInstance(MobEffects.REGENERATION, 100, 4, true, false, true)); } } else { // Growth if (isBlockSafe(pos, player.level)) { BlockState state = player.level.getBlockState(pos); if (state.getBlock() instanceof BonemealableBlock igrowable) { if (igrowable.isValidBonemealTarget(player.level, pos, state, player.level.isClientSide)) { if (igrowable.isBonemealSuccess(player.level, player.level.random, pos, state)) { if (EffectHelper.drainStormlight(player, 100)) { igrowable.performBonemeal(player.getLevel(), player.level.random, pos, state); Network.sendTo(new SurgePacket(Surge.PROGRESSION, pos, shiftHeld), player); } } } } } } } public static void transformation(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (shiftHeld) { player.openMenu(new SimpleMenuProvider((i, inv, oplayer) -> new PortableCraftingContainer(i, inv), Component.translatable("surge.cohesion.soulcasting"))); } else { if (isBlockSafe(pos, player.level)) { Block block = player.level.getBlockState(pos).getBlock(); if (transformableBlocks.containsKey(block) && EffectHelper.drainStormlight(player, 600)) { Block newBlock = transformableBlocks.get(block); player.level.setBlockAndUpdate(pos, newBlock.defaultBlockState()); } } } } public static void transportation(ServerPlayer player, @Nullable BlockPos pos, boolean shiftHeld) { if (shiftHeld) { if (EffectHelper.drainStormlight(player, 1200)) { // similar to allomancy double x, y, z; BlockPos respawnPosition = player.getRespawnPosition(); ResourceKey<Level> dimension = player.getRespawnDimension(); if (respawnPosition == null) { LevelData info = player.level.getLevelData(); x = info.getXSpawn(); y = info.getYSpawn(); z = info.getZSpawn(); dimension = Level.OVERWORLD; } else { x = respawnPosition.getX() + 0.5; y = respawnPosition.getY(); z = respawnPosition.getZ() + 0.5; } if (!dimension.equals(player.level.dimension())) { player.changeDimension(player.getLevel().getServer().getLevel(player.getRespawnDimension()), new ITeleporter() { @Override public Entity placeEntity(Entity entity, ServerLevel currentWorld, ServerLevel destWorld, float yaw, Function<Boolean, Entity> repositionEntity) { Entity repositionedEntity = repositionEntity.apply(false); repositionedEntity.teleportTo(x, y, z); return repositionedEntity; } }); } player.teleportToWithTicket(x, y + 1.5, z); } } else { if (isBlockSafe(pos, player.level)) { pos = findAdjacentBlock(pos, player); if (pos != null && EffectHelper.drainStormlight(player, 100)) { player.teleportToWithTicket(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5); } } } } }
14,810
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PowersSetup.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
package com.legobmw99.stormlight.modules.powers; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.powers.command.StormlightArgType; import com.legobmw99.stormlight.modules.powers.effect.GenericEffect; import com.legobmw99.stormlight.modules.powers.effect.StormlightEffect; import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.commands.synchronization.ArgumentTypeInfos; import net.minecraft.commands.synchronization.SingletonArgumentInfo; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; public class PowersSetup { public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID); public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0)); public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535)); public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455)); public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010)); public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780)); public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation", () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(), "a81758d2-c355-11eb-8529-0242ac130003", -0.08, AttributeModifier.Operation.ADDITION)); private static final DeferredRegister<ArgumentTypeInfo<?, ?>> COMMAND_ARGUMENT_TYPES = DeferredRegister.create(ForgeRegistries.COMMAND_ARGUMENT_TYPES, Stormlight.MODID); private static final RegistryObject<SingletonArgumentInfo<StormlightArgType.IdealType>> COMMAND_IDEAL_TYPE = COMMAND_ARGUMENT_TYPES.register("stormlight_ideal", () -> ArgumentTypeInfos.registerByClass( StormlightArgType.IdealType.class, SingletonArgumentInfo.contextFree( StormlightArgType.IdealType::new))); private static final RegistryObject<SingletonArgumentInfo<StormlightArgType.OrderType>> COMMAND_ORDER_TYPE = COMMAND_ARGUMENT_TYPES.register("stormlight_order", () -> ArgumentTypeInfos.registerByClass( StormlightArgType.OrderType.class, SingletonArgumentInfo.contextFree( StormlightArgType.OrderType::new))); public static void register() { EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus()); COMMAND_ARGUMENT_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus()); } public static void init(final FMLCommonSetupEvent e) { e.enqueueWork(() -> MinecraftForge.EVENT_BUS.register(PowersEventHandler.class)); } }
5,049
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SurgebindingDataProvider.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingDataProvider.java
package com.legobmw99.stormlight.modules.powers.data; import com.legobmw99.stormlight.api.ISurgebindingData; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class SurgebindingDataProvider implements ICapabilitySerializable<CompoundTag> { private final DefaultSurgebindingData data = new DefaultSurgebindingData(); private final LazyOptional<ISurgebindingData> dataOptional = LazyOptional.of(() -> this.data); @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return SurgebindingCapability.PLAYER_CAP.orEmpty(cap, this.dataOptional.cast()); } @Override public CompoundTag serializeNBT() { if (SurgebindingCapability.PLAYER_CAP == null) { return new CompoundTag(); } else { return this.data.save(); } } @Override public void deserializeNBT(CompoundTag data) { if (SurgebindingCapability.PLAYER_CAP != null) { this.data.load(data); } } public void invalidate() { this.dataOptional.invalidate(); } }
1,401
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SurgebindingCapability.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
package com.legobmw99.stormlight.modules.powers.data; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.api.ISurgebindingData; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.CapabilityToken; import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; public class SurgebindingCapability { public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() { }); public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data"); public static void registerCapability(final RegisterCapabilitiesEvent event) { event.register(ISurgebindingData.class); } }
884
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
DefaultSurgebindingData.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/data/DefaultSurgebindingData.java
package com.legobmw99.stormlight.modules.powers.data; import com.legobmw99.stormlight.api.ISurgebindingData; import com.legobmw99.stormlight.util.Ideal; import com.legobmw99.stormlight.util.Order; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.UUID; public class DefaultSurgebindingData implements ISurgebindingData { private Order order; private Ideal ideal; private ItemStack blade; private UUID sprenID; public DefaultSurgebindingData() { this.order = null; this.ideal = Ideal.UNINVESTED; this.blade = ItemStack.EMPTY; this.sprenID = null; } @Nullable public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public Ideal getIdeal() { return ideal; } public void setIdeal(Ideal ideal) { this.ideal = ideal; } public void storeBlade(@Nonnull ItemStack blade) { this.blade = blade.copy(); } public boolean isBladeStored() { return !blade.isEmpty(); } public boolean addBladeToInventory(Player player) { if (player.getInventory().add(this.blade)) { this.blade = ItemStack.EMPTY; return true; } return false; } public UUID getSprenID() { return sprenID; } public void setSprenID(UUID sprenID) { this.sprenID = sprenID; } @Override public String toString() { return "Order: " + order + ", Ideal: " + ideal + ", Blade: " + blade + ", Spren: " + sprenID; } @Override public CompoundTag save() { CompoundTag nbt = new CompoundTag(); nbt.putInt("order", this.getOrder() != null ? this.getOrder().getIndex() : -1); nbt.putInt("ideal", this.getIdeal().getIndex()); nbt.put("blade", this.blade.copy().serializeNBT()); if (this.getSprenID() != null) { nbt.putUUID("sprenID", this.getSprenID()); } return nbt; } @Override public void load(CompoundTag surgebinding_data) { this.setOrder(Order.getOrNull(surgebinding_data.getInt("order"))); this.ideal = (Ideal.get(surgebinding_data.getInt("ideal"))); this.storeBlade(ItemStack.of(surgebinding_data.getCompound("blade"))); if (surgebinding_data.contains("sprenID")) { this.setSprenID(surgebinding_data.getUUID("sprenID")); } } }
2,605
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
GenericEffect.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/effect/GenericEffect.java
package com.legobmw99.stormlight.modules.powers.effect; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; public class GenericEffect extends MobEffect { public GenericEffect(MobEffectCategory type, int color) { super(type, color); } }
302
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
EffectHelper.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/effect/EffectHelper.java
package com.legobmw99.stormlight.modules.powers.effect; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; public class EffectHelper { private static final int BASE_TIME = 600; // 20 seconds public static boolean toggleEffect(Player player, MobEffect effect) { return toggleEffect(player, effect, 0, true, true); } public static boolean toggleEffect(Player player, MobEffect effect, int level, boolean ambient, boolean showicon) { if (player.hasEffect(effect)) { player.removeEffect(effect); return false; } else { player.addEffect(new MobEffectInstance(effect, MobEffectInstance.INFINITE_DURATION, level, ambient, false, showicon)); return true; } } public static int increasePermanentEffect(Player player, MobEffect effect, int max) { int level = player.hasEffect(effect) ? player.getEffect(effect).getAmplifier() : -1; level = level < max ? level + 1 : max; player.addEffect(new MobEffectInstance(effect, MobEffectInstance.INFINITE_DURATION, level, true, false, true)); return level; } public static int decreasePermanentEffect(Player player, MobEffect effect) { if (!player.hasEffect(effect)) { return -1; } int level = player.getEffect(effect).getAmplifier() - 1; player.removeEffect(effect); if (level >= 0) { player.addEffect(new MobEffectInstance(effect, MobEffectInstance.INFINITE_DURATION, level, true, false, true)); } return level; } public static boolean drainStormlight(LivingEntity entity, int duration) { MobEffect stormlight = PowersSetup.STORMLIGHT.get(); if (!entity.hasEffect(stormlight)) { return false; } MobEffectInstance effect = entity.getEffect(stormlight); if (effect.getDuration() < duration) { return false; } entity.removeEffect(stormlight); entity.addEffect(new MobEffectInstance(stormlight, effect.getDuration() - duration)); return true; } public static void addOrUpdateEffect(Player player, int modifier) { addOrUpdateEffect(player, modifier, BASE_TIME); } public static void addOrUpdateEffect(Player player, int modifier, int baseTime) { int toAdd = baseTime * modifier; if (player.hasEffect(PowersSetup.STORMLIGHT.get())) { player.addEffect(new MobEffectInstance(PowersSetup.STORMLIGHT.get(), Math.min(toAdd + player.getEffect(PowersSetup.STORMLIGHT.get()).getDuration(), 36 * baseTime))); } else { player.addEffect(new MobEffectInstance(PowersSetup.STORMLIGHT.get(), toAdd)); } } }
2,947
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
StormlightEffect.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/effect/StormlightEffect.java
package com.legobmw99.stormlight.modules.powers.effect; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.entity.LivingEntity; public class StormlightEffect extends GenericEffect { public StormlightEffect(int color) { super(MobEffectCategory.BENEFICIAL, color); } @Override public void applyEffectTick(LivingEntity entity, int amplifier) { if (!entity.hasEffect(PowersSetup.STORMLIGHT.get())) { entity.removeEffect(this); } } @Override public boolean isDurationEffectTick(int duration, int amplifier) { return true; } }
690
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SurgeEffects.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/client/SurgeEffects.java
package com.legobmw99.stormlight.modules.powers.client; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.item.BoneMealItem; import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; public class SurgeEffects { private static final Minecraft mc = Minecraft.getInstance(); public static void progressionEffect(@Nonnull BlockPos pos, boolean shiftHeld) { if (!shiftHeld) { BoneMealItem.addGrowthParticles(Minecraft.getInstance().level, pos, 0); } } public static void adhesionEffect(@Nonnull BlockPos blockPos, boolean shiftHeld) { if (!shiftHeld) { for (int i = 0; i < 15; i++) { Vec3 pos = mc.player.position().add(0, mc.player.getEyeHeight() / 1.5, 0); Vec3 motion = Vec3 .atBottomCenterOf(blockPos) .add((new Vec3(mc.level.random.nextDouble(), mc.level.random.nextDouble(), mc.level.random.nextDouble())).normalize()) .subtract(pos) .normalize(); mc.level.addParticle(ParticleTypes.END_ROD, pos.x(), pos.y(), pos.z(), motion.x(), motion.y(), motion.z()); } } } }
1,319
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
ClientPowerUtils.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/client/ClientPowerUtils.java
package com.legobmw99.stormlight.modules.powers.client; import com.legobmw99.stormlight.modules.combat.item.ShardbladeItem; import com.legobmw99.stormlight.modules.powers.PowersSetup; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.network.Network; import com.legobmw99.stormlight.network.packets.SummonBladePacket; import com.legobmw99.stormlight.network.packets.SurgePacket; import com.legobmw99.stormlight.util.Surge; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.phys.*; import org.lwjgl.glfw.GLFW; import javax.annotation.Nullable; import java.util.Set; import java.util.stream.Collectors; public class ClientPowerUtils { private static final Minecraft mc = Minecraft.getInstance(); /** * Adapted from vanilla, allows getting mouseover at given distances * * @param dist the distance requested * @return a RayTraceResult for the requested raytrace */ @Nullable protected static HitResult getMouseOverExtended(float dist) { float partialTicks = mc.getFrameTime(); HitResult objectMouseOver = null; Entity entity = mc.getCameraEntity(); if (entity != null) { if (mc.level != null) { objectMouseOver = entity.pick(dist, partialTicks, false); Vec3 vec3d = entity.getEyePosition(partialTicks); double d1 = objectMouseOver.getLocation().distanceToSqr(vec3d); Vec3 vec3d1 = entity.getViewVector(1.0F); Vec3 vec3d2 = vec3d.add(vec3d1.x * dist, vec3d1.y * dist, vec3d1.z * dist); AABB axisalignedbb = entity.getBoundingBox().expandTowards(vec3d1.scale(dist)).inflate(1.0D, 1.0D, 1.0D); EntityHitResult entityraytraceresult = ProjectileUtil.getEntityHitResult(entity, vec3d, vec3d2, axisalignedbb, (e) -> true, d1); if (entityraytraceresult != null) { Vec3 vec3d3 = entityraytraceresult.getLocation(); double d2 = vec3d.distanceToSqr(vec3d3); if (d2 < d1) { objectMouseOver = entityraytraceresult; } } } } return objectMouseOver; } protected static Set<BlockPos> getEyePos(LivingEntity entity, float rangeX, float rangeY, float rangeZ) { Vec3 pos = entity.position().add(0, entity.getEyeHeight(entity.getPose()), 0); AABB cameraBox = new AABB(pos, pos); cameraBox = cameraBox.inflate(rangeX, rangeY, rangeZ); return BlockPos.betweenClosedStream(cameraBox).map(BlockPos::immutable).collect(Collectors.toSet()); } @Nullable protected static BlockPos getMouseBlockPos(float dist) { HitResult trace = getMouseOverExtended(dist); if (trace != null) { if (trace.getType() == HitResult.Type.BLOCK) { return ((BlockHitResult) trace).getBlockPos(); } if (trace.getType() == HitResult.Type.ENTITY) { return ((EntityHitResult) trace).getEntity().blockPosition(); } } return null; } protected static void fireSurge(Surge surge) { boolean shiftDown = Minecraft.getInstance().options.keyShift.isDown(); BlockPos pos = getMouseBlockPos(surge.getRange()); // if (pos != null) { // surge.displayEffect(pos, shiftDown); // } Network.sendToServer(new SurgePacket(surge, pos, shiftDown)); } /** * Handles either mouse or button presses for the mod's keybinds */ protected static void acceptInput(final int action) { Player player = mc.player; if (mc.screen == null) { if (player == null || !mc.isWindowActive()) { return; } player.getCapability(SurgebindingCapability.PLAYER_CAP).ifPresent(data -> { if (data.isKnight()) { if (PowersClientSetup.blade.isDown() && (data.isBladeStored() || player.getMainHandItem().getItem() instanceof ShardbladeItem)) { Network.sendToServer(new SummonBladePacket()); PowersClientSetup.blade.setDown(false); } if (player.hasEffect(PowersSetup.STORMLIGHT.get())) { if (PowersClientSetup.firstSurge.isDown() && (action == GLFW.GLFW_PRESS || data.getOrder().getFirst().isRepeating())) { fireSurge(data.getOrder().getFirst()); } if (PowersClientSetup.secondSurge.isDown() && (action == GLFW.GLFW_PRESS || data.getOrder().getSecond().isRepeating())) { fireSurge(data.getOrder().getSecond()); } } } }); } } }
5,175
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PowersClientSetup.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/client/PowersClientSetup.java
package com.legobmw99.stormlight.modules.powers.client; import net.minecraft.client.KeyMapping; import net.minecraftforge.client.event.RegisterKeyMappingsEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import org.lwjgl.glfw.GLFW; public class PowersClientSetup { public static KeyMapping firstSurge; public static KeyMapping secondSurge; public static KeyMapping blade; public static void clientInit(final FMLClientSetupEvent e) { e.enqueueWork(() -> MinecraftForge.EVENT_BUS.register(PowerClientEventHandler.class)); } public static void registerKeyBinding(final RegisterKeyMappingsEvent evt) { firstSurge = new KeyMapping("key.firstSurge", GLFW.GLFW_KEY_F, "key.categories.stormlight"); secondSurge = new KeyMapping("key.secondSurge", GLFW.GLFW_KEY_G, "key.categories.stormlight"); blade = new KeyMapping("key.blade", GLFW.GLFW_KEY_V, "key.categories.stormlight"); evt.register(firstSurge); evt.register(secondSurge); evt.register(blade); } }
1,110
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PowerClientEventHandler.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/client/PowerClientEventHandler.java
package com.legobmw99.stormlight.modules.powers.client; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.client.event.RenderLevelStageEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @OnlyIn(Dist.CLIENT) public class PowerClientEventHandler { private static final Minecraft mc = Minecraft.getInstance(); private static final Map<BlockPos, BlockState> savedStates = new HashMap<>(); @SubscribeEvent public static void onKeyInput(final InputEvent.Key event) { if (event.getKey() == PowersClientSetup.firstSurge.getKey().getValue() || event.getKey() == PowersClientSetup.secondSurge.getKey().getValue() || event.getKey() == PowersClientSetup.blade.getKey().getValue()) { ClientPowerUtils.acceptInput(event.getAction()); } } @SubscribeEvent public static void onMouseInput(final InputEvent.MouseButton event) { // todo investigate // ClientPowerUtils.acceptInput(event.getAction()); } // Heavily inspired by Origins, but not a mixin @SubscribeEvent public static void renderLast(final RenderLevelStageEvent event) { if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES) { return; } if (mc.player != null && mc.player.hasEffect(PowersSetup.COHESION.get())) { Set<BlockPos> eyePositions = ClientPowerUtils.getEyePos(mc.player, 0.25F, 0.05F, 0.25F); Set<BlockPos> noLongerEyePositions = savedStates.keySet().stream().filter((p -> !eyePositions.contains(p))).collect(Collectors.toSet()); // restore states noLongerEyePositions.forEach(eyePosition -> { BlockState state = savedStates.get(eyePosition); mc.level.setBlock(eyePosition, state, 0); savedStates.remove(eyePosition); }); // set to air (on client only) eyePositions.forEach(p -> { BlockState stateAtP = mc.level.getBlockState(p); if (!savedStates.containsKey(p) && !stateAtP.isAir() && !(stateAtP.getBlock() instanceof LiquidBlock)) { savedStates.put(p, stateAtP); mc.level.setBlock(p, Blocks.LIGHT.defaultBlockState(), 0); } }); } else if (savedStates.size() > 0) { // restore all if power is not had Set<BlockPos> noLongerEyePositions = new HashSet<>(savedStates.keySet()); noLongerEyePositions.forEach(eyePosition -> { BlockState state = savedStates.get(eyePosition); mc.level.setBlock(eyePosition, state, 0); savedStates.remove(eyePosition); }); } } }
3,279
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PortableCraftingContainer.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableCraftingContainer.java
package com.legobmw99.stormlight.modules.powers.container; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.CraftingMenu; public class PortableCraftingContainer extends CraftingMenu { public PortableCraftingContainer(int p_i50089_1_, Inventory p_i50089_2_) { super(p_i50089_1_, p_i50089_2_); } @Override public boolean stillValid(Player player) { return player.hasEffect(PowersSetup.STORMLIGHT.get()); } }
595
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
PortableStonecutterContainer.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableStonecutterContainer.java
package com.legobmw99.stormlight.modules.powers.container; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.StonecutterMenu; public class PortableStonecutterContainer extends StonecutterMenu { public PortableStonecutterContainer(int p_i50060_1_, Inventory p_i50060_2_) { super(p_i50060_1_, p_i50060_2_); } @Override public boolean stillValid(Player player) { return player.hasEffect(PowersSetup.STORMLIGHT.get()); } }
608
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
StormlightCommand.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/command/StormlightCommand.java
package com.legobmw99.stormlight.modules.powers.command; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.network.Network; import com.legobmw99.stormlight.util.Ideal; import com.legobmw99.stormlight.util.Order; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.EntityArgument; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import java.util.Collection; import java.util.Collections; import java.util.function.Predicate; public class StormlightCommand { private static Predicate<CommandSourceStack> permissions(int level) { return (player) -> player.hasPermission(level); } private static Collection<ServerPlayer> sender(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException { return Collections.singleton(ctx.getSource().getPlayerOrException()); } private static Collection<ServerPlayer> targets(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException { return EntityArgument.getPlayers(ctx, "targets"); } public static void register(CommandDispatcher<CommandSourceStack> dispatcher) { LiteralArgumentBuilder<CommandSourceStack> root = Commands.literal("stormlight").requires(permissions(0)); LiteralArgumentBuilder<CommandSourceStack> order = Commands.literal("order") .then(Commands .literal("get") .requires(permissions(0)) .executes(ctx -> getOrder(ctx, sender(ctx))) .then(Commands .argument("targets", EntityArgument.players()) .executes(ctx -> getOrder(ctx, targets(ctx))))) .then(Commands .literal("set") .requires(permissions(2)) .then(Commands .argument("order", StormlightArgType.OrderType.INSTANCE) .executes(ctx -> setOrder(ctx, sender(ctx))) .then(Commands .argument("targets", EntityArgument.players()) .executes(ctx -> setOrder(ctx, targets(ctx)))))); LiteralArgumentBuilder<CommandSourceStack> ideal = Commands.literal("ideal") .then(Commands .literal("get") .requires(permissions(0)) .executes(ctx -> getIdeal(ctx, sender(ctx))) .then(Commands .argument("targets", EntityArgument.players()) .executes(ctx -> getIdeal(ctx, targets(ctx))))) .then(Commands .literal("set") .requires(permissions(2)) .then(Commands .argument("ideal", StormlightArgType.IdealType.INSTANCE) .executes(ctx -> setIdeal(ctx, sender(ctx))) .then(Commands .argument("targets", EntityArgument.players()) .executes(ctx -> setIdeal(ctx, targets(ctx)))))); root.then(order); root.then(ideal); dispatcher.register(root); } private static int setOrder(CommandContext<CommandSourceStack> ctx, Collection<ServerPlayer> players) { int i = 0; Order order = ctx.getArgument("order", Order.class); for (ServerPlayer player : players) { int success = player.getCapability(SurgebindingCapability.PLAYER_CAP).map(data -> { data.setOrder(order); ctx.getSource().sendSuccess(Component.translatable("commands.stormlight.setorder", player.getDisplayName(), order.toString()), true); return 1; }).orElse(0); if (success == 1) { Network.sync(player); } i += success; } return i; } private static int setIdeal(CommandContext<CommandSourceStack> ctx, Collection<ServerPlayer> players) { int i = 0; Ideal ideal = ctx.getArgument("ideal", Ideal.class); for (ServerPlayer player : players) { int success = player.getCapability(SurgebindingCapability.PLAYER_CAP).map(data -> { data.setIdeal(ideal); ctx.getSource().sendSuccess(Component.translatable("commands.stormlight.setideal", player.getDisplayName(), ideal.toString()), true); return 1; }).orElse(0); if (success == 1) { Network.sync(player); } i += success; } return i; } private static int getOrder(CommandContext<CommandSourceStack> ctx, Collection<ServerPlayer> players) { int i = 0; for (ServerPlayer player : players) { i += player.getCapability(SurgebindingCapability.PLAYER_CAP).map(data -> { ctx.getSource().sendSuccess(Component.translatable("commands.stormlight.getorder", player.getDisplayName(), data.getOrder().toString()), true); return 1; }).orElse(0); } return i; } private static int getIdeal(CommandContext<CommandSourceStack> ctx, Collection<ServerPlayer> players) { int i = 0; for (ServerPlayer player : players) { i += player.getCapability(SurgebindingCapability.PLAYER_CAP).map(data -> { ctx.getSource().sendSuccess(Component.translatable("commands.stormlight.getideal", player.getDisplayName(), data.getIdeal().toString()), true); return 1; }).orElse(0); } return i; } }
8,105
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
StormlightArgType.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/command/StormlightArgType.java
package com.legobmw99.stormlight.modules.powers.command; import com.legobmw99.stormlight.util.Ideal; import com.legobmw99.stormlight.util.Order; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.network.chat.Component; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class StormlightArgType { public static class OrderType implements ArgumentType<Order> { public static final OrderType INSTANCE = new OrderType(); private static final Set<String> types = Arrays.stream(Order.values()).map(Order::getName).collect(Collectors.toSet()); private static final DynamicCommandExceptionType unknown_power = new DynamicCommandExceptionType( o -> Component.translatable("commands.stormlight.unrecognized_order", o)); @Override public Order parse(StringReader reader) throws CommandSyntaxException { String in = reader.readUnquotedString(); if (types.contains(in)) { return Order.valueOf(in.toUpperCase(Locale.ROOT)); } throw unknown_power.create(in); } @Override public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) { return SharedSuggestionProvider.suggest(types, builder).toCompletableFuture(); } @Override public Collection<String> getExamples() { return types; } } public static class IdealType implements ArgumentType<Ideal> { public static final IdealType INSTANCE = new IdealType(); private static final Set<String> types = Arrays.stream(Ideal.values()).map(Ideal::getName).collect(Collectors.toSet()); private static final DynamicCommandExceptionType unknown_power = new DynamicCommandExceptionType( o -> Component.translatable("commands.stormlight.unrecognized_ideal", o)); @Override public Ideal parse(StringReader reader) throws CommandSyntaxException { String in = reader.readUnquotedString(); if (types.contains(in)) { return Ideal.valueOf(in.toUpperCase(Locale.ROOT)); } throw unknown_power.create(in); } @Override public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) { return SharedSuggestionProvider.suggest(types, builder).toCompletableFuture(); } @Override public Collection<String> getExamples() { return types; } } }
3,135
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
AdhesionBlock.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/block/AdhesionBlock.java
package com.legobmw99.stormlight.modules.powers.block; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.FaceAttachedHorizontalDirectionalBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.PushReaction; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import java.util.Random; // TODO look into GlowLichen and MultifaceBlock public class AdhesionBlock extends FaceAttachedHorizontalDirectionalBlock { private static final VoxelShape TOP = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 0.5D, 16.0D); private static final VoxelShape BOTTOM = Block.box(0.0D, 15.5D, 0.0D, 16.0D, 16.0D, 16.0D); private static final VoxelShape NORTH = Block.box(0.0D, 0.0D, 15.5D, 16.0D, 16.0D, 16.0D); private static final VoxelShape SOUTH = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 0.5D); private static final VoxelShape EAST = Block.box(0.0D, 0.0D, 0.0D, 0.5D, 16.0D, 16.0D); private static final VoxelShape WEST = Block.box(15.5D, .0D, 0.0D, 16.0D, 16.0D, 16.0D); public AdhesionBlock() { super(BlockBehaviour.Properties .of(Material.TOP_SNOW) .lightLevel((d) -> 15) .jumpFactor(0.0F) .noLootTable() .strength(-1.0F, 3600000.0F) .randomTicks() .speedFactor(0.0F) .noOcclusion() .isValidSpawn((a, b, c, d) -> false) .isRedstoneConductor((a, b, c) -> false) .isSuffocating((a, b, c) -> false) .isViewBlocking((a, b, c) -> false) .sound(SoundType.GLASS)); this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(FACE, AttachFace.WALL)); } public static AttachFace fromDirection(Direction dir) { return switch (dir) { case UP -> AttachFace.CEILING; case DOWN -> AttachFace.FLOOR; default -> AttachFace.WALL; }; } @Override public PushReaction getPistonPushReaction(BlockState state) { return PushReaction.BLOCK; } public int coat(Level world, BlockPos pos) { int sides = 0; for (Direction d : Direction.values()) { if (canAttachFrom(world, pos, d) && world.getBlockState(pos.relative(d)).isAir()/*.getMaterial().isReplaceable()*/) { AttachFace face = fromDirection(d.getOpposite()); BlockState newBlock = defaultBlockState().setValue(FACE, face); if (face == AttachFace.WALL) { newBlock = newBlock.setValue(FACING, d); } world.setBlockAndUpdate(pos.relative(d), newBlock); sides++; } } return sides; } public boolean canAttachFrom(Level world, BlockPos pos, Direction d) { return canAttach(world, pos.relative(d), d.getOpposite()); } @Override public VoxelShape getShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext ctx) { return switch (state.getValue(FACE)) { case FLOOR -> TOP; case CEILING -> BOTTOM; default -> switch (state.getValue(FACING)) { case EAST -> EAST; case WEST -> WEST; case SOUTH -> SOUTH; default -> NORTH; }; }; } @Override public VoxelShape getCollisionShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext ctx) { return Shapes.empty(); } @Override public boolean useShapeForLightOcclusion(BlockState state) { return true; } @Override public VoxelShape getVisualShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext ctx) { return Shapes.empty(); } @OnlyIn(Dist.CLIENT) @Override public float getShadeBrightness(BlockState state, BlockGetter reader, BlockPos pos) { return 1.0F; } @Override public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) { return true; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(FACING, FACE); } @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { super.randomTick(state, world, pos, random); world.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState()); } @Override public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { if (!entity.isNoGravity() && (entity instanceof LivingEntity && !((LivingEntity) entity).hasEffect(PowersSetup.GRAVITATION.get()))) { Vec3 target = switch (state.getValue(FACE)) { case FLOOR -> Vec3.atBottomCenterOf(pos); case CEILING -> Vec3.atBottomCenterOf(pos.above()); default -> switch (state.getValue(FACING)) { case EAST -> Vec3.atCenterOf(pos.below().west()); case WEST -> Vec3.atCenterOf(pos.below().east()); case SOUTH -> Vec3.atCenterOf(pos.below().north()); default -> Vec3.atCenterOf(pos.below().south()); }; }; entity.setDeltaMovement(target.subtract(entity.position()).normalize()); entity.makeStuckInBlock(state, new Vec3(0.01, 1, 0.01)); } } }
6,617
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
AbstractBlockstateMixin.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/mixin/AbstractBlockstateMixin.java
package com.legobmw99.stormlight.modules.powers.mixin; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.EntityCollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * Primarily handles the Cohesion effect of phasing through blocks. Inspired by Origins */ @Mixin(BlockBehaviour.BlockStateBase.class) public abstract class AbstractBlockstateMixin { @Shadow(remap = false) public abstract Block getBlock(); @Shadow(remap = false) protected abstract BlockState asState(); @Inject(at = @At("HEAD"), method = "getCollisionShape(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Lnet/minecraft/world/phys/shapes/VoxelShape;", cancellable = true, remap = false) private void noClip(BlockGetter world, BlockPos pos, CollisionContext context, CallbackInfoReturnable<VoxelShape> info) { if (context instanceof EntityCollisionContext ectx) { Entity entity = ectx.getEntity(); if (entity instanceof LivingEntity && ((LivingEntity) entity).hasEffect(PowersSetup.COHESION.get())) { boolean isAbove = isAbove(entity, getBlock().getCollisionShape(asState(), world, pos, context), pos); if (getBlock() != Blocks.BEDROCK && (!isAbove || entity.isShiftKeyDown())) { info.setReturnValue(Shapes.empty()); } } } } @Unique private boolean isAbove(Entity entity, VoxelShape shape, BlockPos pos) { return entity.getY() > (double) pos.getY() + shape.max(Direction.Axis.Y) - (entity.isOnGround() ? 8.05 / 16.0 : 0.0015); } @Inject(method = "entityInside", at = @At("HEAD"), cancellable = true, remap = false) private void preventPushOut(Level world, BlockPos pos, Entity entity, CallbackInfo ci) { if (entity instanceof LivingEntity && ((LivingEntity) entity).hasEffect(PowersSetup.COHESION.get())) { ci.cancel(); } } }
2,991
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
IForgeBlockStateMixin.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/mixin/IForgeBlockStateMixin.java
package com.legobmw99.stormlight.modules.powers.mixin; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.extensions.IForgeBlockState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import javax.annotation.Nullable; @Mixin(IForgeBlockState.class) public interface IForgeBlockStateMixin { @Shadow(remap = false) BlockState shadow$self(); /** * Add stormlight mod checks for slipperiness * * @author legobmw99 * @reason unable to inject into default interface method */ @Overwrite(remap = false) default float getFriction(LevelReader world, BlockPos pos, @Nullable Entity entity) { if (entity instanceof LivingEntity p && p.hasEffect(PowersSetup.SLICKING.get())) { return 0.989f; } if ((entity instanceof Boat && entity.hasPassenger(LivingEntity.class::isInstance) && entity.getPassengers().stream().anyMatch(e -> e instanceof LivingEntity p && p.hasEffect(PowersSetup.SLICKING.get())))) { return 0.989f; } return shadow$self().getBlock().getFriction(shadow$self(), world, pos, entity); } }
1,525
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
LivingEntityMixin.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/powers/mixin/LivingEntityMixin.java
package com.legobmw99.stormlight.modules.powers.mixin; import com.legobmw99.stormlight.modules.powers.PowersSetup; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.FluidState; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Optional; @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity { @Shadow(remap = false) private Optional<BlockPos> lastClimbablePos; public LivingEntityMixin(EntityType<?> type, Level world) { super(type, world); } // todo actually mixin to IForgeBlockState? @Inject(at = @At("RETURN"), method = "onClimbable", cancellable = true, remap = false) public void doCohesionClimb(CallbackInfoReturnable<Boolean> info) { if (!info.getReturnValue()) { LivingEntity entity = (LivingEntity) (Entity) this; if (entity.hasEffect(PowersSetup.STICKING.get()) && entity.level.getBlockCollisions(entity, entity.getBoundingBox().inflate(0.15, 0, 0.15)).iterator().hasNext()) { this.lastClimbablePos = Optional.of(blockPosition()); info.setReturnValue(true); } } } @Inject(at = @At("RETURN"), method = "canStandOnFluid(Lnet/minecraft/world/level/material/FluidState;)Z", cancellable = true, remap = false) public void doTensionStand(FluidState fluid, CallbackInfoReturnable<Boolean> info) { if (!info.getReturnValue()) { LivingEntity entity = (LivingEntity) (Entity) this; if (entity.hasEffect(PowersSetup.TENSION.get())) { info.setReturnValue(true); } } } }
2,045
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
WorldSetup.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/world/WorldSetup.java
package com.legobmw99.stormlight.modules.world; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.powers.block.AdhesionBlock; import com.legobmw99.stormlight.modules.world.entity.SprenEntity; import com.legobmw99.stormlight.modules.world.entity.client.SprenModel; import com.legobmw99.stormlight.modules.world.entity.client.SprenRenderer; import com.legobmw99.stormlight.modules.world.item.SphereItem; import com.legobmw99.stormlight.util.Gemstone; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.SpawnEggItem; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraftforge.common.ForgeSpawnEggItem; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.ArrayList; import java.util.List; public class WorldSetup { public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Stormlight.MODID); public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Stormlight.MODID); public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, Stormlight.MODID); public static final List<RegistryObject<SphereItem>> DUN_SPHERES = new ArrayList<>(); public static final List<RegistryObject<SphereItem>> INFUSED_SPHERES = new ArrayList<>(); public static final RegistryObject<AdhesionBlock> ADHESION_BLOCK = BLOCKS.register("adhesion_light", AdhesionBlock::new); public static final RegistryObject<BlockItem> ADHESION_BLOCK_ITEM = ITEMS.register("adhesion_light", () -> new BlockItem(ADHESION_BLOCK.get(), new Item.Properties().stacksTo(64))); public static final RegistryObject<EntityType<SprenEntity>> SPREN_ENTITY = ENTITIES.register("spren", () -> EntityType.Builder .<SprenEntity>of(SprenEntity::new, MobCategory.AMBIENT) .setShouldReceiveVelocityUpdates(true) .setUpdateInterval(5) .clientTrackingRange(8) .setCustomClientFactory((spawnEntity, world) -> new SprenEntity(world, spawnEntity.getEntity())) .sized(0.6F, 0.6F) .canSpawnFarFromPlayer() .build("spren")); public static final RegistryObject<SpawnEggItem> SPREN_SPAWN_EGG = ITEMS.register("spren_spawn_egg", () -> new ForgeSpawnEggItem(SPREN_ENTITY, 16382457, 10123246, new Item.Properties().stacksTo(64))); static { for (Gemstone gem : Gemstone.values()) { String name = gem.getName(); DUN_SPHERES.add(ITEMS.register("dun_" + name + "_sphere", () -> new SphereItem(false, gem))); INFUSED_SPHERES.add(ITEMS.register("infused_" + name + "_sphere", () -> new SphereItem(true, gem))); } } public static void register() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(bus); BLOCKS.register(bus); ENTITIES.register(bus); } public static void registerEntityRenders(final EntityRenderersEvent.RegisterRenderers e) { e.registerEntityRenderer(SPREN_ENTITY.get(), SprenRenderer::new); } public static void registerEntityModels(final EntityRenderersEvent.RegisterLayerDefinitions e) { e.registerLayerDefinition(SprenModel.MODEL_LOC, SprenModel::createLayer); } public static void onEntityAttribute(final net.minecraftforge.event.entity.EntityAttributeCreationEvent e) { Stormlight.LOGGER.info("Registering Spren entity attributes"); e.put(SPREN_ENTITY.get(), SprenEntity.createAttributes()); } }
4,229
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SprenEntity.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/world/entity/SprenEntity.java
package com.legobmw99.stormlight.modules.world.entity; import com.legobmw99.stormlight.api.ISurgebindingData; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.util.Order; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.core.particles.SimpleParticleType; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializer; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.control.FlyingMoveControl; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; import net.minecraft.world.entity.ai.navigation.PathNavigation; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.animal.FlyingAnimal; import net.minecraft.world.entity.monster.Monster; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; public class SprenEntity extends TamableAnimal implements FlyingAnimal { public static final EntityDataSerializer<Enum<Order>> ORDER = new EntityDataSerializer<>() { public void write(FriendlyByteBuf buf, Enum<Order> order) { buf.writeEnum(order); } public Enum<Order> read(FriendlyByteBuf buf) { return buf.readEnum(Order.class); } public Enum<Order> copy(Enum<Order> order) { return order; } }; private static final EntityDataAccessor<Enum<Order>> SPREN_TYPE = SynchedEntityData.defineId(SprenEntity.class, ORDER); private static final float[][] colors = {{0.737F, 0.960F, 0.945F}, {0.356F, 0.333F, 0.407F}, {0.819F, 0.819F, 0.819F}, {0.349F, 0.670F, 0.466F}, {0.913F, 0.945F, 0.945F}, {0.337F, 0.286F, 0.396F}, {0.188F, 0.145F, 0.129F}, {0.815F, 0.588F, 0.207F}, {0.513F, 0.027F, 0.098F}, {0.380F, 0.352F, 0.886F}}; private static final SimpleParticleType[] particles = {ParticleTypes.CLOUD, ParticleTypes.PORTAL, ParticleTypes.ASH, ParticleTypes.HAPPY_VILLAGER, ParticleTypes.END_ROD, ParticleTypes.ENCHANT, ParticleTypes.SQUID_INK, ParticleTypes.EFFECT, ParticleTypes.LAVA, ParticleTypes.SOUL}; static { EntityDataSerializers.registerSerializer(ORDER); } private int delay = 0; public SprenEntity(Level world, Entity other) { this(null, world); if (other instanceof SprenEntity) { this.setSprenType(((SprenEntity) other).getSprenType()); } } public SprenEntity(EntityType<? extends TamableAnimal> entityEntityType, Level world) { super(entityEntityType, world); this.setTame(false); this.moveControl = new FlyingMoveControl(this, 20, true); } public static AttributeSupplier createAttributes() { return Monster.createMonsterAttributes().add(Attributes.FLYING_SPEED, 0.4D).add(Attributes.MOVEMENT_SPEED, 0.2D).add(Attributes.MAX_HEALTH, 18.0D).build(); } public static <T extends Mob> boolean checkSprenSpawnRules(EntityType<T> tEntityType, ServerLevelAccessor iServerWorld, MobSpawnType spawnReason, BlockPos blockPos, RandomSource random) { //todo biomes return checkMobSpawnRules(tEntityType, iServerWorld, spawnReason, blockPos, random); } public Order getSprenType() { return (Order) this.entityData.get(SPREN_TYPE); } public void setSprenType(Order order) { this.entityData.set(SPREN_TYPE, order); } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor world, DifficultyInstance difficulty, MobSpawnType reason, @Nullable SpawnGroupData data, @Nullable CompoundTag nbt) { //todo biomes this.setSprenType(Order.getOrNull(this.random.nextInt(10))); return super.finalizeSpawn(world, difficulty, reason, data, nbt); } @Nullable @Override public AgeableMob getBreedOffspring(ServerLevel p_146743_, AgeableMob p_146744_) { return null; } @Override public void die(DamageSource p_70645_1_) { // TODO break oaths super.die(p_70645_1_); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { return super.mobInteract(player, hand); } @Override public void setTame(boolean tamed) { super.setTame(tamed); if (tamed) { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(180.0D); } } @Override public void aiStep() { if (this.level.isClientSide && delay == 0) { AABB aabb = getBoundingBox(); double x = aabb.minX + Math.random() * (aabb.maxX - aabb.minX); double y = aabb.minY + Math.random() * (aabb.maxY - aabb.minY); double z = aabb.minZ + Math.random() * (aabb.maxZ - aabb.minZ); this.level.addParticle(particles[getSprenType().getIndex()], x, y, z, 0, 0, 0); } delay++; delay = delay % 10; super.aiStep(); } @Override public void tick() { super.tick(); if (this.random.nextInt(100) == 0) { this.heal(2.0F); } } @Override public int getMaxSpawnClusterSize() { return 1; } @Override protected int calculateFallDamage(float p_225508_1_, float p_225508_2_) { return 0; } @Override public boolean isInvulnerableTo(DamageSource in) { return (!isTame() || in.equals(this.level.damageSources().playerAttack((Player) getOwner()))) && !in.equals(this.level.damageSources().outOfWorld()); } @Override protected PathNavigation createNavigation(Level world) { var flying = new FlyingPathNavigation(this, world); flying.setCanOpenDoors(true); flying.setCanFloat(true); flying.setCanPassDoors(true); flying.canFloat(); return flying; } @Override public float getEyeHeight(Pose p) { return 0.8f; } @Override protected void registerGoals() { this.goalSelector.addGoal(0, new PanicGoal(this, 1.25D)); this.goalSelector.addGoal(0, new FloatGoal(this)); this.goalSelector.addGoal(1, new LookAtPlayerGoal(this, Player.class, 8.0F)); this.goalSelector.addGoal(2, new FollowOwnerGoal(this, 1.0D, 5.0F, 1.0F, true)); this.goalSelector.addGoal(2, new WaterAvoidingRandomFlyingGoal(this, 1.0D)); this.goalSelector.addGoal(3, new FollowMobGoal(this, 1.0D, 3.0F, 7.0F)); this.goalSelector.addGoal(4, new SitWhenOrderedToGoal(this)); } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(SPREN_TYPE, Order.WINDRUNNERS); } @Override public void addAdditionalSaveData(CompoundTag compoundNBT) { super.addAdditionalSaveData(compoundNBT); compoundNBT.putByte("type", (byte) getSprenType().getIndex()); } @Override public void readAdditionalSaveData(CompoundTag compoundNBT) { super.readAdditionalSaveData(compoundNBT); setSprenType(Order.getOrNull(compoundNBT.getByte("type"))); } @Override public boolean causeFallDamage(float pFallDistance, float pMultiplier, DamageSource pSource) { return false; } @Override protected void checkFallDamage(double p_184231_1_, boolean p_184231_3_, BlockState p_184231_4_, BlockPos p_184231_5_) { } @Override public boolean isPushable() { return false; } @Override protected void doPush(Entity e) { if (e.equals(this.getOwner())) { super.doPush(e); } } @Override public boolean isAlliedTo(Entity e) { if (e instanceof Player) { Order order = e.getCapability(SurgebindingCapability.PLAYER_CAP).map(ISurgebindingData::getOrder).orElse(null); return order != null && order == this.entityData.get(SPREN_TYPE); } return false; } @Override public boolean canBeLeashed(Player p) { return false; } @Override public boolean canMate(Animal p_70878_1_) { return false; } @OnlyIn(Dist.CLIENT) public float getRed() { return colors[getSprenType().getIndex()][0]; } @OnlyIn(Dist.CLIENT) public float getGreen() { return colors[getSprenType().getIndex()][1]; } @OnlyIn(Dist.CLIENT) public float getBlue() { return colors[getSprenType().getIndex()][2]; } @Override public boolean isFlying() { return false; } }
9,852
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SprenModel.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/world/entity/client/SprenModel.java
package com.legobmw99.stormlight.modules.world.entity.client; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.world.entity.SprenEntity; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.client.model.HierarchicalModel; import net.minecraft.client.model.geom.ModelLayerLocation; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; import net.minecraft.client.model.geom.builders.CubeListBuilder; import net.minecraft.client.model.geom.builders.LayerDefinition; import net.minecraft.client.model.geom.builders.MeshDefinition; import net.minecraft.client.model.geom.builders.PartDefinition; import net.minecraft.client.renderer.RenderType; import net.minecraft.resources.ResourceLocation; public class SprenModel extends HierarchicalModel<SprenEntity> { public static final ModelLayerLocation MODEL_LOC = new ModelLayerLocation(new ResourceLocation(Stormlight.MODID, "spren_model"), "main"); private final ModelPart root; private SprenEntity spren; public SprenModel(ModelPart p_170955_) { super(RenderType::entityTranslucent); this.root = p_170955_; } public static LayerDefinition createLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); var builder = CubeListBuilder.create().texOffs(0, 0).addBox(-4F, 16F, -4.0F, 8, 8, 8); partdefinition.addOrReplaceChild("cube", builder, PartPose.ZERO); return LayerDefinition.create(meshdefinition, 32, 16); } @Override public void renderToBuffer(PoseStack matrix, VertexConsumer iVertexBuilder, int packedLightIn, int packedOverlayIn, float red, float green, float blue, float alpha) { matrix.pushPose(); this.root.render(matrix, iVertexBuilder, packedLightIn, packedOverlayIn, spren.getRed(), spren.getGreen(), spren.getBlue(), 0.3F); matrix.popPose(); } @Override public ModelPart root() { return this.root; } @Override public void setupAnim(SprenEntity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { this.root.yRot = netHeadYaw * ((float) Math.PI / 180F); this.root.xRot = headPitch * ((float) Math.PI / 180F); this.spren = entity; } }
2,438
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SprenRenderer.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/world/entity/client/SprenRenderer.java
package com.legobmw99.stormlight.modules.world.entity.client; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.modules.world.entity.SprenEntity; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.client.renderer.entity.MobRenderer; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; public class SprenRenderer extends MobRenderer<SprenEntity, SprenModel> { public SprenRenderer(EntityRendererProvider.Context manager) { super(manager, new SprenModel(manager.bakeLayer(SprenModel.MODEL_LOC)), 0.0f); } @Override protected int getBlockLightLevel(@Nonnull SprenEntity e, @Nonnull BlockPos p) { return 15; } @Nonnull @Override public ResourceLocation getTextureLocation(@Nonnull SprenEntity entity) { return new ResourceLocation(Stormlight.MODID, "textures/entity/spren.png"); } }
976
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
SphereItem.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/modules/world/item/SphereItem.java
package com.legobmw99.stormlight.modules.world.item; import com.legobmw99.stormlight.Stormlight; import com.legobmw99.stormlight.api.ISurgebindingData; import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability; import com.legobmw99.stormlight.modules.powers.effect.EffectHelper; import com.legobmw99.stormlight.modules.world.WorldSetup; import com.legobmw99.stormlight.util.Gemstone; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import java.util.List; public class SphereItem extends Item { private final boolean infused; private final Gemstone setting; public SphereItem(boolean infused, Gemstone setting) { super(new Properties().stacksTo(infused ? 1 : 4)); this.infused = infused; this.setting = setting; } @Override public UseAnim getUseAnimation(ItemStack stack) { return this.infused ? UseAnim.DRINK : UseAnim.NONE; } @Override public int getUseDuration(ItemStack stack) { return 5; } @Override public InteractionResultHolder<ItemStack> use(Level worldIn, Player player, InteractionHand hand) { if (infused && player.getCapability(SurgebindingCapability.PLAYER_CAP).filter(ISurgebindingData::isKnight).isPresent()) { player.startUsingItem(hand); return new InteractionResultHolder<>(InteractionResult.SUCCESS, player.getItemInHand(hand)); } else { return new InteractionResultHolder<>(InteractionResult.FAIL, player.getItemInHand(hand)); } } @Override public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity entityLiving) { if (entityLiving instanceof Player player && this.infused) { // Don't consume items in creative mode if (!player.getAbilities().instabuild) { stack.shrink(1); player.getInventory().add(new ItemStack(this.swap(), 1, stack.getTag())); } if (!worldIn.isClientSide) { EffectHelper.addOrUpdateEffect(player, this.setting.getModifier()); } } return stack; } @Override public void appendHoverText(ItemStack pStack, @Nullable Level pLevel, List<Component> pTooltipComponents, TooltipFlag pIsAdvanced) { super.appendHoverText(pStack, pLevel, pTooltipComponents, pIsAdvanced); // TODO add information on setting/quality? } public SphereItem swap() { if (infused) { return WorldSetup.DUN_SPHERES.get(setting.getIndex()).get(); } else { return WorldSetup.INFUSED_SPHERES.get(setting.getIndex()).get(); } } @Override public Rarity getRarity(ItemStack stack) { return infused ? Rarity.RARE : Rarity.COMMON; } }
3,139
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Surge.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/util/Surge.java
package com.legobmw99.stormlight.util; import com.legobmw99.stormlight.modules.powers.Surges; import com.legobmw99.stormlight.modules.powers.client.SurgeEffects; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import javax.annotation.Nullable; public enum Surge { ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect), GRAVITATION(Surges::gravitation), DIVISION(Surges::division), ABRASION(Surges::abrasion), PROGRESSION(Surges::progression, SurgeEffects::progressionEffect), ILLUMINATION(Surges::illumination), TRANSFORMATION(Surges::transformation), TRANSPORTATION(Surges::transportation, 40F), COHESION(Surges::cohesion), TENSION(Surges::tension); private final ISurgePower surge; private final ISurgeEffect effect; private final float range; private final boolean repeating; Surge(ISurgePower surge) { this(surge, 30F, false, null); } Surge(ISurgePower surge, float range) { this(surge, range, false, null); } Surge(ISurgePower surge, float range, boolean repeating) { this(surge, range, repeating, null); } Surge(ISurgePower surge, ISurgeEffect effect) { this(surge, 30F, false, effect); } Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) { this.surge = surge; this.range = range; this.repeating = repeating; this.effect = effect; } public boolean hasEffect() { return effect != null; } public boolean isRepeating() {return repeating;} public float getRange() { return range; } public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) { surge.fire(player, looking, modified); } public void displayEffect(BlockPos looking, boolean modified) { if (hasEffect()) { effect.fire(looking, modified); } } } @FunctionalInterface interface ISurgePower { void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified); } @FunctionalInterface interface ISurgeEffect { void fire(BlockPos looking, boolean modified); }
2,202
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Gemstone.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/util/Gemstone.java
package com.legobmw99.stormlight.util; import net.minecraft.util.StringRepresentable; import java.util.Locale; public enum Gemstone implements StringRepresentable { DIAMOND(5), EMERALD(3), QUARTZ(1); private final int modifier; Gemstone(int mod) { this.modifier = mod; } public int getModifier() { return modifier; } public String getName() { return name().toLowerCase(Locale.ROOT); } public int getIndex() { return ordinal(); } @Override public String getSerializedName() { return this.getName(); } }
610
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Ideal.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/util/Ideal.java
package com.legobmw99.stormlight.util; import java.util.Locale; public enum Ideal { TRAITOR, UNINVESTED, FIRST, SECOND, THIRD, FOURTH, FIFTH; public static Ideal get(int index) { for (Ideal order : values()) { if (order.getIndex() == index) { return order; } } throw new IllegalArgumentException("Bad ideal index"); } public String getName() { return name().toLowerCase(Locale.ROOT); } public int getIndex() { return ordinal() - 1; } public Ideal progressIdeal() { int i = getIndex() + 1; if (i > 5) { i = 5; } return get(i); } public Ideal regressIdeal() { int i = getIndex() - 1; if (i < -1) { i = -1; } return get(i); } }
869
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Order.java
/FileExtraction/Java_unseen/legobmw99_Stormlight/src/main/java/com/legobmw99/stormlight/util/Order.java
package com.legobmw99.stormlight.util; import java.util.Locale; import static com.legobmw99.stormlight.util.Ideal.*; import static com.legobmw99.stormlight.util.Surge.*; public enum Order { WINDRUNNERS(ADHESION, GRAVITATION), SKYBREAKERS(GRAVITATION, DIVISION), DUSTBRINGERS(DIVISION, ABRASION), EDGEDANCERS(ABRASION, PROGRESSION), TRUTHWATCHERS(PROGRESSION, ILLUMINATION), LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION), ELSECALLERS(TRANSFORMATION, TRANSPORTATION), WILLSHAPERS(TRANSPORTATION, COHESION), STONEWARDS(COHESION, TENSION), BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD); private final Surge first; private final Surge second; private final Ideal blade_gate; private final Ideal first_gate; private final Ideal second_gate; Order(Surge fst, Surge snd) { this(fst, snd, FIRST, FIRST, FIRST); } Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) { this.first = fst; this.second = snd; this.blade_gate = blade; this.first_gate = first; this.second_gate = second; } public static Order getOrNull(int index) { for (Order order : values()) { if (order.getIndex() == index) { return order; } } return null; } public Surge getFirst() { return first; } public Surge getSecond() { return second; } public Ideal getFirstIdeal() {return first_gate;} public Ideal getSecondIdeal() {return second_gate;} public Ideal getBladeIdeal() {return blade_gate;} public String getName() { return name().toLowerCase(Locale.ROOT); } public String getSingularName() { String name = this.getName(); return name.substring(0, name.length() - 1); } public int getIndex() { return ordinal(); } public boolean hasSurge(Surge surge) { return first == surge || second == surge; } }
2,009
Java
.java
legobmw99/Stormlight
11
1
1
2016-08-30T01:45:37Z
2023-03-19T21:10:24Z
Test.java
/FileExtraction/Java_unseen/GalaxySciTech_tokencore/src/test/java/org/consenlabs/tokencore/Test.java
// package org.consenlabs.tokencore; // import cn.hutool.core.codec.Base64; // import com.fasterxml.jackson.databind.ObjectMapper; // import org.consenlabs.tokencore.foundation.utils.MnemonicUtil; // import org.consenlabs.tokencore.wallet.Identity; // import org.consenlabs.tokencore.wallet.KeystoreStorage; // import org.consenlabs.tokencore.wallet.Wallet; // import org.consenlabs.tokencore.wallet.WalletManager; // import org.consenlabs.tokencore.wallet.model.ChainId; // import org.consenlabs.tokencore.wallet.model.ChainType; // import org.consenlabs.tokencore.wallet.model.Metadata; // import org.consenlabs.tokencore.wallet.model.Network; // import org.consenlabs.tokencore.wallet.transaction.BitcoinTransaction; // import org.consenlabs.tokencore.wallet.transaction.TronTransaction; // import org.consenlabs.tokencore.wallet.transaction.TxSignResult; // import org.tron.trident.core.ApiWrapper; // import org.tron.trident.core.exceptions.IllegalException; // import org.tron.trident.proto.Response; // import java.io.File; // import java.nio.file.Files; // import java.nio.file.Paths; // import java.util.ArrayList; // public class Test implements KeystoreStorage { // static String path = "/tmp"; // @Override // public File getKeystoreDir() { // return new File(path); // } // static public void init() { // try { // Files.createDirectories(Paths.get(path + "/wallets")); // } catch (Throwable ignored) { // } // //KeystoreStorage是接口,实现它的getdir方法 // WalletManager.storage = new Test(); // WalletManager.scanWallets(); // String password = "123456"; // Identity identity = Identity.getCurrentIdentity(); // if (identity == null) { // Identity.createIdentity( // "token", // password, // "", // Network.MAINNET, // Metadata.P2WPKH // ); // } // } // static public void genBitcoinWallet() { // init(); // Identity identity = Identity.getCurrentIdentity(); // String password = "123456"; // Wallet wallet = identity.deriveWalletByMnemonics( // ChainType.BITCOIN, // password, // MnemonicUtil.randomMnemonicCodes() // ); // System.out.println(wallet.getAddress()); // } // static public void genFilecoinWallet() { // init(); // Identity identity = Identity.getCurrentIdentity(); // String password = "123456"; // Wallet wallet = identity.deriveWalletByMnemonics( // ChainType.FILECOIN, // password, // MnemonicUtil.randomMnemonicCodes() // ); // System.out.println(wallet.getAddress()); // String privateKey=wallet.exportPrivateKey("123456"); // System.out.println(privateKey); // } // static public void signBitcoinTx() { // init(); // String password = "123456"; // String toAddress = "33sXfhCBPyHqeVsVthmyYonCBshw5XJZn9"; // int changeIdx = 0; // long amount = 1000L; // long fee = 555L; // //utxos需要去节点或者外部api获取 // ArrayList<BitcoinTransaction.UTXO> utxos = new ArrayList(); // BitcoinTransaction bitcoinTransaction = new BitcoinTransaction( // toAddress, // changeIdx, // amount, // fee, // utxos // ); // Wallet wallet = WalletManager.findWalletByAddress(ChainType.BITCOIN, "33sXfhCBPyHqeVsVthmyYonCBshw5XJZn9"); // TxSignResult txSignResult = bitcoinTransaction.signTransaction( // String.valueOf(ChainId.BITCOIN_MAINNET), // password, // wallet // ); // System.out.println(txSignResult); // } // static public void signTrxTx() { // init(); // String from = "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8"; // String to = "TF17BgPaZYbz8oxbjhriubPDsA7ArKoLX3"; // long amount = 1; // String password = "123456"; // Wallet wallet = WalletManager.findWalletByAddress(ChainType.BITCOIN, "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8"); // TronTransaction transaction = new TronTransaction(from, to, amount); // //离线签名,不建议签名和广播放一块 // TxSignResult txSignResult = transaction.signTransaction(String.valueOf(ChainId.BITCOIN_MAINNET), password, wallet); // System.out.println(txSignResult); // } // public static void main(String[] args) throws IllegalException { // ApiWrapper tronClient= ApiWrapper.ofMainnet(""); // Response.TransactionInfo tx=tronClient.getTransactionInfoById("f3a54e8418edb5a91772e3fe6768a7a4e55fc6c33f212641c239589d8a453a58"); // System.out.println(tx); // } // }
4,998
Java
.java
GalaxySciTech/tokencore
418
38
5
2019-01-22T10:30:29Z
2023-12-25T03:34:34Z