li.cil.oc.api.machine.Context Java Examples

The following examples show how to use li.cil.oc.api.machine.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnvironmentGeneratorTest.java    From OpenPeripheral with MIT License 6 votes vote down vote up
private static void testMethod(Object target, Object wrapper, Class<?> generatedClass, String name, IMethodExecutor executor, IMethodCall call, ArgVerifier verifier) throws Exception {
	Method m = getMethod(generatedClass, name.substring(0, 1));

	Callback callback = m.getAnnotation(Callback.class);
	Assert.assertNotNull(callback);

	Assert.assertEquals(executor.isAsynchronous(), callback.direct());

	// that's what I get for not injecting ...
	Assert.assertEquals("function()", callback.doc());

	Arguments args = mock(Arguments.class);
	final Object[] argArray = new Object[] { 1, 2, 3 };
	when(args.toArray()).thenReturn(argArray);
	Context context = mock(Context.class);

	m.invoke(wrapper, context, args);

	verify(executor).startCall(target);

	verify(args).toArray();
	verifier.verifyCall(call, context);
	verify(call).call(argArray);
}
 
Example #2
Source File: EnvironmentMotor.java    From Framez with GNU General Public License v3.0 6 votes vote down vote up
@Callback(doc = "function(face, direction):boolean -- Sets the motor's face and direction. Returns true if it succeeded, false if it didn't.")
public Object[] set(Context context, Arguments args) {

    if (args.count() < 2)
        throw new RuntimeException("At least 2 arguments are required (face, direction)");

    ForgeDirection face = toFD(args.checkAny(0));
    ForgeDirection direction = toFD(args.checkAny(1));

    if (face == null || direction == null)
        throw new RuntimeException("Invalid directions!");
    if (face == direction || face == direction.getOpposite())
        throw new RuntimeException("Motors cannot push or pull blocks!");

    // te.setFace(face, true);
    // te.setDirection(direction, true);

    return new Object[] { true };
}
 
Example #3
Source File: TickablePeripheralEnvironmentBase.java    From OpenPeripheral with MIT License 6 votes vote down vote up
protected Object[] executeSignallingTask(ITaskSink taskSink, Object target, IMethodExecutor executor, final String signal, final Context context, Arguments arguments) {
	final Object[] args = arguments.toArray();
	final IMethodCall preparedCall = prepareCall(target, executor, context);
	final int callbackId = SignallingGlobals.instance.nextCallbackId();

	taskSink.accept(new Runnable() {
		@Override
		public void run() {
			if (context.isRunning() || context.isPaused()) {
				Object[] result = callForSignal(args, preparedCall, callbackId);
				context.signal(signal, result);
			}
		}
	});

	return new Object[] { callbackId };
}
 
Example #4
Source File: TileEntityPeripheral.java    From AgriCraft with MIT License 6 votes vote down vote up
@Override
@Nullable
@Optional.Method(modid = "opencomputers")
public Object[] invoke(@Nullable String methodName, Context context, @Nullable Arguments args) throws Exception {
    // Step 0. Fetch the respective method.
    final IAgriPeripheralMethod method = AgriApi.getPeripheralMethodRegistry().get(methodName).orElse(null);

    // Step 1. Check method actually exists.
    if (method == null) {
        return null;
    }

    // Step 2. Convert arguments to object array.
    final Object[] argObjects = (args == null) ? null : args.toArray();

    // Step 3. Attempt to evaluate the method.
    try {
        return method.call(this.getWorld(), this.getPos(), this.getJournal(), argObjects);
    } catch (IAgriPeripheralMethod.InvocationException e) {
        throw new Exception(e.getDescription());
    }
}
 
Example #5
Source File: TileEntity_GTDataServer.java    From bartworks with MIT License 5 votes vote down vote up
@Optional.Method(modid = "OpenComputers")
@Callback
public Object[] listData(Context context, Arguments args) {
    Set<String> ret = new HashSet<>();
    for (Map.Entry<Long,GT_NBT_DataBase> entry : OrbDataBase.entrySet()){
        ret.add((entry.getValue().getId()+Long.MAX_VALUE)+". "+entry.getValue().getmDataTitle());
    }
    return ret.toArray(new String[0]);
}
 
Example #6
Source File: TileEntityTurbineComputerPort.java    From BigReactors with MIT License 5 votes vote down vote up
@Override
@Optional.Method(modid = "OpenComputers")
public Object[] invoke(final String method, final Context context,
					   final Arguments args) throws Exception {
	final Object[] arguments = new Object[args.count()];
	for (int i = 0; i < args.count(); ++i) {
		arguments[i] = args.checkAny(i);
	}
	final Integer methodId = methodIds.get(method);
	if (methodId == null) {
		throw new NoSuchMethodError();
	}
	return callMethod(methodId, arguments);
}
 
