Search in sources :

Example 1 with ILuaContext

use of dan200.computercraft.api.lua.ILuaContext in project LogisticsPipes by RS485.

the class CCCommandWrapper method callMethod.

@Override
public Object[] callMethod(@Nonnull ILuaContext context, int methodId, @Nonnull Object[] arguments) {
    if (methodId == 0) {
        return help(arguments);
    }
    methodId--;
    if (methodId == 0) {
        return helpCommand(arguments);
    }
    methodId--;
    if (methodId == 0) {
        return CCObjectWrapper.createArray(info.type);
    }
    methodId--;
    String name = info.commandMap.get(methodId);
    Method match = null;
    for (Method method : info.commands.values()) {
        if (!method.getName().equalsIgnoreCase(name)) {
            continue;
        }
        if (!argumentsMatch(method, arguments)) {
            continue;
        }
        match = method;
        break;
    }
    if (match == null) {
        StringBuilder error = new StringBuilder();
        error.append("No such method.");
        boolean handled = false;
        for (Method method : info.commands.values()) {
            if (!method.getName().equalsIgnoreCase(name)) {
                continue;
            }
            if (handled) {
                error.append("\n");
            }
            handled = true;
            error.append(method.getName());
            error.append("(");
            boolean a = false;
            for (Class<?> clazz : method.getParameterTypes()) {
                if (a) {
                    error.append(", ");
                }
                error.append(clazz.getName());
                a = true;
            }
            error.append(")");
        }
        if (!handled) {
            error = new StringBuilder();
            error.append("Internal Excption (Code: 1, ");
            error.append(name);
            error.append(")");
        }
        throw new UnsupportedOperationException(error.toString());
    }
    if (match.getAnnotation(CCDirectCall.class) != null) {
        if (!isDirectCall) {
            throw new PermissionException();
        }
    }
    if (match.getAnnotation(CCCommand.class).needPermission()) {
        if (info.securityMethod != null) {
            try {
                info.securityMethod.invoke(object);
            } catch (InvocationTargetException e) {
                if (e.getTargetException() instanceof Exception) {
                    throw new RuntimeException(e.getTargetException());
                }
                throw new RuntimeException(e);
            } catch (IllegalAccessException | IllegalArgumentException e) {
                throw new RuntimeException(e);
            }
        }
    }
    if (match.getAnnotation(CCQueued.class) != null) {
        final Method m = match;
        final Object[] a = arguments;
        final Object[] resultArray = new Object[1];
        final Boolean[] booleans = new Boolean[2];
        booleans[0] = false;
        booleans[1] = false;
        QueuedTasks.queueTask(() -> {
            try {
                Object result = m.invoke(object, a);
                if (result != null) {
                    resultArray[0] = result;
                }
            } catch (InvocationTargetException e) {
                if (e.getTargetException() instanceof PermissionException) {
                    booleans[1] = true;
                    resultArray[0] = e.getTargetException();
                } else {
                    booleans[0] = true;
                    throw e;
                }
            }
            booleans[0] = true;
            return null;
        });
        int count = 0;
        while (!booleans[0] && count < 200) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            count++;
        }
        if (count >= 199) {
            LogisticsPipes.log.warn("CC call " + m.getName() + " on " + object.getClass().getName() + ", (" + object.toString() + ") took too long.");
            throw new RuntimeException("Took too long");
        }
        if (m.getReturnType().equals(Void.class)) {
            return null;
        }
        if (booleans[1]) {
            // PermissionException
            throw ((RuntimeException) resultArray[0]);
        }
        return CCObjectWrapper.createArray(CCObjectWrapper.getWrappedObject(resultArray[0], CCCommandWrapper.WRAPPER));
    }
    Object result;
    try {
        result = match.invoke(object, arguments);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof Exception) {
            throw new RuntimeException(e.getTargetException());
        }
        throw new RuntimeException(e);
    } catch (IllegalAccessException | IllegalArgumentException e) {
        throw new RuntimeException(e);
    }
    return CCObjectWrapper.createArray(CCObjectWrapper.getWrappedObject(result, CCCommandWrapper.WRAPPER));
}
Also used : PermissionException(logisticspipes.security.PermissionException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PermissionException(logisticspipes.security.PermissionException) CCQueued(logisticspipes.proxy.computers.interfaces.CCQueued) ILuaObject(dan200.computercraft.api.lua.ILuaObject) CCDirectCall(logisticspipes.proxy.computers.interfaces.CCDirectCall) CCCommand(logisticspipes.proxy.computers.interfaces.CCCommand)

Example 2 with ILuaContext

use of dan200.computercraft.api.lua.ILuaContext in project Minechem by iopleke.

the class ChemicalTurtlePeripheral method addLuaMethods.

@Optional.Method(modid = "ComputerCraft")
protected void addLuaMethods() {
    methods.add(new LuaMethod("getMethods") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                String[] result = new String[methods.size()];
                int i = 0;
                for (LuaMethod method : methods) {
                    result[i++] = method.getMethodName() + method.getArgs();
                }
                return result;
            } else {
                throw new LuaException("getMethods does not take any arguments");
            }
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Returns: List of Method Names and Arguments" };
        }
    });
    methods.add(new LuaMethod("getDetails") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 1) {
                String methodName = (String) args[0];
                if (methodName != null) {
                    for (LuaMethod method : methods) {
                        if (method.getMethodName().equalsIgnoreCase(methodName)) {
                            return method.getDetails();
                        }
                    }
                }
                throw new LuaException("Invalid Method Name - do not include brackets");
            } else {
                throw new LuaException("getDetails takes a single argument");
            }
        }

        @Override
        public String getArgs() {
            return "(Method Name)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Method Name - from getMethods()", "Returns: Details of arguments and results" };
        }
    });
    methods.add(new LuaMethod("getChemicalName") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                String result = getName(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    String result = getName(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private String getName(int slot) {
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            if (Compare.isStackAnElement(current)) {
                return current.getDisplayName();
            } else if (Compare.isStackAMolecule(current)) {
                return current.getDisplayName();
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Chemical name of stack in slot, or nil if not a chemical" };
        }
    });
    methods.add(new LuaMethod("getChemicalFormula") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                String result = getChemicalFormula(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    String result = getChemicalFormula(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private String getChemicalFormula(int slot) {
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            if (Compare.isStackAnElement(current)) {
                return ElementItem.getElement(current).name();
            }
            if (Compare.isStackAMolecule(current)) {
                return MoleculeItem.getMolecule(current).getFormula();
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Chemical formula of stack in slot, or nil if not a chemical" };
        }
    });
    methods.add(new LuaMethod("getChemicalsAsTable") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                HashMap<Number, Object> result = getChemicalsAsTable(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    HashMap<Number, Object> result = getChemicalsAsTable(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private HashMap<Number, Object> getChemicalsAsTable(int slot) {
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            HashMap<Number, Object> map = new HashMap<Number, Object>();
            if (Compare.isStackAnElement(current)) {
                HashMap<String, Object> chemMap = new HashMap<String, Object>();
                chemMap.put("chemical", current.getDisplayName());
                chemMap.put("quantity", 1);
                map.put(1, chemMap);
                return map;
            }
            if (Compare.isStackAMolecule(current)) {
                MoleculeEnum molecule = MoleculeItem.getMolecule(current);
                ArrayList<PotionChemical> chemicals = molecule.components();
                for (int i = 0; i < chemicals.size(); i++) {
                    PotionChemical chemical = chemicals.get(i);
                    HashMap<String, Object> chemMap = new HashMap<String, Object>();
                    chemMap.put("chemical", MinechemUtil.getChemicalName(chemical));
                    chemMap.put("quantity", chemical.amount);
                    map.put(i + 1, chemMap);
                }
                return map;
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Chemical formula of stack in slot as a table, or nil if not a chemical" };
        }
    });
    methods.add(new LuaMethod("getAtomicMass") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                Integer result = getAtomicMass(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    Integer result = getAtomicMass(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private Integer getAtomicMass(Integer slot) {
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            if (Compare.isStackAnElement(current)) {
                return ElementItem.getElement(current).atomicNumber();
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Atomic Mass of elements" };
        }
    });
    methods.add(new LuaMethod("getRadioactivity") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                String result = getRadioactivity(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    String result = getRadioactivity(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private String getRadioactivity(Integer slot) {
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            if (Compare.isStackAnElement(current)) {
                return ElementItem.getElement(current).radioactivity().toString();
            } else if (Compare.isStackAMolecule(current)) {
                return MoleculeItem.getMolecule(current).radioactivity().toString();
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Radioactivity level of chemicals" };
        }
    });
    methods.add(new LuaMethod("getDecayTimeInTicks") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                Object result = getDecayTime(turtle.getSelectedSlot());
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    Object result = getDecayTime(slot);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Time left to Radioactive Decay in Ticks - Infinite for stable chemicals, null for non-chemicals" };
        }
    });
    methods.add(new LuaMethod("getDecayTime") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                Object result = getDecayTime(turtle.getSelectedSlot());
                if (result != null) {
                    if (result instanceof Long) {
                        return new Object[] { TimeHelper.getTimeFromTicks((Long) result) };
                    } else if (result instanceof String) {
                        return new Object[] { result };
                    }
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    Object result = getDecayTime(slot);
                    if (result != null) {
                        if (result instanceof Long) {
                            return new Object[] { TimeHelper.getTimeFromTicks((Long) result) };
                        } else if (result instanceof String) {
                            return new Object[] { result };
                        }
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Time left to Radioactive Decay - Infinite for stable chemicals, null for non-chemicals" };
        }
    });
    methods.add(new LuaMethod("syncJournal") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                String result = sync(turtle.getSelectedSlot(), computer);
                if (result != null) {
                    return new Object[] { result };
                }
            } else if (args.length == 1) {
                Integer slot = getInt(args[0]);
                if (validateInteger(slot, turtle.getInventory().getSizeInventory())) {
                    String result = sync(slot, computer);
                    if (result != null) {
                        return new Object[] { result };
                    }
                } else {
                    throw new LuaException("Invalid Slot Number.");
                }
            } else {
                throw new LuaException("Maximum 1 argument for slot number.");
            }
            return null;
        }

        private String sync(int slot, IComputerAccess computer) throws LuaException {
            ItemStack journal = getJournal(slot);
            if (journal != null) {
                return upload(journal) + " - " + download(journal, computer);
            }
            ItemStack book = getBook(slot);
            if (book != null) {
                return download(book, slot, computer);
            }
            throw new LuaException("Invalid Stack - not a journal or a book");
        }

        private String upload(ItemStack journal) {
            List<MapKey> journalItems = stackListToKeys(MinechemItemsRegistration.journal.getItemList(journal));
            if (journalItems == null) {
                journalItems = new ArrayList<MapKey>();
            }
            ArrayList<MapKey> addItems = new ArrayList<MapKey>();
            addItems.addAll(journalItems);
            addItems.removeAll(known);
            known.addAll(addItems);
            int added = addItems.size();
            return "Loaded " + added + " recipe" + (added != 1 ? "s" : "");
        }

        private String download(ItemStack journal, IComputerAccess computer) {
            return download(journal, -1, computer);
        }

        private String download(ItemStack journal, int slot, IComputerAccess computer) {
            if (journal.getItem() == Items.book) {
                journal = new ItemStack(MinechemItemsRegistration.journal);
            }
            List<MapKey> journalItems = stackListToKeys(MinechemItemsRegistration.journal.getItemList(journal));
            if (journalItems == null) {
                journalItems = new ArrayList<MapKey>();
            }
            ArrayList<MapKey> addItems = new ArrayList<MapKey>();
            addItems.addAll(known);
            addItems.removeAll(journalItems);
            for (ItemStack item : keyListToStacks(addItems)) {
                MinechemItemsRegistration.journal.addItemStackToJournal(item, journal, turtle.getWorld());
            }
            int added = addItems.size();
            String owner = journal.stackTagCompound.getString("owner");
            if (owner.equals("")) {
                journal.stackTagCompound.setString("owner", "Chemistry Turtle " + computer.getID());
            }
            if (!(slot < 0)) {
                turtle.getInventory().setInventorySlotContents(slot, journal);
            }
            return "Saved " + added + " recipe" + (added != 1 ? "s" : "");
        }

        private ItemStack getBook(int slot) {
            ItemStack result = turtle.getInventory().getStackInSlot(slot);
            if (result.getItem() == Items.book && result.stackSize == 1) {
                return result;
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Slot Number, defaults to current slot", "Returns: Number of Journal Entries loaded and saved" };
        }
    });
    methods.add(new LuaMethod("readRecipe") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            ForgeDirection dir = null;
            if (args.length == 0) {
                dir = getDirForString("front", turtle);
            } else if (args.length == 1) {
                dir = getDirForString((String) args[0], turtle);
            }
            if (dir == null) {
                throw new LuaException("Invalid Arguments");
            }
            TileEntity te = turtle.getWorld().getTileEntity(turtle.getPosition().posX + dir.offsetX, turtle.getPosition().posY + dir.offsetY, turtle.getPosition().posZ + dir.offsetZ);
            if (te != null) {
                if (te instanceof SynthesisTileEntity) {
                    SynthesisRecipe thisRecipe = ((SynthesisTileEntity) te).getCurrentRecipe();
                    if (thisRecipe != null) {
                        if (addStackToKnown(thisRecipe.getOutput())) {
                            return new Object[] { "Synthesis Recipe Scanned", stackToMap(thisRecipe.getOutput()) };
                        } else {
                            return new Object[] { "Item already known" };
                        }
                    }
                } else if (te instanceof DecomposerTileEntity) {
                    DecomposerRecipe thisRecipe = DecomposerRecipe.get(((DecomposerTileEntity) te).inventory[((DecomposerTileEntity) te).kInputSlot]);
                    if (thisRecipe != null) {
                        if (addStackToKnown(thisRecipe.getInput())) {
                            return new Object[] { "Decomposer Recipe Scanned", stackToMap(thisRecipe.getInput()) };
                        } else {
                            return new Object[] { "Item already known" };
                        }
                    }
                } else if (te instanceof MicroscopeTileEntity) {
                    ItemStack thisStack = ((MicroscopeTileEntity) te).inventory[0];
                    if (thisStack != null) {
                        if (addStackToKnown(thisStack)) {
                            return new Object[] { "Microscope scan complete", stackToMap(thisStack) };
                        } else {
                            return new Object[] { "Item already known" };
                        }
                    }
                }
            }
            return null;
        }

        @Override
        public String getArgs() {
            return "(?Direction)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Direction, defaults to front", "Returns: Confirmtion String, Recipe read" };
        }
    });
    methods.add(new LuaMethod("getSynthesisRecipe") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 1 || args.length == 2) {
                String UUID = (String) args[0];
                Integer metadata = args.length == 2 ? getInt(args[1]) : 0;
                if (metadata == null || metadata < 0) {
                    metadata = 0;
                }
                for (ItemStack current : keyListToStacks(known)) {
                    if (GameRegistry.findUniqueIdentifierFor(current.getItem()).toString().equals(UUID) && current.getItemDamage() == metadata) {
                        SynthesisRecipe output = SynthesisRecipeHandler.instance.getRecipeFromOutput(current);
                        if (output != null) {
                            return new Object[] { synthesisRecipeToMap(output) };
                        } else {
                            return new Object[] { "No Synthesiser recipe exists for " + UUID + ":" + metadata };
                        }
                    }
                }
                return new Object[] { UUID + ":" + metadata + " is unknown." };
            } else {
                throw new LuaException("Invalid arguments");
            }
        }

        @Override
        public String getArgs() {
            return "(name,?metadata)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Args: Item Name and optional metadata, default 0", "Returns: Synthesiser Recipes in table form" };
        }
    });
    methods.add(new LuaMethod("getSynthesisRecipes") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            if (args.length == 0) {
                int i = 1;
                HashMap<Number, Object> result = new HashMap<Number, Object>();
                for (ItemStack current : keyListToStacks(known)) {
                    SynthesisRecipe output = SynthesisRecipeHandler.instance.getRecipeFromOutput(current);
                    if (output != null) {
                        result.put(i++, synthesisRecipeToMap(output));
                    }
                }
                return new Object[] { result };
            } else {
                throw new LuaException("getSynthesisRecipes does not take any arguments");
            }
        }

        @Override
        public String getArgs() {
            return "()";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Returns: All Synthesiser Recipes in table form" };
        }
    });
    methods.add(new LuaMethod("setRecipe") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            ForgeDirection dir = null;
            if (args.length > 0 && args.length < 4) {
                String UUID = null;
                dir = getDirForString((String) args[0], turtle);
                if (dir == null && args.length < 3) {
                    UUID = (String) args[0];
                    dir = getDirForString("front", turtle);
                } else if (dir == null) {
                    throw new LuaException("Invalid Arguments");
                }
                TileEntity te = turtle.getWorld().getTileEntity(turtle.getPosition().posX + dir.offsetX, turtle.getPosition().posY + dir.offsetY, turtle.getPosition().posZ + dir.offsetZ);
                if (te instanceof SynthesisTileEntity) {
                    Integer metadata = getInt(args[args.length - 1]);
                    if (metadata == null || metadata < 0) {
                        metadata = 0;
                    }
                    if (UUID == null) {
                        UUID = (String) args[1];
                    }
                    for (ItemStack current : keyListToStacks(known)) {
                        if (GameRegistry.findUniqueIdentifierFor(current.getItem()).toString().equals(UUID) && current.getItemDamage() == metadata) {
                            SynthesisRecipe output = SynthesisRecipeHandler.instance.getRecipeFromOutput(current);
                            if (output != null) {
                                ((SynthesisTileEntity) te).setRecipe(output);
                                return new Object[] { true };
                            } else {
                                return new Object[] { false };
                            }
                        }
                    }
                }
            }
            return new Object[] { false };
        }

        @Override
        public String getArgs() {
            return "(?Direction,name,?metadata)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Direction, defaults to front", "Arg: Item name", "Arg: Optional metadata, defaults to 0", "Returns: boolean success" };
        }
    });
    methods.add(new LuaMethod("setMicroscope") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            ForgeDirection dir = null;
            Integer slot = null;
            switch(args.length) {
                case 0:
                    slot = turtle.getSelectedSlot();
                    dir = getDirForString("front", turtle);
                    break;
                case 1:
                    dir = getDirForString((String) args[0], turtle);
                    if (dir == null && args.length == 1) {
                        slot = getInt(args[0]);
                        slot = validateInteger(slot, turtle.getInventory().getSizeInventory()) ? slot : null;
                        dir = getDirForString("front", turtle);
                    }
                    break;
                case 2:
                    dir = getDirForString((String) args[0], turtle);
                    slot = getInt(args[0]);
                    slot = validateInteger(slot, turtle.getInventory().getSizeInventory()) ? slot : null;
                default:
            }
            if (dir == null || slot == null) {
                throw new LuaException("Invalid Arguments");
            }
            ItemStack current = turtle.getInventory().getStackInSlot(slot);
            TileEntity te = turtle.getWorld().getTileEntity(turtle.getPosition().posX + dir.offsetX, turtle.getPosition().posY + dir.offsetY, turtle.getPosition().posZ + dir.offsetZ);
            if (te instanceof MicroscopeTileEntity) {
                ItemStack microStack = ((MicroscopeTileEntity) te).getStackInSlot(0);
                if (microStack == null && current == null) {
                    return new Object[] { false };
                } else if (microStack == null) {
                    ((MicroscopeTileEntity) te).setInventorySlotContents(0, turtle.getInventory().decrStackSize(slot, 1));
                    return new Object[] { true };
                } else if (current == null) {
                    turtle.getInventory().setInventorySlotContents(slot, ((MicroscopeTileEntity) te).decrStackSize(0, 1));
                    return new Object[] { true };
                } else if (current.isItemEqual(microStack)) {
                    if (current.stackSize < current.getMaxStackSize()) {
                        ((MicroscopeTileEntity) te).decrStackSize(0, 1);
                        current.stackSize++;
                    }
                }
            }
            return new Object[] { false };
        }

        @Override
        public String getArgs() {
            return "(?Direction,?slot)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Direction, defaults to front", "Arg: Optional slot number, defaults to current", "Returns: boolean success" };
        }
    });
    methods.add(new LuaMethod("getState") {

        @Override
        public Object[] call(IComputerAccess computer, ILuaContext context, Object[] args) throws LuaException, InterruptedException {
            ForgeDirection dir = ForgeDirection.getOrientation(turtle.getDirection());
            if (args.length < 2) {
                if (args.length == 1) {
                    dir = getDirForString((String) args[0], turtle);
                    if (dir == null) {
                        throw new LuaException("Invalid Arguments");
                    }
                }
                TileEntity te = turtle.getWorld().getTileEntity(turtle.getPosition().posX + dir.offsetX, turtle.getPosition().posY + dir.offsetY, turtle.getPosition().posZ + dir.offsetZ);
                if (te instanceof SynthesisTileEntity) {
                    return new Object[] { ((SynthesisTileEntity) te).getState() };
                } else if (te instanceof DecomposerTileEntity) {
                    return new Object[] { ((DecomposerTileEntity) te).getStateString() };
                }
                throw new LuaException("Invalid TileEntity");
            }
            throw new LuaException("Invalid Arguments");
        }

        @Override
        public String getArgs() {
            return "(?Direction)";
        }

        @Override
        public String[] getDetails() {
            return new String[] { super.getDetails()[0], "Arg: Optional Direction, defaults to front", "Returns: Machine state" };
        }
    });
}
Also used : HashMap(java.util.HashMap) DecomposerTileEntity(minechem.tileentity.decomposer.DecomposerTileEntity) ArrayList(java.util.ArrayList) PotionChemical(minechem.potion.PotionChemical) ILuaContext(dan200.computercraft.api.lua.ILuaContext) LuaException(dan200.computercraft.api.lua.LuaException) MicroscopeTileEntity(minechem.tileentity.microscope.MicroscopeTileEntity) DecomposerTileEntity(minechem.tileentity.decomposer.DecomposerTileEntity) SynthesisTileEntity(minechem.tileentity.synthesis.SynthesisTileEntity) TileEntity(net.minecraft.tileentity.TileEntity) IComputerAccess(dan200.computercraft.api.peripheral.IComputerAccess) ForgeDirection(net.minecraftforge.common.util.ForgeDirection) ArrayList(java.util.ArrayList) List(java.util.List) MoleculeEnum(minechem.item.molecule.MoleculeEnum) DecomposerRecipe(minechem.tileentity.decomposer.DecomposerRecipe) SynthesisTileEntity(minechem.tileentity.synthesis.SynthesisTileEntity) MapKey(minechem.utils.MapKey) SynthesisRecipe(minechem.tileentity.synthesis.SynthesisRecipe) LuaMethod(minechem.computercraft.lua.LuaMethod) MicroscopeTileEntity(minechem.tileentity.microscope.MicroscopeTileEntity) ItemStack(net.minecraft.item.ItemStack)

Aggregations

ILuaContext (dan200.computercraft.api.lua.ILuaContext)1 ILuaObject (dan200.computercraft.api.lua.ILuaObject)1 LuaException (dan200.computercraft.api.lua.LuaException)1 IComputerAccess (dan200.computercraft.api.peripheral.IComputerAccess)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 CCCommand (logisticspipes.proxy.computers.interfaces.CCCommand)1 CCDirectCall (logisticspipes.proxy.computers.interfaces.CCDirectCall)1 CCQueued (logisticspipes.proxy.computers.interfaces.CCQueued)1 PermissionException (logisticspipes.security.PermissionException)1 LuaMethod (minechem.computercraft.lua.LuaMethod)1 MoleculeEnum (minechem.item.molecule.MoleculeEnum)1 PotionChemical (minechem.potion.PotionChemical)1 DecomposerRecipe (minechem.tileentity.decomposer.DecomposerRecipe)1 DecomposerTileEntity (minechem.tileentity.decomposer.DecomposerTileEntity)1 MicroscopeTileEntity (minechem.tileentity.microscope.MicroscopeTileEntity)1 SynthesisRecipe (minechem.tileentity.synthesis.SynthesisRecipe)1