57 lines
1.5 KiB
Kotlin
57 lines
1.5 KiB
Kotlin
package net.shadowfacts.asmr.program.blocks.math
|
|
|
|
import net.shadowfacts.asmr.program.ExecutableBlock
|
|
import net.shadowfacts.asmr.program.ProgramBlockInput
|
|
import net.shadowfacts.asmr.program.ProgramBlockOutput
|
|
import net.shadowfacts.asmr.program.ProgramType
|
|
import java.lang.RuntimeException
|
|
|
|
/**
|
|
* @author shadowfacts
|
|
*/
|
|
class BinaryOperatorBlock<Type: Any>(
|
|
val type: ProgramType<Type>,
|
|
val operation: Operation
|
|
): ExecutableBlock() {
|
|
|
|
init {
|
|
if (type != ProgramType.int && type != ProgramType.float) {
|
|
throw RuntimeException("BinaryOperatorBlock type must be int or float")
|
|
}
|
|
}
|
|
|
|
val left = ProgramBlockInput(type)
|
|
val right = ProgramBlockInput(type)
|
|
|
|
val output = ProgramBlockOutput(type)
|
|
|
|
override val inputs: Array<ProgramBlockInput<*>> = arrayOf(left, right)
|
|
override val outputs: Array<ProgramBlockOutput<*>> = arrayOf(output)
|
|
|
|
override fun execute() {
|
|
if (type == ProgramType.int) {
|
|
val left = left.value as Int
|
|
val right = right.value as Int
|
|
output.value = when (operation) {
|
|
Operation.add -> left + right
|
|
Operation.subtract -> left - right
|
|
Operation.multiply -> left * right
|
|
Operation.divide -> left / right
|
|
} as Type
|
|
} else if (type == ProgramType.float) {
|
|
val left = left.value as Float
|
|
val right = right.value as Float
|
|
output.value = when (operation) {
|
|
Operation.add -> left + right
|
|
Operation.subtract -> left - right
|
|
Operation.multiply -> left * right
|
|
Operation.divide -> left / right
|
|
} as Type
|
|
}
|
|
}
|
|
|
|
enum class Operation {
|
|
add, subtract, multiply, divide
|
|
}
|
|
|
|
} |