Example #7
Source File: DriverPneumaticCraft.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object[] invoke(String method, Context context, Arguments args) throws Exception{
    if("greet".equals(method)) {
        return new Object[]{String.format("Hello, %s!", args.checkString(0))};
    }
    List<ILuaMethod> luaMethods = tile.getLuaMethods();
    for(ILuaMethod m : luaMethods) {
        if(m.getMethodName().equals(method)) {
            return m.call(args.toArray());
        }
    }
    throw new IllegalArgumentException("Can't invoke method with name \"" + method + "\". not registered");
}
 
Example #8
Source File: EnvironmentGeneratorTest.java    From OpenPeripheral with MIT License 5 votes vote down vote up
@Test
public void testObject() throws Exception {
	setupEnvMocks();

	Map<String, Pair<IMethodExecutor, IMethodCall>> mocks = Maps.newHashMap();
	addDefaultMethods(mocks);

	Map<String, IMethodExecutor> methods = extractExecutors(mocks);

	ICodeGenerator generator = new ObjectCodeGenerator();

	Class<?> cls = generateClass("TestClass\u2656", TargetClass.class, ImmutableSet.of(InterfaceA.class, InterfaceB.class), methods, generator);

	final TargetClass target = mock(TargetClass.class);
	Object o = cls.getConstructor(TargetClass.class).newInstance(target);

	Assert.assertTrue(o instanceof ICallerBase);
	Assert.assertTrue(o instanceof Value);
	Assert.assertTrue(o instanceof InterfaceA);
	Assert.assertTrue(o instanceof InterfaceB);

	verifyCallThrough(target, o);

	testMethods(mocks, cls, target, o, new ArgVerifier() {
		@Override
		public void verifyCall(IMethodCall call, Context context) {
			verify(ModuleOpenComputers.ENV).addObjectArgs(call, context);
		}
	});
}
 
Example #9
Source File: ModuleOpenComputers.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public static void init() {
	final MethodSelector peripheralSelector = new MethodSelector(Constants.ARCH_OPEN_COMPUTERS)
			.allowReturnSignal()
			.addDefaultEnv()
			.addProvidedEnv(Constants.ARG_ACCESS, IArchitectureAccess.class)
			.addProvidedEnv(Constants.ARG_CONTEXT, Context.class)
			.addProvidedEnv(Constants.ARG_NODE, Node.class);

	PERIPHERAL_METHODS_FACTORY = new EnvironmentMethodsFactory<ManagedEnvironment>(
			AdapterRegistry.PERIPHERAL_ADAPTERS,
			peripheralSelector,
			PERIPHERAL_CLASS_PREFIX,
			new PeripheralCodeGenerator());

	InjectedClassesManager.instance.registerProvider(PERIPHERAL_CLASS_PREFIX, new EnvironmentClassBytesProvider<ManagedEnvironment>(PERIPHERAL_METHODS_FACTORY));

	final MethodSelector objectSelector = new MethodSelector(Constants.ARCH_OPEN_COMPUTERS)
			// .allowReturnSignal() // for symmetry with CC
			.addDefaultEnv()
			.addProvidedEnv(Constants.ARG_CONTEXT, Context.class);

	OBJECT_METHODS_FACTORY = new EnvironmentMethodsFactory<Value>(
			AdapterRegistry.OBJECT_ADAPTERS,
			objectSelector,
			OBJECT_CLASS_PREFIX,
			new ObjectCodeGenerator());

	InjectedClassesManager.instance.registerProvider(OBJECT_CLASS_PREFIX, new EnvironmentClassBytesProvider<Value>(OBJECT_METHODS_FACTORY));

	CommandDump.addArchSerializer("OpenComputers", "peripheral", DocBuilder.TILE_ENTITY_DECORATOR, PERIPHERAL_METHODS_FACTORY);
	CommandDump.addArchSerializer("OpenComputers", "object", DocBuilder.SCRIPT_OBJECT_DECORATOR, OBJECT_METHODS_FACTORY);

	final IConverter converter = new TypeConversionRegistryOC();
	TypeConvertersProvider.INSTANCE.registerConverter(Constants.ARCH_OPEN_COMPUTERS, converter);

	TypeClassifier.INSTANCE.registerType(Value.class, SingleArgType.OBJECT);

	ENV = new OpenComputersEnv(converter);
}
 
Example #10
Source File: OpenComputersEnv.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public IMethodCall addPeripheralArgs(IMethodCall call, Node node, Context context) {
	final OCArchitectureAccess wrapper = new OCArchitectureAccess(node, context, converter);
	return addCommonArgs(call, context)
			.setEnv(Constants.ARG_ARCHITECTURE, wrapper)
			.setEnv(Constants.ARG_ACCESS, wrapper)
			.setEnv(Constants.ARG_NODE, node);
}
 
Example #11
Source File: EnvironmentGeneratorTest.java    From OpenPeripheral with MIT License 5 votes vote down vote up
@Test
public void testPeripheral() throws Exception {
	setupEnvMocks();

	final Node node = setupOpenComputersApiMock();

	Map<String, Pair<IMethodExecutor, IMethodCall>> mocks = Maps.newHashMap();
	addDefaultMethods(mocks);
	Map<String, IMethodExecutor> methods = extractExecutors(mocks);

	ICodeGenerator generator = new PeripheralCodeGenerator();

	Class<?> cls = generateClass("TestClass\u2652", TargetClass.class, ImmutableSet.of(InterfaceA.class, InterfaceB.class), methods, generator);

	final TargetClass target = mock(TargetClass.class);
	Object o = cls.getConstructor(TargetClass.class).newInstance(target);

	Assert.assertTrue(o instanceof ICallerBase);
	Assert.assertTrue(o instanceof ManagedEnvironment);
	Assert.assertTrue(o instanceof InterfaceA);
	Assert.assertTrue(o instanceof InterfaceB);

	ManagedEnvironment e = (ManagedEnvironment)o;
	Assert.assertFalse(e.canUpdate());

	verifyCallThrough(target, o);

	testMethods(mocks, cls, target, o, new ArgVerifier() {
		@Override
		public void verifyCall(IMethodCall call, Context context) {
			verify(ModuleOpenComputers.ENV).addPeripheralArgs(call, node, context);
		}
	});
}
 
Example #12
Source File: TileEntityReactorComputerPort.java    From BigReactors with MIT License 5 votes vote down vote up
@Override
@Optional.Method(modid = "OpenComputers")
public Object[] invoke(final String method, final Context context,
					   final Arguments args) throws Exception {
	final Object[] arguments = new Object[args.count()];
	for (int i = 0; i < args.count(); ++i) {
		arguments[i] = args.checkAny(i);
	}
	final Integer methodId = methodIds.get(method);
	if (methodId == null) {
		throw new NoSuchMethodError();
	}
	return callMethod(methodId, arguments);
}
 
Example #13
Source File: PeripheralEnvironmentBase.java    From OpenPeripheral with MIT License 5 votes vote down vote up
protected void onConnect(IAttachable target, Node node) {
	final Environment host = node.host();
	if (host instanceof Context) {
		IArchitectureAccess access = accessCache.getOrCreate((Context)host);
		target.addComputer(access);
	}
}
 
Example #14
Source File: TileEntityDroneInterface.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Optional.Method(modid = ModIds.OPEN_COMPUTERS)
public Object[] invoke(String method, Context context, Arguments args) throws Exception{
    if("greet".equals(method)) return new Object[]{String.format("Hello, %s!", args.checkString(0))};
    for(ILuaMethod m : luaMethods) {
        if(m.getMethodName().equals(method)) {
            return m.call(args.toArray());
        }
    }
    throw new IllegalArgumentException("Can't invoke method with name \"" + method + "\". not registered");
}
 
Example #15
Source File: EnvironmentGeneratorTest.java    From OpenPeripheral with MIT License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testPeripheralNullTarget() throws Throwable {
	setupEnvMocks();
	setupOpenComputersApiMock();

	Map<String, Pair<IMethodExecutor, IMethodCall>> mocks = Maps.newHashMap();
	addMethod(mocks, "a1", true, "desc1");

	Map<String, IMethodExecutor> methods = extractExecutors(mocks);

	ICodeGenerator generator = new PeripheralCodeGenerator();

	Class<?> cls = generateClass("TestClass\u2655", TargetClass.class, ImmutableSet.<Class<?>> of(), methods, generator);

	Object o = cls.getConstructor(TargetClass.class).newInstance(new Object[] { null });

	Assert.assertTrue(o instanceof ManagedEnvironment);

	Method m = getMethod(cls, "a1");

	Arguments args = mock(Arguments.class);
	Context context = mock(Context.class);

	try {
		m.invoke(o, context, args);
	} catch (InvocationTargetException e) {
		throw e.getTargetException();
	}
}
 
Example #16
Source File: EnvironmentGeneratorTest.java    From OpenPeripheral with MIT License 5 votes vote down vote up
private static void setupEnvMocks() {
	IConverter converter = mock(IConverter.class);
	TypeConvertersProvider.INSTANCE.registerConverter(Constants.ARCH_OPEN_COMPUTERS, converter);

	final OpenComputersEnv env = mock(OpenComputersEnv.class);
	when(env.addObjectArgs(any(IMethodCall.class), any(Context.class))).then(returnFirstArg());
	when(env.addPeripheralArgs(any(IMethodCall.class), any(Node.class), any(Context.class))).then(returnFirstArg());
	ModuleOpenComputers.ENV = env;
}
 
Example #17
Source File: EnvironmentMotor.java    From Framez with GNU General Public License v3.0 5 votes vote down vote up
@Callback(doc = "function(direction):boolean -- Sets the motor's direction. Returns true if it succeeded, false if it didn't.")
public Object[] setDirection(Context context, Arguments args) {

    if (args.count() == 0)
        throw new RuntimeException("At least 1 argument is required (direction)");
    return new Object[] { /* te.setDirection(toFD(args.checkAny(0))) */};
}
 
Example #18
Source File: FabricatorTileEntity.java    From EmergingTechnology with MIT License 5 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] setProgram(Context context, Arguments args) {

    boolean success = false;
    String message = "There was an error setting the program";

    try {

        int max = FabricatorRecipes.getRecipes().size() - 1;

        Object[] arguments = args.toArray();

        if (arguments == null) {
            message = "Invalid argument. Must be integer between 0 and " + max;
            return new Object[] { success, message };
        }

        Double thing = (Double) arguments[0];

        int program = thing.intValue();

        if (program < 0 || program > max) {
            message = "Invalid argument. Must be integer between 0 and " + max;
        } else {
            this.setProgram(program);
            success = true;
            message = "Fabricator program set to " + program;
        }

    } catch (Exception ex) {
        message = ex.toString();
    }

    return new Object[] { success, message };
}
 
Example #19
Source File: GPSTileEntity.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getRotation(Context context, Arguments args) {
    java.util.Optional<PhysicsObject> physicsObjectOptional = ValkyrienUtils
        .getPhysicsObject(getWorld(), getPos());
    if (physicsObjectOptional.isPresent()) {
        PhysicsWrapperEntity ship = physicsObjectOptional.get()
            .getWrapperEntity();
        return new Object[]{ship.getYaw(), ship.getPitch(), ship.getRoll()};
    }
    return null;
}
 
Example #20
Source File: GPSTileEntity.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getPosition(Context context, Arguments args) {
    java.util.Optional<PhysicsObject> physicsObjectOptional = ValkyrienUtils
        .getPhysicsObject(getWorld(), getPos());
    if (physicsObjectOptional.isPresent()) {
        BlockPos pos = physicsObjectOptional.get()
            .getWrapperEntity()
            .getPosition();
        return new Object[]{pos.getX(), pos.getY(), pos.getZ()};
    }
    return null;
}
 
Example #21
Source File: PeripheralEnvironmentBase.java    From OpenPeripheral with MIT License 5 votes vote down vote up
protected void onDisconnect(IAttachable target, Node node) {
	final Environment host = node.host();
	if (host instanceof Context) {
		IArchitectureAccess access = accessCache.remove((Context)host);
		if (access != null) target.removeComputer(access);
	}
}
 
Example #22
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getMediumName(Context context, Arguments args) {
    String name = getItemStack().getDisplayName();
    return new Object[] { name };
}
 
Example #23
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getLightLevel(Context context, Arguments args) {
    int level = PlantHelper.getPlantLightAtPosition(world, pos);
    return new Object[] { level };
}
 
Example #24
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getEnergyLevel(Context context, Arguments args) {
    int level = getEnergy();
    return new Object[] { level };
}
 
Example #25
Source File: PeripheralEnvironmentBase.java    From OpenPeripheral with MIT License 4 votes vote down vote up
protected IMethodCall prepareCall(Object target, IMethodExecutor executor, Context context) {
	final IMethodCall call = executor.startCall(target);
	return ModuleOpenComputers.ENV.addPeripheralArgs(call, node(), context);
}
 
Example #26
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getMaxEnergyLevel(Context context, Arguments args) {
    int level = Reference.HYDROPONIC_ENERGY_CAPACITY;
    return new Object[] { level };
}
 
Example #27
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getPlantGrowth(Context context, Arguments args) {
    int growth = PlantHelper.getPlantGrowthAtPosition(world, pos.add(0, 1, 0));
    return new Object[] { growth };
}
 
Example #28
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getPlantName(Context context, Arguments args) {
    String name = PlantHelper.getPlantNameAtPosition(world, pos);
    return new Object[] { name };
}
 
Example #29
Source File: OptimiserTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getEnergyLevel(Context context, Arguments args) {
    int level = getEnergy();
    return new Object[] { level };
}
 
Example #30
Source File: HydroponicTileEntity.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Callback
@Optional.Method(modid = "opencomputers")
public Object[] getMediumGrowthMultiplier(Context context, Arguments args) {
    int probability = HydroponicHelper.getGrowthProbabilityForMedium(getItemStack());
    return new Object[] { probability };
}