ImpreciseFraction -> Decimal

because it truly is.
This commit is contained in:
DBotThePony 2022-11-24 21:44:45 +07:00
parent 5eaa8adc6c
commit aa32dea682
Signed by: DBot
GPG Key ID: DCC23B5715498507
70 changed files with 1480 additions and 1560 deletions

View File

@ -1,11 +1,10 @@
package ru.dbotthepony.mc.otm.datagen package ru.dbotthepony.mc.otm.datagen
import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.ItemTags import net.minecraft.tags.ItemTags
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import net.minecraft.world.item.Items import net.minecraft.world.item.Items
import net.minecraftforge.common.Tags import net.minecraftforge.common.Tags
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.matter.MatterDataProvider import ru.dbotthepony.mc.otm.matter.MatterDataProvider
import ru.dbotthepony.mc.otm.registry.MItemTags import ru.dbotthepony.mc.otm.registry.MItemTags
import ru.dbotthepony.mc.otm.registry.MItems import ru.dbotthepony.mc.otm.registry.MItems
@ -91,7 +90,7 @@ fun addMatterData(provider: MatterDataProvider) {
blacklist(MItemTags.TRITANIUM_ORES) blacklist(MItemTags.TRITANIUM_ORES)
} }
provider.scope(Items.DIRT, ImpreciseFraction(1), 20.0) { provider.scope(Items.DIRT, Decimal(1), 20.0) {
equal( equal(
Items.GRASS_BLOCK, Items.GRASS_BLOCK,
Items.PODZOL, Items.PODZOL,

View File

@ -36,7 +36,7 @@ import ru.dbotthepony.mc.otm.client.render.ShockwaveRenderer;
import ru.dbotthepony.mc.otm.client.render.WidgetAtlasHolder; import ru.dbotthepony.mc.otm.client.render.WidgetAtlasHolder;
import ru.dbotthepony.mc.otm.compat.mekanism.QIOKt; import ru.dbotthepony.mc.otm.compat.mekanism.QIOKt;
import ru.dbotthepony.mc.otm.compat.mekanism.TooltipsKt; import ru.dbotthepony.mc.otm.compat.mekanism.TooltipsKt;
import ru.dbotthepony.mc.otm.core.ImpreciseFraction; import ru.dbotthepony.mc.otm.core.Decimal;
import ru.dbotthepony.mc.otm.item.ItemTritaniumArmor; import ru.dbotthepony.mc.otm.item.ItemTritaniumArmor;
import ru.dbotthepony.mc.otm.item.QuantumBatteryItem; import ru.dbotthepony.mc.otm.item.QuantumBatteryItem;
import ru.dbotthepony.mc.otm.item.weapon.AbstractWeaponItem; import ru.dbotthepony.mc.otm.item.weapon.AbstractWeaponItem;
@ -191,7 +191,7 @@ public final class OverdriveThatMatters {
WorldNetworkChannel.INSTANCE.register(); WorldNetworkChannel.INSTANCE.register();
GenericNetworkChannel.INSTANCE.register(); GenericNetworkChannel.INSTANCE.register();
ITEM_STORAGE = StorageRegistry.register(ItemStackWrapper.class, ItemStackWrapper.EMPTY, new ImpreciseFraction("3.125")); ITEM_STORAGE = StorageRegistry.register(ItemStackWrapper.class, ItemStackWrapper.EMPTY, new Decimal("3.125"));
if (ModList.get().isLoaded("mekanism")) { if (ModList.get().isLoaded("mekanism")) {
EVENT_BUS.addGenericListener(BlockEntity.class, EventPriority.NORMAL, QIOKt::attachCapabilities); EVENT_BUS.addGenericListener(BlockEntity.class, EventPriority.NORMAL, QIOKt::attachCapabilities);

View File

@ -1,11 +1,8 @@
package ru.dbotthepony.mc.otm package ru.dbotthepony.mc.otm
import net.minecraft.world.effect.MobEffect
import net.minecraft.world.effect.MobEffects
import net.minecraftforge.common.ForgeConfigSpec import net.minecraftforge.common.ForgeConfigSpec
import net.minecraftforge.fml.ModLoadingContext import net.minecraftforge.fml.ModLoadingContext
import net.minecraftforge.fml.config.ModConfig import net.minecraftforge.fml.config.ModConfig
import net.minecraftforge.registries.ForgeRegistries
import ru.dbotthepony.mc.otm.block.entity.AndroidStationBlockEntity import ru.dbotthepony.mc.otm.block.entity.AndroidStationBlockEntity
import ru.dbotthepony.mc.otm.block.entity.ChemicalGeneratorBlockEntity import ru.dbotthepony.mc.otm.block.entity.ChemicalGeneratorBlockEntity
import ru.dbotthepony.mc.otm.block.entity.matter.MatterBottlerBlockEntity import ru.dbotthepony.mc.otm.block.entity.matter.MatterBottlerBlockEntity
@ -14,24 +11,24 @@ import ru.dbotthepony.mc.otm.block.entity.matter.MatterRecyclerBlockEntity
import ru.dbotthepony.mc.otm.block.entity.matter.MatterReplicatorBlockEntity import ru.dbotthepony.mc.otm.block.entity.matter.MatterReplicatorBlockEntity
import ru.dbotthepony.mc.otm.block.entity.matter.MatterScannerBlockEntity import ru.dbotthepony.mc.otm.block.entity.matter.MatterScannerBlockEntity
import ru.dbotthepony.mc.otm.capability.BlockEnergyStorageImpl import ru.dbotthepony.mc.otm.capability.BlockEnergyStorageImpl
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.item.EnergySwordItem import ru.dbotthepony.mc.otm.item.EnergySwordItem
import ru.dbotthepony.mc.otm.registry.MNames import ru.dbotthepony.mc.otm.registry.MNames
interface VerboseBalanceValues { interface VerboseBalanceValues {
val capacity: ImpreciseFraction val capacity: Decimal
val receive: ImpreciseFraction val receive: Decimal
val extract: ImpreciseFraction val extract: Decimal
} }
interface BatteryBalanceValues : VerboseBalanceValues { interface BatteryBalanceValues : VerboseBalanceValues {
val initialBatteryLevel: ImpreciseFraction val initialBatteryLevel: Decimal
} }
interface ConciseBalanceValues { interface ConciseBalanceValues {
val capacity: ImpreciseFraction val capacity: Decimal
val throughput: ImpreciseFraction val throughput: Decimal
} }
object ServerConfig { object ServerConfig {
@ -39,13 +36,13 @@ object ServerConfig {
private val spec: ForgeConfigSpec private val spec: ForgeConfigSpec
private var registered = false private var registered = false
private fun verboseValues(name: String, storage: ImpreciseFraction, receive: ImpreciseFraction, extract: ImpreciseFraction = receive): VerboseBalanceValues { private fun verboseValues(name: String, storage: Decimal, receive: Decimal, extract: Decimal = receive): VerboseBalanceValues {
specBuilder.push(name) specBuilder.push(name)
val obj = object : VerboseBalanceValues { val obj = object : VerboseBalanceValues {
override val capacity: ImpreciseFraction by specBuilder.defineImpreciseFraction("capacity", storage, minimum = ImpreciseFraction.ONE) override val capacity: Decimal by specBuilder.defineDecimal("capacity", storage, minimum = Decimal.ONE)
override val receive: ImpreciseFraction by specBuilder.defineImpreciseFraction("receive", receive, minimum = ImpreciseFraction.ONE) override val receive: Decimal by specBuilder.defineDecimal("receive", receive, minimum = Decimal.ONE)
override val extract: ImpreciseFraction by specBuilder.defineImpreciseFraction("extract", extract, minimum = ImpreciseFraction.ONE) override val extract: Decimal by specBuilder.defineDecimal("extract", extract, minimum = Decimal.ONE)
} }
specBuilder.pop() specBuilder.pop()
@ -53,14 +50,14 @@ object ServerConfig {
return obj return obj
} }
private fun batteryValues(name: String, storage: ImpreciseFraction, receive: ImpreciseFraction, extract: ImpreciseFraction = receive, initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO): BatteryBalanceValues { private fun batteryValues(name: String, storage: Decimal, receive: Decimal, extract: Decimal = receive, initialBatteryLevel: Decimal = Decimal.ZERO): BatteryBalanceValues {
specBuilder.push(name) specBuilder.push(name)
val obj = object : BatteryBalanceValues { val obj = object : BatteryBalanceValues {
override val capacity: ImpreciseFraction by specBuilder.defineImpreciseFraction("capacity", storage, minimum = ImpreciseFraction.ONE) override val capacity: Decimal by specBuilder.defineDecimal("capacity", storage, minimum = Decimal.ONE)
override val receive: ImpreciseFraction by specBuilder.defineImpreciseFraction("receive", receive, minimum = ImpreciseFraction.ONE) override val receive: Decimal by specBuilder.defineDecimal("receive", receive, minimum = Decimal.ONE)
override val extract: ImpreciseFraction by specBuilder.defineImpreciseFraction("extract", extract, minimum = ImpreciseFraction.ONE) override val extract: Decimal by specBuilder.defineDecimal("extract", extract, minimum = Decimal.ONE)
override val initialBatteryLevel: ImpreciseFraction by specBuilder.defineImpreciseFraction("initialBatteryLevel", initialBatteryLevel, minimum = ImpreciseFraction.ZERO) override val initialBatteryLevel: Decimal by specBuilder.defineDecimal("initialBatteryLevel", initialBatteryLevel, minimum = Decimal.ZERO)
} }
specBuilder.pop() specBuilder.pop()
@ -68,12 +65,12 @@ object ServerConfig {
return obj return obj
} }
private fun conciseValues(name: String, storage: ImpreciseFraction, throughput: ImpreciseFraction): ConciseBalanceValues { private fun conciseValues(name: String, storage: Decimal, throughput: Decimal): ConciseBalanceValues {
specBuilder.push(name) specBuilder.push(name)
val obj = object : ConciseBalanceValues { val obj = object : ConciseBalanceValues {
override val capacity: ImpreciseFraction by specBuilder.defineImpreciseFraction("capacity", storage, minimum = ImpreciseFraction.ONE) override val capacity: Decimal by specBuilder.defineDecimal("capacity", storage, minimum = Decimal.ONE)
override val throughput: ImpreciseFraction by specBuilder.defineImpreciseFraction("throughput", throughput, minimum = ImpreciseFraction.ONE) override val throughput: Decimal by specBuilder.defineDecimal("throughput", throughput, minimum = Decimal.ONE)
} }
specBuilder.pop() specBuilder.pop()
@ -91,16 +88,16 @@ object ServerConfig {
specBuilder.comment("Energy batteries balance values").push("energyBatteries") specBuilder.comment("Energy batteries balance values").push("energyBatteries")
} }
val BATTERY_CRUDE = batteryValues(MNames.BATTERY_CRUDE, ImpreciseFraction(100_000), ImpreciseFraction(160), ImpreciseFraction(40), ImpreciseFraction(80_000)) val BATTERY_CRUDE = batteryValues(MNames.BATTERY_CRUDE, Decimal(100_000), Decimal(160), Decimal(40), Decimal(80_000))
val BATTERY_BASIC = batteryValues(MNames.BATTERY_BASIC, ImpreciseFraction(400_000), ImpreciseFraction(600)) val BATTERY_BASIC = batteryValues(MNames.BATTERY_BASIC, Decimal(400_000), Decimal(600))
val BATTERY_NORMAL = batteryValues(MNames.BATTERY_NORMAL, ImpreciseFraction(2_000_000), ImpreciseFraction(1_000)) val BATTERY_NORMAL = batteryValues(MNames.BATTERY_NORMAL, Decimal(2_000_000), Decimal(1_000))
val BATTERY_DENSE = batteryValues(MNames.BATTERY_DENSE, ImpreciseFraction(10_000_000), ImpreciseFraction(2_000)) val BATTERY_DENSE = batteryValues(MNames.BATTERY_DENSE, Decimal(10_000_000), Decimal(2_000))
val BATTERY_CAPACITOR = batteryValues(MNames.BATTERY_CAPACITOR, ImpreciseFraction(500_000), ImpreciseFraction(50_000)) val BATTERY_CAPACITOR = batteryValues(MNames.BATTERY_CAPACITOR, Decimal(500_000), Decimal(50_000))
val QUANTUM_BATTERY = conciseValues(MNames.QUANTUM_BATTERY, ImpreciseFraction(40_000_000), ImpreciseFraction(10_000)) val QUANTUM_BATTERY = conciseValues(MNames.QUANTUM_BATTERY, Decimal(40_000_000), Decimal(10_000))
val QUANTUM_CAPACITOR = conciseValues(MNames.QUANTUM_CAPACITOR, ImpreciseFraction(1_000_000), ImpreciseFraction(200_000)) val QUANTUM_CAPACITOR = conciseValues(MNames.QUANTUM_CAPACITOR, Decimal(1_000_000), Decimal(200_000))
val ZPM_BATTERY = conciseValues(MNames.ZPM_BATTERY, ImpreciseFraction(200_000_000_000_000L), ImpreciseFraction(200_000_000L)) val ZPM_BATTERY = conciseValues(MNames.ZPM_BATTERY, Decimal(200_000_000_000_000L), Decimal(200_000_000L))
init { init {
specBuilder.pop() specBuilder.pop()
@ -108,11 +105,11 @@ object ServerConfig {
specBuilder.comment("Matter capacitors and pattern drives balance values").push("matterCapacitorsAndDrives") specBuilder.comment("Matter capacitors and pattern drives balance values").push("matterCapacitorsAndDrives")
} }
val MATTER_CAPACITOR_BASIC by specBuilder.defineImpreciseFraction(MNames.MATTER_CAPACITOR_BASIC, ImpreciseFraction(2_000), minimum = ImpreciseFraction.ONE_TENTH) val MATTER_CAPACITOR_BASIC by specBuilder.defineDecimal(MNames.MATTER_CAPACITOR_BASIC, Decimal(2_000), minimum = Decimal.ONE_TENTH)
val MATTER_CAPACITOR_NORMAL by specBuilder.defineImpreciseFraction(MNames.MATTER_CAPACITOR_NORMAL, ImpreciseFraction(40_000), minimum = ImpreciseFraction.ONE_TENTH) val MATTER_CAPACITOR_NORMAL by specBuilder.defineDecimal(MNames.MATTER_CAPACITOR_NORMAL, Decimal(40_000), minimum = Decimal.ONE_TENTH)
val MATTER_CAPACITOR_DENSE by specBuilder.defineImpreciseFraction(MNames.MATTER_CAPACITOR_DENSE, ImpreciseFraction(400_000), minimum = ImpreciseFraction.ONE_TENTH) val MATTER_CAPACITOR_DENSE by specBuilder.defineDecimal(MNames.MATTER_CAPACITOR_DENSE, Decimal(400_000), minimum = Decimal.ONE_TENTH)
val MATTER_DUST_CAPACITY by specBuilder.comment("Maximal matter value one matter dust item can have").defineImpreciseFraction("matterDustCapacity", ImpreciseFraction(2_000), minimum = ImpreciseFraction.ONE_TENTH) val MATTER_DUST_CAPACITY by specBuilder.comment("Maximal matter value one matter dust item can have").defineDecimal("matterDustCapacity", Decimal(2_000), minimum = Decimal.ONE_TENTH)
val PATTERN_DRIVE_NORMAL: Int by specBuilder.defineInRange(MNames.PATTERN_DRIVE_NORMAL, 4, 1, Int.MAX_VALUE) val PATTERN_DRIVE_NORMAL: Int by specBuilder.defineInRange(MNames.PATTERN_DRIVE_NORMAL, 4, 1, Int.MAX_VALUE)
@ -131,11 +128,11 @@ object ServerConfig {
} }
val PLATE_PRESS = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.PLATE_PRESS) val PLATE_PRESS = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.PLATE_PRESS)
val STORAGE_POWER_SUPPLIER = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.STORAGE_POWER_SUPPLIER, capacity = ImpreciseFraction(100_000), throughput = ImpreciseFraction(320)) val STORAGE_POWER_SUPPLIER = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.STORAGE_POWER_SUPPLIER, capacity = Decimal(100_000), throughput = Decimal(320))
val STORAGE_INTERFACES = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, "storage_interfaces", capacity = ImpreciseFraction(10_000)) val STORAGE_INTERFACES = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, "storage_interfaces", capacity = Decimal(10_000))
val ITEM_MONITOR = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.ITEM_MONITOR) val ITEM_MONITOR = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.ITEM_MONITOR)
val DRIVE_VIEWER = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.DRIVE_VIEWER) val DRIVE_VIEWER = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.DRIVE_VIEWER)
val DRIVE_RACK = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.DRIVE_RACK, capacity = ImpreciseFraction(80_000)) val DRIVE_RACK = BlockEnergyStorageImpl.makeConfigEntry(specBuilder, MNames.DRIVE_RACK, capacity = Decimal(80_000))
init { init {
specBuilder.pop() specBuilder.pop()
@ -167,12 +164,12 @@ object ServerConfig {
val ENERGY_PER_HITPOINT by specBuilder val ENERGY_PER_HITPOINT by specBuilder
.comment("Energy required to regenerate 1 health point (half a heart)") .comment("Energy required to regenerate 1 health point (half a heart)")
.defineImpreciseFraction("energyPerHitpoint", ImpreciseFraction(800)) .defineDecimal("energyPerHitpoint", Decimal(800))
} }
val ANDROID_ENERGY_PER_HUNGER_POINT by specBuilder.defineImpreciseFraction("energyPerHunger", ImpreciseFraction(2000), ImpreciseFraction.ZERO) val ANDROID_ENERGY_PER_HUNGER_POINT by specBuilder.defineDecimal("energyPerHunger", Decimal(2000), Decimal.ZERO)
val ANDROID_MAX_ENERGY by specBuilder.comment("Internal battery of every android has this much storage").defineImpreciseFraction("capacity", ImpreciseFraction(80_000), ImpreciseFraction.ZERO) val ANDROID_MAX_ENERGY by specBuilder.comment("Internal battery of every android has this much storage").defineDecimal("capacity", Decimal(80_000), Decimal.ZERO)
val NIGHT_VISION_POWER_DRAW by specBuilder.defineImpreciseFraction("nightVisionPowerDraw", ImpreciseFraction(8), ImpreciseFraction.ZERO) val NIGHT_VISION_POWER_DRAW by specBuilder.defineDecimal("nightVisionPowerDraw", Decimal(8), Decimal.ZERO)
val FALL_DAMAGE_REDUCTION_PER_LEVEL: Double by specBuilder.comment("In percent. Level of feature is multiplied by this").defineInRange("fallDamageReductionPerDampenerLevel", 0.25, 0.01, 1.0) val FALL_DAMAGE_REDUCTION_PER_LEVEL: Double by specBuilder.comment("In percent. Level of feature is multiplied by this").defineInRange("fallDamageReductionPerDampenerLevel", 0.25, 0.01, 1.0)
object EnderTeleporter { object EnderTeleporter {
@ -180,7 +177,7 @@ object ServerConfig {
specBuilder.comment("Ender Teleporter ability").push("ender_teleporter") specBuilder.comment("Ender Teleporter ability").push("ender_teleporter")
} }
val ENERGY_COST by specBuilder.defineImpreciseFraction("energyCost", ImpreciseFraction(4096), ImpreciseFraction.ZERO) val ENERGY_COST by specBuilder.defineDecimal("energyCost", Decimal(4096), Decimal.ZERO)
val COOLDOWN: Int by specBuilder.comment("In ticks").defineInRange("cooldown", 40, 0, Int.MAX_VALUE) val COOLDOWN: Int by specBuilder.comment("In ticks").defineInRange("cooldown", 40, 0, Int.MAX_VALUE)
val MAX_PHASE_DISTANCE: Int by specBuilder.comment("Determines how much blocks can we 'phase' through to teleport on solid surface").defineInRange("maxPhaseDistance", 6, 0, Int.MAX_VALUE) val MAX_PHASE_DISTANCE: Int by specBuilder.comment("Determines how much blocks can we 'phase' through to teleport on solid surface").defineInRange("maxPhaseDistance", 6, 0, Int.MAX_VALUE)
val MAX_DISTANCE: Double by specBuilder.comment("In blocks, euclidean distance").defineInRange("maxDistance", 12.0, 2.0, Int.MAX_VALUE.toDouble()) val MAX_DISTANCE: Double by specBuilder.comment("In blocks, euclidean distance").defineInRange("maxDistance", 12.0, 2.0, Int.MAX_VALUE.toDouble())
@ -195,7 +192,7 @@ object ServerConfig {
specBuilder.comment("Jump boost ability").push("jump_boost") specBuilder.comment("Jump boost ability").push("jump_boost")
} }
val ENERGY_COST by specBuilder.defineImpreciseFraction("energyCost", ImpreciseFraction(1024), ImpreciseFraction.ZERO) val ENERGY_COST by specBuilder.defineDecimal("energyCost", Decimal(1024), Decimal.ZERO)
val POWER: Double by specBuilder.comment("The jump height on jump boost, as (level + 1) of feature, in meters per second").defineInRange("power", 6.0, 0.0, Double.MAX_VALUE) val POWER: Double by specBuilder.comment("The jump height on jump boost, as (level + 1) of feature, in meters per second").defineInRange("power", 6.0, 0.0, Double.MAX_VALUE)
val BASE_COOLDOWN: Int by specBuilder.comment("In ticks").defineInRange("baseCooldown", 40, 0, Int.MAX_VALUE) val BASE_COOLDOWN: Int by specBuilder.comment("In ticks").defineInRange("baseCooldown", 40, 0, Int.MAX_VALUE)
val COOLDOWN_REDUCTION: Int by specBuilder.comment("In ticks, per level of feature").defineInRange("cooldownReduction", 20, 0, Int.MAX_VALUE) val COOLDOWN_REDUCTION: Int by specBuilder.comment("In ticks, per level of feature").defineInRange("cooldownReduction", 20, 0, Int.MAX_VALUE)
@ -210,7 +207,7 @@ object ServerConfig {
specBuilder.comment("Item magnet ability").push("item_magnet") specBuilder.comment("Item magnet ability").push("item_magnet")
} }
val POWER_DRAW by specBuilder.comment("Per tick per stack").defineImpreciseFraction("powerDraw", ImpreciseFraction(8), ImpreciseFraction.ZERO) val POWER_DRAW by specBuilder.comment("Per tick per stack").defineDecimal("powerDraw", Decimal(8), Decimal.ZERO)
val RADIUS_HORIZONTAL: Double by specBuilder.defineInRange("radiusHorizontal", 6.0, 0.0, Double.MAX_VALUE / 4.0) val RADIUS_HORIZONTAL: Double by specBuilder.defineInRange("radiusHorizontal", 6.0, 0.0, Double.MAX_VALUE / 4.0)
val RADIUS_VERTICAL: Double by specBuilder.defineInRange("radiusVertical", 3.0, 0.0, Double.MAX_VALUE / 4.0) val RADIUS_VERTICAL: Double by specBuilder.defineInRange("radiusVertical", 3.0, 0.0, Double.MAX_VALUE / 4.0)
@ -236,7 +233,7 @@ object ServerConfig {
val BREAK_BLOCKS: Boolean by specBuilder.comment("Break blocks without any blast resistance").define("breakBlocks", true) val BREAK_BLOCKS: Boolean by specBuilder.comment("Break blocks without any blast resistance").define("breakBlocks", true)
val DAMAGE: Double by specBuilder.comment("Max potential damage done by shockwave").defineInRange("damage", 12.0, 0.0, Float.MAX_VALUE.toDouble()) val DAMAGE: Double by specBuilder.comment("Max potential damage done by shockwave").defineInRange("damage", 12.0, 0.0, Float.MAX_VALUE.toDouble())
val WARDEN_DAMAGE_MULT: Double by specBuilder.defineInRange("wardenDamageMultiplier", 4.0, 0.0, Float.MAX_VALUE.toDouble()) val WARDEN_DAMAGE_MULT: Double by specBuilder.defineInRange("wardenDamageMultiplier", 4.0, 0.0, Float.MAX_VALUE.toDouble())
val ENERGY_COST by specBuilder.defineImpreciseFraction("energyCost", ImpreciseFraction(2048), ImpreciseFraction.ZERO) val ENERGY_COST by specBuilder.defineDecimal("energyCost", Decimal(2048), Decimal.ZERO)
init { init {
specBuilder.pop() specBuilder.pop()

View File

@ -9,7 +9,7 @@ import ru.dbotthepony.mc.otm.android.AndroidFeature
import ru.dbotthepony.mc.otm.android.AndroidResearchManager import ru.dbotthepony.mc.otm.android.AndroidResearchManager
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.capability.extractEnergyInnerExact import ru.dbotthepony.mc.otm.capability.extractEnergyInnerExact
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.registry.AndroidFeatures import ru.dbotthepony.mc.otm.registry.AndroidFeatures
import ru.dbotthepony.mc.otm.registry.StatNames import ru.dbotthepony.mc.otm.registry.StatNames
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
@ -85,8 +85,8 @@ class NanobotsArmorFeature(android: MatteryPlayerCapability) : AndroidFeature(An
} }
companion object { companion object {
private val ENERGY_PER_LAYER = ImpreciseFraction(200) private val ENERGY_PER_LAYER = Decimal(200)
private val ENERGY_PER_HITPOINT = ImpreciseFraction(500) private val ENERGY_PER_HITPOINT = Decimal(500)
private val TICKS = intArrayOf( private val TICKS = intArrayOf(
80, // 4 seconds to build a layer 80, // 4 seconds to build a layer

View File

@ -6,7 +6,6 @@ import net.minecraftforge.event.entity.living.LivingHurtEvent
import ru.dbotthepony.mc.otm.ServerConfig import ru.dbotthepony.mc.otm.ServerConfig
import ru.dbotthepony.mc.otm.android.AndroidFeature import ru.dbotthepony.mc.otm.android.AndroidFeature
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import ru.dbotthepony.mc.otm.registry.AndroidFeatures import ru.dbotthepony.mc.otm.registry.AndroidFeatures
import ru.dbotthepony.mc.otm.registry.StatNames import ru.dbotthepony.mc.otm.registry.StatNames
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set

View File

@ -13,9 +13,9 @@ import net.minecraft.world.phys.AABB
import net.minecraftforge.common.ForgeConfigSpec import net.minecraftforge.common.ForgeConfigSpec
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.ImpreciseFractionConfigValue import ru.dbotthepony.mc.otm.core.DecimalConfigValue
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.core.ifPresentK import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.menu.AndroidStationMenu import ru.dbotthepony.mc.otm.menu.AndroidStationMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
@ -35,7 +35,7 @@ class AndroidStationBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
get() = MBlocks.ANDROID_STATION.name get() = MBlocks.ANDROID_STATION.name
override val energy = object : WorkerEnergyStorage(this@AndroidStationBlockEntity::setChangedLight, ::CAPACITY, ::MAX_IO, { null }) { override val energy = object : WorkerEnergyStorage(this@AndroidStationBlockEntity::setChangedLight, ::CAPACITY, ::MAX_IO, { null }) {
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return super.extractEnergyInner(howMuch, simulate).also { return super.extractEnergyInner(howMuch, simulate).also {
if (!simulate && this.batteryLevel.isZero) { if (!simulate && this.batteryLevel.isZero) {
if (blockState.getValue(WorkerState.SEMI_WORKER_STATE) != WorkerState.IDLE) { if (blockState.getValue(WorkerState.SEMI_WORKER_STATE) != WorkerState.IDLE) {
@ -45,7 +45,7 @@ class AndroidStationBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
} }
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return super.receiveEnergyInner(howMuch, simulate).also { return super.receiveEnergyInner(howMuch, simulate).also {
if (!simulate && it.isPositive) { if (!simulate && it.isPositive) {
if (blockState.getValue(WorkerState.SEMI_WORKER_STATE) != WorkerState.WORKING) { if (blockState.getValue(WorkerState.SEMI_WORKER_STATE) != WorkerState.WORKING) {
@ -84,10 +84,10 @@ class AndroidStationBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
val missing = it.androidEnergy.missingPower val missing = it.androidEnergy.missingPower
if (missing > ImpreciseFraction.ZERO) { if (missing > Decimal.ZERO) {
val extract = energy.extractEnergyInner(missing, true) val extract = energy.extractEnergyInner(missing, true)
if (extract > ImpreciseFraction.ZERO) { if (extract > Decimal.ZERO) {
val received = it.androidEnergy.receiveEnergyOuter(extract, false) val received = it.androidEnergy.receiveEnergyOuter(extract, false)
energy.extractEnergyInner(received, false) energy.extractEnergyInner(received, false)
} }
@ -97,10 +97,10 @@ class AndroidStationBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
} }
companion object { companion object {
private var _CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _CAPACITY: DecimalConfigValue by WriteOnce()
private var _MAX_IO: ImpreciseFractionConfigValue by WriteOnce() private var _MAX_IO: DecimalConfigValue by WriteOnce()
private var _ENERGY_PER_OPERATION: ImpreciseFractionConfigValue by WriteOnce() private var _ENERGY_PER_OPERATION: DecimalConfigValue by WriteOnce()
private var _ENERGY_PER_RESEARCH: ImpreciseFractionConfigValue by WriteOnce() private var _ENERGY_PER_RESEARCH: DecimalConfigValue by WriteOnce()
val CAPACITY get() = _CAPACITY.get() val CAPACITY get() = _CAPACITY.get()
val MAX_IO get() = _MAX_IO.get() val MAX_IO get() = _MAX_IO.get()
@ -110,10 +110,10 @@ class AndroidStationBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.ANDROID_STATION) builder.push(MNames.ANDROID_STATION)
_CAPACITY = builder.defineImpreciseFraction("capacity", ImpreciseFraction(100_000), ImpreciseFraction.ONE) _CAPACITY = builder.defineDecimal("capacity", Decimal(100_000), Decimal.ONE)
_MAX_IO = builder.defineImpreciseFraction("throughput", ImpreciseFraction.valueOf(2048), ImpreciseFraction.ONE) _MAX_IO = builder.defineDecimal("throughput", Decimal.valueOf(2048), Decimal.ONE)
_ENERGY_PER_OPERATION = builder.comment("Swapping parts, etc").defineImpreciseFraction("energyPerOperation", ImpreciseFraction.valueOf(2048), ImpreciseFraction.ONE) _ENERGY_PER_OPERATION = builder.comment("Swapping parts, etc").defineDecimal("energyPerOperation", Decimal.valueOf(2048), Decimal.ONE)
_ENERGY_PER_RESEARCH = builder.defineImpreciseFraction("energyPerResearch", ImpreciseFraction.valueOf(16384), ImpreciseFraction.ONE) _ENERGY_PER_RESEARCH = builder.defineDecimal("energyPerResearch", Decimal.valueOf(16384), Decimal.ONE)
builder.pop() builder.pop()
} }

View File

@ -69,30 +69,30 @@ class BatteryBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Matte
} }
) )
private data class BatteryBankDistribution(val distribution: Array<ImpreciseFraction>, val maxThroughput: ImpreciseFraction) private data class BatteryBankDistribution(val distribution: Array<Decimal>, val maxThroughput: Decimal)
private enum class BankMode { RECEIVE, EXTRACT, BIDIRECTIONAL } private enum class BankMode { RECEIVE, EXTRACT, BIDIRECTIONAL }
private inner class BatteryBankEnergy(private val mode: BankMode) : IMatteryEnergyStorage { private inner class BatteryBankEnergy(private val mode: BankMode) : IMatteryEnergyStorage {
override fun canExtract() = mode != BankMode.RECEIVE override fun canExtract() = mode != BankMode.RECEIVE
override fun canReceive() = mode != BankMode.EXTRACT override fun canReceive() = mode != BankMode.EXTRACT
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (mode == BankMode.RECEIVE) if (mode == BankMode.RECEIVE)
return ImpreciseFraction.ZERO return Decimal.ZERO
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
fun getDistribution(isReceiving: Boolean): BatteryBankDistribution { fun getDistribution(isReceiving: Boolean): BatteryBankDistribution {
val distribution = Array(container.containerSize) { ImpreciseFraction.ZERO } val distribution = Array(container.containerSize) { Decimal.ZERO }
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (i in 0 until container.containerSize) { for (i in 0 until container.containerSize) {
val stack = container.getItem(i) val stack = container.getItem(i)
if (!stack.isEmpty) { if (!stack.isEmpty) {
stack.energy?.let { stack.energy?.let {
val diff: ImpreciseFraction val diff: Decimal
if (isReceiving) { if (isReceiving) {
diff = it.receiveEnergy(it.maxEnergyStoredMattery, true) diff = it.receiveEnergy(it.maxEnergyStoredMattery, true)
@ -115,17 +115,17 @@ class BatteryBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Matte
return BatteryBankDistribution(distribution, summ) return BatteryBankDistribution(distribution, summ)
} }
private fun distributeEnergy(isReceiving: Boolean, howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { private fun distributeEnergy(isReceiving: Boolean, howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
val distribution = getDistribution(isReceiving) val distribution = getDistribution(isReceiving)
if (distribution.maxThroughput.isZero) if (distribution.maxThroughput.isZero)
return ImpreciseFraction.ZERO return Decimal.ZERO
val distList = distribution.distribution val distList = distribution.distribution
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (i in 0 until container.containerSize) { for (i in 0 until container.containerSize) {
if (!distList[i].isZero) { if (!distList[i].isZero) {
@ -133,7 +133,7 @@ class BatteryBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Matte
if (!stack.isEmpty) { if (!stack.isEmpty) {
stack.energy?.let { stack.energy?.let {
val diff: ImpreciseFraction val diff: Decimal
if (isReceiving) { if (isReceiving) {
diff = it.receiveEnergy(howMuch * distList[i], simulate) diff = it.receiveEnergy(howMuch * distList[i], simulate)
@ -155,23 +155,23 @@ class BatteryBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Matte
return summ return summ
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return distributeEnergy(isReceiving = false, howMuch, simulate) return distributeEnergy(isReceiving = false, howMuch, simulate)
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (mode == BankMode.EXTRACT) if (mode == BankMode.EXTRACT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return distributeEnergy(isReceiving = true, howMuch, simulate) return distributeEnergy(isReceiving = true, howMuch, simulate)
} }
override val batteryLevel: ImpreciseFraction get() { override val batteryLevel: Decimal get() {
var result = ImpreciseFraction.ZERO var result = Decimal.ZERO
for (i in 0 until container.containerSize) { for (i in 0 until container.containerSize) {
val stack = container.getItem(i) val stack = container.getItem(i)
@ -186,8 +186,8 @@ class BatteryBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Matte
return result return result
} }
override val maxBatteryLevel: ImpreciseFraction get() { override val maxBatteryLevel: Decimal get() {
var result = ImpreciseFraction.ZERO var result = Decimal.ZERO
for (i in 0 until container.containerSize) { for (i in 0 until container.containerSize) {
val stack = container.getItem(i) val stack = container.getItem(i)

View File

@ -195,7 +195,7 @@ class ChemicalGeneratorBlockEntity(pos: BlockPos, state: BlockState) : MatteryBl
val residue = container[SLOT_INPUT].item.getCraftingRemainingItem(container[SLOT_INPUT].copy().also { it.count = 1 }) val residue = container[SLOT_INPUT].item.getCraftingRemainingItem(container[SLOT_INPUT].copy().also { it.count = 1 })
val canPutResidue = residue.isEmpty || container[SLOT_RESIDUE].isEmpty || ItemStack.isSameItemSameTags(container[SLOT_RESIDUE], residue) && container[SLOT_RESIDUE].count < container[2].maxStackSize val canPutResidue = residue.isEmpty || container[SLOT_RESIDUE].isEmpty || ItemStack.isSameItemSameTags(container[SLOT_RESIDUE], residue) && container[SLOT_RESIDUE].count < container[2].maxStackSize
if (canPutResidue && ticks >= 4 && (energy.batteryLevel < ImpreciseFraction.ONE || GENERATION_SPEED * (ticks / 4) + energy.batteryLevel <= energy.maxBatteryLevel)) { if (canPutResidue && ticks >= 4 && (energy.batteryLevel < Decimal.ONE || GENERATION_SPEED * (ticks / 4) + energy.batteryLevel <= energy.maxBatteryLevel)) {
workTicksTotal = ticks / 4 workTicksTotal = ticks / 4
workTicks = ticks / 4 workTicks = ticks / 4
container[SLOT_INPUT].shrink(1) container[SLOT_INPUT].shrink(1)
@ -235,9 +235,9 @@ class ChemicalGeneratorBlockEntity(pos: BlockPos, state: BlockState) : MatteryBl
private val CAPACITY get() = _CAPACITY.get() private val CAPACITY get() = _CAPACITY.get()
private val MACHINE_NAME = TranslatableComponent("block.overdrive_that_matters.chemical_generator") private val MACHINE_NAME = TranslatableComponent("block.overdrive_that_matters.chemical_generator")
private var _THROUGHPUT: ImpreciseFractionConfigValue by WriteOnce() private var _THROUGHPUT: DecimalConfigValue by WriteOnce()
private var _GENERATION_SPEED: ImpreciseFractionConfigValue by WriteOnce() private var _GENERATION_SPEED: DecimalConfigValue by WriteOnce()
private var _CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _CAPACITY: DecimalConfigValue by WriteOnce()
const val SLOT_INPUT = 0 const val SLOT_INPUT = 0
const val SLOT_BATTERY = 1 const val SLOT_BATTERY = 1
@ -247,9 +247,9 @@ class ChemicalGeneratorBlockEntity(pos: BlockPos, state: BlockState) : MatteryBl
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.CHEMICAL_GENERATOR) builder.push(MNames.CHEMICAL_GENERATOR)
_THROUGHPUT = builder.defineImpreciseFraction("throughput", ImpreciseFraction(160), ImpreciseFraction.ONE) _THROUGHPUT = builder.defineDecimal("throughput", Decimal(160), Decimal.ONE)
_GENERATION_SPEED = builder.defineImpreciseFraction("generationSpeed", ImpreciseFraction(40), ImpreciseFraction.ONE) _GENERATION_SPEED = builder.defineDecimal("generationSpeed", Decimal(40), Decimal.ONE)
_CAPACITY = builder.defineImpreciseFraction("capacity", ImpreciseFraction(24_000), ImpreciseFraction.ONE) _CAPACITY = builder.defineDecimal("capacity", Decimal(24_000), Decimal.ONE)
builder.pop() builder.pop()
} }

View File

@ -29,25 +29,25 @@ import java.util.*
class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.ENERGY_COUNTER, p_155229_, p_155230_) { class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.ENERGY_COUNTER, p_155229_, p_155230_) {
var passed by synchronizer.fraction() var passed by synchronizer.fraction()
private val history = Array(10 * 20) { ImpreciseFraction.ZERO } private val history = Array(10 * 20) { Decimal.ZERO }
internal var historyTick = 0 internal var historyTick = 0
var lastTick by synchronizer.fraction() var lastTick by synchronizer.fraction()
internal set internal set
var ioLimit: ImpreciseFraction? = null var ioLimit: Decimal? = null
fun resetStats() { fun resetStats() {
historyTick = 0 historyTick = 0
lastTick = ImpreciseFraction.ZERO lastTick = Decimal.ZERO
passed = ImpreciseFraction.ZERO passed = Decimal.ZERO
Arrays.fill(history, ImpreciseFraction.ZERO) Arrays.fill(history, Decimal.ZERO)
} }
fun getHistory(ticks: Int): Array<ImpreciseFraction> { fun getHistory(ticks: Int): Array<Decimal> {
require(!(ticks < 1 || ticks >= history.size)) { "Invalid history length provided" } require(!(ticks < 1 || ticks >= history.size)) { "Invalid history length provided" }
val history = Array(ticks) { ImpreciseFraction.ZERO } val history = Array(ticks) { Decimal.ZERO }
for (i in 0 until ticks) { for (i in 0 until ticks) {
var index = (historyTick - i) % this.history.size var index = (historyTick - i) % this.history.size
@ -58,14 +58,14 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return history return history
} }
fun calcAverage(ticks: Int): ImpreciseFraction { fun calcAverage(ticks: Int): Decimal {
return sumHistory(ticks) / ticks return sumHistory(ticks) / ticks
} }
fun sumHistory(ticks: Int): ImpreciseFraction { fun sumHistory(ticks: Int): Decimal {
require(!(ticks < 1 || ticks >= history.size)) { "Invalid history length provided" } require(!(ticks < 1 || ticks >= history.size)) { "Invalid history length provided" }
var value = ImpreciseFraction.ZERO var value = Decimal.ZERO
for (i in 0 until ticks) { for (i in 0 until ticks) {
var index = (historyTick - i) % history.size var index = (historyTick - i) % history.size
@ -93,17 +93,17 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
override fun load(nbt: CompoundTag) { override fun load(nbt: CompoundTag) {
super.load(nbt) super.load(nbt)
passed = nbt.getImpreciseFraction(PASSED_ENERGY_KEY) passed = nbt.getDecimal(PASSED_ENERGY_KEY)
ioLimit = nbt.map(IO_LIMIT_KEY, ImpreciseFraction.Companion::deserializeNBT) ioLimit = nbt.map(IO_LIMIT_KEY, Decimal.Companion::deserializeNBT)
nbt.ifHas(POWER_HISTORY_POINTER_KEY, IntTag::class.java) { nbt.ifHas(POWER_HISTORY_POINTER_KEY, IntTag::class.java) {
historyTick = it.asInt historyTick = it.asInt
} }
Arrays.fill(history, ImpreciseFraction.ZERO) Arrays.fill(history, Decimal.ZERO)
for ((i, bytes) in nbt.getByteArrayList(POWER_HISTORY_KEY).withIndex()) { for ((i, bytes) in nbt.getByteArrayList(POWER_HISTORY_KEY).withIndex()) {
history[i] = ImpreciseFraction.deserializeNBT(bytes) history[i] = Decimal.deserializeNBT(bytes)
} }
} }
@ -126,18 +126,18 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
} }
private inner class EnergyCounterCap(val isInput: Boolean) : IMatteryEnergyStorage { private inner class EnergyCounterCap(val isInput: Boolean) : IMatteryEnergyStorage {
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (isInput) if (isInput)
return ImpreciseFraction.ZERO return Decimal.ZERO
if (inputCapability.isPresent) { if (inputCapability.isPresent) {
val it = inputCapability.resolve().get() val it = inputCapability.resolve().get()
val diff: ImpreciseFraction val diff: Decimal
val ioLimit = ioLimit val ioLimit = ioLimit
@ -155,21 +155,21 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return diff return diff
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!isInput) if (!isInput)
return ImpreciseFraction.ZERO return Decimal.ZERO
if (outputCapability.isPresent) { if (outputCapability.isPresent) {
val it = outputCapability.resolve().get() val it = outputCapability.resolve().get()
val diff: ImpreciseFraction val diff: Decimal
val ioLimit = ioLimit val ioLimit = ioLimit
@ -187,10 +187,10 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return diff return diff
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override val batteryLevel: ImpreciseFraction override val batteryLevel: Decimal
get() { get() {
if (isInput) { if (isInput) {
if (outputCapability.isPresent) { if (outputCapability.isPresent) {
@ -200,7 +200,7 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.batteryLevel return it.batteryLevel
} }
return ImpreciseFraction(it.energyStored) return Decimal(it.energyStored)
} }
} else { } else {
if (inputCapability.isPresent) { if (inputCapability.isPresent) {
@ -210,14 +210,14 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.batteryLevel return it.batteryLevel
} }
return ImpreciseFraction(it.energyStored) return Decimal(it.energyStored)
} }
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override val maxBatteryLevel: ImpreciseFraction override val maxBatteryLevel: Decimal
get() { get() {
if (isInput) { if (isInput) {
if (outputCapability.isPresent) { if (outputCapability.isPresent) {
@ -227,7 +227,7 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.maxBatteryLevel return it.maxBatteryLevel
} }
return ImpreciseFraction(it.maxEnergyStored) return Decimal(it.maxEnergyStored)
} }
} else { } else {
if (inputCapability.isPresent) { if (inputCapability.isPresent) {
@ -237,14 +237,14 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.maxBatteryLevel return it.maxBatteryLevel
} }
return ImpreciseFraction(it.maxEnergyStored) return Decimal(it.maxEnergyStored)
} }
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override val missingPower: ImpreciseFraction override val missingPower: Decimal
get() { get() {
if (isInput) { if (isInput) {
if (outputCapability.isPresent) { if (outputCapability.isPresent) {
@ -254,7 +254,7 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.missingPower return it.missingPower
} }
return ImpreciseFraction((it.maxEnergyStored - it.energyStored).coerceAtLeast(0)) return Decimal((it.maxEnergyStored - it.energyStored).coerceAtLeast(0))
} }
} else { } else {
if (inputCapability.isPresent) { if (inputCapability.isPresent) {
@ -264,11 +264,11 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
return it.missingPower return it.missingPower
} }
return ImpreciseFraction((it.maxEnergyStored - it.energyStored).coerceAtLeast(0)) return Decimal((it.maxEnergyStored - it.energyStored).coerceAtLeast(0))
} }
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override fun canExtract() = !isInput override fun canExtract() = !isInput
@ -394,7 +394,7 @@ class EnergyCounterBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Mat
fun tick() { fun tick() {
lastTick = history[historyTick] lastTick = history[historyTick]
historyTick = (historyTick + 1) % history.size historyTick = (historyTick + 1) % history.size
history[historyTick] = ImpreciseFraction.ZERO history[historyTick] = Decimal.ZERO
} }
fun clientTick() { fun clientTick() {

View File

@ -23,7 +23,7 @@ import ru.dbotthepony.mc.otm.capability.maxEnergyStoredMattery
import ru.dbotthepony.mc.otm.capability.receiveEnergy import ru.dbotthepony.mc.otm.capability.receiveEnergy
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.container.MatteryContainerHooks import ru.dbotthepony.mc.otm.container.MatteryContainerHooks
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.menu.EnergyServoMenu import ru.dbotthepony.mc.otm.menu.EnergyServoMenu
@ -58,27 +58,27 @@ class EnergyServoBlockEntity(blockPos: BlockPos, blockState: BlockState) : Matte
}) })
val energy = object : IMatteryEnergyStorage { val energy = object : IMatteryEnergyStorage {
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return container[SLOT_DISCHARGE].energy?.extractEnergy(howMuch, simulate) ?: ImpreciseFraction.ZERO return container[SLOT_DISCHARGE].energy?.extractEnergy(howMuch, simulate) ?: Decimal.ZERO
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return container[SLOT_CHARGE].energy?.receiveEnergy(howMuch, simulate) ?: ImpreciseFraction.ZERO return container[SLOT_CHARGE].energy?.receiveEnergy(howMuch, simulate) ?: Decimal.ZERO
} }
override val batteryLevel: ImpreciseFraction override val batteryLevel: Decimal
get() = container[SLOT_CHARGE].energy?.energyStoredMattery ?: container[SLOT_DISCHARGE].energy?.energyStoredMattery ?: ImpreciseFraction.ZERO get() = container[SLOT_CHARGE].energy?.energyStoredMattery ?: container[SLOT_DISCHARGE].energy?.energyStoredMattery ?: Decimal.ZERO
override val maxBatteryLevel: ImpreciseFraction override val maxBatteryLevel: Decimal
get() = container[SLOT_CHARGE].energy?.maxEnergyStoredMattery ?: container[SLOT_DISCHARGE].energy?.maxEnergyStoredMattery ?: ImpreciseFraction.ZERO get() = container[SLOT_CHARGE].energy?.maxEnergyStoredMattery ?: container[SLOT_DISCHARGE].energy?.maxEnergyStoredMattery ?: Decimal.ZERO
} }
private var resolverEnergy = LazyOptional.of { energy } private var resolverEnergy = LazyOptional.of { energy }
@ -132,7 +132,7 @@ class EnergyServoBlockEntity(blockPos: BlockPos, blockState: BlockState) : Matte
val chargeEnergy = charge.energy ?: return val chargeEnergy = charge.energy ?: return
val dischargeEnergy = discharge.energy ?: return val dischargeEnergy = discharge.energy ?: return
val extracted = dischargeEnergy.extractEnergy(ImpreciseFraction.LONG_MAX_VALUE, true) val extracted = dischargeEnergy.extractEnergy(Decimal.LONG_MAX_VALUE, true)
if (extracted.isPositive) { if (extracted.isPositive) {
val received = chargeEnergy.receiveEnergy(extracted, true) val received = chargeEnergy.receiveEnergy(extracted, true)

View File

@ -4,7 +4,6 @@ import net.minecraft.ChatFormatting
import net.minecraft.core.BlockPos import net.minecraft.core.BlockPos
import net.minecraft.core.Direction import net.minecraft.core.Direction
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import net.minecraft.network.chat.Component import net.minecraft.network.chat.Component
import net.minecraft.world.item.BlockItem import net.minecraft.world.item.BlockItem
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
@ -17,10 +16,9 @@ import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.common.util.LazyOptional import net.minecraftforge.common.util.LazyOptional
import ru.dbotthepony.mc.otm.capability.* import ru.dbotthepony.mc.otm.capability.*
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.ifHas import ru.dbotthepony.mc.otm.core.ifHas
import ru.dbotthepony.mc.otm.core.ifPresentK import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.container.set
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
@ -61,7 +59,7 @@ abstract class MatteryPoweredBlockEntity(p_155228_: BlockEntityType<*>, p_155229
} }
} }
if (demand <= ImpreciseFraction.ZERO) if (demand <= Decimal.ZERO)
return return
} }
} }

View File

@ -24,11 +24,11 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
) : MatteryPoweredBlockEntity(type, blockPos, blockState) { ) : MatteryPoweredBlockEntity(type, blockPos, blockState) {
open class Job { open class Job {
open val ticks: Double open val ticks: Double
open val powerUsage: ImpreciseFraction open val powerUsage: Decimal
constructor( constructor(
ticks: Double, ticks: Double,
powerUsage: ImpreciseFraction = ImpreciseFraction.ZERO powerUsage: Decimal = Decimal.ZERO
) { ) {
this.ticks = ticks this.ticks = ticks
this.powerUsage = powerUsage this.powerUsage = powerUsage
@ -36,7 +36,7 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
constructor( constructor(
tag: CompoundTag tag: CompoundTag
) : this(tag.getDouble(TICKS_KEY), tag.getImpreciseFraction(POWER_KEY)) ) : this(tag.getDouble(TICKS_KEY), tag.getDecimal(POWER_KEY))
open fun serializeNBT(): CompoundTag { open fun serializeNBT(): CompoundTag {
return CompoundTag().also { return CompoundTag().also {
@ -58,7 +58,7 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
constructor( constructor(
itemStack: ItemStack, itemStack: ItemStack,
ticks: Double, ticks: Double,
power: ImpreciseFraction = ImpreciseFraction.ZERO power: Decimal = Decimal.ZERO
) : super(ticks, power) { ) : super(ticks, power) {
this.itemStack = itemStack this.itemStack = itemStack
} }
@ -95,7 +95,7 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
val success: Boolean, val success: Boolean,
val throttleTicks: Int = 0, val throttleTicks: Int = 0,
val idleReason: IdleReason? = null, val idleReason: IdleReason? = null,
val newDrainedPower: ImpreciseFraction? = null val newDrainedPower: Decimal? = null
) { ) {
companion object { companion object {
val SUCCESS = Status(true) val SUCCESS = Status(true)
@ -206,7 +206,7 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
*/ */
protected abstract fun computeNextJob(): Pair<JobType?, Any?> protected abstract fun computeNextJob(): Pair<JobType?, Any?>
protected open fun onWorkTick(requiredPower: ImpreciseFraction, extractedPower: ImpreciseFraction, ticksAdvanced: Double, job: JobType): Status { protected open fun onWorkTick(requiredPower: Decimal, extractedPower: Decimal, ticksAdvanced: Double, job: JobType): Status {
return Status.SUCCESS return Status.SUCCESS
} }
@ -296,8 +296,8 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
val ticksLeft = currentJob.ticks - workTicks val ticksLeft = currentJob.ticks - workTicks
val ticksAdvanced: Double val ticksAdvanced: Double
var requiredPower: ImpreciseFraction? = null var requiredPower: Decimal? = null
var extractedPower: ImpreciseFraction? = null var extractedPower: Decimal? = null
if (currentJob.powerUsage.isZero) { if (currentJob.powerUsage.isZero) {
ticksAdvanced = availableTicks.coerceAtMost(ticksLeft) ticksAdvanced = availableTicks.coerceAtMost(ticksLeft)
@ -311,7 +311,7 @@ abstract class MatteryWorkerBlockEntity<JobType : MatteryWorkerBlockEntity.Job>(
break break
} }
val status = onWorkTick(requiredPower ?: ImpreciseFraction.ZERO, extractedPower ?: ImpreciseFraction.ZERO, ticksAdvanced, currentJob) val status = onWorkTick(requiredPower ?: Decimal.ZERO, extractedPower ?: Decimal.ZERO, ticksAdvanced, currentJob)
if (!status.success) { if (!status.success) {
throttleTicks += status.throttleTicks throttleTicks += status.throttleTicks

View File

@ -19,7 +19,7 @@ import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.container.MatteryContainerHooks import ru.dbotthepony.mc.otm.container.MatteryContainerHooks
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.menu.PlatePressMenu import ru.dbotthepony.mc.otm.menu.PlatePressMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.registry.MRecipes import ru.dbotthepony.mc.otm.registry.MRecipes
@ -100,7 +100,7 @@ class PlatePressBlockEntity(
} }
companion object { companion object {
private val BASELINE_CONSUMPTION = ImpreciseFraction(15) private val BASELINE_CONSUMPTION = Decimal(15)
private val MACHINE_NAME = TranslatableComponent("block.overdrive_that_matters.plate_press") private val MACHINE_NAME = TranslatableComponent("block.overdrive_that_matters.plate_press")
const val SLOT_INPUT = 0 const val SLOT_INPUT = 0
const val SLOT_OUTPUT = 1 const val SLOT_OUTPUT = 1

View File

@ -22,7 +22,7 @@ import ru.dbotthepony.mc.otm.block.BlackHoleBlock
import ru.dbotthepony.mc.otm.block.entity.GravitationStabilizerBlockEntity import ru.dbotthepony.mc.otm.block.entity.GravitationStabilizerBlockEntity
import ru.dbotthepony.mc.otm.block.entity.SynchronizedBlockEntity import ru.dbotthepony.mc.otm.block.entity.SynchronizedBlockEntity
import ru.dbotthepony.mc.otm.block.entity.blackhole.ExplosionQueue.Companion.queueForLevel import ru.dbotthepony.mc.otm.block.entity.blackhole.ExplosionQueue.Companion.queueForLevel
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.plus import ru.dbotthepony.mc.otm.core.plus
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.registry.MItems import ru.dbotthepony.mc.otm.registry.MItems
@ -39,7 +39,7 @@ import kotlin.math.sqrt
class BlackHoleBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : SynchronizedBlockEntity(MBlockEntities.BLACK_HOLE, p_155229_, p_155230_) { class BlackHoleBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : SynchronizedBlockEntity(MBlockEntities.BLACK_HOLE, p_155229_, p_155230_) {
var mass by synchronizer.fraction(BASELINE_MASS, setter = setter@{ mass, field, setByRemote -> var mass by synchronizer.fraction(BASELINE_MASS, setter = setter@{ mass, field, setByRemote ->
if (mass <= ImpreciseFraction.ZERO) { if (mass <= Decimal.ZERO) {
collapse() collapse()
return@setter return@setter
} }
@ -164,7 +164,7 @@ class BlackHoleBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Synchro
override fun load(tag: CompoundTag) { override fun load(tag: CompoundTag) {
super.load(tag) super.load(tag)
mass = tag.mapIf("mass", ImpreciseFraction::deserializeNBT) ?: BASELINE_MASS mass = tag.mapIf("mass", Decimal::deserializeNBT) ?: BASELINE_MASS
spinDirection = tag.getBoolean("spin_direction") spinDirection = tag.getBoolean("spin_direction")
} }
@ -327,7 +327,7 @@ class BlackHoleBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : Synchro
companion object { companion object {
const val ITERATIONS = 30_000 const val ITERATIONS = 30_000
val BASELINE_MASS = ImpreciseFraction(50_000) val BASELINE_MASS = Decimal(50_000)
val HAWKING_MASS_LOSE_STEP = ImpreciseFraction(-100) val HAWKING_MASS_LOSE_STEP = Decimal(-100)
} }
} }

View File

@ -120,7 +120,7 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
} }
} }
private var initialCapacity: ImpreciseFraction? = null private var initialCapacity: Decimal? = null
private var lastWorkStack: ItemStack? = null private var lastWorkStack: ItemStack? = null
override fun getMatterHandler(): IMatterHandler { override fun getMatterHandler(): IMatterHandler {
@ -195,18 +195,18 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
val cap = lastWorkStack.getCapability(MatteryCapability.MATTER).orNull() ?: return 0f val cap = lastWorkStack.getCapability(MatteryCapability.MATTER).orNull() ?: return 0f
if (this.isBottling) { if (this.isBottling) {
if (cap.maxStoredMatter - initialCapacity <= ImpreciseFraction.ZERO) { if (cap.maxStoredMatter - initialCapacity <= Decimal.ZERO) {
return 0f return 0f
} }
return ((cap.storedMatter - initialCapacity) / (cap.maxStoredMatter - initialCapacity)).toFloat() return ((cap.storedMatter - initialCapacity) / (cap.maxStoredMatter - initialCapacity)).toFloat()
} }
if (initialCapacity <= ImpreciseFraction.ZERO) { if (initialCapacity <= Decimal.ZERO) {
return 0f return 0f
} }
return (ImpreciseFraction.ONE - cap.storedMatter / initialCapacity).toFloat() return (Decimal.ONE - cap.storedMatter / initialCapacity).toFloat()
} }
override fun setRemoved() { override fun setRemoved() {
@ -242,7 +242,7 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
val cap = itemStack.getCapability(MatteryCapability.MATTER).orNull() ?: continue val cap = itemStack.getCapability(MatteryCapability.MATTER).orNull() ?: continue
if (cap.direction !== unexpectedDirection) { if (cap.direction !== unexpectedDirection) {
if (this.isBottling && cap.missingMatter > ImpreciseFraction.ZERO || !this.isBottling && cap.storedMatter > ImpreciseFraction.ZERO) { if (this.isBottling && cap.missingMatter > Decimal.ZERO || !this.isBottling && cap.storedMatter > Decimal.ZERO) {
work_stack = itemStack work_stack = itemStack
capability = cap capability = cap
work_slot = i work_slot = i
@ -273,13 +273,13 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
matter.missingMatter.coerceAtMost(MATTER_EXCHANGE_RATE * EXTRACTION_TICKS).coerceAtMost(capability.missingMatter - matter.storedMatter), true matter.missingMatter.coerceAtMost(MATTER_EXCHANGE_RATE * EXTRACTION_TICKS).coerceAtMost(capability.missingMatter - matter.storedMatter), true
) )
if (extracted > ImpreciseFraction.ZERO) { if (extracted > Decimal.ZERO) {
val received = matter.receiveMatterOuter(extracted, false) val received = matter.receiveMatterOuter(extracted, false)
graph.extractMatter(received, false) graph.extractMatter(received, false)
} }
} }
if (matter.storedMatter > ImpreciseFraction.ZERO) { if (matter.storedMatter > Decimal.ZERO) {
val energyExtracted = energy.extractEnergyInner(ENERGY_CONSUMPTION, true) val energyExtracted = energy.extractEnergyInner(ENERGY_CONSUMPTION, true)
if (!energyExtracted.isZero) { if (!energyExtracted.isZero) {
@ -345,10 +345,10 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
val EXTRACTION_TICKS get() = _EXTRACTION_TICKS.get() val EXTRACTION_TICKS get() = _EXTRACTION_TICKS.get()
val CAPACITY get() = _CAPACITY.get() val CAPACITY get() = _CAPACITY.get()
private var _MATTER_EXCHANGE_RATE: ImpreciseFractionConfigValue by WriteOnce() private var _MATTER_EXCHANGE_RATE: DecimalConfigValue by WriteOnce()
private var _ENERGY_CONSUMPTION: ImpreciseFractionConfigValue by WriteOnce() private var _ENERGY_CONSUMPTION: DecimalConfigValue by WriteOnce()
private var _EXTRACTION_TICKS: ImpreciseFractionConfigValue by WriteOnce() private var _EXTRACTION_TICKS: DecimalConfigValue by WriteOnce()
private var _CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _CAPACITY: DecimalConfigValue by WriteOnce()
var ENERGY_VALUES: ConciseBalanceValues by WriteOnce() var ENERGY_VALUES: ConciseBalanceValues by WriteOnce()
private set private set
@ -358,10 +358,10 @@ class MatterBottlerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder) ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder)
_MATTER_EXCHANGE_RATE = builder.defineImpreciseFraction("matterExchangeRate", ImpreciseFraction("0.04"), ImpreciseFraction("0.0001")) _MATTER_EXCHANGE_RATE = builder.defineDecimal("matterExchangeRate", Decimal("0.04"), Decimal("0.0001"))
_ENERGY_CONSUMPTION = builder.defineImpreciseFraction("energyConsumption", ImpreciseFraction(20), ImpreciseFraction.ONE) _ENERGY_CONSUMPTION = builder.defineDecimal("energyConsumption", Decimal(20), Decimal.ONE)
_EXTRACTION_TICKS = builder.defineImpreciseFraction("extractionTicks", ImpreciseFraction(200), ImpreciseFraction.ONE) _EXTRACTION_TICKS = builder.defineDecimal("extractionTicks", Decimal(200), Decimal.ONE)
_CAPACITY = builder.defineImpreciseFraction("matterCapacity", ImpreciseFraction(4_000), ImpreciseFraction.ONE_TENTH) _CAPACITY = builder.defineDecimal("matterCapacity", Decimal(4_000), Decimal.ONE_TENTH)
builder.pop() builder.pop()
} }

View File

@ -1,6 +1,5 @@
package ru.dbotthepony.mc.otm.block.entity.matter package ru.dbotthepony.mc.otm.block.entity.matter
import net.minecraft.MethodsReturnNonnullByDefault
import net.minecraft.core.BlockPos import net.minecraft.core.BlockPos
import net.minecraft.core.Direction import net.minecraft.core.Direction
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
@ -24,16 +23,14 @@ import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.matter.IMatterHandler import ru.dbotthepony.mc.otm.capability.matter.IMatterHandler
import ru.dbotthepony.mc.otm.capability.matter.MatterDirection import ru.dbotthepony.mc.otm.capability.matter.MatterDirection
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.graph.Graph6Node import ru.dbotthepony.mc.otm.graph.Graph6Node
import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode
import ru.dbotthepony.mc.otm.graph.matter.MatterNetworkGraph import ru.dbotthepony.mc.otm.graph.matter.MatterNetworkGraph
import ru.dbotthepony.mc.otm.menu.MatterCapacitorBankMenu import ru.dbotthepony.mc.otm.menu.MatterCapacitorBankMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.container.set
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import javax.annotation.ParametersAreNonnullByDefault
class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.MATTER_CAPACITOR_BANK, p_155229_, p_155230_), IMatterGraphNode, IMatterHandler, IDroppableContainer { class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.MATTER_CAPACITOR_BANK, p_155229_, p_155230_), IMatterGraphNode, IMatterHandler, IDroppableContainer {
var gaugeLevel by synchronizer.float() var gaugeLevel by synchronizer.float()
@ -42,8 +39,8 @@ class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState)
override val matterNode = Graph6Node<IMatterGraphNode>(this) override val matterNode = Graph6Node<IMatterGraphNode>(this)
private val resolverNode = LazyOptional.of { this } private val resolverNode = LazyOptional.of { this }
override val storedMatter: ImpreciseFraction get() { override val storedMatter: Decimal get() {
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (stack in container) for (stack in container)
if (!stack.isEmpty) if (!stack.isEmpty)
@ -54,8 +51,8 @@ class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState)
return summ return summ
} }
override val maxStoredMatter: ImpreciseFraction get() { override val maxStoredMatter: Decimal get() {
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (stack in container) for (stack in container)
if (!stack.isEmpty) if (!stack.isEmpty)
@ -66,17 +63,17 @@ class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState)
return summ return summ
} }
override fun receiveMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveMatterInner(howMuch, simulate) return receiveMatterInner(howMuch, simulate)
} }
override fun receiveMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (stack in container) { for (stack in container) {
if (!stack.isEmpty) { if (!stack.isEmpty) {
@ -99,17 +96,17 @@ class MatterCapacitorBankBlockEntity(p_155229_: BlockPos, p_155230_: BlockState)
return summ return summ
} }
override fun extractMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return extractMatterInner(howMuch, simulate) return extractMatterInner(howMuch, simulate)
} }
override fun extractMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
var summ = ImpreciseFraction.ZERO var summ = Decimal.ZERO
for (stack in container) { for (stack in container) {
if (!stack.isEmpty) { if (!stack.isEmpty) {

View File

@ -41,11 +41,11 @@ import ru.dbotthepony.mc.otm.registry.MNames
import ru.dbotthepony.mc.otm.core.WriteOnce import ru.dbotthepony.mc.otm.core.WriteOnce
import ru.dbotthepony.mc.otm.matter.MatterManager import ru.dbotthepony.mc.otm.matter.MatterManager
fun moveMatterAsDustIntoContainer(_matterValue: ImpreciseFraction, container: MatteryContainer, OUTPUT_DUST_MAIN: Int, OUTPUT_DUST_STACKING: Int): ImpreciseFraction { fun moveMatterAsDustIntoContainer(_matterValue: Decimal, container: MatteryContainer, OUTPUT_DUST_MAIN: Int, OUTPUT_DUST_STACKING: Int): Decimal {
var matterValue = _matterValue var matterValue = _matterValue
val item = MItems.MATTER_DUST as MatterDustItem val item = MItems.MATTER_DUST as MatterDustItem
while (matterValue > ImpreciseFraction.ZERO) { while (matterValue > Decimal.ZERO) {
val stack = container[OUTPUT_DUST_MAIN] val stack = container[OUTPUT_DUST_MAIN]
// первый слот пустой // первый слот пустой
@ -91,7 +91,7 @@ fun moveMatterAsDustIntoContainer(_matterValue: ImpreciseFraction, container: Ma
} }
} }
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
class MatterDecomposerBlockEntity(pos: BlockPos, state: BlockState) class MatterDecomposerBlockEntity(pos: BlockPos, state: BlockState)
@ -99,14 +99,14 @@ class MatterDecomposerBlockEntity(pos: BlockPos, state: BlockState)
class DecomposerJob : Job { class DecomposerJob : Job {
val toDust: Boolean val toDust: Boolean
var matterValue: ImpreciseFraction var matterValue: Decimal
constructor(tag: CompoundTag) : super(tag) { constructor(tag: CompoundTag) : super(tag) {
toDust = tag.getBoolean(TO_DUST_KEY) toDust = tag.getBoolean(TO_DUST_KEY)
matterValue = tag.getImpreciseFraction(MATTER_VALUE_KEY) matterValue = tag.getDecimal(MATTER_VALUE_KEY)
} }
constructor(toDust: Boolean, matterValue: ImpreciseFraction, ticks: Double) : super(ticks, BASE_CONSUMPTION) { constructor(toDust: Boolean, matterValue: Decimal, ticks: Double) : super(ticks, BASE_CONSUMPTION) {
this.toDust = toDust this.toDust = toDust
this.matterValue = matterValue this.matterValue = matterValue
} }
@ -269,8 +269,8 @@ class MatterDecomposerBlockEntity(pos: BlockPos, state: BlockState)
val CAPACITY get() = _CAPACITY.get() val CAPACITY get() = _CAPACITY.get()
val BASE_CONSUMPTION get() = _BASE_CONSUMPTION.get() val BASE_CONSUMPTION get() = _BASE_CONSUMPTION.get()
private var _CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _CAPACITY: DecimalConfigValue by WriteOnce()
private var _BASE_CONSUMPTION: ImpreciseFractionConfigValue by WriteOnce() private var _BASE_CONSUMPTION: DecimalConfigValue by WriteOnce()
var ENERGY_VALUES: ConciseBalanceValues by WriteOnce() var ENERGY_VALUES: ConciseBalanceValues by WriteOnce()
private set private set
@ -278,10 +278,10 @@ class MatterDecomposerBlockEntity(pos: BlockPos, state: BlockState)
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.MATTER_DECOMPOSER) builder.push(MNames.MATTER_DECOMPOSER)
ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = ImpreciseFraction(400_000), throughput = ImpreciseFraction(2_000)) ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = Decimal(400_000), throughput = Decimal(2_000))
_CAPACITY = builder.defineImpreciseFraction("matterCapacity", ImpreciseFraction(20_000), ImpreciseFraction.ONE_TENTH) _CAPACITY = builder.defineDecimal("matterCapacity", Decimal(20_000), Decimal.ONE_TENTH)
_BASE_CONSUMPTION = builder.defineImpreciseFraction("baseConsumption", ImpreciseFraction(240), ImpreciseFraction.ONE) _BASE_CONSUMPTION = builder.defineDecimal("baseConsumption", Decimal(240), Decimal.ONE)
builder.pop() builder.pop()
} }

View File

@ -28,7 +28,7 @@ import ru.dbotthepony.mc.otm.capability.matter.MatterDirection
import ru.dbotthepony.mc.otm.capability.matter.MatterHandlerImpl import ru.dbotthepony.mc.otm.capability.matter.MatterHandlerImpl
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.container.MatteryContainerHooks import ru.dbotthepony.mc.otm.container.MatteryContainerHooks
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.graph.Graph6Node import ru.dbotthepony.mc.otm.graph.Graph6Node
import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode
import ru.dbotthepony.mc.otm.graph.matter.MatterNetworkGraph import ru.dbotthepony.mc.otm.graph.matter.MatterNetworkGraph
@ -36,30 +36,30 @@ import ru.dbotthepony.mc.otm.item.MatterDustItem
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.menu.MatterRecyclerMenu import ru.dbotthepony.mc.otm.menu.MatterRecyclerMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.core.ImpreciseFractionConfigValue import ru.dbotthepony.mc.otm.core.DecimalConfigValue
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.registry.MBlocks import ru.dbotthepony.mc.otm.registry.MBlocks
import ru.dbotthepony.mc.otm.registry.MNames import ru.dbotthepony.mc.otm.registry.MNames
import ru.dbotthepony.mc.otm.core.WriteOnce import ru.dbotthepony.mc.otm.core.WriteOnce
import ru.dbotthepony.mc.otm.core.getImpreciseFraction import ru.dbotthepony.mc.otm.core.getDecimal
class MatterRecyclerBlockEntity(blockPos: BlockPos, blockState: BlockState) class MatterRecyclerBlockEntity(blockPos: BlockPos, blockState: BlockState)
: MatteryWorkerBlockEntity<MatterRecyclerBlockEntity.RecyclerJob>(MBlockEntities.MATTER_RECYCLER, blockPos, blockState, ::RecyclerJob), IMatterGraphNode, IDroppableContainer { : MatteryWorkerBlockEntity<MatterRecyclerBlockEntity.RecyclerJob>(MBlockEntities.MATTER_RECYCLER, blockPos, blockState, ::RecyclerJob), IMatterGraphNode, IDroppableContainer {
class RecyclerJob : Job { class RecyclerJob : Job {
var totalMatter: ImpreciseFraction var totalMatter: Decimal
constructor( constructor(
ticks: Double, ticks: Double,
powerUsage: ImpreciseFraction, powerUsage: Decimal,
totalMatter: ImpreciseFraction totalMatter: Decimal
) : super(ticks, powerUsage) { ) : super(ticks, powerUsage) {
this.totalMatter = totalMatter this.totalMatter = totalMatter
} }
constructor(tag: CompoundTag) : super(tag) { constructor(tag: CompoundTag) : super(tag) {
this.totalMatter = tag.getImpreciseFraction(KEY) this.totalMatter = tag.getDecimal(KEY)
} }
override fun serializeNBT(): CompoundTag { override fun serializeNBT(): CompoundTag {
@ -180,7 +180,7 @@ class MatterRecyclerBlockEntity(blockPos: BlockPos, blockState: BlockState)
return RecyclerJob(dustMatter.matter.toDouble() * TICKS_PER_MATTER, POWER_CONSUMPTION, dustMatter.matter * (0.4 + level!!.random.nextDouble() * 0.6)) to null return RecyclerJob(dustMatter.matter.toDouble() * TICKS_PER_MATTER, POWER_CONSUMPTION, dustMatter.matter * (0.4 + level!!.random.nextDouble() * 0.6)) to null
} }
override fun onWorkTick(requiredPower: ImpreciseFraction, extractedPower: ImpreciseFraction, ticksAdvanced: Double, job: RecyclerJob): Status { override fun onWorkTick(requiredPower: Decimal, extractedPower: Decimal, ticksAdvanced: Double, job: RecyclerJob): Status {
val receive = job.totalMatter / job.ticks val receive = job.totalMatter / job.ticks
if (receive.isZero) if (receive.isZero)
@ -208,8 +208,8 @@ class MatterRecyclerBlockEntity(blockPos: BlockPos, blockState: BlockState)
} }
companion object { companion object {
private var _CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _CAPACITY: DecimalConfigValue by WriteOnce()
private var _POWER_CONSUMPTION: ImpreciseFractionConfigValue by WriteOnce() private var _POWER_CONSUMPTION: DecimalConfigValue by WriteOnce()
private var _TICKS_PER_MATTER: ConfigValue<Double> by WriteOnce() private var _TICKS_PER_MATTER: ConfigValue<Double> by WriteOnce()
var ENERGY_CONFIG: ConciseBalanceValues by WriteOnce() var ENERGY_CONFIG: ConciseBalanceValues by WriteOnce()
@ -222,10 +222,10 @@ class MatterRecyclerBlockEntity(blockPos: BlockPos, blockState: BlockState)
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.MATTER_RECYCLER) builder.push(MNames.MATTER_RECYCLER)
ENERGY_CONFIG = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = ImpreciseFraction(80_000)) ENERGY_CONFIG = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = Decimal(80_000))
_CAPACITY = builder.defineImpreciseFraction("matterCapacity", ImpreciseFraction(2_000), ImpreciseFraction.ONE) _CAPACITY = builder.defineDecimal("matterCapacity", Decimal(2_000), Decimal.ONE)
_POWER_CONSUMPTION = builder.defineImpreciseFraction("powerConsumption", ImpreciseFraction(80), ImpreciseFraction.ONE) _POWER_CONSUMPTION = builder.defineDecimal("powerConsumption", Decimal(80), Decimal.ONE)
_TICKS_PER_MATTER = builder.define("ticksPerMatter", 2.0) _TICKS_PER_MATTER = builder.define("ticksPerMatter", 2.0)
builder.pop() builder.pop()

View File

@ -46,15 +46,15 @@ class MatterReplicatorBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
}), IMatterGraphNode, IDroppableContainer { }), IMatterGraphNode, IDroppableContainer {
class ReplicatorJob : ItemJob { class ReplicatorJob : ItemJob {
val matterPerTick: ImpreciseFraction val matterPerTick: Decimal
val task: ReplicationTask val task: ReplicationTask
var matterValue: ImpreciseFraction var matterValue: Decimal
val pattern: PatternState? val pattern: PatternState?
val asDust: Boolean val asDust: Boolean
constructor(tag: CompoundTag) : super(tag) { constructor(tag: CompoundTag) : super(tag) {
matterPerTick = tag.getImpreciseFraction(MATTER_PER_TICK_KEY) matterPerTick = tag.getDecimal(MATTER_PER_TICK_KEY)
matterValue = tag.getImpreciseFraction(MATTER_VALUE_KEY) matterValue = tag.getDecimal(MATTER_VALUE_KEY)
pattern = tag.map(PATTERN_KEY, PatternState::deserializeNBT) pattern = tag.map(PATTERN_KEY, PatternState::deserializeNBT)
asDust = tag.getBoolean(AS_DUST_KEY) asDust = tag.getBoolean(AS_DUST_KEY)
task = tag.map(TASK_KEY, ReplicationTask::deserializeNBT) ?: throw NoSuchElementException("Unable to deserialize matter task") task = tag.map(TASK_KEY, ReplicationTask::deserializeNBT) ?: throw NoSuchElementException("Unable to deserialize matter task")
@ -62,9 +62,9 @@ class MatterReplicatorBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
constructor( constructor(
itemStack: ItemStack, itemStack: ItemStack,
matterPerTick: ImpreciseFraction, matterPerTick: Decimal,
task: ReplicationTask, task: ReplicationTask,
matterValue: ImpreciseFraction, matterValue: Decimal,
pattern: PatternState?, pattern: PatternState?,
asDust: Boolean, asDust: Boolean,
ticks: Double, ticks: Double,
@ -212,7 +212,7 @@ class MatterReplicatorBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
) to null ) to null
} }
override fun onWorkTick(requiredPower: ImpreciseFraction, extractedPower: ImpreciseFraction, ticksAdvanced: Double, job: ReplicatorJob): Status { override fun onWorkTick(requiredPower: Decimal, extractedPower: Decimal, ticksAdvanced: Double, job: ReplicatorJob): Status {
val drainPerTick = currentJob!!.matterPerTick * ticksAdvanced val drainPerTick = currentJob!!.matterPerTick * ticksAdvanced
val graph = matterNode.graph as MatterNetworkGraph? ?: return Status.FAILURE_WAIT_FAST val graph = matterNode.graph as MatterNetworkGraph? ?: return Status.FAILURE_WAIT_FAST
@ -303,9 +303,9 @@ class MatterReplicatorBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
private val DRAIN_MULT get() = _DRAIN_MULT.get() private val DRAIN_MULT get() = _DRAIN_MULT.get()
private val MATTER_CAPACITY get() = _MATTER_CAPACITY.get() private val MATTER_CAPACITY get() = _MATTER_CAPACITY.get()
private var _BASE_CONSUMPTION: ImpreciseFractionConfigValue by WriteOnce() private var _BASE_CONSUMPTION: DecimalConfigValue by WriteOnce()
private var _DRAIN_MULT: ImpreciseFractionConfigValue by WriteOnce() private var _DRAIN_MULT: DecimalConfigValue by WriteOnce()
private var _MATTER_CAPACITY: ImpreciseFractionConfigValue by WriteOnce() private var _MATTER_CAPACITY: DecimalConfigValue by WriteOnce()
var ENERGY_VALUES: ConciseBalanceValues by WriteOnce() var ENERGY_VALUES: ConciseBalanceValues by WriteOnce()
private set private set
@ -313,11 +313,11 @@ class MatterReplicatorBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.MATTER_REPLICATOR) builder.push(MNames.MATTER_REPLICATOR)
ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = ImpreciseFraction(200_000), throughput = ImpreciseFraction(4_000)) ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = Decimal(200_000), throughput = Decimal(4_000))
_BASE_CONSUMPTION = builder.defineImpreciseFraction("basePowerConsumption", ImpreciseFraction(400), ImpreciseFraction.ONE) _BASE_CONSUMPTION = builder.defineDecimal("basePowerConsumption", Decimal(400), Decimal.ONE)
_DRAIN_MULT = builder.comment("How much 'ticks' of replication should replicator drain matter from network when running low on internal matter buffer. This is ultimately a performance value.").defineImpreciseFraction("drainMultiplier", ImpreciseFraction(200), ImpreciseFraction.ONE) _DRAIN_MULT = builder.comment("How much 'ticks' of replication should replicator drain matter from network when running low on internal matter buffer. This is ultimately a performance value.").defineDecimal("drainMultiplier", Decimal(200), Decimal.ONE)
_MATTER_CAPACITY = builder.defineImpreciseFraction("matterCapacity", ImpreciseFraction(400), ImpreciseFraction.ONE_TENTH) _MATTER_CAPACITY = builder.defineDecimal("matterCapacity", Decimal(400), Decimal.ONE_TENTH)
builder.pop() builder.pop()
} }

View File

@ -26,9 +26,9 @@ import ru.dbotthepony.mc.otm.capability.matter.IPatternState
import ru.dbotthepony.mc.otm.capability.matter.PatternState import ru.dbotthepony.mc.otm.capability.matter.PatternState
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.container.MatteryContainerHooks import ru.dbotthepony.mc.otm.container.MatteryContainerHooks
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.ImpreciseFractionConfigValue import ru.dbotthepony.mc.otm.core.DecimalConfigValue
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.graph.Graph6Node import ru.dbotthepony.mc.otm.graph.Graph6Node
import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode import ru.dbotthepony.mc.otm.graph.matter.IMatterGraphNode
@ -216,15 +216,15 @@ class MatterScannerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) :
companion object { companion object {
private val BASE_CONSUMPTION get() = _BASE_CONSUMPTION.get() private val BASE_CONSUMPTION get() = _BASE_CONSUMPTION.get()
private var _BASE_CONSUMPTION: ImpreciseFractionConfigValue by WriteOnce() private var _BASE_CONSUMPTION: DecimalConfigValue by WriteOnce()
var ENERGY_VALUES: ConciseBalanceValues by WriteOnce() var ENERGY_VALUES: ConciseBalanceValues by WriteOnce()
private set private set
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.push(MNames.MATTER_SCANNER) builder.push(MNames.MATTER_SCANNER)
ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = ImpreciseFraction(80_000), throughput = ImpreciseFraction(400)) ENERGY_VALUES = BlockEnergyStorageImpl.makeConfigEntry(builder, capacity = Decimal(80_000), throughput = Decimal(400))
_BASE_CONSUMPTION = builder.defineImpreciseFraction("baseConsumption", ImpreciseFraction(40), ImpreciseFraction.ONE) _BASE_CONSUMPTION = builder.defineDecimal("baseConsumption", Decimal(40), Decimal.ONE)
builder.pop() builder.pop()
} }

View File

@ -14,13 +14,11 @@ import net.minecraft.world.level.block.state.BlockState
import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.util.LazyOptional import net.minecraftforge.common.util.LazyOptional
import ru.dbotthepony.mc.otm.ServerConfig import ru.dbotthepony.mc.otm.ServerConfig
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.block.entity.MatteryPoweredBlockEntity import ru.dbotthepony.mc.otm.block.entity.MatteryPoweredBlockEntity
import ru.dbotthepony.mc.otm.graph.storage.BasicStorageGraphNode import ru.dbotthepony.mc.otm.graph.storage.BasicStorageGraphNode
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.container.MatteryContainer import ru.dbotthepony.mc.otm.container.MatteryContainer
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import ru.dbotthepony.mc.otm.menu.DriveRackMenu import ru.dbotthepony.mc.otm.menu.DriveRackMenu
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set

View File

@ -123,7 +123,7 @@ abstract class AbstractStorageImportExport<T>(
} }
companion object { companion object {
val MAX_POWER = ImpreciseFraction(10_000) val MAX_POWER = Decimal(10_000)
const val FILTER_KEY = "filter" const val FILTER_KEY = "filter"
} }
} }

View File

@ -19,13 +19,13 @@ import ru.dbotthepony.mc.otm.block.entity.MatteryPoweredBlockEntity
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage import ru.dbotthepony.mc.otm.capability.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.capability.transferInner import ru.dbotthepony.mc.otm.capability.transferInner
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.graph.storage.BasicStorageGraphNode import ru.dbotthepony.mc.otm.graph.storage.BasicStorageGraphNode
import ru.dbotthepony.mc.otm.graph.storage.StorageNetworkGraph import ru.dbotthepony.mc.otm.graph.storage.StorageNetworkGraph
import ru.dbotthepony.mc.otm.menu.StoragePowerSupplierMenu import ru.dbotthepony.mc.otm.menu.StoragePowerSupplierMenu
import ru.dbotthepony.mc.otm.registry.MBlockEntities import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.registry.MNames import ru.dbotthepony.mc.otm.registry.MNames
import ru.dbotthepony.mc.otm.core.getImpreciseFraction import ru.dbotthepony.mc.otm.core.getDecimal
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
class StoragePowerSupplierBlockEntity(blockPos: BlockPos, blockState: BlockState) : MatteryPoweredBlockEntity(MBlockEntities.STORAGE_POWER_SUPPLIER, blockPos, blockState) { class StoragePowerSupplierBlockEntity(blockPos: BlockPos, blockState: BlockState) : MatteryPoweredBlockEntity(MBlockEntities.STORAGE_POWER_SUPPLIER, blockPos, blockState) {
@ -38,7 +38,7 @@ class StoragePowerSupplierBlockEntity(blockPos: BlockPos, blockState: BlockState
val cell = BasicStorageGraphNode() val cell = BasicStorageGraphNode()
var powerPassed = ImpreciseFraction.ZERO var powerPassed = Decimal.ZERO
private set private set
override fun setLevel(p_155231_: Level) { override fun setLevel(p_155231_: Level) {
@ -86,7 +86,7 @@ class StoragePowerSupplierBlockEntity(blockPos: BlockPos, blockState: BlockState
if (graph.powerDemandingNodes.isEmpty()) if (graph.powerDemandingNodes.isEmpty())
return return
var demand = ImpreciseFraction.ZERO var demand = Decimal.ZERO
var i = 0 var i = 0
val available = energy.batteryLevel.coerceAtMost(ServerConfig.STORAGE_POWER_SUPPLIER.throughput) val available = energy.batteryLevel.coerceAtMost(ServerConfig.STORAGE_POWER_SUPPLIER.throughput)
@ -124,7 +124,7 @@ class StoragePowerSupplierBlockEntity(blockPos: BlockPos, blockState: BlockState
override fun load(nbt: CompoundTag) { override fun load(nbt: CompoundTag) {
super.load(nbt) super.load(nbt)
powerPassed = nbt.getImpreciseFraction(POWER_PASSED_KEY) powerPassed = nbt.getDecimal(POWER_PASSED_KEY)
} }
companion object { companion object {

View File

@ -6,8 +6,8 @@ import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import net.minecraftforge.common.capabilities.ForgeCapabilities import net.minecraftforge.common.capabilities.ForgeCapabilities
import net.minecraftforge.common.util.INBTSerializable import net.minecraftforge.common.util.INBTSerializable
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.getImpreciseFraction import ru.dbotthepony.mc.otm.core.getDecimal
import ru.dbotthepony.mc.otm.core.getItemStack import ru.dbotthepony.mc.otm.core.getItemStack
import ru.dbotthepony.mc.otm.core.ifPresentK import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
@ -18,8 +18,8 @@ import ru.dbotthepony.mc.otm.triggers.AndroidBatteryTrigger
class AndroidPowerSource( class AndroidPowerSource(
private val ply: Player, private val ply: Player,
synchronizer: FieldSynchronizer, synchronizer: FieldSynchronizer,
initialCharge: ImpreciseFraction, initialCharge: Decimal,
maxCharge: ImpreciseFraction maxCharge: Decimal
) : IMatteryEnergyStorage, INBTSerializable<CompoundTag> { ) : IMatteryEnergyStorage, INBTSerializable<CompoundTag> {
private var battery by synchronizer.fraction(initialCharge, name = "android battery") private var battery by synchronizer.fraction(initialCharge, name = "android battery")
private var maxBattery by synchronizer.fraction(maxCharge, name = "android max battery") private var maxBattery by synchronizer.fraction(maxCharge, name = "android max battery")
@ -41,8 +41,8 @@ class AndroidPowerSource(
} }
override fun deserializeNBT(tag: CompoundTag) { override fun deserializeNBT(tag: CompoundTag) {
battery = tag.getImpreciseFraction("battery") battery = tag.getDecimal("battery")
maxBattery = tag.getImpreciseFraction("maxBattery") maxBattery = tag.getDecimal("maxBattery")
item = tag.getItemStack("item") item = tag.getItemStack("item")
} }
@ -58,18 +58,18 @@ class AndroidPowerSource(
} }
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyOuter(howMuch, simulate) return receiveEnergyOuter(howMuch, simulate)
} }
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
@Suppress("name_shadowing") @Suppress("name_shadowing")
var howMuch = howMuch var howMuch = howMuch
var drained = ImpreciseFraction.ZERO var drained = Decimal.ZERO
if (!item.isEmpty) { if (!item.isEmpty) {
item.getCapability(ForgeCapabilities.ENERGY).ifPresentK { item.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
@ -107,10 +107,10 @@ class AndroidPowerSource(
return drained return drained
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
@Suppress("name_shadowing") @Suppress("name_shadowing")
var howMuch = howMuch var howMuch = howMuch
var received = ImpreciseFraction.ZERO var received = Decimal.ZERO
if (!item.isEmpty) { if (!item.isEmpty) {
item.getCapability(ForgeCapabilities.ENERGY).ifPresentK { item.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
@ -140,7 +140,7 @@ class AndroidPowerSource(
return received return received
} }
override var batteryLevel: ImpreciseFraction override var batteryLevel: Decimal
get() { get() {
if (!item.isEmpty) { if (!item.isEmpty) {
item.getCapability(ForgeCapabilities.ENERGY).ifPresentK { item.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
@ -158,7 +158,7 @@ class AndroidPowerSource(
battery = value battery = value
} }
override var maxBatteryLevel: ImpreciseFraction override var maxBatteryLevel: Decimal
get() { get() {
if (item != ItemStack.EMPTY) { if (item != ItemStack.EMPTY) {
item.getCapability(ForgeCapabilities.ENERGY).ifPresentK { item.getCapability(ForgeCapabilities.ENERGY).ifPresentK {

View File

@ -24,9 +24,9 @@ import ru.dbotthepony.mc.otm.ConciseBalanceValues
import ru.dbotthepony.mc.otm.VerboseBalanceValues import ru.dbotthepony.mc.otm.VerboseBalanceValues
import ru.dbotthepony.mc.otm.block.entity.MatteryBlockEntity import ru.dbotthepony.mc.otm.block.entity.MatteryBlockEntity
import ru.dbotthepony.mc.otm.compat.mekanism.Mattery2MekanismEnergyWrapper import ru.dbotthepony.mc.otm.compat.mekanism.Mattery2MekanismEnergyWrapper
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.core.formatPower import ru.dbotthepony.mc.otm.core.formatPower
import ru.dbotthepony.mc.otm.core.map import ru.dbotthepony.mc.otm.core.map
import ru.dbotthepony.mc.otm.core.mapIf import ru.dbotthepony.mc.otm.core.mapIf
@ -34,8 +34,8 @@ import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.core.tagNotNull import ru.dbotthepony.mc.otm.core.tagNotNull
sealed interface IEnergyStorageImpl { sealed interface IEnergyStorageImpl {
val maxInput: ImpreciseFraction? val maxInput: Decimal?
val maxOutput: ImpreciseFraction? val maxOutput: Decimal?
val direction: FlowDirection val direction: FlowDirection
} }
@ -102,15 +102,15 @@ private fun batteryLevel(it: IMatteryEnergyStorage, tooltips: MutableList<Compon
sealed class ItemEnergyStorageImpl( sealed class ItemEnergyStorageImpl(
final override val direction: FlowDirection, final override val direction: FlowDirection,
protected val itemStack: ItemStack, protected val itemStack: ItemStack,
maxBatteryLevel: ImpreciseFraction, maxBatteryLevel: Decimal,
maxInput: ImpreciseFraction?, maxInput: Decimal?,
maxOutput: ImpreciseFraction?, maxOutput: Decimal?,
val initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO val initialBatteryLevel: Decimal = Decimal.ZERO
) : IMatteryEnergyStorage, ICapabilityProvider, IEnergyStorageImpl { ) : IMatteryEnergyStorage, ICapabilityProvider, IEnergyStorageImpl {
final override var maxInput: ImpreciseFraction? = maxInput final override var maxInput: Decimal? = maxInput
protected set protected set
final override var maxOutput: ImpreciseFraction? = maxOutput final override var maxOutput: Decimal? = maxOutput
protected set protected set
private val resolver = LazyOptional.of { this } private val resolver = LazyOptional.of { this }
@ -126,32 +126,32 @@ sealed class ItemEnergyStorageImpl(
return LazyOptional.empty() return LazyOptional.empty()
} }
override var maxBatteryLevel: ImpreciseFraction = maxBatteryLevel override var maxBatteryLevel: Decimal = maxBatteryLevel
protected set protected set
override var batteryLevel: ImpreciseFraction override var batteryLevel: Decimal
get() = itemStack.tag?.map(ENERGY_KEY, ImpreciseFraction::deserializeNBT) ?: initialBatteryLevel get() = itemStack.tag?.map(ENERGY_KEY, Decimal::deserializeNBT) ?: initialBatteryLevel
protected set(value) { protected set(value) {
itemStack.tagNotNull[ENERGY_KEY] = value.serializeNBT() itemStack.tagNotNull[ENERGY_KEY] = value.serializeNBT()
} }
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction == FlowDirection.INPUT) if (direction == FlowDirection.INPUT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction == FlowDirection.OUTPUT) if (direction == FlowDirection.OUTPUT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive || itemStack.count != 1) if (!howMuch.isPositive || itemStack.count != 1)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
@ -164,7 +164,7 @@ sealed class ItemEnergyStorageImpl(
val batteryLevel = batteryLevel val batteryLevel = batteryLevel
if (!batteryLevel.isPositive) if (!batteryLevel.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
val newLevel = (batteryLevel - howMuch).moreThanZero() val newLevel = (batteryLevel - howMuch).moreThanZero()
val diff = (batteryLevel - newLevel) val diff = (batteryLevel - newLevel)
@ -176,9 +176,9 @@ sealed class ItemEnergyStorageImpl(
return diff return diff
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive || itemStack.count != 1) if (!howMuch.isPositive || itemStack.count != 1)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
@ -191,7 +191,7 @@ sealed class ItemEnergyStorageImpl(
val batteryLevel = batteryLevel val batteryLevel = batteryLevel
if (batteryLevel >= maxBatteryLevel) if (batteryLevel >= maxBatteryLevel)
return ImpreciseFraction.ZERO return Decimal.ZERO
val newLevel = (batteryLevel + howMuch).coerceAtMost(maxBatteryLevel) val newLevel = (batteryLevel + howMuch).coerceAtMost(maxBatteryLevel)
val diff = (newLevel - batteryLevel) val diff = (newLevel - batteryLevel)
@ -232,48 +232,48 @@ sealed class ItemEnergyStorageImpl(
open class EnergyConsumerItem( open class EnergyConsumerItem(
stack: ItemStack, stack: ItemStack,
maxBatteryLevel: ImpreciseFraction, maxBatteryLevel: Decimal,
maxInput: ImpreciseFraction? = null, maxInput: Decimal? = null,
maxOutput: ImpreciseFraction? = maxInput, maxOutput: Decimal? = maxInput,
initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO initialBatteryLevel: Decimal = Decimal.ZERO
) : ItemEnergyStorageImpl(FlowDirection.INPUT, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel) ) : ItemEnergyStorageImpl(FlowDirection.INPUT, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel)
open class EnergyProducerItem( open class EnergyProducerItem(
stack: ItemStack, stack: ItemStack,
maxBatteryLevel: ImpreciseFraction, maxBatteryLevel: Decimal,
maxInput: ImpreciseFraction? = null, maxInput: Decimal? = null,
maxOutput: ImpreciseFraction? = maxInput, maxOutput: Decimal? = maxInput,
initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO initialBatteryLevel: Decimal = Decimal.ZERO
) : ItemEnergyStorageImpl(FlowDirection.OUTPUT, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel) ) : ItemEnergyStorageImpl(FlowDirection.OUTPUT, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel)
open class EnergyCapacitorItem( open class EnergyCapacitorItem(
stack: ItemStack, stack: ItemStack,
maxBatteryLevel: ImpreciseFraction, maxBatteryLevel: Decimal,
maxInput: ImpreciseFraction? = null, maxInput: Decimal? = null,
maxOutput: ImpreciseFraction? = maxInput, maxOutput: Decimal? = maxInput,
initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO initialBatteryLevel: Decimal = Decimal.ZERO
) : ItemEnergyStorageImpl(FlowDirection.BI_DIRECTIONAL, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel) ) : ItemEnergyStorageImpl(FlowDirection.BI_DIRECTIONAL, stack, maxBatteryLevel, maxInput, maxOutput, initialBatteryLevel)
sealed class BlockEnergyStorageImpl( sealed class BlockEnergyStorageImpl(
protected val listener: () -> Unit, protected val listener: () -> Unit,
final override val direction: FlowDirection, final override val direction: FlowDirection,
private val maxBatteryLevelProvider: () -> ImpreciseFraction, private val maxBatteryLevelProvider: () -> Decimal,
private val maxInputProvider: () -> ImpreciseFraction?, private val maxInputProvider: () -> Decimal?,
private val maxOutputProvider: () -> ImpreciseFraction?, private val maxOutputProvider: () -> Decimal?,
) : IMatteryEnergyStorage, INBTSerializable<CompoundTag>, IEnergyStorageImpl { ) : IMatteryEnergyStorage, INBTSerializable<CompoundTag>, IEnergyStorageImpl {
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
direction: FlowDirection, direction: FlowDirection,
maxBatteryLevel: ImpreciseFraction, maxBatteryLevel: Decimal,
maxInput: ImpreciseFraction?, maxInput: Decimal?,
maxOutput: ImpreciseFraction?, maxOutput: Decimal?,
) : this(listener, direction, { maxBatteryLevel }, { maxInput }, { maxOutput }) ) : this(listener, direction, { maxBatteryLevel }, { maxInput }, { maxOutput })
private var maxInputStorage: ImpreciseFraction? = null private var maxInputStorage: Decimal? = null
private var maxOutputStorage: ImpreciseFraction? = null private var maxOutputStorage: Decimal? = null
private var maxBatteryLevelStorage: ImpreciseFraction? = null private var maxBatteryLevelStorage: Decimal? = null
final override var maxInput: ImpreciseFraction? final override var maxInput: Decimal?
get() = maxInputStorage ?: maxInputProvider.invoke() get() = maxInputStorage ?: maxInputProvider.invoke()
protected set(value) { protected set(value) {
if (value != maxInputStorage) { if (value != maxInputStorage) {
@ -282,7 +282,7 @@ sealed class BlockEnergyStorageImpl(
} }
} }
final override var maxOutput: ImpreciseFraction? final override var maxOutput: Decimal?
get() = maxOutputStorage ?: maxOutputProvider.invoke() get() = maxOutputStorage ?: maxOutputProvider.invoke()
protected set(value) { protected set(value) {
if (value != maxOutputStorage) { if (value != maxOutputStorage) {
@ -291,7 +291,7 @@ sealed class BlockEnergyStorageImpl(
} }
} }
override var maxBatteryLevel: ImpreciseFraction override var maxBatteryLevel: Decimal
get() = maxBatteryLevelStorage ?: maxBatteryLevelProvider.invoke() get() = maxBatteryLevelStorage ?: maxBatteryLevelProvider.invoke()
protected set(value) { protected set(value) {
if (value != maxBatteryLevelStorage) { if (value != maxBatteryLevelStorage) {
@ -300,7 +300,7 @@ sealed class BlockEnergyStorageImpl(
} }
} }
override var batteryLevel = ImpreciseFraction.ZERO override var batteryLevel = Decimal.ZERO
protected set(value) { protected set(value) {
if (value != field) { if (value != field) {
field = value field = value
@ -308,23 +308,23 @@ sealed class BlockEnergyStorageImpl(
} }
} }
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction == FlowDirection.INPUT) if (direction == FlowDirection.INPUT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction == FlowDirection.OUTPUT) if (direction == FlowDirection.OUTPUT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
@ -335,7 +335,7 @@ sealed class BlockEnergyStorageImpl(
} }
if (!batteryLevel.isPositive) if (!batteryLevel.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
val newLevel = (batteryLevel - howMuch).moreThanZero() val newLevel = (batteryLevel - howMuch).moreThanZero()
val diff = (batteryLevel - newLevel) val diff = (batteryLevel - newLevel)
@ -347,9 +347,9 @@ sealed class BlockEnergyStorageImpl(
return diff return diff
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
@ -360,7 +360,7 @@ sealed class BlockEnergyStorageImpl(
} }
if (batteryLevel >= maxBatteryLevel) if (batteryLevel >= maxBatteryLevel)
return ImpreciseFraction.ZERO return Decimal.ZERO
val newLevel = (batteryLevel + howMuch).coerceAtMost(maxBatteryLevel) val newLevel = (batteryLevel + howMuch).coerceAtMost(maxBatteryLevel)
val diff = (newLevel - batteryLevel) val diff = (newLevel - batteryLevel)
@ -392,10 +392,10 @@ sealed class BlockEnergyStorageImpl(
} }
override fun deserializeNBT(nbt: CompoundTag) { override fun deserializeNBT(nbt: CompoundTag) {
batteryLevel = nbt.map(ENERGY_STORED_KEY, ImpreciseFraction.Companion::deserializeNBT) ?: ImpreciseFraction.ZERO batteryLevel = nbt.map(ENERGY_STORED_KEY, Decimal.Companion::deserializeNBT) ?: Decimal.ZERO
maxBatteryLevelStorage = nbt.mapIf(ENERGY_STORED_MAX_KEY, ImpreciseFraction.Companion::deserializeNBT) maxBatteryLevelStorage = nbt.mapIf(ENERGY_STORED_MAX_KEY, Decimal.Companion::deserializeNBT)
maxInputStorage = nbt.mapIf(MAX_INPUT_KEY, ImpreciseFraction.Companion::deserializeNBT) maxInputStorage = nbt.mapIf(MAX_INPUT_KEY, Decimal.Companion::deserializeNBT)
maxOutputStorage = nbt.mapIf(MAX_OUTPUT_KEY, ImpreciseFraction.Companion::deserializeNBT) maxOutputStorage = nbt.mapIf(MAX_OUTPUT_KEY, Decimal.Companion::deserializeNBT)
} }
var resolver: LazyOptional<IMatteryEnergyStorage> = LazyOptional.of { this } var resolver: LazyOptional<IMatteryEnergyStorage> = LazyOptional.of { this }
@ -410,21 +410,21 @@ sealed class BlockEnergyStorageImpl(
} }
companion object { companion object {
val DEFAULT_MAX_IO = ImpreciseFraction(200) val DEFAULT_MAX_IO = Decimal(200)
val DEFAULT_MAX_CAPACITY = ImpreciseFraction(60_000) val DEFAULT_MAX_CAPACITY = Decimal(60_000)
const val ENERGY_STORED_KEY = "energy_stored" const val ENERGY_STORED_KEY = "energy_stored"
const val ENERGY_STORED_MAX_KEY = "energy_stored_max" const val ENERGY_STORED_MAX_KEY = "energy_stored_max"
const val MAX_INPUT_KEY = "max_input" const val MAX_INPUT_KEY = "max_input"
const val MAX_OUTPUT_KEY = "max_output" const val MAX_OUTPUT_KEY = "max_output"
fun makeConfigEntry(builder: ForgeConfigSpec.Builder, name: String? = null, capacity: ImpreciseFraction = DEFAULT_MAX_CAPACITY, throughput: ImpreciseFraction = DEFAULT_MAX_IO): ConciseBalanceValues { fun makeConfigEntry(builder: ForgeConfigSpec.Builder, name: String? = null, capacity: Decimal = DEFAULT_MAX_CAPACITY, throughput: Decimal = DEFAULT_MAX_IO): ConciseBalanceValues {
if (name != null) if (name != null)
builder.push(name) builder.push(name)
val obj = object : ConciseBalanceValues { val obj = object : ConciseBalanceValues {
override val capacity: ImpreciseFraction by builder.defineImpreciseFraction("capacity", capacity, ImpreciseFraction.ONE) override val capacity: Decimal by builder.defineDecimal("capacity", capacity, Decimal.ONE)
override val throughput: ImpreciseFraction by builder.defineImpreciseFraction("throughput", throughput, ImpreciseFraction.ONE) override val throughput: Decimal by builder.defineDecimal("throughput", throughput, Decimal.ONE)
} }
if (name != null) if (name != null)
@ -437,15 +437,15 @@ sealed class BlockEnergyStorageImpl(
open class WorkerEnergyStorage( open class WorkerEnergyStorage(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: () -> ImpreciseFraction = { DEFAULT_MAX_CAPACITY }, maxBatteryLevel: () -> Decimal = { DEFAULT_MAX_CAPACITY },
maxInput: () -> ImpreciseFraction? = { DEFAULT_MAX_IO }, maxInput: () -> Decimal? = { DEFAULT_MAX_IO },
maxOutput: () -> ImpreciseFraction? = maxInput maxOutput: () -> Decimal? = maxInput
) : BlockEnergyStorageImpl(listener, FlowDirection.INPUT, maxBatteryLevel, maxInput, maxOutput) { ) : BlockEnergyStorageImpl(listener, FlowDirection.INPUT, maxBatteryLevel, maxInput, maxOutput) {
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput }) maxOutput: Decimal? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput })
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
@ -465,9 +465,9 @@ open class WorkerEnergyStorage(
constructor( constructor(
listener: BlockEntity, listener: BlockEntity,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput) maxOutput: Decimal? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput)
companion object { companion object {
fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) { fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) {
@ -485,15 +485,15 @@ open class WorkerEnergyStorage(
open class GeneratorEnergyStorage( open class GeneratorEnergyStorage(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: () -> ImpreciseFraction = { DEFAULT_MAX_CAPACITY }, maxBatteryLevel: () -> Decimal = { DEFAULT_MAX_CAPACITY },
maxInput: () -> ImpreciseFraction? = { DEFAULT_MAX_IO }, maxInput: () -> Decimal? = { DEFAULT_MAX_IO },
maxOutput: () -> ImpreciseFraction? = maxInput maxOutput: () -> Decimal? = maxInput
) : BlockEnergyStorageImpl(listener, FlowDirection.OUTPUT, maxBatteryLevel, maxInput, maxOutput) { ) : BlockEnergyStorageImpl(listener, FlowDirection.OUTPUT, maxBatteryLevel, maxInput, maxOutput) {
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput }) maxOutput: Decimal? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput })
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
@ -513,9 +513,9 @@ open class GeneratorEnergyStorage(
constructor( constructor(
listener: BlockEntity, listener: BlockEntity,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput) maxOutput: Decimal? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput)
companion object { companion object {
fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) { fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) {
@ -533,15 +533,15 @@ open class GeneratorEnergyStorage(
open class CapacitorEnergyStorage( open class CapacitorEnergyStorage(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: () -> ImpreciseFraction = { DEFAULT_MAX_CAPACITY }, maxBatteryLevel: () -> Decimal = { DEFAULT_MAX_CAPACITY },
maxInput: () -> ImpreciseFraction? = { DEFAULT_MAX_IO }, maxInput: () -> Decimal? = { DEFAULT_MAX_IO },
maxOutput: () -> ImpreciseFraction? = maxInput maxOutput: () -> Decimal? = maxInput
) : BlockEnergyStorageImpl(listener, FlowDirection.BI_DIRECTIONAL, maxBatteryLevel, maxInput, maxOutput) { ) : BlockEnergyStorageImpl(listener, FlowDirection.BI_DIRECTIONAL, maxBatteryLevel, maxInput, maxOutput) {
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput }) maxOutput: Decimal? = maxInput) : this(listener, { maxBatteryLevel }, { maxInput }, { maxOutput })
constructor( constructor(
listener: () -> Unit, listener: () -> Unit,
@ -561,9 +561,9 @@ open class CapacitorEnergyStorage(
constructor( constructor(
listener: BlockEntity, listener: BlockEntity,
maxBatteryLevel: ImpreciseFraction = DEFAULT_MAX_CAPACITY, maxBatteryLevel: Decimal = DEFAULT_MAX_CAPACITY,
maxInput: ImpreciseFraction? = DEFAULT_MAX_IO, maxInput: Decimal? = DEFAULT_MAX_IO,
maxOutput: ImpreciseFraction? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput) maxOutput: Decimal? = maxInput) : this(listener::setChanged, maxBatteryLevel, maxInput, maxOutput)
companion object { companion object {
fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) { fun appendHoverText(itemStack: ItemStack, tooltips: MutableList<Component>) {

View File

@ -21,7 +21,7 @@ import ru.dbotthepony.mc.otm.container.awareStream
import ru.dbotthepony.mc.otm.container.stream import ru.dbotthepony.mc.otm.container.stream
import ru.dbotthepony.mc.otm.core.AwareItemStack import ru.dbotthepony.mc.otm.core.AwareItemStack
import ru.dbotthepony.mc.otm.core.ContainerItemStackEntry import ru.dbotthepony.mc.otm.core.ContainerItemStackEntry
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.orNull import ru.dbotthepony.mc.otm.core.orNull
import java.util.IdentityHashMap import java.util.IdentityHashMap
import java.util.LinkedList import java.util.LinkedList
@ -29,46 +29,46 @@ import java.util.stream.Stream
val ICapabilityProvider.matteryPlayer: MatteryPlayerCapability? get() = getCapability(MatteryCapability.MATTERY_PLAYER).orNull() val ICapabilityProvider.matteryPlayer: MatteryPlayerCapability? get() = getCapability(MatteryCapability.MATTERY_PLAYER).orNull()
fun IEnergyStorage.receiveEnergy(amount: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IEnergyStorage.receiveEnergy(amount: Decimal, simulate: Boolean): Decimal {
if (this is IMatteryEnergyStorage) if (this is IMatteryEnergyStorage)
return receiveEnergyOuter(amount, simulate) return receiveEnergyOuter(amount, simulate)
if (!amount.isPositive) if (!amount.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
if (amount > ImpreciseFraction.INT_MAX_VALUE) if (amount > Decimal.INT_MAX_VALUE)
return ImpreciseFraction.valueOf(receiveEnergy(Int.MAX_VALUE, simulate)) return Decimal.valueOf(receiveEnergy(Int.MAX_VALUE, simulate))
return ImpreciseFraction.valueOf(receiveEnergy(amount.toInt(), simulate)) return Decimal.valueOf(receiveEnergy(amount.toInt(), simulate))
} }
fun IEnergyStorage.extractEnergy(amount: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IEnergyStorage.extractEnergy(amount: Decimal, simulate: Boolean): Decimal {
if (this is IMatteryEnergyStorage) if (this is IMatteryEnergyStorage)
return extractEnergyOuter(amount, simulate) return extractEnergyOuter(amount, simulate)
if (!amount.isPositive) if (!amount.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
if (amount > ImpreciseFraction.INT_MAX_VALUE) if (amount > Decimal.INT_MAX_VALUE)
return ImpreciseFraction.valueOf(extractEnergy(Int.MAX_VALUE, simulate)) return Decimal.valueOf(extractEnergy(Int.MAX_VALUE, simulate))
return ImpreciseFraction.valueOf(extractEnergy(amount.toInt(), simulate)) return Decimal.valueOf(extractEnergy(amount.toInt(), simulate))
} }
val IEnergyStorage.maxEnergyStoredMattery: ImpreciseFraction get() { val IEnergyStorage.maxEnergyStoredMattery: Decimal get() {
if (this is IMatteryEnergyStorage) { if (this is IMatteryEnergyStorage) {
return maxBatteryLevel return maxBatteryLevel
} }
return ImpreciseFraction.valueOf(maxEnergyStored) return Decimal.valueOf(maxEnergyStored)
} }
val IEnergyStorage.energyStoredMattery: ImpreciseFraction get() { val IEnergyStorage.energyStoredMattery: Decimal get() {
if (this is IMatteryEnergyStorage) { if (this is IMatteryEnergyStorage) {
return batteryLevel return batteryLevel
} }
return ImpreciseFraction.valueOf(energyStored) return Decimal.valueOf(energyStored)
} }
val IEnergyStorage.chargeRatio: Float get() { val IEnergyStorage.chargeRatio: Float get() {

View File

@ -1,8 +1,7 @@
package ru.dbotthepony.mc.otm.capability package ru.dbotthepony.mc.otm.capability
import net.minecraft.util.Mth
import net.minecraftforge.energy.IEnergyStorage import net.minecraftforge.energy.IEnergyStorage
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.RGBAColor import ru.dbotthepony.mc.otm.core.RGBAColor
import java.math.BigInteger import java.math.BigInteger
import kotlin.math.roundToInt import kotlin.math.roundToInt
@ -14,7 +13,7 @@ interface IMatteryEnergyStorage : IEnergyStorage {
* *
* @return energy extracted * @return energy extracted
*/ */
fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal
/** /**
* Energy extraction by internal processes * Energy extraction by internal processes
@ -24,14 +23,14 @@ interface IMatteryEnergyStorage : IEnergyStorage {
* *
* @return energy extracted * @return energy extracted
*/ */
fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal
/** /**
* Energy insertion by external interacts * Energy insertion by external interacts
* *
* @return energy accepted * @return energy accepted
*/ */
fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal
/** /**
* Energy insertion by internal processes * Energy insertion by internal processes
@ -41,11 +40,11 @@ interface IMatteryEnergyStorage : IEnergyStorage {
* *
* @return energy accepted * @return energy accepted
*/ */
fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal
val batteryLevel: ImpreciseFraction val batteryLevel: Decimal
val maxBatteryLevel: ImpreciseFraction val maxBatteryLevel: Decimal
val missingPower: ImpreciseFraction val missingPower: Decimal
get() = (maxBatteryLevel - batteryLevel).moreThanZero() get() = (maxBatteryLevel - batteryLevel).moreThanZero()
override fun receiveEnergy(maxReceive: Int, simulate: Boolean): Int { override fun receiveEnergy(maxReceive: Int, simulate: Boolean): Int {
@ -55,7 +54,7 @@ interface IMatteryEnergyStorage : IEnergyStorage {
if (received == 0) if (received == 0)
return 0 return 0
return receiveEnergyOuter(ImpreciseFraction(received), simulate).toInt() return receiveEnergyOuter(Decimal(received), simulate).toInt()
} }
override fun extractEnergy(maxReceive: Int, simulate: Boolean): Int { override fun extractEnergy(maxReceive: Int, simulate: Boolean): Int {
@ -65,7 +64,7 @@ interface IMatteryEnergyStorage : IEnergyStorage {
if (extracted == 0) if (extracted == 0)
return 0 return 0
return extractEnergyOuter(ImpreciseFraction(extracted), simulate).toInt() return extractEnergyOuter(Decimal(extracted), simulate).toInt()
} }
override fun getEnergyStored(): Int { override fun getEnergyStored(): Int {
@ -77,19 +76,19 @@ interface IMatteryEnergyStorage : IEnergyStorage {
} }
override fun canExtract(): Boolean { override fun canExtract(): Boolean {
return extractEnergyOuter(ImpreciseFraction.ONE, true) > ImpreciseFraction.ZERO return extractEnergyOuter(Decimal.ONE, true) > Decimal.ZERO
} }
override fun canReceive(): Boolean { override fun canReceive(): Boolean {
return receiveEnergyOuter(ImpreciseFraction.ONE, true) > ImpreciseFraction.ZERO return receiveEnergyOuter(Decimal.ONE, true) > Decimal.ZERO
} }
} }
fun IMatteryEnergyStorage.receiveEnergyOuterExact(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyOuterExact(howMuch: Decimal, simulate: Boolean): Decimal {
val extracted = receiveEnergyOuter(howMuch, true) val extracted = receiveEnergyOuter(howMuch, true)
if (extracted != howMuch) { if (extracted != howMuch) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (!simulate) { if (!simulate) {
@ -103,11 +102,11 @@ fun IMatteryEnergyStorage.receiveEnergyOuterExact(howMuch: ImpreciseFraction, si
* *
* @return energy extracted * @return energy extracted
*/ */
fun IMatteryEnergyStorage.extractEnergyOuterExact(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyOuterExact(howMuch: Decimal, simulate: Boolean): Decimal {
val extracted = extractEnergyOuter(howMuch, true) val extracted = extractEnergyOuter(howMuch, true)
if (extracted != howMuch) { if (extracted != howMuch) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (!simulate) { if (!simulate) {
@ -122,11 +121,11 @@ fun IMatteryEnergyStorage.extractEnergyOuterExact(howMuch: ImpreciseFraction, si
* *
* @return energy accepted * @return energy accepted
*/ */
fun IMatteryEnergyStorage.receiveEnergyInnerExact(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyInnerExact(howMuch: Decimal, simulate: Boolean): Decimal {
val extracted = receiveEnergyInner(howMuch, true) val extracted = receiveEnergyInner(howMuch, true)
if (extracted != howMuch) { if (extracted != howMuch) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (!simulate) { if (!simulate) {
@ -141,11 +140,11 @@ fun IMatteryEnergyStorage.receiveEnergyInnerExact(howMuch: ImpreciseFraction, si
* *
* @return energy extracted * @return energy extracted
*/ */
fun IMatteryEnergyStorage.extractEnergyInnerExact(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyInnerExact(howMuch: Decimal, simulate: Boolean): Decimal {
val extracted = extractEnergyInner(howMuch, true) val extracted = extractEnergyInner(howMuch, true)
if (extracted != howMuch) { if (extracted != howMuch) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (!simulate) { if (!simulate) {
@ -155,41 +154,41 @@ fun IMatteryEnergyStorage.extractEnergyInnerExact(howMuch: ImpreciseFraction, si
return extracted return extracted
} }
fun IMatteryEnergyStorage.extractEnergyOuter(howMuch: Long, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyOuter(howMuch: Long, simulate: Boolean): Decimal {
return extractEnergyOuter(ImpreciseFraction(howMuch), simulate) return extractEnergyOuter(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.extractEnergyOuter(howMuch: Int, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyOuter(howMuch: Int, simulate: Boolean): Decimal {
return extractEnergyOuter(ImpreciseFraction(howMuch), simulate) return extractEnergyOuter(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.receiveEnergyOuter(howMuch: Long, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyOuter(howMuch: Long, simulate: Boolean): Decimal {
return receiveEnergyOuter(ImpreciseFraction(howMuch), simulate) return receiveEnergyOuter(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.receiveEnergyOuter(howMuch: Int, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyOuter(howMuch: Int, simulate: Boolean): Decimal {
return receiveEnergyOuter(ImpreciseFraction(howMuch), simulate) return receiveEnergyOuter(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.extractEnergyInner(howMuch: Long, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyInner(howMuch: Long, simulate: Boolean): Decimal {
return extractEnergyInner(ImpreciseFraction(howMuch), simulate) return extractEnergyInner(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.extractEnergyInner(howMuch: Int, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.extractEnergyInner(howMuch: Int, simulate: Boolean): Decimal {
return extractEnergyInner(ImpreciseFraction(howMuch), simulate) return extractEnergyInner(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.receiveEnergyInner(howMuch: Long, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyInner(howMuch: Long, simulate: Boolean): Decimal {
return receiveEnergyInner(ImpreciseFraction(howMuch), simulate) return receiveEnergyInner(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.receiveEnergyInner(howMuch: Int, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.receiveEnergyInner(howMuch: Int, simulate: Boolean): Decimal {
return receiveEnergyInner(ImpreciseFraction(howMuch), simulate) return receiveEnergyInner(Decimal(howMuch), simulate)
} }
fun IMatteryEnergyStorage.transferInner(other: IMatteryEnergyStorage, amount: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.transferInner(other: IMatteryEnergyStorage, amount: Decimal, simulate: Boolean): Decimal {
if (!amount.isPositive) if (!amount.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
val extracted = extractEnergyInner(amount, true) val extracted = extractEnergyInner(amount, true)
val received = other.receiveEnergyOuter(extracted, simulate) val received = other.receiveEnergyOuter(extracted, simulate)
@ -200,9 +199,9 @@ fun IMatteryEnergyStorage.transferInner(other: IMatteryEnergyStorage, amount: Im
return received return received
} }
fun IMatteryEnergyStorage.transferOuter(other: IMatteryEnergyStorage, amount: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun IMatteryEnergyStorage.transferOuter(other: IMatteryEnergyStorage, amount: Decimal, simulate: Boolean): Decimal {
if (!amount.isPositive) if (!amount.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
val extracted = extractEnergyOuter(amount, true) val extracted = extractEnergyOuter(amount, true)
val received = other.receiveEnergyOuter(extracted, simulate) val received = other.receiveEnergyOuter(extracted, simulate)
@ -213,35 +212,35 @@ fun IMatteryEnergyStorage.transferOuter(other: IMatteryEnergyStorage, amount: Im
return received return received
} }
fun IMatteryEnergyStorage.extractStepInner(base: ImpreciseFraction, multiplier: Int, simulate: Boolean): Int { fun IMatteryEnergyStorage.extractStepInner(base: Decimal, multiplier: Int, simulate: Boolean): Int {
return (extractEnergyInner(base * multiplier, simulate) / base).toInt() return (extractEnergyInner(base * multiplier, simulate) / base).toInt()
} }
fun IMatteryEnergyStorage.extractStepOuter(base: ImpreciseFraction, multiplier: Int, simulate: Boolean): Int { fun IMatteryEnergyStorage.extractStepOuter(base: Decimal, multiplier: Int, simulate: Boolean): Int {
return (extractEnergyOuter(base * multiplier, simulate) / base).toInt() return (extractEnergyOuter(base * multiplier, simulate) / base).toInt()
} }
fun IMatteryEnergyStorage.extractStepInnerBi(base: ImpreciseFraction, multiplier: Int, simulate: Boolean): BigInteger { fun IMatteryEnergyStorage.extractStepInnerBi(base: Decimal, multiplier: Int, simulate: Boolean): BigInteger {
return (extractEnergyInner(base * multiplier, simulate) / base).whole return (extractEnergyInner(base * multiplier, simulate) / base).whole
} }
fun IMatteryEnergyStorage.extractStepOuterBi(base: ImpreciseFraction, multiplier: Int, simulate: Boolean): BigInteger { fun IMatteryEnergyStorage.extractStepOuterBi(base: Decimal, multiplier: Int, simulate: Boolean): BigInteger {
return (extractEnergyOuter(base * multiplier, simulate) / base).whole return (extractEnergyOuter(base * multiplier, simulate) / base).whole
} }
fun IMatteryEnergyStorage.extractStepInner(base: ImpreciseFraction, multiplier: BigInteger, simulate: Boolean): Int { fun IMatteryEnergyStorage.extractStepInner(base: Decimal, multiplier: BigInteger, simulate: Boolean): Int {
return (extractEnergyInner(base * multiplier, simulate) / base).toInt() return (extractEnergyInner(base * multiplier, simulate) / base).toInt()
} }
fun IMatteryEnergyStorage.extractStepOuter(base: ImpreciseFraction, multiplier: BigInteger, simulate: Boolean): Int { fun IMatteryEnergyStorage.extractStepOuter(base: Decimal, multiplier: BigInteger, simulate: Boolean): Int {
return (extractEnergyOuter(base * multiplier, simulate) / base).toInt() return (extractEnergyOuter(base * multiplier, simulate) / base).toInt()
} }
fun IMatteryEnergyStorage.extractStepInnerBi(base: ImpreciseFraction, multiplier: BigInteger, simulate: Boolean): BigInteger { fun IMatteryEnergyStorage.extractStepInnerBi(base: Decimal, multiplier: BigInteger, simulate: Boolean): BigInteger {
return (extractEnergyInner(base * multiplier, simulate) / base).whole return (extractEnergyInner(base * multiplier, simulate) / base).whole
} }
fun IMatteryEnergyStorage.extractStepOuterBi(base: ImpreciseFraction, multiplier: BigInteger, simulate: Boolean): BigInteger { fun IMatteryEnergyStorage.extractStepOuterBi(base: Decimal, multiplier: BigInteger, simulate: Boolean): BigInteger {
return (extractEnergyOuter(base * multiplier, simulate) / base).whole return (extractEnergyOuter(base * multiplier, simulate) / base).whole
} }

View File

@ -1,7 +1,6 @@
package ru.dbotthepony.mc.otm.capability package ru.dbotthepony.mc.otm.capability
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.ReferenceArraySet
import net.minecraft.ChatFormatting import net.minecraft.ChatFormatting
import net.minecraft.core.Direction import net.minecraft.core.Direction
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
@ -251,7 +250,7 @@ class MatteryPlayerCapability(val ply: Player) : ICapabilityProvider, INBTSerial
shouldPlaySound = false shouldPlaySound = false
iteration = 0 iteration = 0
deathLog.clear() deathLog.clear()
androidEnergy.batteryLevel = ImpreciseFraction.ZERO androidEnergy.batteryLevel = Decimal.ZERO
androidEnergy.maxBatteryLevel = ServerConfig.ANDROID_MAX_ENERGY androidEnergy.maxBatteryLevel = ServerConfig.ANDROID_MAX_ENERGY
dropBattery() dropBattery()

View File

@ -3,8 +3,6 @@ package ru.dbotthepony.mc.otm.capability.drive
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import ru.dbotthepony.mc.otm.core.Fraction
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import ru.dbotthepony.mc.otm.storage.IStorageComponent import ru.dbotthepony.mc.otm.storage.IStorageComponent
import ru.dbotthepony.mc.otm.storage.IStorageStack import ru.dbotthepony.mc.otm.storage.IStorageStack
import ru.dbotthepony.mc.otm.storage.IStorageTuple import ru.dbotthepony.mc.otm.storage.IStorageTuple

View File

@ -1,24 +1,23 @@
package ru.dbotthepony.mc.otm.capability.matter package ru.dbotthepony.mc.otm.capability.matter
import net.minecraft.util.Mth
import net.minecraftforge.common.capabilities.ICapabilityProvider import net.minecraftforge.common.capabilities.ICapabilityProvider
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.RGBAColor import ru.dbotthepony.mc.otm.core.RGBAColor
import ru.dbotthepony.mc.otm.core.orNull import ru.dbotthepony.mc.otm.core.orNull
import kotlin.math.roundToInt import kotlin.math.roundToInt
interface IMatterHandler { interface IMatterHandler {
val storedMatter: ImpreciseFraction val storedMatter: Decimal
val maxStoredMatter: ImpreciseFraction val maxStoredMatter: Decimal
fun receiveMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun receiveMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal
fun receiveMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun receiveMatterInner(howMuch: Decimal, simulate: Boolean): Decimal
fun extractMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun extractMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal
fun extractMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction fun extractMatterInner(howMuch: Decimal, simulate: Boolean): Decimal
val direction: MatterDirection val direction: MatterDirection
val missingMatter: ImpreciseFraction val missingMatter: Decimal
get() = maxStoredMatter.minus(storedMatter).moreThanZero() get() = maxStoredMatter.minus(storedMatter).moreThanZero()
val allowsExtract: Boolean val allowsExtract: Boolean

View File

@ -5,23 +5,22 @@ import net.minecraftforge.common.util.INBTSerializable
import net.minecraftforge.common.util.LazyOptional import net.minecraftforge.common.util.LazyOptional
import ru.dbotthepony.mc.otm.ConciseBalanceValues import ru.dbotthepony.mc.otm.ConciseBalanceValues
import ru.dbotthepony.mc.otm.VerboseBalanceValues import ru.dbotthepony.mc.otm.VerboseBalanceValues
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.container.set
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
open class MatterHandlerImpl @JvmOverloads constructor( open class MatterHandlerImpl @JvmOverloads constructor(
protected val listener: Runnable?, protected val listener: Runnable?,
override val direction: MatterDirection, override val direction: MatterDirection,
protected val maxStoredMatterSupplier: () -> ImpreciseFraction, protected val maxStoredMatterSupplier: () -> Decimal,
protected val maxReceiveSupplier: () -> ImpreciseFraction? = { null }, protected val maxReceiveSupplier: () -> Decimal? = { null },
protected val maxExtractSupplier: () -> ImpreciseFraction? = maxReceiveSupplier protected val maxExtractSupplier: () -> Decimal? = maxReceiveSupplier
) : IMatterHandler, INBTSerializable<CompoundTag> { ) : IMatterHandler, INBTSerializable<CompoundTag> {
constructor( constructor(
listener: Runnable?, listener: Runnable?,
direction: MatterDirection, direction: MatterDirection,
maxStoredMatter: ImpreciseFraction, maxStoredMatter: Decimal,
maxReceive: ImpreciseFraction? = null, maxReceive: Decimal? = null,
maxExtract: ImpreciseFraction? = null, maxExtract: Decimal? = null,
) : this(listener, direction, { maxStoredMatter }, { maxReceive }, { maxExtract }) ) : this(listener, direction, { maxStoredMatter }, { maxReceive }, { maxExtract })
constructor( constructor(
@ -39,10 +38,10 @@ open class MatterHandlerImpl @JvmOverloads constructor(
val maxReceive get() = maxReceiveSupplier.invoke() val maxReceive get() = maxReceiveSupplier.invoke()
val maxExtract get() = maxExtractSupplier.invoke() val maxExtract get() = maxExtractSupplier.invoke()
override val maxStoredMatter: ImpreciseFraction override val maxStoredMatter: Decimal
get() = maxStoredMatterSupplier.invoke() get() = maxStoredMatterSupplier.invoke()
override var storedMatter = ImpreciseFraction.ZERO override var storedMatter = Decimal.ZERO
protected set protected set
private var handler = LazyOptional.of<IMatterHandler> { this } private var handler = LazyOptional.of<IMatterHandler> { this }
@ -59,19 +58,19 @@ open class MatterHandlerImpl @JvmOverloads constructor(
return handler return handler
} }
open fun canReceiveAll(value: ImpreciseFraction): Boolean { open fun canReceiveAll(value: Decimal): Boolean {
return maxStoredMatter >= value && storedMatter + value <= maxStoredMatter return maxStoredMatter >= value && storedMatter + value <= maxStoredMatter
} }
override fun receiveMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction === MatterDirection.EXTRACT) if (direction === MatterDirection.EXTRACT)
return ImpreciseFraction.ZERO return Decimal.ZERO
return receiveMatterInner(howMuch, simulate) return receiveMatterInner(howMuch, simulate)
} }
override fun receiveMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
val new: ImpreciseFraction val new: Decimal
if (maxReceive == null) { if (maxReceive == null) {
new = (storedMatter + howMuch).coerceAtMost(maxStoredMatter) new = (storedMatter + howMuch).coerceAtMost(maxStoredMatter)
@ -89,15 +88,15 @@ open class MatterHandlerImpl @JvmOverloads constructor(
return diff return diff
} }
override fun extractMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
if (direction === MatterDirection.RECEIVE) if (direction === MatterDirection.RECEIVE)
return ImpreciseFraction.ZERO return Decimal.ZERO
return extractMatterInner(howMuch, simulate) return extractMatterInner(howMuch, simulate)
} }
override fun extractMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
val new: ImpreciseFraction val new: Decimal
if (maxExtract == null) { if (maxExtract == null) {
new = (storedMatter - howMuch).moreThanZero() new = (storedMatter - howMuch).moreThanZero()
@ -125,7 +124,7 @@ open class MatterHandlerImpl @JvmOverloads constructor(
} }
override fun deserializeNBT(tag: CompoundTag) { override fun deserializeNBT(tag: CompoundTag) {
storedMatter = ImpreciseFraction.deserializeNBT(tag["stored"]) storedMatter = Decimal.deserializeNBT(tag["stored"])
//maxStoredMatter = ImpreciseFraction.deserializeNBT(tag["max_storage"]) //maxStoredMatter = ImpreciseFraction.deserializeNBT(tag["max_storage"])
//maxReceive = if (tag.contains("max_receive")) ImpreciseFraction.deserializeNBT(tag["max_receive"]) else null //maxReceive = if (tag.contains("max_receive")) ImpreciseFraction.deserializeNBT(tag["max_receive"]) else null
//maxExtract = if (tag.contains("max_extract")) ImpreciseFraction.deserializeNBT(tag["max_extract"]) else null //maxExtract = if (tag.contains("max_extract")) ImpreciseFraction.deserializeNBT(tag["max_extract"]) else null

View File

@ -1,13 +1,13 @@
package ru.dbotthepony.mc.otm.compat.mekanism package ru.dbotthepony.mc.otm.compat.mekanism
import mekanism.api.math.FloatingLong import mekanism.api.math.FloatingLong
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import java.math.BigInteger import java.math.BigInteger
private val LONG_OVERFLOW = BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.TWO private val LONG_OVERFLOW = BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.TWO
private val LONG_OVERFLOW1 = BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.ONE private val LONG_OVERFLOW1 = BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.valueOf(Long.MAX_VALUE) + BigInteger.ONE
fun ImpreciseFraction.toFloatingLong(): FloatingLong { fun Decimal.toFloatingLong(): FloatingLong {
if (isNegative) { if (isNegative) {
// Floating long can't be negative // Floating long can't be negative
return FloatingLong.ZERO return FloatingLong.ZERO
@ -20,11 +20,11 @@ fun ImpreciseFraction.toFloatingLong(): FloatingLong {
return FloatingLong.create(whole.toLong(), (decimal * 10_000.0).toInt().toShort()) return FloatingLong.create(whole.toLong(), (decimal * 10_000.0).toInt().toShort())
} }
fun FloatingLong.toImpreciseFraction(): ImpreciseFraction { fun FloatingLong.toImpreciseFraction(): Decimal {
// Overflow // Overflow
if (value < 0L) { if (value < 0L) {
return ImpreciseFraction(LONG_OVERFLOW + BigInteger.valueOf(value), decimal / 10_000.0) return Decimal(LONG_OVERFLOW + BigInteger.valueOf(value), decimal / 10_000.0)
} }
return ImpreciseFraction(value, decimal / 10_000.0) return Decimal(value, decimal / 10_000.0)
} }

View File

@ -11,7 +11,7 @@ import org.apache.logging.log4j.LogManager
import ru.dbotthepony.mc.otm.capability.IMatteryEnergyStorage import ru.dbotthepony.mc.otm.capability.IMatteryEnergyStorage
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.isMekanismLoaded import ru.dbotthepony.mc.otm.capability.isMekanismLoaded
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import java.lang.ref.WeakReference import java.lang.ref.WeakReference
import java.util.WeakHashMap import java.util.WeakHashMap
@ -48,12 +48,12 @@ private class DoubleLazy<T>(onion: () -> Lazy<T>) : Lazy<T> {
private val mekanism2MtJ by DoubleLazy lazy@{ private val mekanism2MtJ by DoubleLazy lazy@{
try { try {
val conf = MekanismConfig.general val conf = MekanismConfig.general
return@lazy LazyCache(conf.forgeConversionRate::get) { ImpreciseFraction.ONE / it.toImpreciseFraction() } return@lazy LazyCache(conf.forgeConversionRate::get) { Decimal.ONE / it.toImpreciseFraction() }
} catch(err: Throwable) { } catch(err: Throwable) {
LOGGER.error("Unable to get Forge Energy to Mekanism Joules's conversion rate! Expect issues", err) LOGGER.error("Unable to get Forge Energy to Mekanism Joules's conversion rate! Expect issues", err)
} }
return@lazy lazyOf(ImpreciseFraction.ONE) return@lazy lazyOf(Decimal.ONE)
} }
private val mtj2Mekanism by DoubleLazy lazy@{ private val mtj2Mekanism by DoubleLazy lazy@{
@ -64,11 +64,11 @@ private val mtj2Mekanism by DoubleLazy lazy@{
LOGGER.error("Unable to get Mekanism Joules's to Forge Energy conversion rate! Expect issues", err) LOGGER.error("Unable to get Mekanism Joules's to Forge Energy conversion rate! Expect issues", err)
} }
return@lazy lazyOf(ImpreciseFraction.ONE) return@lazy lazyOf(Decimal.ONE)
} }
class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : IMatteryEnergyStorage { class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : IMatteryEnergyStorage {
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
val action = when (simulate) { val action = when (simulate) {
true -> Action.SIMULATE true -> Action.SIMULATE
false -> Action.EXECUTE false -> Action.EXECUTE
@ -77,11 +77,11 @@ class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : I
return power.extractEnergy((howMuch * mtj2Mekanism).toFloatingLong(), action).toImpreciseFraction() * mekanism2MtJ return power.extractEnergy((howMuch * mtj2Mekanism).toFloatingLong(), action).toImpreciseFraction() * mekanism2MtJ
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return extractEnergyOuter(howMuch, simulate) return extractEnergyOuter(howMuch, simulate)
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
val action = when (simulate) { val action = when (simulate) {
true -> Action.SIMULATE true -> Action.SIMULATE
false -> Action.EXECUTE false -> Action.EXECUTE
@ -90,13 +90,13 @@ class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : I
return howMuch - power.insertEnergy((howMuch * mtj2Mekanism).toFloatingLong(), action).toImpreciseFraction() * mekanism2MtJ return howMuch - power.insertEnergy((howMuch * mtj2Mekanism).toFloatingLong(), action).toImpreciseFraction() * mekanism2MtJ
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyOuter(howMuch, simulate) return receiveEnergyOuter(howMuch, simulate)
} }
override val batteryLevel: ImpreciseFraction override val batteryLevel: Decimal
get() { get() {
var sum = ImpreciseFraction.ZERO var sum = Decimal.ZERO
for (i in 0 until power.energyContainerCount) { for (i in 0 until power.energyContainerCount) {
sum += power.getEnergy(i).toImpreciseFraction() sum += power.getEnergy(i).toImpreciseFraction()
@ -105,9 +105,9 @@ class Mekanism2MatteryEnergyWrapper(private val power: IStrictEnergyHandler) : I
return sum * mekanism2MtJ return sum * mekanism2MtJ
} }
override val maxBatteryLevel: ImpreciseFraction override val maxBatteryLevel: Decimal
get() { get() {
var sum = ImpreciseFraction.ZERO var sum = Decimal.ZERO
for (i in 0 until power.energyContainerCount) { for (i in 0 until power.energyContainerCount) {
sum += power.getMaxEnergy(i).toImpreciseFraction() sum += power.getMaxEnergy(i).toImpreciseFraction()

View File

@ -66,7 +66,7 @@ val LongValueCodec = StreamCodec(DataInputStream::readLong, DataOutputStream::wr
val FloatValueCodec = StreamCodec(DataInputStream::readFloat, DataOutputStream::writeFloat) val FloatValueCodec = StreamCodec(DataInputStream::readFloat, DataOutputStream::writeFloat)
val DoubleValueCodec = StreamCodec(DataInputStream::readDouble, DataOutputStream::writeDouble) val DoubleValueCodec = StreamCodec(DataInputStream::readDouble, DataOutputStream::writeDouble)
val ItemStackValueCodec = StreamCodec(DataInputStream::readItem, DataOutputStream::writeItem, ItemStack::copy, ItemStack::isSameItemSameTags) val ItemStackValueCodec = StreamCodec(DataInputStream::readItem, DataOutputStream::writeItem, ItemStack::copy, ItemStack::isSameItemSameTags)
val ImpreciseFractionValueCodec = StreamCodec(DataInputStream::readImpreciseFraction, DataOutputStream::writeImpreciseFraction) val ImpreciseFractionValueCodec = StreamCodec(DataInputStream::readDecimal, DataOutputStream::writeDecimal)
val BigDecimalValueCodec = StreamCodec(DataInputStream::readBigDecimal, DataOutputStream::writeBigDecimal) val BigDecimalValueCodec = StreamCodec(DataInputStream::readBigDecimal, DataOutputStream::writeBigDecimal)
val UUIDValueCodec = StreamCodec({ s -> UUID(s.readLong(), s.readLong()) }, { s, v -> s.writeLong(v.mostSignificantBits); s.writeLong(v.leastSignificantBits) }) val UUIDValueCodec = StreamCodec({ s -> UUID(s.readLong(), s.readLong()) }, { s, v -> s.writeLong(v.mostSignificantBits); s.writeLong(v.leastSignificantBits) })
val VarIntValueCodec = StreamCodec(DataInputStream::readVarIntLE, DataOutputStream::writeVarIntLE) val VarIntValueCodec = StreamCodec(DataInputStream::readVarIntLE, DataOutputStream::writeVarIntLE)

View File

@ -131,13 +131,13 @@ private val MEANINGFUL_BITS_BI = BigInteger.valueOf(MEANINGFUL_BITS_LONG)
private val BI_MINUS_ONE = -BigInteger.ONE private val BI_MINUS_ONE = -BigInteger.ONE
fun ImpreciseFraction(value: Byte) = ImpreciseFraction.valueOf(value) fun Decimal(value: Byte) = Decimal.valueOf(value)
fun ImpreciseFraction(value: Short) = ImpreciseFraction.valueOf(value) fun Decimal(value: Short) = Decimal.valueOf(value)
fun ImpreciseFraction(value: Int) = ImpreciseFraction.valueOf(value) fun Decimal(value: Int) = Decimal.valueOf(value)
fun ImpreciseFraction(value: Long) = ImpreciseFraction.valueOf(value) fun Decimal(value: Long) = Decimal.valueOf(value)
/** /**
* Imprecise Fraction class for dealing with huge numbers that need fractional part to some extent. * Decimal class for having infinitely precise [whole] part, while having fixed precision [decimal] part.
* *
* In essence, this class is pretty much like [BigDecimal], except decimal part of this number is * In essence, this class is pretty much like [BigDecimal], except decimal part of this number is
* not guaranteed to be precise (stored as [Double]). The reason behind creation of this class, however, * not guaranteed to be precise (stored as [Double]). The reason behind creation of this class, however,
@ -145,11 +145,9 @@ fun ImpreciseFraction(value: Long) = ImpreciseFraction.valueOf(value)
* *
* This class is value based, however, [equals] and [compareTo] are not doing *exact* comparison. Whole part is always compared * This class is value based, however, [equals] and [compareTo] are not doing *exact* comparison. Whole part is always compared
* exactly, but decimal part is considered equal if their difference is less than [EPSILON]. * exactly, but decimal part is considered equal if their difference is less than [EPSILON].
*
*
*/ */
@Suppress("unused") @Suppress("unused")
class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Double = 0.0) : Number(), Comparable<ImpreciseFraction>, java.io.Serializable { class Decimal @JvmOverloads constructor(whole: BigInteger, decimal: Double = 0.0) : Number(), Comparable<Decimal>, java.io.Serializable {
constructor(whole: Byte, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal) constructor(whole: Byte, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal)
constructor(whole: Short, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal) constructor(whole: Short, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal)
constructor(whole: Int, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal) constructor(whole: Int, decimal: Double) : this(BigInteger.valueOf(whole.toLong()), decimal)
@ -212,10 +210,10 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val isNaN get() = decimal.isNaN() val isNaN get() = decimal.isNaN()
operator fun plus(other: ImpreciseFraction) = ImpreciseFraction(whole + other.whole, decimal + other.decimal) operator fun plus(other: Decimal) = Decimal(whole + other.whole, decimal + other.decimal)
operator fun minus(other: ImpreciseFraction) = ImpreciseFraction(whole - other.whole, decimal - other.decimal) operator fun minus(other: Decimal) = Decimal(whole - other.whole, decimal - other.decimal)
operator fun times(other: ImpreciseFraction): ImpreciseFraction { operator fun times(other: Decimal): Decimal {
if (other == ONE) if (other == ONE)
return this return this
else if (other == MINUS_ONE) else if (other == MINUS_ONE)
@ -231,12 +229,12 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
if (isZero(a) || isZero(c)) if (isZero(a) || isZero(c))
return ZERO return ZERO
return ImpreciseFraction(a * c) return Decimal(a * c)
} else if (isZero(a) && isZero(c)) { } else if (isZero(a) && isZero(c)) {
if (bZero || dZero) if (bZero || dZero)
return ZERO return ZERO
return ImpreciseFraction(0, decimal * other.decimal) return Decimal(0, decimal * other.decimal)
} else if (bZero) { } else if (bZero) {
val d = other.decimal * MEANINGFUL_BITS_DOUBLE val d = other.decimal * MEANINGFUL_BITS_DOUBLE
val dL = d.toLong() val dL = d.toLong()
@ -244,13 +242,13 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val ad = adInflated.divideAndRemainder(MEANINGFUL_BITS_BI) val ad = adInflated.divideAndRemainder(MEANINGFUL_BITS_BI)
if (isZero(c)) { if (isZero(c)) {
return ImpreciseFraction( return Decimal(
ad[0], ad[0],
ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE
) )
} }
return ImpreciseFraction( return Decimal(
a * c + ad[0], a * c + ad[0],
ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE
) )
@ -261,13 +259,13 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val bc = bcInflated.divideAndRemainder(MEANINGFUL_BITS_BI) val bc = bcInflated.divideAndRemainder(MEANINGFUL_BITS_BI)
if (isZero(a)) { if (isZero(a)) {
return ImpreciseFraction( return Decimal(
bc[0], bc[0],
bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE
) )
} }
return ImpreciseFraction( return Decimal(
a * c + bc[0], a * c + bc[0],
bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE
) )
@ -285,13 +283,13 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val bc = bcInflated.divideAndRemainder(MEANINGFUL_BITS_BI) val bc = bcInflated.divideAndRemainder(MEANINGFUL_BITS_BI)
val ad = adInflated.divideAndRemainder(MEANINGFUL_BITS_BI) val ad = adInflated.divideAndRemainder(MEANINGFUL_BITS_BI)
return ImpreciseFraction( return Decimal(
a * c + bc[0] + ad[0], a * c + bc[0] + ad[0],
decimal * other.decimal + bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE + ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE decimal * other.decimal + bc[1].toDouble() / MEANINGFUL_BITS_DOUBLE + ad[1].toDouble() / MEANINGFUL_BITS_DOUBLE
) )
} }
operator fun div(other: ImpreciseFraction): ImpreciseFraction { operator fun div(other: Decimal): Decimal {
if (other == ONE) if (other == ONE)
return this return this
else if (other == MINUS_ONE) else if (other == MINUS_ONE)
@ -313,29 +311,29 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val bD = b.toDouble() val bD = b.toDouble()
if (bD.isInfinite() || bD == 0.0) { if (bD.isInfinite() || bD == 0.0) {
return ImpreciseFraction(div[0].toBigInteger()) return Decimal(div[0].toBigInteger())
} }
return ImpreciseFraction(div[0].toBigInteger(), div[1].toDouble() / bD) return Decimal(div[0].toBigInteger(), div[1].toDouble() / bD)
} }
operator fun plus(other: Float): ImpreciseFraction { operator fun plus(other: Float): Decimal {
if (other == 0f) { if (other == 0f) {
return this return this
} }
return plus(ImpreciseFraction(other)) return plus(Decimal(other))
} }
operator fun minus(other: Float): ImpreciseFraction { operator fun minus(other: Float): Decimal {
if (other == 0f) { if (other == 0f) {
return this return this
} }
return minus(ImpreciseFraction(other)) return minus(Decimal(other))
} }
operator fun times(other: Float): ImpreciseFraction { operator fun times(other: Float): Decimal {
if (other == 1f) { if (other == 1f) {
return this return this
} else if (other == 0f) { } else if (other == 0f) {
@ -344,10 +342,10 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return times(ImpreciseFraction(other)) return times(Decimal(other))
} }
operator fun div(other: Float): ImpreciseFraction { operator fun div(other: Float): Decimal {
if (other == 0f) { if (other == 0f) {
if (isZero) if (isZero)
return NaN return NaN
@ -359,26 +357,26 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return div(ImpreciseFraction(other)) return div(Decimal(other))
} }
operator fun plus(other: Double): ImpreciseFraction { operator fun plus(other: Double): Decimal {
if (other == 0.0) { if (other == 0.0) {
return this return this
} }
return plus(ImpreciseFraction(other)) return plus(Decimal(other))
} }
operator fun minus(other: Double): ImpreciseFraction { operator fun minus(other: Double): Decimal {
if (other == 0.0) { if (other == 0.0) {
return this return this
} }
return minus(ImpreciseFraction(other)) return minus(Decimal(other))
} }
operator fun times(other: Double): ImpreciseFraction { operator fun times(other: Double): Decimal {
if (other == 1.0) { if (other == 1.0) {
return this return this
} else if (other == 0.0) { } else if (other == 0.0) {
@ -387,10 +385,10 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return times(ImpreciseFraction(other)) return times(Decimal(other))
} }
operator fun div(other: Double): ImpreciseFraction { operator fun div(other: Double): Decimal {
if (other == 0.0) { if (other == 0.0) {
if (isZero) if (isZero)
return NaN return NaN
@ -402,10 +400,10 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return div(ImpreciseFraction(other)) return div(Decimal(other))
} }
operator fun plus(other: Int): ImpreciseFraction { operator fun plus(other: Int): Decimal {
if (other == 0) { if (other == 0) {
return this return this
} }
@ -413,7 +411,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return plus(valueOf(other)) return plus(valueOf(other))
} }
operator fun minus(other: Int): ImpreciseFraction { operator fun minus(other: Int): Decimal {
if (other == 0) { if (other == 0) {
return this return this
} }
@ -421,7 +419,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return minus(valueOf(other)) return minus(valueOf(other))
} }
operator fun times(other: Int): ImpreciseFraction { operator fun times(other: Int): Decimal {
if (other == 1) { if (other == 1) {
return this return this
} else if (other == 0) { } else if (other == 0) {
@ -433,7 +431,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return times(valueOf(other)) return times(valueOf(other))
} }
operator fun div(other: Int): ImpreciseFraction { operator fun div(other: Int): Decimal {
if (other == 0) { if (other == 0) {
if (isZero) if (isZero)
return NaN return NaN
@ -448,7 +446,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return div(valueOf(other)) return div(valueOf(other))
} }
operator fun plus(other: Long): ImpreciseFraction { operator fun plus(other: Long): Decimal {
if (other == 0L) { if (other == 0L) {
return this return this
} }
@ -456,7 +454,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return plus(valueOf(other)) return plus(valueOf(other))
} }
operator fun minus(other: Long): ImpreciseFraction { operator fun minus(other: Long): Decimal {
if (other == 0L) { if (other == 0L) {
return this return this
} }
@ -464,7 +462,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return minus(valueOf(other)) return minus(valueOf(other))
} }
operator fun times(other: Long): ImpreciseFraction { operator fun times(other: Long): Decimal {
if (other == 1L) { if (other == 1L) {
return this return this
} else if (other == 0L) { } else if (other == 0L) {
@ -476,7 +474,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return times(valueOf(other)) return times(valueOf(other))
} }
operator fun div(other: Long): ImpreciseFraction { operator fun div(other: Long): Decimal {
if (other == 0L) { if (other == 0L) {
if (isZero) if (isZero)
return NaN return NaN
@ -491,23 +489,23 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return div(valueOf(other)) return div(valueOf(other))
} }
operator fun plus(other: BigInteger): ImpreciseFraction { operator fun plus(other: BigInteger): Decimal {
if (other == BigInteger.ZERO) { if (other == BigInteger.ZERO) {
return this return this
} }
return plus(ImpreciseFraction(other)) return plus(Decimal(other))
} }
operator fun minus(other: BigInteger): ImpreciseFraction { operator fun minus(other: BigInteger): Decimal {
if (other == BigInteger.ZERO) { if (other == BigInteger.ZERO) {
return this return this
} }
return minus(ImpreciseFraction(other)) return minus(Decimal(other))
} }
operator fun times(other: BigInteger): ImpreciseFraction { operator fun times(other: BigInteger): Decimal {
if (other == BigInteger.ONE) { if (other == BigInteger.ONE) {
return this return this
} else if (other == BigInteger.ZERO) { } else if (other == BigInteger.ZERO) {
@ -516,10 +514,10 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return times(ImpreciseFraction(other)) return times(Decimal(other))
} }
operator fun div(other: BigInteger): ImpreciseFraction { operator fun div(other: BigInteger): Decimal {
if (other == BigInteger.ZERO) { if (other == BigInteger.ZERO) {
return NaN return NaN
} else if (other == BigInteger.ONE) { } else if (other == BigInteger.ONE) {
@ -528,18 +526,18 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return -this return -this
} }
return div(ImpreciseFraction(other)) return div(Decimal(other))
} }
operator fun unaryMinus(): ImpreciseFraction { operator fun unaryMinus(): Decimal {
return ImpreciseFraction(-whole, -decimal) return Decimal(-whole, -decimal)
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (isNaN) if (isNaN)
return false return false
if (other is ImpreciseFraction) { if (other is Decimal) {
return other.whole == whole && weakEqualDoubles(decimal, other.decimal) return other.whole == whole && weakEqualDoubles(decimal, other.decimal)
} }
@ -548,9 +546,9 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
fun equalsStrict(other: Any?): Boolean { fun equalsStrict(other: Any?): Boolean {
if (isNaN) if (isNaN)
return other is ImpreciseFraction && other.isNaN // ибо hashCode() так требует return other is Decimal && other.isNaN // ибо hashCode() так требует
if (other is ImpreciseFraction) { if (other is Decimal) {
return other.whole == whole && other.decimal == decimal return other.whole == whole && other.decimal == decimal
} }
@ -564,11 +562,11 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return 31 * (decimal - decimal % EPSILON).hashCode() + whole.hashCode() return 31 * (decimal - decimal % EPSILON).hashCode() + whole.hashCode()
} }
fun floor(): ImpreciseFraction { fun floor(): Decimal {
if (decimal == 0.0) if (decimal == 0.0)
return this return this
return ImpreciseFraction(whole) return Decimal(whole)
} }
fun toString(decimals: Int): String { fun toString(decimals: Int): String {
@ -612,7 +610,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return if (decimal > 0.0) 1 else -1 return if (decimal > 0.0) 1 else -1
} }
override fun compareTo(other: ImpreciseFraction): Int { override fun compareTo(other: Decimal): Int {
if (isNaN) if (isNaN)
return 1 return 1
else if (other.isNaN) else if (other.isNaN)
@ -633,7 +631,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return whole.compareTo(other.whole) return whole.compareTo(other.whole)
} }
fun compareToStrict(other: ImpreciseFraction): Int { fun compareToStrict(other: Decimal): Int {
if (isNaN) if (isNaN)
return 1 return 1
else if (other.isNaN) else if (other.isNaN)
@ -671,14 +669,14 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
val isPositive get() = this > ZERO val isPositive get() = this > ZERO
val isNegative get() = this < ZERO val isNegative get() = this < ZERO
fun moreThanZero(): ImpreciseFraction { fun moreThanZero(): Decimal {
if (signum() >= 0) if (signum() >= 0)
return this return this
return ZERO return ZERO
} }
fun lessOrZero(): ImpreciseFraction { fun lessOrZero(): Decimal {
if (signum() <= 0) if (signum() <= 0)
return this return this
@ -743,7 +741,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return Fraction(toBigDecmial()) return Fraction(toBigDecmial())
} }
fun percentage(divisor: ImpreciseFraction, zeroing: Boolean = true): Float { fun percentage(divisor: Decimal, zeroing: Boolean = true): Float {
if ((isZero || divisor.isZero) && zeroing) return 0f if ((isZero || divisor.isZero) && zeroing) return 0f
if (isNaN || divisor.isNaN || divisor.isZero) return Float.NaN if (isNaN || divisor.isNaN || divisor.isZero) return Float.NaN
@ -756,7 +754,7 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
return toBigDecmial().divide(divisor.toBigDecmial(), PERCENTAGE_CONTEXT).toFloat() return toBigDecmial().divide(divisor.toBigDecmial(), PERCENTAGE_CONTEXT).toFloat()
} }
operator fun rem(divisor: ImpreciseFraction): ImpreciseFraction { operator fun rem(divisor: Decimal): Decimal {
TODO("Not yet implemented") TODO("Not yet implemented")
} }
@ -764,47 +762,47 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
@JvmStatic @JvmStatic
val serialVersionUID: Long = 287354739494574838L val serialVersionUID: Long = 287354739494574838L
@JvmField val MINUS_ZERO = ImpreciseFraction(0, -0.0) @JvmField val MINUS_ZERO = Decimal(0, -0.0)
@JvmField val ZERO = ImpreciseFraction(BigInteger.ZERO) @JvmField val ZERO = Decimal(BigInteger.ZERO)
@JvmField val ONE = ImpreciseFraction(BigInteger.ONE) @JvmField val ONE = Decimal(BigInteger.ONE)
@JvmField val MINUS_ONE = ImpreciseFraction(-BigInteger.ONE) @JvmField val MINUS_ONE = Decimal(-BigInteger.ONE)
@JvmField val TWO = ImpreciseFraction(BigInteger.TWO) @JvmField val TWO = Decimal(BigInteger.TWO)
@JvmField val TEN = ImpreciseFraction(BigInteger.TEN) @JvmField val TEN = Decimal(BigInteger.TEN)
@JvmField val INT_MAX_VALUE = ImpreciseFraction(BI_INT_MAX) @JvmField val INT_MAX_VALUE = Decimal(BI_INT_MAX)
@JvmField val INT_MIN_VALUE = ImpreciseFraction(BI_INT_MIN) @JvmField val INT_MIN_VALUE = Decimal(BI_INT_MIN)
@JvmField val LONG_MAX_VALUE = ImpreciseFraction(BI_LONG_MAX) @JvmField val LONG_MAX_VALUE = Decimal(BI_LONG_MAX)
@JvmField val LONG_MIN_VALUE = ImpreciseFraction(BI_LONG_MIN) @JvmField val LONG_MIN_VALUE = Decimal(BI_LONG_MIN)
@JvmField val FLOAT_MAX_VALUE = ImpreciseFraction(BI_FLOAT_MAX) @JvmField val FLOAT_MAX_VALUE = Decimal(BI_FLOAT_MAX)
@JvmField val FLOAT_MIN_VALUE = ImpreciseFraction(BI_FLOAT_MIN) @JvmField val FLOAT_MIN_VALUE = Decimal(BI_FLOAT_MIN)
@JvmField val DOUBLE_MAX_VALUE = ImpreciseFraction(BI_DOUBLE_MAX) @JvmField val DOUBLE_MAX_VALUE = Decimal(BI_DOUBLE_MAX)
@JvmField val DOUBLE_MIN_VALUE = ImpreciseFraction(BI_DOUBLE_MIN) @JvmField val DOUBLE_MIN_VALUE = Decimal(BI_DOUBLE_MIN)
@JvmField val ONE_TENTH = ImpreciseFraction("0.1") @JvmField val ONE_TENTH = Decimal("0.1")
private val cache = Array(2048) { ImpreciseFraction(it - 1024, 0.0) } private val cache = Array(2048) { Decimal(it - 1024, 0.0) }
/** /**
* Returns pooled value if present, otherwise constructs new object * Returns pooled value if present, otherwise constructs new object
*/ */
fun valueOf(value: Int): ImpreciseFraction { fun valueOf(value: Int): Decimal {
if (value in -1024 .. 1023) { if (value in -1024 .. 1023) {
return cache[value + 1024] return cache[value + 1024]
} }
return ImpreciseFraction(value, 0.0) return Decimal(value, 0.0)
} }
/** /**
* Returns pooled value if present, otherwise constructs new object * Returns pooled value if present, otherwise constructs new object
*/ */
fun valueOf(value: Long): ImpreciseFraction { fun valueOf(value: Long): Decimal {
if (value in -1024L .. 1023L) { if (value in -1024L .. 1023L) {
return cache[value.toInt() + 1024] return cache[value.toInt() + 1024]
} }
return ImpreciseFraction(value, 0.0) return Decimal(value, 0.0)
} }
/** /**
@ -818,81 +816,81 @@ class ImpreciseFraction @JvmOverloads constructor(whole: BigInteger, decimal: Do
fun valueOf(value: Byte) = valueOf(value.toInt()) fun valueOf(value: Byte) = valueOf(value.toInt())
@JvmField @JvmField
val NaN = ImpreciseFraction(0, Double.NaN) val NaN = Decimal(0, Double.NaN)
@JvmStatic @JvmStatic
fun fromByteArray(input: ByteArray): ImpreciseFraction { fun fromByteArray(input: ByteArray): Decimal {
val size = unsignedInt(input[0]) val size = unsignedInt(input[0])
if (size > 0) { if (size > 0) {
val slice = input.copyOfRange(1, 1 + size) val slice = input.copyOfRange(1, 1 + size)
val bits = bytesToLongBE(input, 1 + size) val bits = bytesToLongBE(input, 1 + size)
return ImpreciseFraction(BigInteger(slice), Double.fromBits(bits)) return Decimal(BigInteger(slice), Double.fromBits(bits))
} else { } else {
return ImpreciseFraction(BigInteger.ZERO, Double.fromBits(bytesToLongBE(input, 1))) return Decimal(BigInteger.ZERO, Double.fromBits(bytesToLongBE(input, 1)))
} }
} }
@JvmStatic @JvmStatic
fun deserializeNBT(input: Tag?): ImpreciseFraction { fun deserializeNBT(input: Tag?): Decimal {
if (input is ByteArrayTag) { if (input is ByteArrayTag) {
return fromByteArray(input.asByteArray) return fromByteArray(input.asByteArray)
} else if (input is StringTag) { } else if (input is StringTag) {
return ImpreciseFraction(input.asString) return Decimal(input.asString)
} }
return ZERO return ZERO
} }
@JvmStatic @JvmStatic
fun deserializeNBT(input: ByteArrayTag): ImpreciseFraction { fun deserializeNBT(input: ByteArrayTag): Decimal {
return fromByteArray(input.asByteArray) return fromByteArray(input.asByteArray)
} }
@JvmStatic @JvmStatic
fun read(buff: FriendlyByteBuf): ImpreciseFraction { fun read(buff: FriendlyByteBuf): Decimal {
return ImpreciseFraction(BigInteger(buff.readByteArray()), buff.readDouble()) return Decimal(BigInteger(buff.readByteArray()), buff.readDouble())
} }
} }
} }
fun FriendlyByteBuf.readImpreciseFraction() = ImpreciseFraction.read(this) fun FriendlyByteBuf.readDecimal() = Decimal.read(this)
fun FriendlyByteBuf.writeImpreciseFraction(value: ImpreciseFraction) = value.write(this) fun FriendlyByteBuf.writeDecimal(value: Decimal) = value.write(this)
fun InputStream.readImpreciseFraction(): ImpreciseFraction { fun InputStream.readDecimal(): Decimal {
val bytes = ByteArray(readVarIntLE()) val bytes = ByteArray(readVarIntLE())
read(bytes) read(bytes)
return ImpreciseFraction(BigInteger(bytes), readDouble()) return Decimal(BigInteger(bytes), readDouble())
} }
fun OutputStream.writeImpreciseFraction(value: ImpreciseFraction) { fun OutputStream.writeDecimal(value: Decimal) {
val bytes = value.whole.toByteArray() val bytes = value.whole.toByteArray()
writeVarIntLE(bytes.size) writeVarIntLE(bytes.size)
write(bytes) write(bytes)
writeDouble(value.decimal) writeDouble(value.decimal)
} }
fun CompoundTag.getImpreciseFraction(key: String) = ImpreciseFraction.deserializeNBT(this[key]) fun CompoundTag.getDecimal(key: String) = Decimal.deserializeNBT(this[key])
fun CompoundTag.putImpreciseFraction(key: String, value: ImpreciseFraction) = put(key, value.serializeNBT()) fun CompoundTag.putDecimal(key: String, value: Decimal) = put(key, value.serializeNBT())
operator fun CompoundTag.set(key: String, value: ImpreciseFraction) = putImpreciseFraction(key, value) operator fun CompoundTag.set(key: String, value: Decimal) = putDecimal(key, value)
fun Float.toImpreciseFraction() = ImpreciseFraction(this) fun Float.toDecimal() = Decimal(this)
fun Double.toImpreciseFraction() = ImpreciseFraction(this) fun Double.toDecimal() = Decimal(this)
fun Int.toImpreciseFraction() = ImpreciseFraction(this) fun Int.toDecimal() = Decimal(this)
fun Byte.toImpreciseFraction() = ImpreciseFraction(this) fun Byte.toDecimal() = Decimal(this)
fun Short.toImpreciseFraction() = ImpreciseFraction(this) fun Short.toDecimal() = Decimal(this)
fun Long.toImpreciseFraction() = ImpreciseFraction(this) fun Long.toDecimal() = Decimal(this)
fun ImpreciseFraction.toImpreciseFraction() = this fun Decimal.toDecimal() = this
class ImpreciseFractionConfigValue( class DecimalConfigValue(
parent: ForgeConfigSpec.ConfigValue<String>, parent: ForgeConfigSpec.ConfigValue<String>,
val minimum: ImpreciseFraction? = null, val minimum: Decimal? = null,
val maximum: ImpreciseFraction? = null, val maximum: Decimal? = null,
) : ObservedConfigValue<ImpreciseFraction>(parent) { ) : ObservedConfigValue<Decimal>(parent) {
override fun fromString(value: String): ImpreciseFraction? { override fun fromString(value: String): Decimal? {
try { try {
val parsed = ImpreciseFraction(value) val parsed = Decimal(value)
if (minimum != null && minimum > parsed) { if (minimum != null && minimum > parsed) {
return minimum return minimum
@ -906,7 +904,7 @@ class ImpreciseFractionConfigValue(
} }
} }
override fun toString(value: ImpreciseFraction): Pair<String, ImpreciseFraction> { override fun toString(value: Decimal): Pair<String, Decimal> {
if (minimum != null && minimum > value) { if (minimum != null && minimum > value) {
return minimum.toString() to minimum return minimum.toString() to minimum
} else if (maximum != null && maximum < value) { } else if (maximum != null && maximum < value) {
@ -917,7 +915,7 @@ class ImpreciseFractionConfigValue(
} }
} }
private fun ForgeConfigSpec.Builder.commentRange(minimum: ImpreciseFraction?, maximum: ImpreciseFraction?) { private fun ForgeConfigSpec.Builder.commentRange(minimum: Decimal?, maximum: Decimal?) {
if (minimum != null && maximum != null) { if (minimum != null && maximum != null) {
comment("Range: $minimum ~ $maximum") comment("Range: $minimum ~ $maximum")
} else if (minimum != null) { } else if (minimum != null) {
@ -927,14 +925,14 @@ private fun ForgeConfigSpec.Builder.commentRange(minimum: ImpreciseFraction?, ma
} }
} }
fun ForgeConfigSpec.Builder.defineImpreciseFraction(path: String, defaultValue: ImpreciseFraction, minimum: ImpreciseFraction? = null, maximum: ImpreciseFraction? = null): ImpreciseFractionConfigValue { fun ForgeConfigSpec.Builder.defineDecimal(path: String, defaultValue: Decimal, minimum: Decimal? = null, maximum: Decimal? = null): DecimalConfigValue {
commentRange(minimum, maximum) commentRange(minimum, maximum)
comment("Default: $defaultValue") comment("Default: $defaultValue")
return ImpreciseFractionConfigValue(define(path, defaultValue.toString()), minimum, maximum) return DecimalConfigValue(define(path, defaultValue.toString()), minimum, maximum)
} }
fun ForgeConfigSpec.Builder.defineImpreciseFraction(path: List<String>, defaultValue: ImpreciseFraction, minimum: ImpreciseFraction? = null, maximum: ImpreciseFraction? = null): ImpreciseFractionConfigValue { fun ForgeConfigSpec.Builder.defineDecimal(path: List<String>, defaultValue: Decimal, minimum: Decimal? = null, maximum: Decimal? = null): DecimalConfigValue {
commentRange(minimum, maximum) commentRange(minimum, maximum)
comment("Default: $defaultValue") comment("Default: $defaultValue")
return ImpreciseFractionConfigValue(define(path, defaultValue.toString()), minimum, maximum) return DecimalConfigValue(define(path, defaultValue.toString()), minimum, maximum)
} }

View File

@ -50,13 +50,13 @@ fun Number.dynPlus(other: Number): Number {
is Short -> this + other.toShort() is Short -> this + other.toShort()
is Byte -> this + other.toByte() is Byte -> this + other.toByte()
is ImpreciseFraction -> { is Decimal -> {
when (other) { when (other) {
is Float -> this + other.toFloat() is Float -> this + other.toFloat()
is Double -> this + other.toDouble() is Double -> this + other.toDouble()
is Int, is Byte, is Short -> this + other.toInt() is Int, is Byte, is Short -> this + other.toInt()
is Long -> this + other.toLong() is Long -> this + other.toLong()
is ImpreciseFraction -> this + other is Decimal -> this + other
is Fraction -> this + other.toImpreciseFraction() is Fraction -> this + other.toImpreciseFraction()
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -68,7 +68,7 @@ fun Number.dynPlus(other: Number): Number {
is Double -> this + other.toDouble() is Double -> this + other.toDouble()
is Int, is Byte, is Short -> this + other.toInt() is Int, is Byte, is Short -> this + other.toInt()
is Long -> this + other.toLong() is Long -> this + other.toLong()
is ImpreciseFraction -> this + other.toFraction() is Decimal -> this + other.toFraction()
is Fraction -> this + other is Fraction -> this + other
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -92,13 +92,13 @@ fun Number.dynMinus(other: Number): Number {
is Short -> this - other.toShort() is Short -> this - other.toShort()
is Byte -> this - other.toByte() is Byte -> this - other.toByte()
is ImpreciseFraction -> { is Decimal -> {
when (other) { when (other) {
is Float -> this - other.toFloat() is Float -> this - other.toFloat()
is Double -> this - other.toDouble() is Double -> this - other.toDouble()
is Int, is Byte, is Short -> this - other.toInt() is Int, is Byte, is Short -> this - other.toInt()
is Long -> this - other.toLong() is Long -> this - other.toLong()
is ImpreciseFraction -> this - other is Decimal -> this - other
is Fraction -> this - other.toImpreciseFraction() is Fraction -> this - other.toImpreciseFraction()
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -110,7 +110,7 @@ fun Number.dynMinus(other: Number): Number {
is Double -> this - other.toDouble() is Double -> this - other.toDouble()
is Int, is Byte, is Short -> this - other.toInt() is Int, is Byte, is Short -> this - other.toInt()
is Long -> this - other.toLong() is Long -> this - other.toLong()
is ImpreciseFraction -> this - other.toFraction() is Decimal -> this - other.toFraction()
is Fraction -> this - other is Fraction -> this - other
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -134,13 +134,13 @@ fun Number.dynTimes(other: Number): Number {
is Short -> this * other.toShort() is Short -> this * other.toShort()
is Byte -> this * other.toByte() is Byte -> this * other.toByte()
is ImpreciseFraction -> { is Decimal -> {
when (other) { when (other) {
is Float -> this * other.toFloat() is Float -> this * other.toFloat()
is Double -> this * other.toDouble() is Double -> this * other.toDouble()
is Int, is Byte, is Short -> this * other.toInt() is Int, is Byte, is Short -> this * other.toInt()
is Long -> this * other.toLong() is Long -> this * other.toLong()
is ImpreciseFraction -> this * other is Decimal -> this * other
is Fraction -> this * other.toImpreciseFraction() is Fraction -> this * other.toImpreciseFraction()
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -152,7 +152,7 @@ fun Number.dynTimes(other: Number): Number {
is Double -> this * other.toDouble() is Double -> this * other.toDouble()
is Int, is Byte, is Short -> this * other.toInt() is Int, is Byte, is Short -> this * other.toInt()
is Long -> this * other.toLong() is Long -> this * other.toLong()
is ImpreciseFraction -> this * other.toFraction() is Decimal -> this * other.toFraction()
is Fraction -> this * other is Fraction -> this * other
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -176,13 +176,13 @@ fun Number.dynDiv(other: Number): Number {
is Short -> this / other.toShort() is Short -> this / other.toShort()
is Byte -> this / other.toByte() is Byte -> this / other.toByte()
is ImpreciseFraction -> { is Decimal -> {
when (other) { when (other) {
is Float -> this / other.toFloat() is Float -> this / other.toFloat()
is Double -> this / other.toDouble() is Double -> this / other.toDouble()
is Int, is Byte, is Short -> this / other.toInt() is Int, is Byte, is Short -> this / other.toInt()
is Long -> this / other.toLong() is Long -> this / other.toLong()
is ImpreciseFraction -> this / other is Decimal -> this / other
is Fraction -> this / other.toImpreciseFraction() is Fraction -> this / other.toImpreciseFraction()
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -194,7 +194,7 @@ fun Number.dynDiv(other: Number): Number {
is Double -> this / other.toDouble() is Double -> this / other.toDouble()
is Int, is Byte, is Short -> this / other.toInt() is Int, is Byte, is Short -> this / other.toInt()
is Long -> this / other.toLong() is Long -> this / other.toLong()
is ImpreciseFraction -> this / other.toFraction() is Decimal -> this / other.toFraction()
is Fraction -> this / other is Fraction -> this / other
else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)") else -> throw IllegalStateException("I don't know what to do with ${other::class.qualifiedName} (right hand operand)")
} }
@ -204,18 +204,18 @@ fun Number.dynDiv(other: Number): Number {
} }
} }
val Number.isFractional get() = this is Float || this is Double || this is ImpreciseFraction || this is Fraction val Number.isFractional get() = this is Float || this is Double || this is Decimal || this is Fraction
val Number.isWhole get() = !isFractional val Number.isWhole get() = !isFractional
fun Number.toImpreciseFraction(): ImpreciseFraction { fun Number.toDecimal(): Decimal {
return when (this) { return when (this) {
is ImpreciseFraction -> this is Decimal -> this
is Float -> ImpreciseFraction(this) is Float -> Decimal(this)
is Double -> ImpreciseFraction(this) is Double -> Decimal(this)
is Int -> ImpreciseFraction(this) is Int -> Decimal(this)
is Byte -> ImpreciseFraction(this) is Byte -> Decimal(this)
is Short -> ImpreciseFraction(this) is Short -> Decimal(this)
is Long -> ImpreciseFraction(this) is Long -> Decimal(this)
is Fraction -> this.toImpreciseFraction() is Fraction -> this.toImpreciseFraction()
else -> throw ClassCastException("Can not turn $this into ImpreciseFraction") else -> throw ClassCastException("Can not turn $this into ImpreciseFraction")
} }

View File

@ -88,7 +88,7 @@ enum class SiPrefix(
val decimal = BigDecimal(string) val decimal = BigDecimal(string)
val fraction = Fraction(decimal) val fraction = Fraction(decimal)
val impreciseFraction = ImpreciseFraction(string) val impreciseFraction = Decimal(string)
val integer = if (!fractional) BigInteger(string) else null val integer = if (!fractional) BigInteger(string) else null
val long = if (!fractional) string.toLongOrNull() else null val long = if (!fractional) string.toLongOrNull() else null
@ -280,7 +280,7 @@ fun BigInteger.formatSiComponent(suffix: Any = "", decimalPlaces: Int = 2): Comp
return TranslatableComponent(prefix.formatLocaleKey, String(buffer), suffix) return TranslatableComponent(prefix.formatLocaleKey, String(buffer), suffix)
} }
fun ImpreciseFraction.determineSiPrefix(): SiPrefix? { fun Decimal.determineSiPrefix(): SiPrefix? {
if (isZero) { if (isZero) {
return null return null
} }
@ -293,7 +293,7 @@ fun ImpreciseFraction.determineSiPrefix(): SiPrefix? {
var prev: SiPrefix? = null var prev: SiPrefix? = null
if (num >= ImpreciseFraction.ONE) { if (num >= Decimal.ONE) {
for (value in SiPrefix.MULTIPLIES) { for (value in SiPrefix.MULTIPLIES) {
if (value.impreciseFraction <= num) { if (value.impreciseFraction <= num) {
prev = value prev = value
@ -366,7 +366,7 @@ fun Double.determineSiPrefix(): SiPrefix? {
return prev return prev
} }
fun ImpreciseFraction.formatSi(decimalPlaces: Int = 2): String { fun Decimal.formatSi(decimalPlaces: Int = 2): String {
require(decimalPlaces >= 0) { "Invalid amount of decimal places required: $decimalPlaces" } require(decimalPlaces >= 0) { "Invalid amount of decimal places required: $decimalPlaces" }
val prefix = determineSiPrefix() ?: return toString(decimalPlaces) val prefix = determineSiPrefix() ?: return toString(decimalPlaces)
return (this / prefix.impreciseFraction).toString(decimalPlaces) + prefix.symbol return (this / prefix.impreciseFraction).toString(decimalPlaces) + prefix.symbol
@ -384,7 +384,7 @@ fun Double.formatSiComponent(suffix: Any = "", decimalPlaces: Int = 2): Componen
return TranslatableComponent(prefix.formatLocaleKey, "%.${decimalPlaces}f".format(this / prefix.double), suffix) return TranslatableComponent(prefix.formatLocaleKey, "%.${decimalPlaces}f".format(this / prefix.double), suffix)
} }
fun ImpreciseFraction.formatSiComponent(suffix: Any = "", decimalPlaces: Int = 2): Component { fun Decimal.formatSiComponent(suffix: Any = "", decimalPlaces: Int = 2): Component {
require(decimalPlaces >= 0) { "Invalid amount of decimal places required: $decimalPlaces" } require(decimalPlaces >= 0) { "Invalid amount of decimal places required: $decimalPlaces" }
val prefix = determineSiPrefix() ?: return if (suffix == "") TextComponent(toString(decimalPlaces)) else if (suffix is Component) TextComponent(toString(decimalPlaces) + " " + suffix.string) else TextComponent(toString(decimalPlaces) + " " + suffix) val prefix = determineSiPrefix() ?: return if (suffix == "") TextComponent(toString(decimalPlaces)) else if (suffix is Component) TextComponent(toString(decimalPlaces) + " " + suffix.string) else TextComponent(toString(decimalPlaces) + " " + suffix)
return TranslatableComponent(prefix.formatLocaleKey, (this / prefix.impreciseFraction).toString(decimalPlaces), suffix) return TranslatableComponent(prefix.formatLocaleKey, (this / prefix.impreciseFraction).toString(decimalPlaces), suffix)
@ -395,16 +395,16 @@ val MATTER_NAME = TranslatableComponent("otm.gui.matter.name")
fun Int.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces) fun Int.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces)
fun ImpreciseFraction.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces) fun Decimal.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces)
fun ImpreciseFraction.formatMatter(decimalPlaces: Int = 2) = formatSiComponent(MATTER_NAME, decimalPlaces) fun Decimal.formatMatter(decimalPlaces: Int = 2) = formatSiComponent(MATTER_NAME, decimalPlaces)
fun ImpreciseFraction.formatMatterFull(decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.matter.format", formatSiComponent(MATTER_NAME, decimalPlaces)) fun Decimal.formatMatterFull(decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.matter.format", formatSiComponent(MATTER_NAME, decimalPlaces))
fun BigInteger.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces) fun BigInteger.formatPower(decimalPlaces: Int = 2) = formatSiComponent(POWER_NAME, decimalPlaces)
fun BigInteger.formatMatter(decimalPlaces: Int = 2) = formatSiComponent(MATTER_NAME, decimalPlaces) fun BigInteger.formatMatter(decimalPlaces: Int = 2) = formatSiComponent(MATTER_NAME, decimalPlaces)
fun BigInteger.formatMatterFull(decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.matter.format", formatSiComponent(MATTER_NAME, decimalPlaces)) fun BigInteger.formatMatterFull(decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.matter.format", formatSiComponent(MATTER_NAME, decimalPlaces))
fun formatPowerLevel(a: ImpreciseFraction, b: ImpreciseFraction, decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.level", a.formatPower(decimalPlaces), b.formatPower(decimalPlaces)) fun formatPowerLevel(a: Decimal, b: Decimal, decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.level", a.formatPower(decimalPlaces), b.formatPower(decimalPlaces))
fun formatMatterLevel(a: ImpreciseFraction, b: ImpreciseFraction, decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.level", a.formatMatter(decimalPlaces), b.formatMatter(decimalPlaces)) fun formatMatterLevel(a: Decimal, b: Decimal, decimalPlaces: Int = 2) = TranslatableComponent("otm.gui.level", a.formatMatter(decimalPlaces), b.formatMatter(decimalPlaces))
private fun padded(num: Int): String { private fun padded(num: Int): String {
if (num in 0 .. 9) { if (num in 0 .. 9) {

View File

@ -602,25 +602,25 @@ class Fraction @JvmOverloads constructor(
return (value / divisor).toDouble() + ((value % divisor).toDouble() / divisor.toDouble()) return (value / divisor).toDouble() + ((value % divisor).toDouble() / divisor.toDouble())
} }
fun toImpreciseFraction(): ImpreciseFraction { fun toImpreciseFraction(): Decimal {
if (isNaN()) if (isNaN())
return ImpreciseFraction.NaN return Decimal.NaN
val div = value.divideAndRemainder(divisor) val div = value.divideAndRemainder(divisor)
val a = divisor.toDouble() val a = divisor.toDouble()
val b = div[1].toDouble() val b = div[1].toDouble()
if (b == 0.0 || !a.isFinite() || !b.isFinite()) { if (b == 0.0 || !a.isFinite() || !b.isFinite()) {
return ImpreciseFraction(div[0]) return Decimal(div[0])
} }
val div2 = a / b val div2 = a / b
if (div2.isFinite() && !div2.isNaN()) { if (div2.isFinite() && !div2.isNaN()) {
return ImpreciseFraction(div[0], div2) return Decimal(div[0], div2)
} }
return ImpreciseFraction(div[0]) return Decimal(div[0])
} }
fun toByteArray(): ByteArray { fun toByteArray(): ByteArray {

View File

@ -6,7 +6,7 @@ import net.minecraft.world.item.Item
import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntity
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.matter.* import ru.dbotthepony.mc.otm.capability.matter.*
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.graph.Abstract6Graph import ru.dbotthepony.mc.otm.graph.Abstract6Graph
import ru.dbotthepony.mc.otm.graph.Graph6Node import ru.dbotthepony.mc.otm.graph.Graph6Node
import java.util.* import java.util.*
@ -73,8 +73,8 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
} }
} }
fun getMatterStorageLevel(): ImpreciseFraction { fun getMatterStorageLevel(): Decimal {
var level = ImpreciseFraction.ZERO var level = Decimal.ZERO
for (node in nodes) { for (node in nodes) {
val matter = node.value.getMatterHandler() val matter = node.value.getMatterHandler()
@ -87,8 +87,8 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
return level return level
} }
fun getMatterStorageMaxLevel(): ImpreciseFraction { fun getMatterStorageMaxLevel(): Decimal {
var level = ImpreciseFraction.ZERO var level = Decimal.ZERO
for (node in nodes) { for (node in nodes) {
val matter = node.value.getMatterHandler() val matter = node.value.getMatterHandler()
@ -101,13 +101,13 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
return level return level
} }
fun extractMatter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun extractMatter(howMuch: Decimal, simulate: Boolean): Decimal {
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("name_shadowing") @Suppress("name_shadowing")
var howMuch = howMuch var howMuch = howMuch
var extracted = ImpreciseFraction.ZERO var extracted = Decimal.ZERO
for (node in nodes) { for (node in nodes) {
val matter = node.value.getMatterHandler() val matter = node.value.getMatterHandler()
@ -117,7 +117,7 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
howMuch -= value howMuch -= value
extracted += value extracted += value
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return extracted return extracted
} }
} }
@ -125,13 +125,13 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
return extracted return extracted
} }
fun receiveMatter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun receiveMatter(howMuch: Decimal, simulate: Boolean): Decimal {
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("name_shadowing") @Suppress("name_shadowing")
var howMuch = howMuch var howMuch = howMuch
var received = ImpreciseFraction.ZERO var received = Decimal.ZERO
for (node in nodes) { for (node in nodes) {
val matter = node.value.getMatterHandler() val matter = node.value.getMatterHandler()
@ -141,7 +141,7 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
howMuch -= value howMuch -= value
received += value received += value
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return received return received
} }
} }
@ -149,13 +149,13 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
return received return received
} }
fun receiveMatterForce(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun receiveMatterForce(howMuch: Decimal, simulate: Boolean): Decimal {
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("name_shadowing") @Suppress("name_shadowing")
var howMuch = howMuch var howMuch = howMuch
var received = ImpreciseFraction.ZERO var received = Decimal.ZERO
for (node in nodes) { for (node in nodes) {
val matter = node.value.getMatterHandler() val matter = node.value.getMatterHandler()
@ -165,7 +165,7 @@ class MatterNetworkGraph : Abstract6Graph<IMatterGraphNode>(), IMatterGraphListe
howMuch -= value howMuch -= value
received += value received += value
if (howMuch <= ImpreciseFraction.ZERO) if (howMuch <= Decimal.ZERO)
return received return received
} }
} }

View File

@ -18,7 +18,6 @@ import net.minecraftforge.common.capabilities.ICapabilityProvider
import ru.dbotthepony.mc.otm.BatteryBalanceValues import ru.dbotthepony.mc.otm.BatteryBalanceValues
import ru.dbotthepony.mc.otm.OverdriveThatMatters import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.ServerConfig import ru.dbotthepony.mc.otm.ServerConfig
import ru.dbotthepony.mc.otm.VerboseBalanceValues
import ru.dbotthepony.mc.otm.capability.* import ru.dbotthepony.mc.otm.capability.*
import ru.dbotthepony.mc.otm.client.minecraft import ru.dbotthepony.mc.otm.client.minecraft
import ru.dbotthepony.mc.otm.core.* import ru.dbotthepony.mc.otm.core.*
@ -28,50 +27,50 @@ import kotlin.math.roundToInt
open class BatteryItem : Item { open class BatteryItem : Item {
private inner class Power(stack: ItemStack) : EnergyCapacitorItem(stack, this@BatteryItem.capacity, this@BatteryItem.receive, this@BatteryItem.extract, initialBatteryLevel = this@BatteryItem.initialBatteryLevel) { private inner class Power(stack: ItemStack) : EnergyCapacitorItem(stack, this@BatteryItem.capacity, this@BatteryItem.receive, this@BatteryItem.extract, initialBatteryLevel = this@BatteryItem.initialBatteryLevel) {
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (isCreative) return howMuch if (isCreative) return howMuch
return super.extractEnergyInner(howMuch, simulate) return super.extractEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (isCreative) return howMuch if (isCreative) return howMuch
return super.receiveEnergyInner(howMuch, simulate) return super.receiveEnergyInner(howMuch, simulate)
} }
override val missingPower: ImpreciseFraction get() { override val missingPower: Decimal get() {
return if (isCreative) ImpreciseFraction.LONG_MAX_VALUE else super.missingPower return if (isCreative) Decimal.LONG_MAX_VALUE else super.missingPower
} }
fun maxPower() { fun maxPower() {
batteryLevel = maxBatteryLevel batteryLevel = maxBatteryLevel
} }
override var batteryLevel: ImpreciseFraction override var batteryLevel: Decimal
get() { return if (isCreative) ImpreciseFraction.LONG_MAX_VALUE else super.batteryLevel } get() { return if (isCreative) Decimal.LONG_MAX_VALUE else super.batteryLevel }
set(value) { super.batteryLevel = value } set(value) { super.batteryLevel = value }
} }
private val isCreative: Boolean private val isCreative: Boolean
val _capacity: () -> ImpreciseFraction val _capacity: () -> Decimal
val _receive: () -> ImpreciseFraction val _receive: () -> Decimal
val _extract: () -> ImpreciseFraction val _extract: () -> Decimal
val _initialBatteryLevel: () -> ImpreciseFraction val _initialBatteryLevel: () -> Decimal
val capacity: ImpreciseFraction val capacity: Decimal
get() = _capacity.invoke() get() = _capacity.invoke()
val receive: ImpreciseFraction val receive: Decimal
get() = _receive.invoke() get() = _receive.invoke()
val extract: ImpreciseFraction val extract: Decimal
get() = _extract.invoke() get() = _extract.invoke()
val initialBatteryLevel: ImpreciseFraction val initialBatteryLevel: Decimal
get() = _initialBatteryLevel.invoke() get() = _initialBatteryLevel.invoke()
constructor( constructor(
storage: ImpreciseFraction, storage: Decimal,
receive: ImpreciseFraction, receive: Decimal,
extract: ImpreciseFraction = receive, extract: Decimal = receive,
initialBatteryLevel: ImpreciseFraction = ImpreciseFraction.ZERO initialBatteryLevel: Decimal = Decimal.ZERO
) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { ) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = false isCreative = false
this._capacity = { storage } this._capacity = { storage }
@ -81,10 +80,10 @@ open class BatteryItem : Item {
} }
constructor( constructor(
storage: () -> ImpreciseFraction, storage: () -> Decimal,
receive: () -> ImpreciseFraction, receive: () -> Decimal,
extract: () -> ImpreciseFraction = receive, extract: () -> Decimal = receive,
initialBatteryLevel: () -> ImpreciseFraction = { ImpreciseFraction.ZERO } initialBatteryLevel: () -> Decimal = { Decimal.ZERO }
) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { ) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = false isCreative = false
this._capacity = storage this._capacity = storage
@ -103,10 +102,10 @@ open class BatteryItem : Item {
constructor() : super(Properties().stacksTo(1).rarity(Rarity.EPIC).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { constructor() : super(Properties().stacksTo(1).rarity(Rarity.EPIC).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = true isCreative = true
_capacity = { ImpreciseFraction.LONG_MAX_VALUE } _capacity = { Decimal.LONG_MAX_VALUE }
_receive = { ImpreciseFraction.LONG_MAX_VALUE } _receive = { Decimal.LONG_MAX_VALUE }
_extract = { ImpreciseFraction.LONG_MAX_VALUE } _extract = { Decimal.LONG_MAX_VALUE }
_initialBatteryLevel = { ImpreciseFraction.LONG_MAX_VALUE } _initialBatteryLevel = { Decimal.LONG_MAX_VALUE }
} }
override fun isBarVisible(p_150899_: ItemStack): Boolean { override fun isBarVisible(p_150899_: ItemStack): Boolean {

View File

@ -35,10 +35,10 @@ import ru.dbotthepony.mc.otm.capability.getBarColor
import ru.dbotthepony.mc.otm.capability.getBarWidth import ru.dbotthepony.mc.otm.capability.getBarWidth
import ru.dbotthepony.mc.otm.capability.matteryEnergy import ru.dbotthepony.mc.otm.capability.matteryEnergy
import ru.dbotthepony.mc.otm.capability.matteryPlayer import ru.dbotthepony.mc.otm.capability.matteryPlayer
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.ImpreciseFractionConfigValue import ru.dbotthepony.mc.otm.core.DecimalConfigValue
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.defineImpreciseFraction import ru.dbotthepony.mc.otm.core.defineDecimal
import ru.dbotthepony.mc.otm.core.ifPresentK import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.core.orNull import ru.dbotthepony.mc.otm.core.orNull
import ru.dbotthepony.mc.otm.registry.EMPDamageSource import ru.dbotthepony.mc.otm.registry.EMPDamageSource
@ -220,20 +220,20 @@ class EnergySwordItem : Item(Properties().stacksTo(1).rarity(Rarity.RARE).tab(Ov
val COBWEB_POWER_COST get() = _COBWEB_POWER_COST.get() val COBWEB_POWER_COST get() = _COBWEB_POWER_COST.get()
val PLANT_POWER_COST get() = _PLANT_POWER_COST.get() val PLANT_POWER_COST get() = _PLANT_POWER_COST.get()
private var _MAX_ENERGY: ImpreciseFractionConfigValue by WriteOnce() private var _MAX_ENERGY: DecimalConfigValue by WriteOnce()
private var _ENERGY_ZAP: ImpreciseFractionConfigValue by WriteOnce() private var _ENERGY_ZAP: DecimalConfigValue by WriteOnce()
private var _ENERGY_PER_SWING: ImpreciseFractionConfigValue by WriteOnce() private var _ENERGY_PER_SWING: DecimalConfigValue by WriteOnce()
private var _COBWEB_POWER_COST: ImpreciseFractionConfigValue by WriteOnce() private var _COBWEB_POWER_COST: DecimalConfigValue by WriteOnce()
private var _PLANT_POWER_COST: ImpreciseFractionConfigValue by WriteOnce() private var _PLANT_POWER_COST: DecimalConfigValue by WriteOnce()
fun registerConfig(builder: ForgeConfigSpec.Builder) { fun registerConfig(builder: ForgeConfigSpec.Builder) {
builder.comment("Energy sword values").push("energy_sword") builder.comment("Energy sword values").push("energy_sword")
_MAX_ENERGY = builder.defineImpreciseFraction("MAX_ENERGY", ImpreciseFraction(500_000), ImpreciseFraction.ZERO) _MAX_ENERGY = builder.defineDecimal("MAX_ENERGY", Decimal(500_000), Decimal.ZERO)
_ENERGY_ZAP = builder.defineImpreciseFraction("ENERGY_ZAP", ImpreciseFraction(4_000), ImpreciseFraction.ZERO) _ENERGY_ZAP = builder.defineDecimal("ENERGY_ZAP", Decimal(4_000), Decimal.ZERO)
_ENERGY_PER_SWING = builder.defineImpreciseFraction("ENERGY_PER_SWING", ImpreciseFraction(2_000), ImpreciseFraction.ZERO) _ENERGY_PER_SWING = builder.defineDecimal("ENERGY_PER_SWING", Decimal(2_000), Decimal.ZERO)
_COBWEB_POWER_COST = builder.defineImpreciseFraction("COBWEB_POWER_COST", ImpreciseFraction(2_500), ImpreciseFraction.ZERO) _COBWEB_POWER_COST = builder.defineDecimal("COBWEB_POWER_COST", Decimal(2_500), Decimal.ZERO)
_PLANT_POWER_COST = builder.defineImpreciseFraction("PLANT_POWER_COST", ImpreciseFraction(500), ImpreciseFraction.ZERO) _PLANT_POWER_COST = builder.defineDecimal("PLANT_POWER_COST", Decimal(500), Decimal.ZERO)
builder.pop() builder.pop()
} }

View File

@ -19,7 +19,7 @@ import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.capability.MatteryCapability import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.matter.* import ru.dbotthepony.mc.otm.capability.matter.*
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.formatMatter import ru.dbotthepony.mc.otm.core.formatMatter
import ru.dbotthepony.mc.otm.core.ifPresentK import ru.dbotthepony.mc.otm.core.ifPresentK
import ru.dbotthepony.mc.otm.core.tagNotNull import ru.dbotthepony.mc.otm.core.tagNotNull
@ -35,30 +35,30 @@ class MatterCapacitorItem : Item {
return if (cap === MatteryCapability.MATTER) resolver.cast() else LazyOptional.empty() return if (cap === MatteryCapability.MATTER) resolver.cast() else LazyOptional.empty()
} }
override var storedMatter: ImpreciseFraction override var storedMatter: Decimal
get() { get() {
val tag = stack.orCreateTag val tag = stack.orCreateTag
return if (tag.contains("matter")) { return if (tag.contains("matter")) {
ImpreciseFraction.deserializeNBT(tag["matter"]) Decimal.deserializeNBT(tag["matter"])
} else ImpreciseFraction.ZERO } else Decimal.ZERO
} }
set(value) { set(value) {
stack.tagNotNull.put("matter", value.serializeNBT()) stack.tagNotNull.put("matter", value.serializeNBT())
} }
override val maxStoredMatter: ImpreciseFraction get() { override val maxStoredMatter: Decimal get() {
return capacity return capacity
} }
override val missingMatter: ImpreciseFraction get() { override val missingMatter: Decimal get() {
return if (isCreative) ImpreciseFraction.LONG_MAX_VALUE else super.missingMatter return if (isCreative) Decimal.LONG_MAX_VALUE else super.missingMatter
} }
override fun receiveMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveMatterInner(howMuch, simulate) return receiveMatterInner(howMuch, simulate)
} }
override fun receiveMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (isCreative) return howMuch if (isCreative) return howMuch
val new = storedMatter.plus(howMuch.coerceAtMost(maxInput)).coerceAtMost(capacity) val new = storedMatter.plus(howMuch.coerceAtMost(maxInput)).coerceAtMost(capacity)
val diff = new.minus(storedMatter) val diff = new.minus(storedMatter)
@ -70,11 +70,11 @@ class MatterCapacitorItem : Item {
return diff return diff
} }
override fun extractMatterOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return extractMatterInner(howMuch, simulate) return extractMatterInner(howMuch, simulate)
} }
override fun extractMatterInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractMatterInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (isCreative) return howMuch if (isCreative) return howMuch
val new = storedMatter.minus(howMuch.coerceAtMost(maxOutput)).moreThanZero() val new = storedMatter.minus(howMuch.coerceAtMost(maxOutput)).moreThanZero()
val diff = storedMatter.minus(new) val diff = storedMatter.minus(new)
@ -89,24 +89,24 @@ class MatterCapacitorItem : Item {
override val direction = MatterDirection.BIDIRECTIONAL override val direction = MatterDirection.BIDIRECTIONAL
} }
private val _capacity: () -> ImpreciseFraction private val _capacity: () -> Decimal
val capacity get() = _capacity.invoke() val capacity get() = _capacity.invoke()
private val isCreative: Boolean private val isCreative: Boolean
constructor(storage: ImpreciseFraction) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { constructor(storage: Decimal) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = false isCreative = false
_capacity = { storage } _capacity = { storage }
} }
constructor(storage: () -> ImpreciseFraction) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { constructor(storage: () -> Decimal) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = false isCreative = false
_capacity = storage _capacity = storage
} }
constructor() : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB).rarity(Rarity.EPIC)) { constructor() : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB).rarity(Rarity.EPIC)) {
isCreative = true isCreative = true
_capacity = { ImpreciseFraction.LONG_MAX_VALUE } _capacity = { Decimal.LONG_MAX_VALUE }
} }
override fun fillItemCategory(p_41391_: CreativeModeTab, p_41392_: NonNullList<ItemStack>) { override fun fillItemCategory(p_41391_: CreativeModeTab, p_41392_: NonNullList<ItemStack>) {
@ -171,8 +171,8 @@ class MatterCapacitorItem : Item {
} }
companion object { companion object {
private val maxInput = ImpreciseFraction.LONG_MAX_VALUE private val maxInput = Decimal.LONG_MAX_VALUE
private val maxOutput = ImpreciseFraction.LONG_MAX_VALUE private val maxOutput = Decimal.LONG_MAX_VALUE
private val INFINITE_STORAGE: Component = private val INFINITE_STORAGE: Component =
TranslatableComponent("otm.item.matter.infinite").withStyle(ChatFormatting.GRAY) TranslatableComponent("otm.item.matter.infinite").withStyle(ChatFormatting.GRAY)

View File

@ -9,24 +9,24 @@ import net.minecraft.world.level.Level
import ru.dbotthepony.mc.otm.OverdriveThatMatters import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.ServerConfig import ru.dbotthepony.mc.otm.ServerConfig
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.matter.IMatterItem import ru.dbotthepony.mc.otm.matter.IMatterItem
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.matter.IMatterValue import ru.dbotthepony.mc.otm.matter.IMatterValue
import ru.dbotthepony.mc.otm.matter.MatterValue import ru.dbotthepony.mc.otm.matter.MatterValue
class MatterDustItem : Item(Properties().tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB).stacksTo(64)), IMatterItem { class MatterDustItem : Item(Properties().tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB).stacksTo(64)), IMatterItem {
private fun matter(stack: ItemStack): ImpreciseFraction { private fun matter(stack: ItemStack): Decimal {
return stack.tag?.get("matter")?.let { return@let ImpreciseFraction.deserializeNBT(it) } ?: return ImpreciseFraction.ZERO return stack.tag?.get("matter")?.let { return@let Decimal.deserializeNBT(it) } ?: return Decimal.ZERO
} }
private fun matter(stack: ItemStack, matter: ImpreciseFraction) { private fun matter(stack: ItemStack, matter: Decimal) {
stack.orCreateTag["matter"] = matter.serializeNBT() stack.orCreateTag["matter"] = matter.serializeNBT()
} }
override fun getMatterValue(stack: ItemStack): IMatterValue? { override fun getMatterValue(stack: ItemStack): IMatterValue? {
val value = stack.tag?.get("matter") ?: return null val value = stack.tag?.get("matter") ?: return null
return MatterValue(ImpreciseFraction.deserializeNBT(value), 1.0) return MatterValue(Decimal.deserializeNBT(value), 1.0)
} }
override fun canDecompose(stack: ItemStack) = false override fun canDecompose(stack: ItemStack) = false
@ -51,14 +51,14 @@ class MatterDustItem : Item(Properties().tab(OverdriveThatMatters.INSTANCE.CREAT
} }
} }
fun addMatterValue(stack: ItemStack, matter: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { fun addMatterValue(stack: ItemStack, matter: Decimal, simulate: Boolean): Decimal {
if (stack.count != 1) if (stack.count != 1)
return ImpreciseFraction.ZERO return Decimal.ZERO
val matterThis = matter(stack) val matterThis = matter(stack)
if (matterThis >= ServerConfig.MATTER_DUST_CAPACITY) if (matterThis >= ServerConfig.MATTER_DUST_CAPACITY)
return ImpreciseFraction.ZERO return Decimal.ZERO
val newMatter = (matterThis + matter).coerceAtMost(ServerConfig.MATTER_DUST_CAPACITY) val newMatter = (matterThis + matter).coerceAtMost(ServerConfig.MATTER_DUST_CAPACITY)
val diff = newMatter - matterThis val diff = newMatter - matterThis

View File

@ -9,7 +9,6 @@ import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.Tag import net.minecraft.nbt.Tag
import net.minecraft.network.FriendlyByteBuf import net.minecraft.network.FriendlyByteBuf
import net.minecraft.network.chat.Component import net.minecraft.network.chat.Component
import net.minecraft.util.Mth
import net.minecraft.world.item.* import net.minecraft.world.item.*
import net.minecraft.world.level.Level import net.minecraft.world.level.Level
import net.minecraftforge.client.event.ClientPlayerNetworkEvent import net.minecraftforge.client.event.ClientPlayerNetworkEvent
@ -25,13 +24,10 @@ import net.minecraftforge.registries.ForgeRegistry
import ru.dbotthepony.mc.otm.* import ru.dbotthepony.mc.otm.*
import ru.dbotthepony.mc.otm.capability.* import ru.dbotthepony.mc.otm.capability.*
import ru.dbotthepony.mc.otm.compat.mekanism.Mattery2MekanismEnergyWrapper import ru.dbotthepony.mc.otm.compat.mekanism.Mattery2MekanismEnergyWrapper
import ru.dbotthepony.mc.otm.core.itemStackIterator
import ru.dbotthepony.mc.otm.core.nonEmpty
import ru.dbotthepony.mc.otm.core.* import ru.dbotthepony.mc.otm.core.*
import ru.dbotthepony.mc.otm.network.GenericNetworkChannel import ru.dbotthepony.mc.otm.network.GenericNetworkChannel
import ru.dbotthepony.mc.otm.network.MatteryPacket import ru.dbotthepony.mc.otm.network.MatteryPacket
import ru.dbotthepony.mc.otm.network.packetHandled import ru.dbotthepony.mc.otm.network.packetHandled
import ru.dbotthepony.mc.otm.registry.MItems
import ru.dbotthepony.mc.otm.saveddata.SavedCountingMap import ru.dbotthepony.mc.otm.saveddata.SavedCountingMap
import java.util.function.Supplier import java.util.function.Supplier
@ -39,17 +35,17 @@ class QuantumBatteryItem : Item {
class Data( class Data(
val parent: SavedCountingMap<Data>?, val parent: SavedCountingMap<Data>?,
val index: Int = -1, val index: Int = -1,
energy: ImpreciseFraction = ImpreciseFraction.ZERO, energy: Decimal = Decimal.ZERO,
passed: ImpreciseFraction = ImpreciseFraction.ZERO, passed: Decimal = Decimal.ZERO,
received: ImpreciseFraction = ImpreciseFraction.ZERO, received: Decimal = Decimal.ZERO,
) { ) {
constructor( constructor(
energy: ImpreciseFraction = ImpreciseFraction.ZERO, energy: Decimal = Decimal.ZERO,
passed: ImpreciseFraction = ImpreciseFraction.ZERO, passed: Decimal = Decimal.ZERO,
received: ImpreciseFraction = ImpreciseFraction.ZERO, received: Decimal = Decimal.ZERO,
) : this(null, -1, energy, passed, received) ) : this(null, -1, energy, passed, received)
var energy: ImpreciseFraction = energy var energy: Decimal = energy
set(value) { set(value) {
if (field != value) { if (field != value) {
field = value field = value
@ -57,7 +53,7 @@ class QuantumBatteryItem : Item {
} }
} }
var passed: ImpreciseFraction = passed var passed: Decimal = passed
set(value) { set(value) {
if (field != value) { if (field != value) {
field = value field = value
@ -65,7 +61,7 @@ class QuantumBatteryItem : Item {
} }
} }
var received: ImpreciseFraction = received var received: Decimal = received
set(value) { set(value) {
if (field != value) { if (field != value) {
field = value field = value
@ -90,20 +86,20 @@ class QuantumBatteryItem : Item {
return LazyOptional.empty() return LazyOptional.empty()
} }
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return extractEnergyInner(howMuch, simulate) return extractEnergyInner(howMuch, simulate)
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (howMuch.isNegative) { if (howMuch.isNegative) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (data.parent == null && isServerThread()) { if (data.parent == null && isServerThread()) {
determineQuantumLink() determineQuantumLink()
if (data.parent == null) { if (data.parent == null) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
} }
@ -130,20 +126,20 @@ class QuantumBatteryItem : Item {
return diff return diff
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (howMuch.isNegative) { if (howMuch.isNegative) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
if (data.parent == null && isServerThread()) { if (data.parent == null && isServerThread()) {
determineQuantumLink() determineQuantumLink()
if (data.parent == null) { if (data.parent == null) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
} }
@ -157,7 +153,7 @@ class QuantumBatteryItem : Item {
} }
if (data.energy >= capacity!!) { if (data.energy >= capacity!!) {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
val newEnergy = (data.energy + howMuch.coerceAtMost(throughput!!)).coerceAtMost(capacity!!) val newEnergy = (data.energy + howMuch.coerceAtMost(throughput!!)).coerceAtMost(capacity!!)
@ -171,7 +167,7 @@ class QuantumBatteryItem : Item {
return diff return diff
} }
override val batteryLevel: ImpreciseFraction override val batteryLevel: Decimal
get() { get() {
if (data.parent == null) { if (data.parent == null) {
determineQuantumLink() determineQuantumLink()
@ -184,7 +180,7 @@ class QuantumBatteryItem : Item {
return data.energy return data.energy
} }
val passed: ImpreciseFraction get() { val passed: Decimal get() {
if (data.parent == null) { if (data.parent == null) {
determineQuantumLink() determineQuantumLink()
} }
@ -196,7 +192,7 @@ class QuantumBatteryItem : Item {
return data.passed return data.passed
} }
val received: ImpreciseFraction get() { val received: Decimal get() {
if (data.parent == null) { if (data.parent == null) {
determineQuantumLink() determineQuantumLink()
} }
@ -208,11 +204,11 @@ class QuantumBatteryItem : Item {
return data.received return data.received
} }
override val maxBatteryLevel: ImpreciseFraction override val maxBatteryLevel: Decimal
get() = capacity ?: (batteryLevel + ImpreciseFraction.LONG_MAX_VALUE) get() = capacity ?: (batteryLevel + Decimal.LONG_MAX_VALUE)
override val missingPower: ImpreciseFraction override val missingPower: Decimal
get() = if (isCreative) ImpreciseFraction.LONG_MAX_VALUE else super.missingPower get() = if (isCreative) Decimal.LONG_MAX_VALUE else super.missingPower
override fun canExtract(): Boolean { override fun canExtract(): Boolean {
return true return true
@ -263,8 +259,8 @@ class QuantumBatteryItem : Item {
val isCreative: Boolean val isCreative: Boolean
private val _capacity: () -> ImpreciseFraction? private val _capacity: () -> Decimal?
private val _throughput: () -> ImpreciseFraction? private val _throughput: () -> Decimal?
val capacity get() = _capacity.invoke() val capacity get() = _capacity.invoke()
val throughput get() = _throughput.invoke() val throughput get() = _throughput.invoke()
@ -284,9 +280,9 @@ class QuantumBatteryItem : Item {
} }
data class ClientData( data class ClientData(
val energy: ImpreciseFraction = ImpreciseFraction.ZERO, val energy: Decimal = Decimal.ZERO,
val passed: ImpreciseFraction = ImpreciseFraction.ZERO, val passed: Decimal = Decimal.ZERO,
val received: ImpreciseFraction = ImpreciseFraction.ZERO, val received: Decimal = Decimal.ZERO,
) )
val clientPowerMap: Int2ObjectAVLTreeMap<ClientData> by lazy { val clientPowerMap: Int2ObjectAVLTreeMap<ClientData> by lazy {
@ -301,7 +297,7 @@ class QuantumBatteryItem : Item {
this.saveDataID = "otm_$saveDataID".intern() this.saveDataID = "otm_$saveDataID".intern()
} }
constructor(saveDataID: String, capacity: ImpreciseFraction, io: ImpreciseFraction) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) { constructor(saveDataID: String, capacity: Decimal, io: Decimal) : super(Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) {
isCreative = false isCreative = false
_capacity = { capacity } _capacity = { capacity }
_throughput = { io } _throughput = { io }
@ -385,9 +381,9 @@ class QuantumBatteryItem : Item {
return ChargePacket( return ChargePacket(
(ForgeRegistries.ITEMS as ForgeRegistry<Item>).getValue(buff.readInt()) as QuantumBatteryItem, (ForgeRegistries.ITEMS as ForgeRegistry<Item>).getValue(buff.readInt()) as QuantumBatteryItem,
buff.readInt(), buff.readInt(),
buff.readImpreciseFraction(), buff.readDecimal(),
buff.readImpreciseFraction(), buff.readDecimal(),
buff.readImpreciseFraction(), buff.readDecimal(),
) )
} }
@ -415,9 +411,9 @@ class QuantumBatteryItem : Item {
private fun loadValue(parent: SavedCountingMap<Data>, tag: Tag, index: Int): Data { private fun loadValue(parent: SavedCountingMap<Data>, tag: Tag, index: Int): Data {
if (tag is ByteArrayTag) { if (tag is ByteArrayTag) {
return Data(parent, index, ImpreciseFraction.deserializeNBT(tag)) return Data(parent, index, Decimal.deserializeNBT(tag))
} else if (tag is CompoundTag) { } else if (tag is CompoundTag) {
return Data(parent, index, ImpreciseFraction.deserializeNBT(tag["energy"]), ImpreciseFraction.deserializeNBT(tag["passed"]), ImpreciseFraction.deserializeNBT(tag["received"])) return Data(parent, index, Decimal.deserializeNBT(tag["energy"]), Decimal.deserializeNBT(tag["passed"]), Decimal.deserializeNBT(tag["received"]))
} else { } else {
return Data(parent, index) return Data(parent, index)
} }
@ -435,16 +431,16 @@ class QuantumBatteryItem : Item {
class ChargePacket( class ChargePacket(
val type: QuantumBatteryItem, val type: QuantumBatteryItem,
val channel: Int, val channel: Int,
val energy: ImpreciseFraction, val energy: Decimal,
val passed: ImpreciseFraction, val passed: Decimal,
val received: ImpreciseFraction, val received: Decimal,
) : MatteryPacket { ) : MatteryPacket {
override fun write(buff: FriendlyByteBuf) { override fun write(buff: FriendlyByteBuf) {
buff.writeInt((ForgeRegistries.ITEMS as ForgeRegistry<Item>).getID(type)) buff.writeInt((ForgeRegistries.ITEMS as ForgeRegistry<Item>).getID(type))
buff.writeInt(channel) buff.writeInt(channel)
buff.writeImpreciseFraction(energy) buff.writeDecimal(energy)
buff.writeImpreciseFraction(passed) buff.writeDecimal(passed)
buff.writeImpreciseFraction(received) buff.writeDecimal(received)
} }
override fun play(context: Supplier<NetworkEvent.Context>) { override fun play(context: Supplier<NetworkEvent.Context>) {

View File

@ -16,12 +16,12 @@ import ru.dbotthepony.mc.otm.capability.*
import ru.dbotthepony.mc.otm.core.* import ru.dbotthepony.mc.otm.core.*
open class SingleUseBatteryItem( open class SingleUseBatteryItem(
private val _capacity: () -> ImpreciseFraction, private val _capacity: () -> Decimal,
private val _throughput: () -> ImpreciseFraction? = { null }, private val _throughput: () -> Decimal? = { null },
properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB) properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)
) : Item(properties) { ) : Item(properties) {
constructor(values: ConciseBalanceValues, properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) : this(values::capacity, values::throughput, properties) constructor(values: ConciseBalanceValues, properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) : this(values::capacity, values::throughput, properties)
constructor(storage: ImpreciseFraction, throughput: ImpreciseFraction? = null, properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) : this({ storage }, { throughput }, properties) constructor(storage: Decimal, throughput: Decimal? = null, properties: Properties = Properties().stacksTo(1).tab(OverdriveThatMatters.INSTANCE.CREATIVE_TAB)) : this({ storage }, { throughput }, properties)
val capacity get() = _capacity.invoke() val capacity get() = _capacity.invoke()
val throughput get() = _throughput.invoke() val throughput get() = _throughput.invoke()
@ -70,8 +70,8 @@ class ZPMItem : SingleUseBatteryItem(ServerConfig.ZPM_BATTERY, Properties().stac
} }
companion object { companion object {
val MAX_STORAGE = ImpreciseFraction(200_000_000_000_000L) val MAX_STORAGE = Decimal(200_000_000_000_000L)
val THROUGHPUT = ImpreciseFraction(200_000_000L) val THROUGHPUT = Decimal(200_000_000L)
private val DESCRIPTION = TranslatableComponent("item.${OverdriveThatMatters.MOD_ID}.zpm_battery.description").withStyle(ChatFormatting.DARK_GRAY) private val DESCRIPTION = TranslatableComponent("item.${OverdriveThatMatters.MOD_ID}.zpm_battery.description").withStyle(ChatFormatting.DARK_GRAY)
} }

View File

@ -1,26 +1,16 @@
package ru.dbotthepony.mc.otm.item.weapon package ru.dbotthepony.mc.otm.item.weapon
import net.minecraft.sounds.SoundSource import net.minecraft.sounds.SoundSource
import net.minecraft.util.Mth
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.player.Player import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import net.minecraft.world.phys.Vec3
import ru.dbotthepony.mc.otm.capability.extractEnergyInnerExact import ru.dbotthepony.mc.otm.capability.extractEnergyInnerExact
import ru.dbotthepony.mc.otm.capability.getBarColor
import ru.dbotthepony.mc.otm.capability.getBarWidth
import ru.dbotthepony.mc.otm.capability.matteryEnergy
import ru.dbotthepony.mc.otm.core.* import ru.dbotthepony.mc.otm.core.*
import ru.dbotthepony.mc.otm.core.Vector import ru.dbotthepony.mc.otm.core.Vector
import ru.dbotthepony.mc.otm.entity.PlasmaProjectile import ru.dbotthepony.mc.otm.entity.PlasmaProjectile
import ru.dbotthepony.mc.otm.core.position import ru.dbotthepony.mc.otm.core.position
import ru.dbotthepony.mc.otm.registry.MSoundEvents import ru.dbotthepony.mc.otm.registry.MSoundEvents
import java.util.*
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class PlasmaRifleItem : PlasmaWeaponItem<PlasmaWeaponDataTable>(PlasmaWeaponDataTable::class, ImpreciseFraction(200_000)) { class PlasmaRifleItem : PlasmaWeaponItem<PlasmaWeaponDataTable>(PlasmaWeaponDataTable::class, Decimal(200_000)) {
override val roundsPerMinute: Int = 200 override val roundsPerMinute: Int = 200
override val scopingTime: Int = 7 override val scopingTime: Int = 7
@ -70,6 +60,6 @@ class PlasmaRifleItem : PlasmaWeaponItem<PlasmaWeaponDataTable>(PlasmaWeaponData
} }
companion object { companion object {
private val ENERGY_PER_SHOT = ImpreciseFraction(3_000) private val ENERGY_PER_SHOT = Decimal(3_000)
} }
} }

View File

@ -21,10 +21,10 @@ import ru.dbotthepony.mc.otm.core.*
import ru.dbotthepony.mc.otm.registry.MSoundEvents import ru.dbotthepony.mc.otm.registry.MSoundEvents
import kotlin.reflect.KClass import kotlin.reflect.KClass
class PlasmaWeaponEnergy(val itemStack: ItemStack, private val innerCapacity: ImpreciseFraction) : class PlasmaWeaponEnergy(val itemStack: ItemStack, private val innerCapacity: Decimal) :
IMatteryEnergyStorage, ICapabilityProvider, INBTSerializable<CompoundTag> { IMatteryEnergyStorage, ICapabilityProvider, INBTSerializable<CompoundTag> {
private val energyResolver = LazyOptional.of { this } private val energyResolver = LazyOptional.of { this }
private var innerBatteryLevel = ImpreciseFraction.ZERO private var innerBatteryLevel = Decimal.ZERO
var battery: ItemStack = ItemStack.EMPTY var battery: ItemStack = ItemStack.EMPTY
@ -44,21 +44,21 @@ class PlasmaWeaponEnergy(val itemStack: ItemStack, private val innerCapacity: Im
} }
override fun deserializeNBT(nbt: CompoundTag) { override fun deserializeNBT(nbt: CompoundTag) {
innerBatteryLevel = ImpreciseFraction.deserializeNBT(nbt["battery_level"]) innerBatteryLevel = Decimal.deserializeNBT(nbt["battery_level"])
battery = ItemStack.of(nbt["battery"] as CompoundTag) battery = ItemStack.of(nbt["battery"] as CompoundTag)
} }
override fun extractEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return ImpreciseFraction.ZERO return Decimal.ZERO
} }
override fun extractEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun extractEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
var totalExtracted = ImpreciseFraction.ZERO var totalExtracted = Decimal.ZERO
if (!battery.isEmpty) { if (!battery.isEmpty) {
battery.getCapability(ForgeCapabilities.ENERGY).ifPresentK { battery.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
@ -83,17 +83,17 @@ class PlasmaWeaponEnergy(val itemStack: ItemStack, private val innerCapacity: Im
return diff + totalExtracted return diff + totalExtracted
} }
override fun receiveEnergyOuter(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyOuter(howMuch: Decimal, simulate: Boolean): Decimal {
return receiveEnergyInner(howMuch, simulate) return receiveEnergyInner(howMuch, simulate)
} }
override fun receiveEnergyInner(howMuch: ImpreciseFraction, simulate: Boolean): ImpreciseFraction { override fun receiveEnergyInner(howMuch: Decimal, simulate: Boolean): Decimal {
if (!howMuch.isPositive) if (!howMuch.isPositive)
return ImpreciseFraction.ZERO return Decimal.ZERO
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var howMuch = howMuch var howMuch = howMuch
var totalReceived = ImpreciseFraction.ZERO var totalReceived = Decimal.ZERO
if (!battery.isEmpty) { if (!battery.isEmpty) {
battery.getCapability(ForgeCapabilities.ENERGY).ifPresentK { battery.getCapability(ForgeCapabilities.ENERGY).ifPresentK {
@ -138,11 +138,11 @@ class PlasmaWeaponEnergy(val itemStack: ItemStack, private val innerCapacity: Im
return true return true
} }
override val batteryLevel: ImpreciseFraction override val batteryLevel: Decimal
get() = (battery.energy?.energyStoredMattery ?: ImpreciseFraction.ZERO) + innerBatteryLevel get() = (battery.energy?.energyStoredMattery ?: Decimal.ZERO) + innerBatteryLevel
override val maxBatteryLevel: ImpreciseFraction override val maxBatteryLevel: Decimal
get() = (battery.energy?.maxEnergyStoredMattery ?: ImpreciseFraction.ZERO) + innerCapacity get() = (battery.energy?.maxEnergyStoredMattery ?: Decimal.ZERO) + innerCapacity
} }
open class PlasmaWeaponDataTable(tag: CompoundTag) : WeaponDataTable(tag) { open class PlasmaWeaponDataTable(tag: CompoundTag) : WeaponDataTable(tag) {
@ -150,7 +150,7 @@ open class PlasmaWeaponDataTable(tag: CompoundTag) : WeaponDataTable(tag) {
var heatCooldown by tag.ints var heatCooldown by tag.ints
} }
abstract class PlasmaWeaponItem<D : PlasmaWeaponDataTable>(tables: KClass<D>, private val energyCapacity: ImpreciseFraction) : AbstractWeaponItem<D>(tables) { abstract class PlasmaWeaponItem<D : PlasmaWeaponDataTable>(tables: KClass<D>, private val energyCapacity: Decimal) : AbstractWeaponItem<D>(tables) {
override fun appendHoverText( override fun appendHoverText(
itemStack: ItemStack, itemStack: ItemStack,
p_41422_: Level?, p_41422_: Level?,

View File

@ -8,7 +8,7 @@ import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.ItemTags import net.minecraft.tags.ItemTags
import net.minecraft.tags.TagKey import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> { sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> {
@ -25,7 +25,7 @@ sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> {
val errorOnFailure: Boolean val errorOnFailure: Boolean
val tag: TagKey<Item>? val tag: TagKey<Item>?
val key: ResourceLocation? val key: ResourceLocation?
val matter: ImpreciseFraction? val matter: Decimal?
val complexity: Double? val complexity: Double?
val priority: Int? val priority: Int?
@ -50,7 +50,7 @@ sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> {
} }
try { try {
matter = json["matter"]?.asString?.let(::ImpreciseFraction) matter = json["matter"]?.asString?.let(::Decimal)
if (matter != null && !matter.isPositive) { if (matter != null && !matter.isPositive) {
throw JsonParseException("Can't have non-positive matter value. To remove an entry from registry please use 'delete' action instead.") throw JsonParseException("Can't have non-positive matter value. To remove an entry from registry please use 'delete' action instead.")
@ -72,7 +72,7 @@ sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> {
constructor( constructor(
tag: TagKey<Item>, tag: TagKey<Item>,
matter: ImpreciseFraction?, matter: Decimal?,
complexity: Double?, complexity: Double?,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false errorOnFailure: Boolean = false
@ -95,7 +95,7 @@ sealed class AbstractRegistryAction : Comparable<AbstractRegistryAction> {
constructor( constructor(
key: ResourceLocation, key: ResourceLocation,
matter: ImpreciseFraction?, matter: Decimal?,
complexity: Double?, complexity: Double?,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false errorOnFailure: Boolean = false

View File

@ -2,7 +2,7 @@ package ru.dbotthepony.mc.otm.matter
import com.google.gson.JsonElement import com.google.gson.JsonElement
import com.google.gson.JsonObject import com.google.gson.JsonObject
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
class BoundMatterFunction<T : Number>(val function: MatterFunction, val value: T) { class BoundMatterFunction<T : Number>(val function: MatterFunction, val value: T) {
@ -24,7 +24,7 @@ class BoundMatterFunction<T : Number>(val function: MatterFunction, val value: T
companion object { companion object {
inline fun <reified T : Number> getValue(value: JsonElement): T { inline fun <reified T : Number> getValue(value: JsonElement): T {
return when (T::class) { return when (T::class) {
ImpreciseFraction::class -> ImpreciseFraction(value.asString) as T Decimal::class -> Decimal(value.asString) as T
Double::class -> value.asDouble as T Double::class -> value.asDouble as T
Int::class -> value.asInt as T Int::class -> value.asInt as T
else -> throw RuntimeException("Unknown number type: ${T::class.qualifiedName}") else -> throw RuntimeException("Unknown number type: ${T::class.qualifiedName}")

View File

@ -10,7 +10,7 @@ import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import net.minecraft.world.level.ItemLike import net.minecraft.world.level.ItemLike
import net.minecraftforge.registries.ForgeRegistries import net.minecraftforge.registries.ForgeRegistries
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.registryName import ru.dbotthepony.mc.otm.core.registryName
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.data.stream import ru.dbotthepony.mc.otm.data.stream
@ -78,11 +78,11 @@ class ComputeAction : AbstractRegistryAction {
} }
class Constant : Source { class Constant : Source {
val matter: ImpreciseFraction val matter: Decimal
val complexity: Double val complexity: Double
constructor( constructor(
matter: ImpreciseFraction, matter: Decimal,
complexity: Double, complexity: Double,
matterFunction: MatterFunction, matterFunction: MatterFunction,
complexityFunction: MatterFunction = matterFunction, complexityFunction: MatterFunction = matterFunction,
@ -93,7 +93,7 @@ class ComputeAction : AbstractRegistryAction {
constructor(json: JsonObject) : super(json) { constructor(json: JsonObject) : super(json) {
try { try {
matter = ImpreciseFraction(json["matter"]?.asString ?: throw JsonSyntaxException("Missing matter value")) matter = Decimal(json["matter"]?.asString ?: throw JsonSyntaxException("Missing matter value"))
} catch(err: NumberFormatException) { } catch(err: NumberFormatException) {
throw JsonSyntaxException("Invalid matter value: ${json["matter"]}") throw JsonSyntaxException("Invalid matter value: ${json["matter"]}")
} }

View File

@ -1,12 +1,12 @@
package ru.dbotthepony.mc.otm.matter package ru.dbotthepony.mc.otm.matter
import net.minecraft.network.FriendlyByteBuf import net.minecraft.network.FriendlyByteBuf
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.readImpreciseFraction import ru.dbotthepony.mc.otm.core.readDecimal
import ru.dbotthepony.mc.otm.core.writeImpreciseFraction import ru.dbotthepony.mc.otm.core.writeDecimal
interface IMatterValue : Comparable<IMatterValue> { interface IMatterValue : Comparable<IMatterValue> {
val matter: ImpreciseFraction val matter: Decimal
val complexity: Double val complexity: Double
val hasMatterValue: Boolean get() = matter.isPositive && complexity > 0.0 val hasMatterValue: Boolean get() = matter.isPositive && complexity > 0.0
@ -38,8 +38,8 @@ interface IMatterValue : Comparable<IMatterValue> {
* ZERO * ZERO
*/ */
companion object : IMatterValue { companion object : IMatterValue {
override val matter: ImpreciseFraction override val matter: Decimal
get() = ImpreciseFraction.ZERO get() = Decimal.ZERO
override val complexity: Double override val complexity: Double
get() = 0.0 get() = 0.0
} }
@ -47,12 +47,12 @@ interface IMatterValue : Comparable<IMatterValue> {
fun FriendlyByteBuf.writeMatterValue(value: IMatterValue) { fun FriendlyByteBuf.writeMatterValue(value: IMatterValue) {
writeImpreciseFraction(value.matter) writeDecimal(value.matter)
writeDouble(value.complexity) writeDouble(value.complexity)
} }
fun FriendlyByteBuf.readMatterValue(): IMatterValue { fun FriendlyByteBuf.readMatterValue(): IMatterValue {
val matter = readImpreciseFraction() val matter = readDecimal()
val complexity = readDouble() val complexity = readDouble()
if (matter.isZero && complexity == 0.0) { if (matter.isZero && complexity == 0.0) {
@ -63,6 +63,6 @@ fun FriendlyByteBuf.readMatterValue(): IMatterValue {
} }
data class MatterValue( data class MatterValue(
override val matter: ImpreciseFraction, override val matter: Decimal,
override val complexity: Double override val complexity: Double
) : IMatterValue ) : IMatterValue

View File

@ -4,7 +4,7 @@ import com.google.gson.JsonObject
import net.minecraft.resources.ResourceLocation import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.probablyParallelStream import ru.dbotthepony.mc.otm.core.probablyParallelStream
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
@ -14,7 +14,7 @@ class InsertAction : AbstractRegistryAction {
constructor( constructor(
key: ResourceLocation, key: ResourceLocation,
matter: ImpreciseFraction?, matter: Decimal?,
complexity: Double?, complexity: Double?,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false, errorOnFailure: Boolean = false,
@ -27,7 +27,7 @@ class InsertAction : AbstractRegistryAction {
constructor( constructor(
tag: TagKey<Item>, tag: TagKey<Item>,
matter: ImpreciseFraction?, matter: Decimal?,
complexity: Double?, complexity: Double?,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false, errorOnFailure: Boolean = false,

View File

@ -1,75 +1,75 @@
package ru.dbotthepony.mc.otm.matter package ru.dbotthepony.mc.otm.matter
import com.google.gson.JsonParseException import com.google.gson.JsonParseException
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.integerDivisionDown import ru.dbotthepony.mc.otm.core.integerDivisionDown
import ru.dbotthepony.mc.otm.core.integerDivisionUp import ru.dbotthepony.mc.otm.core.integerDivisionUp
enum class MatterFunction { enum class MatterFunction {
ADD { ADD {
override fun updateValue(self: Int, other: Int): Int = self + other override fun updateValue(self: Int, other: Int): Int = self + other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self + other override fun updateValue(self: Decimal, other: Decimal): Decimal = self + other
override fun updateValue(self: Double, other: Double): Double = self + other override fun updateValue(self: Double, other: Double): Double = self + other
}, },
SUBTRACT { SUBTRACT {
override fun updateValue(self: Int, other: Int): Int = self - other override fun updateValue(self: Int, other: Int): Int = self - other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self - other override fun updateValue(self: Decimal, other: Decimal): Decimal = self - other
override fun updateValue(self: Double, other: Double): Double = self - other override fun updateValue(self: Double, other: Double): Double = self - other
}, },
MULTIPLY { MULTIPLY {
override fun updateValue(self: Int, other: Int): Int = self * other override fun updateValue(self: Int, other: Int): Int = self * other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self * other override fun updateValue(self: Decimal, other: Decimal): Decimal = self * other
override fun updateValue(self: Double, other: Double): Double = self * other override fun updateValue(self: Double, other: Double): Double = self * other
}, },
DIVIDE { DIVIDE {
override fun updateValue(self: Int, other: Int): Int = self / other override fun updateValue(self: Int, other: Int): Int = self / other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self / other override fun updateValue(self: Decimal, other: Decimal): Decimal = self / other
override fun updateValue(self: Double, other: Double): Double = self / other override fun updateValue(self: Double, other: Double): Double = self / other
}, },
DIVIDE_UP { DIVIDE_UP {
override fun updateValue(self: Int, other: Int): Int = integerDivisionUp(self, other) override fun updateValue(self: Int, other: Int): Int = integerDivisionUp(self, other)
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = throw JsonParseException("Integer division up is available only for integers") override fun updateValue(self: Decimal, other: Decimal): Decimal = throw JsonParseException("Integer division up is available only for integers")
override fun updateValue(self: Double, other: Double): Double = throw JsonParseException("Integer division up is available only for integers") override fun updateValue(self: Double, other: Double): Double = throw JsonParseException("Integer division up is available only for integers")
}, },
DIVIDE_DOWN { DIVIDE_DOWN {
override fun updateValue(self: Int, other: Int): Int = integerDivisionDown(self, other) override fun updateValue(self: Int, other: Int): Int = integerDivisionDown(self, other)
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = throw JsonParseException("Integer division down is available only for integers") override fun updateValue(self: Decimal, other: Decimal): Decimal = throw JsonParseException("Integer division down is available only for integers")
override fun updateValue(self: Double, other: Double): Double = throw JsonParseException("Integer division down is available only for integers") override fun updateValue(self: Double, other: Double): Double = throw JsonParseException("Integer division down is available only for integers")
}, },
MODULO { MODULO {
override fun updateValue(self: Int, other: Int): Int = self % other override fun updateValue(self: Int, other: Int): Int = self % other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self % other override fun updateValue(self: Decimal, other: Decimal): Decimal = self % other
override fun updateValue(self: Double, other: Double): Double = self % other override fun updateValue(self: Double, other: Double): Double = self % other
}, },
AT_LEAST { AT_LEAST {
override fun updateValue(self: Int, other: Int): Int = self.coerceAtLeast(other) override fun updateValue(self: Int, other: Int): Int = self.coerceAtLeast(other)
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self.coerceAtLeast(other) override fun updateValue(self: Decimal, other: Decimal): Decimal = self.coerceAtLeast(other)
override fun updateValue(self: Double, other: Double): Double = self.coerceAtLeast(other) override fun updateValue(self: Double, other: Double): Double = self.coerceAtLeast(other)
}, },
AT_MOST { AT_MOST {
override fun updateValue(self: Int, other: Int): Int = self.coerceAtMost(other) override fun updateValue(self: Int, other: Int): Int = self.coerceAtMost(other)
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self.coerceAtMost(other) override fun updateValue(self: Decimal, other: Decimal): Decimal = self.coerceAtMost(other)
override fun updateValue(self: Double, other: Double): Double = self.coerceAtMost(other) override fun updateValue(self: Double, other: Double): Double = self.coerceAtMost(other)
}, },
REPLACE { REPLACE {
override fun updateValue(self: Int, other: Int): Int = other override fun updateValue(self: Int, other: Int): Int = other
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = other override fun updateValue(self: Decimal, other: Decimal): Decimal = other
override fun updateValue(self: Double, other: Double): Double = other override fun updateValue(self: Double, other: Double): Double = other
}, },
NOOP { NOOP {
override fun updateValue(self: Int, other: Int): Int = self override fun updateValue(self: Int, other: Int): Int = self
override fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction = self override fun updateValue(self: Decimal, other: Decimal): Decimal = self
override fun updateValue(self: Double, other: Double): Double = self override fun updateValue(self: Double, other: Double): Double = self
}, },
; ;
protected abstract fun updateValue(self: Int, other: Int): Int protected abstract fun updateValue(self: Int, other: Int): Int
protected abstract fun updateValue(self: ImpreciseFraction, other: ImpreciseFraction): ImpreciseFraction protected abstract fun updateValue(self: Decimal, other: Decimal): Decimal
protected abstract fun updateValue(self: Double, other: Double): Double protected abstract fun updateValue(self: Double, other: Double): Double
fun <T : Number> updateValue(self: T, other: T): T { fun <T : Number> updateValue(self: T, other: T): T {
return when (self) { return when (self) {
is ImpreciseFraction -> updateValue(self as ImpreciseFraction, other as ImpreciseFraction) as T is Decimal -> updateValue(self as Decimal, other as Decimal) as T
is Double -> updateValue(self as Double, other as Double) as T is Double -> updateValue(self as Double, other as Double) as T
is Int -> updateValue(self as Int, other as Int) as T is Int -> updateValue(self as Int, other as Int) as T
else -> throw RuntimeException("Unknown number type: ${self::class.qualifiedName}") else -> throw RuntimeException("Unknown number type: ${self::class.qualifiedName}")

View File

@ -62,7 +62,7 @@ import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.capability.drive.IMatteryDrive import ru.dbotthepony.mc.otm.capability.drive.IMatteryDrive
import ru.dbotthepony.mc.otm.client.minecraft import ru.dbotthepony.mc.otm.client.minecraft
import ru.dbotthepony.mc.otm.container.stream import ru.dbotthepony.mc.otm.container.stream
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.TextComponent import ru.dbotthepony.mc.otm.core.TextComponent
import ru.dbotthepony.mc.otm.core.TranslatableComponent import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.filterNotNull import ru.dbotthepony.mc.otm.core.filterNotNull
@ -96,7 +96,7 @@ import kotlin.math.pow
import kotlin.math.roundToInt import kotlin.math.roundToInt
internal sealed class MutableEntry( internal sealed class MutableEntry(
var matter: ImpreciseFraction, var matter: Decimal,
var complexity: Double, var complexity: Double,
var priority: Int var priority: Int
) { ) {
@ -105,7 +105,7 @@ internal sealed class MutableEntry(
internal class MutableTagEntry( internal class MutableTagEntry(
val tag: TagKey<Item>, val tag: TagKey<Item>,
matter: ImpreciseFraction, matter: Decimal,
complexity: Double, complexity: Double,
priority: Int priority: Int
) : MutableEntry(matter, complexity, priority) { ) : MutableEntry(matter, complexity, priority) {
@ -116,7 +116,7 @@ internal class MutableTagEntry(
internal class MutableKeyEntry( internal class MutableKeyEntry(
val key: ResourceLocation, val key: ResourceLocation,
matter: ImpreciseFraction, matter: Decimal,
complexity: Double, complexity: Double,
priority: Int priority: Int
) : MutableEntry(matter, complexity, priority) { ) : MutableEntry(matter, complexity, priority) {
@ -136,16 +136,16 @@ internal class MutableKeyEntry(
} }
internal sealed class Entry( internal sealed class Entry(
final override val matter: ImpreciseFraction, final override val matter: Decimal,
final override val complexity: Double, final override val complexity: Double,
val priority: Int, val priority: Int,
) : IMatterValue { ) : IMatterValue {
companion object : Entry(ImpreciseFraction.ZERO, 0.0, Int.MIN_VALUE) companion object : Entry(Decimal.ZERO, 0.0, Int.MIN_VALUE)
} }
internal class TagEntry( internal class TagEntry(
val tag: TagKey<Item>, val tag: TagKey<Item>,
matter: ImpreciseFraction, matter: Decimal,
complexity: Double, complexity: Double,
priority: Int, priority: Int,
) : Entry(matter, complexity, priority) { ) : Entry(matter, complexity, priority) {
@ -157,7 +157,7 @@ internal class TagEntry(
internal class KeyEntry( internal class KeyEntry(
val key: ResourceLocation, val key: ResourceLocation,
matter: ImpreciseFraction, matter: Decimal,
complexity: Double, complexity: Double,
priority: Int, priority: Int,
) : Entry(matter, complexity, priority) ) : Entry(matter, complexity, priority)
@ -669,7 +669,7 @@ object MatterManager {
} }
private fun doDetermineValue(item: Item): Result { private fun doDetermineValue(item: Item): Result {
var minimalMatter: ImpreciseFraction? = null var minimalMatter: Decimal? = null
var minimalComplexity: Double? = null var minimalComplexity: Double? = null
val recipes = output2Recipes[item] val recipes = output2Recipes[item]
@ -689,7 +689,7 @@ object MatterManager {
continue continue
} }
var accumulatedMatter: ImpreciseFraction? = null var accumulatedMatter: Decimal? = null
var accumulatedComplexity: Double? = null var accumulatedComplexity: Double? = null
inputsLoop@ for ((i, inputs) in recipe.inputs.withIndex()) { inputsLoop@ for ((i, inputs) in recipe.inputs.withIndex()) {
@ -1059,7 +1059,7 @@ object MatterManager {
if (value.item is IMatterItem) if (value.item is IMatterItem)
can = (value.item as IMatterItem).canDecompose(value) can = (value.item as IMatterItem).canDecompose(value)
can = can && (value.getCapability(MatteryCapability.MATTER).orNull()?.storedMatter ?: ImpreciseFraction.ZERO).isZero can = can && (value.getCapability(MatteryCapability.MATTER).orNull()?.storedMatter ?: Decimal.ZERO).isZero
can = can && (value.getCapability(MatteryCapability.DRIVE).orNull()?.storedCount ?: BigInteger.ZERO).isZero can = can && (value.getCapability(MatteryCapability.DRIVE).orNull()?.storedCount ?: BigInteger.ZERO).isZero
return can && get(value).hasMatterValue return can && get(value).hasMatterValue
@ -1140,7 +1140,7 @@ object MatterManager {
class ResolvedRecipe( class ResolvedRecipe(
inputs: Stream<Stream<ImmutableStack>>, inputs: Stream<Stream<ImmutableStack>>,
val output: ImmutableStack, val output: ImmutableStack,
val transformMatterValue: (ImpreciseFraction) -> ImpreciseFraction = { it }, val transformMatterValue: (Decimal) -> Decimal = { it },
val transformComplexity: (Double) -> Double = { it }, val transformComplexity: (Double) -> Double = { it },
/** /**
@ -1169,7 +1169,7 @@ object MatterManager {
constructor( constructor(
inputs: Collection<Collection<ImmutableStack>>, inputs: Collection<Collection<ImmutableStack>>,
output: ImmutableStack, output: ImmutableStack,
transformMatterValue: (ImpreciseFraction) -> ImpreciseFraction = { it }, transformMatterValue: (Decimal) -> Decimal = { it },
transformComplexity: (Double) -> Double = { it }, transformComplexity: (Double) -> Double = { it },
) : this(inputs.stream().map { it.stream() }, output, transformMatterValue, transformComplexity) ) : this(inputs.stream().map { it.stream() }, output, transformMatterValue, transformComplexity)

View File

@ -1,41 +1,2 @@
package ru.dbotthepony.mc.otm.matter package ru.dbotthepony.mc.otm.matter
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.common.collect.Streams
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.google.gson.JsonSyntaxException
import it.unimi.dsi.fastutil.objects.Reference2ObjectFunction
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap
import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.MinecraftServer
import net.minecraft.server.packs.resources.ResourceManager
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener
import net.minecraft.util.profiling.ProfilerFiller
import net.minecraft.world.Container
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.crafting.Recipe
import net.minecraft.world.item.crafting.RecipeType
import net.minecraftforge.event.AddReloadListenerEvent
import net.minecraftforge.event.server.ServerStartedEvent
import net.minecraftforge.eventbus.api.IEventBus
import net.minecraftforge.registries.DeferredRegister
import net.minecraftforge.registries.ForgeRegistries
import org.apache.logging.log4j.LogManager
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.SystemTime
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import ru.dbotthepony.mc.otm.core.TextComponent
import ru.dbotthepony.mc.otm.core.isActuallyEmpty
import ru.dbotthepony.mc.otm.core.registryName
import ru.dbotthepony.mc.otm.core.stream
import ru.dbotthepony.mc.otm.registry.RegistryDelegate
import java.util.stream.Stream

View File

@ -8,7 +8,7 @@ import com.google.gson.JsonParseException
import net.minecraft.resources.ResourceLocation import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.data.stream import ru.dbotthepony.mc.otm.data.stream
@ -45,7 +45,7 @@ class UpdateAction : AbstractRegistryAction {
} }
} }
val matterFunctions: List<BoundMatterFunction<ImpreciseFraction>> val matterFunctions: List<BoundMatterFunction<Decimal>>
val complexityFunctions: List<BoundMatterFunction<Double>> val complexityFunctions: List<BoundMatterFunction<Double>>
val priorityFunctions: List<BoundMatterFunction<Int>> val priorityFunctions: List<BoundMatterFunction<Int>>
@ -57,11 +57,11 @@ class UpdateAction : AbstractRegistryAction {
constructor( constructor(
tag: TagKey<Item>, tag: TagKey<Item>,
matter: ImpreciseFraction? = null, matter: Decimal? = null,
complexity: Double? = null, complexity: Double? = null,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false, errorOnFailure: Boolean = false,
matterFunctions: List<BoundMatterFunction<ImpreciseFraction>> = ImmutableList.of(), matterFunctions: List<BoundMatterFunction<Decimal>> = ImmutableList.of(),
complexityFunctions: List<BoundMatterFunction<Double>> = ImmutableList.of(), complexityFunctions: List<BoundMatterFunction<Double>> = ImmutableList.of(),
priorityFunctions: List<BoundMatterFunction<Int>> = ImmutableList.of(), priorityFunctions: List<BoundMatterFunction<Int>> = ImmutableList.of(),
) : super(tag = tag, matter = matter, complexity = complexity, priority = priority, errorOnFailure = errorOnFailure) { ) : super(tag = tag, matter = matter, complexity = complexity, priority = priority, errorOnFailure = errorOnFailure) {
@ -76,11 +76,11 @@ class UpdateAction : AbstractRegistryAction {
constructor( constructor(
key: ResourceLocation, key: ResourceLocation,
matter: ImpreciseFraction? = null, matter: Decimal? = null,
complexity: Double? = null, complexity: Double? = null,
priority: Int? = null, priority: Int? = null,
errorOnFailure: Boolean = false, errorOnFailure: Boolean = false,
matterFunctions: List<BoundMatterFunction<ImpreciseFraction>> = ImmutableList.of(), matterFunctions: List<BoundMatterFunction<Decimal>> = ImmutableList.of(),
complexityFunctions: List<BoundMatterFunction<Double>> = ImmutableList.of(), complexityFunctions: List<BoundMatterFunction<Double>> = ImmutableList.of(),
priorityFunctions: List<BoundMatterFunction<Int>> = ImmutableList.of(), priorityFunctions: List<BoundMatterFunction<Int>> = ImmutableList.of(),
) : super(key = key, matter = matter, complexity = complexity, priority = priority, errorOnFailure = errorOnFailure) { ) : super(key = key, matter = matter, complexity = complexity, priority = priority, errorOnFailure = errorOnFailure) {

View File

@ -7,7 +7,7 @@ import net.minecraft.world.inventory.Slot
import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.Block
import ru.dbotthepony.mc.otm.block.EnergyCounterBlock import ru.dbotthepony.mc.otm.block.EnergyCounterBlock
import ru.dbotthepony.mc.otm.block.entity.EnergyCounterBlockEntity import ru.dbotthepony.mc.otm.block.entity.EnergyCounterBlockEntity
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.menu.widget.NumberPlayerInputWidget import ru.dbotthepony.mc.otm.menu.widget.NumberPlayerInputWidget
import ru.dbotthepony.mc.otm.menu.widget.OneWayPlayerInputWidget import ru.dbotthepony.mc.otm.menu.widget.OneWayPlayerInputWidget
import ru.dbotthepony.mc.otm.registry.MMenus import ru.dbotthepony.mc.otm.registry.MMenus
@ -46,7 +46,7 @@ class EnergyCounterMenu @JvmOverloads constructor(
if (it.signum() < 0) { if (it.signum() < 0) {
tile.ioLimit = null tile.ioLimit = null
} else { } else {
tile.ioLimit = ImpreciseFraction(it) tile.ioLimit = Decimal(it)
} }
} }
} }

View File

@ -2,10 +2,9 @@ package ru.dbotthepony.mc.otm.menu
import net.minecraft.world.SimpleContainer import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.inventory.Slot
import ru.dbotthepony.mc.otm.core.ImmutableList import ru.dbotthepony.mc.otm.core.ImmutableList
import ru.dbotthepony.mc.otm.block.entity.matter.MatterCapacitorBankBlockEntity import ru.dbotthepony.mc.otm.block.entity.matter.MatterCapacitorBankBlockEntity
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget
import ru.dbotthepony.mc.otm.registry.MMenus import ru.dbotthepony.mc.otm.registry.MMenus
@ -28,9 +27,9 @@ class MatterCapacitorBankMenu @JvmOverloads constructor(
} else { } else {
matterGauge = LevelGaugeWidget(this, tile) matterGauge = LevelGaugeWidget(this, tile)
totalMatterGauge = LevelGaugeWidget(this, { totalMatterGauge = LevelGaugeWidget(this, {
tile.matterGraph?.getMatterStorageLevel() ?: ImpreciseFraction.ZERO tile.matterGraph?.getMatterStorageLevel() ?: Decimal.ZERO
}, { }, {
tile.matterGraph?.getMatterStorageMaxLevel() ?: ImpreciseFraction.ZERO tile.matterGraph?.getMatterStorageMaxLevel() ?: Decimal.ZERO
}) })
} }

View File

@ -7,7 +7,7 @@ import ru.dbotthepony.mc.otm.menu.widget.ProgressGaugeWidget
import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget
import net.minecraft.world.SimpleContainer import net.minecraft.world.SimpleContainer
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.matter.MatterManager import ru.dbotthepony.mc.otm.matter.MatterManager
import ru.dbotthepony.mc.otm.registry.MMenus import ru.dbotthepony.mc.otm.registry.MMenus
@ -34,8 +34,8 @@ class MatterScannerMenu @JvmOverloads constructor(
if (tile != null) { if (tile != null) {
progress = ProgressGaugeWidget(this, tile::workProgress, tile::isUnableToProcess) progress = ProgressGaugeWidget(this, tile::workProgress, tile::isUnableToProcess)
patterns = LevelGaugeWidget(this, patterns = LevelGaugeWidget(this,
{ ImpreciseFraction(tile.matterGraph?.patternCount ?: 0L) }, { Decimal(tile.matterGraph?.patternCount ?: 0L) },
{ ImpreciseFraction(tile.matterGraph?.patternCapacity ?: 0L) }) { Decimal(tile.matterGraph?.patternCapacity ?: 0L) })
} else { } else {
progress = ProgressGaugeWidget(this) progress = ProgressGaugeWidget(this)
patterns = LevelGaugeWidget(this) patterns = LevelGaugeWidget(this)

View File

@ -4,7 +4,7 @@ import net.minecraft.world.SimpleContainer
import net.minecraft.world.entity.player.Inventory import net.minecraft.world.entity.player.Inventory
import ru.dbotthepony.mc.otm.core.ImmutableList import ru.dbotthepony.mc.otm.core.ImmutableList
import ru.dbotthepony.mc.otm.block.entity.matter.PatternStorageBlockEntity import ru.dbotthepony.mc.otm.block.entity.matter.PatternStorageBlockEntity
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget import ru.dbotthepony.mc.otm.menu.widget.LevelGaugeWidget
import ru.dbotthepony.mc.otm.registry.MMenus import ru.dbotthepony.mc.otm.registry.MMenus
@ -27,9 +27,9 @@ class PatternStorageMenu @JvmOverloads constructor(
} else { } else {
storedThis = LevelGaugeWidget(this, tile) storedThis = LevelGaugeWidget(this, tile)
storedGrid = LevelGaugeWidget(this, { storedGrid = LevelGaugeWidget(this, {
ImpreciseFraction(tile.matterGraph?.patternCount ?: 0) Decimal(tile.matterGraph?.patternCount ?: 0)
}, { }, {
ImpreciseFraction(tile.matterGraph?.patternCapacity ?: 0) Decimal(tile.matterGraph?.patternCapacity ?: 0)
}) })
} }

View File

@ -3,13 +3,13 @@ package ru.dbotthepony.mc.otm.menu.widget
import ru.dbotthepony.mc.otm.capability.IMatteryEnergyStorage import ru.dbotthepony.mc.otm.capability.IMatteryEnergyStorage
import ru.dbotthepony.mc.otm.capability.matter.IMatterHandler import ru.dbotthepony.mc.otm.capability.matter.IMatterHandler
import ru.dbotthepony.mc.otm.capability.matter.IPatternStorage import ru.dbotthepony.mc.otm.capability.matter.IPatternStorage
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.menu.MatteryMenu import ru.dbotthepony.mc.otm.menu.MatteryMenu
@Suppress("unused") @Suppress("unused")
class LevelGaugeWidget(menu: MatteryMenu) : AbstractWidget(menu) { class LevelGaugeWidget(menu: MatteryMenu) : AbstractWidget(menu) {
var levelProvider = { ImpreciseFraction.ONE } var levelProvider = { Decimal.ONE }
var maxLevelProvider = {ImpreciseFraction.ONE } var maxLevelProvider = {Decimal.ONE }
var level by menu.mSynchronizer.fraction() var level by menu.mSynchronizer.fraction()
private set private set
@ -42,14 +42,14 @@ class LevelGaugeWidget(menu: MatteryMenu) : AbstractWidget(menu) {
) : this(menu) { ) : this(menu) {
if (patterns == null) return if (patterns == null) return
this.levelProvider = {ImpreciseFraction(patterns.storedPatterns)} this.levelProvider = {Decimal(patterns.storedPatterns)}
this.maxLevelProvider = {ImpreciseFraction(patterns.patternCapacity)} this.maxLevelProvider = {Decimal(patterns.patternCapacity)}
} }
constructor( constructor(
menu: MatteryMenu, menu: MatteryMenu,
level: () -> ImpreciseFraction, level: () -> Decimal,
maxLevel: () -> ImpreciseFraction, maxLevel: () -> Decimal,
) : this(menu) { ) : this(menu) {
this.levelProvider = level this.levelProvider = level
this.maxLevelProvider = maxLevel this.maxLevelProvider = maxLevel
@ -60,7 +60,7 @@ class LevelGaugeWidget(menu: MatteryMenu) : AbstractWidget(menu) {
maxLevel = maxLevelProvider.invoke() maxLevel = maxLevelProvider.invoke()
} }
fun level(): ImpreciseFraction = level fun level(): Decimal = level
fun maxLevel(): ImpreciseFraction = maxLevel fun maxLevel(): Decimal = maxLevel
fun percentage(): Float = level.percentage(maxLevel) fun percentage(): Float = level.percentage(maxLevel)
} }

View File

@ -147,7 +147,7 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
fun uuid(getter: () -> UUID, name: String = nextFieldName()) = ComputedField(getter, UUIDValueCodec, name) fun uuid(getter: () -> UUID, name: String = nextFieldName()) = ComputedField(getter, UUIDValueCodec, name)
fun int(getter: () -> Int, name: String = nextFieldName()) = ComputedField(getter, VarIntValueCodec, name) fun int(getter: () -> Int, name: String = nextFieldName()) = ComputedField(getter, VarIntValueCodec, name)
fun fixedInt(getter: () -> Int, name: String = nextFieldName()) = ComputedField(getter, IntValueCodec, name) fun fixedInt(getter: () -> Int, name: String = nextFieldName()) = ComputedField(getter, IntValueCodec, name)
fun fraction(getter: () -> ImpreciseFraction, name: String = nextFieldName()) = ComputedField(getter, ImpreciseFractionValueCodec, name) fun fraction(getter: () -> Decimal, name: String = nextFieldName()) = ComputedField(getter, ImpreciseFractionValueCodec, name)
fun bigDecimal(getter: () -> BigDecimal, name: String = nextFieldName()) = ComputedField(getter, BigDecimalValueCodec, name) fun bigDecimal(getter: () -> BigDecimal, name: String = nextFieldName()) = ComputedField(getter, BigDecimalValueCodec, name)
fun item(getter: () -> ItemStack, name: String = nextFieldName()) = ComputedField(getter, ItemStackValueCodec, name) fun item(getter: () -> ItemStack, name: String = nextFieldName()) = ComputedField(getter, ItemStackValueCodec, name)
@ -161,7 +161,7 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
fun uuid(getter: KProperty0<UUID>, name: String = nextFieldName()) = ComputedField(getter, UUIDValueCodec, name) fun uuid(getter: KProperty0<UUID>, name: String = nextFieldName()) = ComputedField(getter, UUIDValueCodec, name)
fun int(getter: KProperty0<Int>, name: String = nextFieldName()) = ComputedField(getter, VarIntValueCodec, name) fun int(getter: KProperty0<Int>, name: String = nextFieldName()) = ComputedField(getter, VarIntValueCodec, name)
fun fixedInt(getter: KProperty0<Int>, name: String = nextFieldName()) = ComputedField(getter, IntValueCodec, name) fun fixedInt(getter: KProperty0<Int>, name: String = nextFieldName()) = ComputedField(getter, IntValueCodec, name)
fun fraction(getter: KProperty0<ImpreciseFraction>, name: String = nextFieldName()) = ComputedField(getter, ImpreciseFractionValueCodec, name) fun fraction(getter: KProperty0<Decimal>, name: String = nextFieldName()) = ComputedField(getter, ImpreciseFractionValueCodec, name)
fun bigDecimal(getter: KProperty0<BigDecimal>, name: String = nextFieldName()) = ComputedField(getter, BigDecimalValueCodec, name) fun bigDecimal(getter: KProperty0<BigDecimal>, name: String = nextFieldName()) = ComputedField(getter, BigDecimalValueCodec, name)
fun item(getter: KProperty0<ItemStack>, name: String = nextFieldName()) = ComputedField(getter, ItemStackValueCodec, name) fun item(getter: KProperty0<ItemStack>, name: String = nextFieldName()) = ComputedField(getter, ItemStackValueCodec, name)
@ -175,7 +175,7 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
fun uuid(getter: Supplier<UUID>, name: String = nextFieldName()) = ComputedField(getter::get, UUIDValueCodec, name) fun uuid(getter: Supplier<UUID>, name: String = nextFieldName()) = ComputedField(getter::get, UUIDValueCodec, name)
fun int(getter: Supplier<Int>, name: String = nextFieldName()) = ComputedField(getter::get, VarIntValueCodec, name) fun int(getter: Supplier<Int>, name: String = nextFieldName()) = ComputedField(getter::get, VarIntValueCodec, name)
fun fixedInt(getter: Supplier<Int>, name: String = nextFieldName()) = ComputedField(getter::get, IntValueCodec, name) fun fixedInt(getter: Supplier<Int>, name: String = nextFieldName()) = ComputedField(getter::get, IntValueCodec, name)
fun fraction(getter: Supplier<ImpreciseFraction>, name: String = nextFieldName()) = ComputedField(getter::get, ImpreciseFractionValueCodec, name) fun fraction(getter: Supplier<Decimal>, name: String = nextFieldName()) = ComputedField(getter::get, ImpreciseFractionValueCodec, name)
fun bigDecimal(getter: Supplier<BigDecimal>, name: String = nextFieldName()) = ComputedField(getter::get, BigDecimalValueCodec, name) fun bigDecimal(getter: Supplier<BigDecimal>, name: String = nextFieldName()) = ComputedField(getter::get, BigDecimalValueCodec, name)
fun item(getter: Supplier<ItemStack>, name: String = nextFieldName()) = ComputedField(getter::get, ItemStackValueCodec, name) fun item(getter: Supplier<ItemStack>, name: String = nextFieldName()) = ComputedField(getter::get, ItemStackValueCodec, name)
@ -279,11 +279,11 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
} }
fun fraction( fun fraction(
value: ImpreciseFraction = ImpreciseFraction.ZERO, value: Decimal = Decimal.ZERO,
getter: FieldGetter<ImpreciseFraction>? = null, getter: FieldGetter<Decimal>? = null,
setter: FieldSetter<ImpreciseFraction>? = null, setter: FieldSetter<Decimal>? = null,
name: String = nextFieldName(), name: String = nextFieldName(),
): Field<ImpreciseFraction> { ): Field<Decimal> {
return Field(value, ImpreciseFractionValueCodec, getter, setter, name = name) return Field(value, ImpreciseFractionValueCodec, getter, setter, name = name)
} }

View File

@ -27,7 +27,7 @@ import ru.dbotthepony.mc.otm.android.feature.ShockwaveFeature
import ru.dbotthepony.mc.otm.block.CargoCrateBlock import ru.dbotthepony.mc.otm.block.CargoCrateBlock
import ru.dbotthepony.mc.otm.block.TritaniumPressurePlate import ru.dbotthepony.mc.otm.block.TritaniumPressurePlate
import ru.dbotthepony.mc.otm.capability.matteryEnergy import ru.dbotthepony.mc.otm.capability.matteryEnergy
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.item.EnergySwordItem import ru.dbotthepony.mc.otm.item.EnergySwordItem
import ru.dbotthepony.mc.otm.registry.objects.ColoredDecorativeBlock import ru.dbotthepony.mc.otm.registry.objects.ColoredDecorativeBlock
import ru.dbotthepony.mc.otm.registry.objects.CrateProperties import ru.dbotthepony.mc.otm.registry.objects.CrateProperties
@ -268,7 +268,7 @@ object MRegistry {
private fun initializeClient(event: FMLClientSetupEvent) { private fun initializeClient(event: FMLClientSetupEvent) {
ItemProperties.register(MItems.ENERGY_SWORD, ResourceLocation(OverdriveThatMatters.MOD_ID, "is_powered")) { stack, _, _, _ -> ItemProperties.register(MItems.ENERGY_SWORD, ResourceLocation(OverdriveThatMatters.MOD_ID, "is_powered")) { stack, _, _, _ ->
if ((stack.matteryEnergy?.batteryLevel ?: ImpreciseFraction.ZERO) >= EnergySwordItem.ENERGY_PER_SWING) { if ((stack.matteryEnergy?.batteryLevel ?: Decimal.ZERO) >= EnergySwordItem.ENERGY_PER_SWING) {
1f 1f
} else { } else {
0f 0f

View File

@ -1,10 +1,7 @@
package ru.dbotthepony.mc.otm.storage package ru.dbotthepony.mc.otm.storage
import net.minecraft.world.item.crafting.Ingredient
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import java.math.BigInteger import java.math.BigInteger
import java.util.* import java.util.*
import java.util.stream.Collectors
import java.util.stream.Stream import java.util.stream.Stream
/** /**

View File

@ -1,8 +1,7 @@
package ru.dbotthepony.mc.otm.storage package ru.dbotthepony.mc.otm.storage
import ru.dbotthepony.mc.otm.OverdriveThatMatters import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.Fraction
import java.util.IdentityHashMap import java.util.IdentityHashMap
open class StorageStackType<T : IStorageStack>( open class StorageStackType<T : IStorageStack>(
@ -12,15 +11,15 @@ open class StorageStackType<T : IStorageStack>(
/** /**
* Speculated energy required per operation on stack with size of 1 * Speculated energy required per operation on stack with size of 1
*/ */
open val energyPerOperation: ImpreciseFraction, open val energyPerOperation: Decimal,
) { ) {
open fun energyPerOperation(stack: T): ImpreciseFraction { open fun energyPerOperation(stack: T): Decimal {
return energyPerOperation * stack.count return energyPerOperation * stack.count
} }
open fun energyPerStorage(stack: T) = energyPerOperation(stack) open fun energyPerStorage(stack: T) = energyPerOperation(stack)
open fun energyPerExtraction(stack: T) = energyPerOperation(stack) open fun energyPerExtraction(stack: T) = energyPerOperation(stack)
open fun energyForUpkeep(stack: T) = ImpreciseFraction.ZERO open fun energyForUpkeep(stack: T) = Decimal.ZERO
} }
@Suppress("unchecked_cast") @Suppress("unchecked_cast")
@ -41,7 +40,7 @@ object StorageRegistry {
fun <T : IStorageStack> register( fun <T : IStorageStack> register(
identity: Class<T>, identity: Class<T>,
empty: T, empty: T,
energyPerOperation: ImpreciseFraction energyPerOperation: Decimal
): StorageStackType<T> { ): StorageStackType<T> {
return register(StorageStackType(identity, empty, energyPerOperation)) as StorageStackType<T> return register(StorageStackType(identity, empty, energyPerOperation)) as StorageStackType<T>
} }

View File

@ -0,0 +1,93 @@
package ru.dbotthepony.mc.otm.tests
import it.unimi.dsi.fastutil.io.FastByteArrayInputStream
import it.unimi.dsi.fastutil.io.FastByteArrayOutputStream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import ru.dbotthepony.mc.otm.core.Decimal
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
object DecimalTests {
@Test
@DisplayName("ImpreciseFraction comparison")
fun comparison() {
check(Decimal(642, 0.43774) > Decimal(641, 0.43774)) { "must be bigger" }
check(Decimal(642, 0.43774) > Decimal(-641, 0.43774)) { "must be bigger" }
check(Decimal(0) == Decimal(0)) { "integer notation" }
check(Decimal(0.1) > Decimal(0)) { "must be bigger" }
check(Decimal(-0.1) < Decimal(0)) { "must be lesser" }
check(Decimal(-1, -0.1) < Decimal(-1)) { "must be lesser" }
check(Decimal(0.1) == Decimal(0.1)) { "double notation" }
check(Decimal("0.1") == Decimal("0.1")) { "string notation" }
}
@Test
@DisplayName("ImpreciseFraction mathematical operations")
fun math() {
check((Decimal(1) + Decimal(2)) == Decimal(3)) { "1 + 2 != 3" }
check((Decimal(0, 0.5) + Decimal(0, 0.5)) == Decimal(1)) { "0.5 + 0.5 != 1" }
check((Decimal(0, 0.5) + Decimal(0, -0.5)) == Decimal(0)) { "0.5 + -0.5 != 1" }
check((Decimal(0, 0.5) - Decimal(0, -0.5)) == Decimal(1)) { "0.5 - -0.5 != 1" }
check((Decimal(0, 0.3) - Decimal(1, 0.2)) == Decimal(0, -0.9)) { "0.3 - 1.2 != -0.9" }
check((Decimal(0, 0.3) * Decimal(0, 0.3)) == Decimal(0, 0.09)) { "0.3 * 0.3 != 0.9 ${Decimal(0, 0.3) * Decimal(0, 0.3)}" }
check((Decimal(2, 0.3) * Decimal(2, 0.3)) == Decimal(5, 0.29)) { "2.3 * 2.3 != 5.29 ${Decimal(2, 0.3) * Decimal(2, 0.3)}" }
check((Decimal(4) / Decimal(2)) == Decimal(2)) { "4 / 2 != 2" }
check((Decimal(6) / Decimal(2)) == Decimal(3)) { "6 / 2 != 2" }
check((Decimal(1) / Decimal(0, 0.25)) == Decimal(4)) { "1 / 0.25 != 4" }
}
@Test
@DisplayName("ImpreciseFraction store/load")
fun storeLoad() {
run {
val f = Decimal(4, 0.28)
val loaded = Decimal.fromByteArray(f.toByteArray())
check(f == loaded) { "$f != $loaded" }
}
run {
val f = Decimal(32748293658335L, 0.3472302174)
val loaded = Decimal.fromByteArray(f.toByteArray())
check(f == loaded) { "$f != $loaded" }
}
}
@Test
@DisplayName("ImpreciseFraction.valueOf")
fun valueOf() {
for (i in -2100 .. 2100) {
assertEquals(Decimal(i), Decimal.valueOf(i))
}
for (i in -2100 .. 2100) {
assertEquals(Decimal(i.toLong()), Decimal.valueOf(i.toLong()))
}
}
@Test
@DisplayName("ImpreciseFraction serialization")
fun serialization() {
val output = FastByteArrayOutputStream()
val outputStream = ObjectOutputStream(output)
val val1 = Decimal("283")
val val2 = Decimal("0")
val val3 = Decimal("-4")
val val4 = Decimal("25.225")
outputStream.writeObject(val1)
outputStream.writeObject(val2)
outputStream.writeObject(val3)
outputStream.writeObject(val4)
val input = FastByteArrayInputStream(output.array, 0, output.length)
val inputStream = ObjectInputStream(input)
assertEquals(val1, inputStream.readObject())
assertEquals(val2, inputStream.readObject())
assertEquals(val3, inputStream.readObject())
assertEquals(val4, inputStream.readObject())
}
}

View File

@ -3,7 +3,7 @@ package ru.dbotthepony.mc.otm.tests
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import ru.dbotthepony.mc.otm.core.formatReadableNumber import ru.dbotthepony.mc.otm.core.formatReadableNumber
import ru.dbotthepony.mc.otm.core.formatSi import ru.dbotthepony.mc.otm.core.formatSi
import java.math.BigInteger import java.math.BigInteger
@ -52,18 +52,18 @@ object FormattingTests {
@Test @Test
@DisplayName("ImpreciseFraction formatting as si number") @DisplayName("ImpreciseFraction formatting as si number")
fun impreciseFractionSi() { fun impreciseFractionSi() {
assertEquals("0.00", ImpreciseFraction("0").formatSi(2)) assertEquals("0.00", Decimal("0").formatSi(2))
assertEquals("14.62", ImpreciseFraction("14.62").formatSi(2)) assertEquals("14.62", Decimal("14.62").formatSi(2))
assertEquals("1.00k", ImpreciseFraction("1000").formatSi(2)) assertEquals("1.00k", Decimal("1000").formatSi(2))
assertEquals("1.00k", ImpreciseFraction("1000.1").formatSi(2)) assertEquals("1.00k", Decimal("1000.1").formatSi(2))
assertEquals("1.00k", ImpreciseFraction("1004.2").formatSi(2)) assertEquals("1.00k", Decimal("1004.2").formatSi(2))
assertEquals("1.01k", ImpreciseFraction("1014.5").formatSi(2)) assertEquals("1.01k", Decimal("1014.5").formatSi(2))
assertEquals("1.014k", ImpreciseFraction("1014.5").formatSi(3)) assertEquals("1.014k", Decimal("1014.5").formatSi(3))
assertEquals("1.01k", ImpreciseFraction("1014.256").formatSi(2)) assertEquals("1.01k", Decimal("1014.256").formatSi(2))
assertEquals("12.73k", ImpreciseFraction("12734.256").formatSi(2)) assertEquals("12.73k", Decimal("12734.256").formatSi(2))
assertEquals("127.34k", ImpreciseFraction("127342.256").formatSi(2)) assertEquals("127.34k", Decimal("127342.256").formatSi(2))
assertEquals("1.27M", ImpreciseFraction("1273421.256").formatSi(2)) assertEquals("1.27M", Decimal("1273421.256").formatSi(2))
assertEquals("1.273M", ImpreciseFraction("1273421.256").formatSi(3)) assertEquals("1.273M", Decimal("1273421.256").formatSi(3))
assertEquals("1.2734M", ImpreciseFraction("1273421.256").formatSi(4)) assertEquals("1.2734M", Decimal("1273421.256").formatSi(4))
} }
} }

View File

@ -4,7 +4,7 @@ import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.assertThrows
import ru.dbotthepony.mc.otm.core.Fraction import ru.dbotthepony.mc.otm.core.Fraction
import ru.dbotthepony.mc.otm.core.ImpreciseFraction import ru.dbotthepony.mc.otm.core.Decimal
import java.math.BigDecimal import java.math.BigDecimal
import java.math.BigInteger import java.math.BigInteger
@ -138,12 +138,12 @@ object FractionTests {
) )
private val samplesIM = arrayOf( private val samplesIM = arrayOf(
ImpreciseFraction(9475.0 / 4729), Decimal(9475.0 / 4729),
ImpreciseFraction(23535.0 / 58723), Decimal(23535.0 / 58723),
ImpreciseFraction(-4852.0 / 6859), Decimal(-4852.0 / 6859),
ImpreciseFraction(-45623.0 / -76849), Decimal(-45623.0 / -76849),
ImpreciseFraction(38494.0 / -76849), Decimal(38494.0 / -76849),
ImpreciseFraction(1043.0 / -648), Decimal(1043.0 / -648),
) )
private val samples2 = arrayOf( private val samples2 = arrayOf(
@ -169,7 +169,7 @@ object FractionTests {
fun performance() { fun performance() {
val rand = java.util.Random() val rand = java.util.Random()
val blackHole = arrayOfNulls<Fraction>(100_000) val blackHole = arrayOfNulls<Fraction>(100_000)
val blackHoleIM = arrayOfNulls<ImpreciseFraction>(100_000) val blackHoleIM = arrayOfNulls<Decimal>(100_000)
val size = samples.size val size = samples.size
var time = System.currentTimeMillis() var time = System.currentTimeMillis()

View File

@ -1,94 +0,0 @@
package ru.dbotthepony.mc.otm.tests
import it.unimi.dsi.fastutil.io.FastByteArrayInputStream
import it.unimi.dsi.fastutil.io.FastByteArrayOutputStream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import ru.dbotthepony.mc.otm.core.ImpreciseFraction
import java.io.File
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
object ImpreciseFractionTests {
@Test
@DisplayName("ImpreciseFraction comparison")
fun comparison() {
check(ImpreciseFraction(642, 0.43774) > ImpreciseFraction(641, 0.43774)) { "must be bigger" }
check(ImpreciseFraction(642, 0.43774) > ImpreciseFraction(-641, 0.43774)) { "must be bigger" }
check(ImpreciseFraction(0) == ImpreciseFraction(0)) { "integer notation" }
check(ImpreciseFraction(0.1) > ImpreciseFraction(0)) { "must be bigger" }
check(ImpreciseFraction(-0.1) < ImpreciseFraction(0)) { "must be lesser" }
check(ImpreciseFraction(-1, -0.1) < ImpreciseFraction(-1)) { "must be lesser" }
check(ImpreciseFraction(0.1) == ImpreciseFraction(0.1)) { "double notation" }
check(ImpreciseFraction("0.1") == ImpreciseFraction("0.1")) { "string notation" }
}
@Test
@DisplayName("ImpreciseFraction mathematical operations")
fun math() {
check((ImpreciseFraction(1) + ImpreciseFraction(2)) == ImpreciseFraction(3)) { "1 + 2 != 3" }
check((ImpreciseFraction(0, 0.5) + ImpreciseFraction(0, 0.5)) == ImpreciseFraction(1)) { "0.5 + 0.5 != 1" }
check((ImpreciseFraction(0, 0.5) + ImpreciseFraction(0, -0.5)) == ImpreciseFraction(0)) { "0.5 + -0.5 != 1" }
check((ImpreciseFraction(0, 0.5) - ImpreciseFraction(0, -0.5)) == ImpreciseFraction(1)) { "0.5 - -0.5 != 1" }
check((ImpreciseFraction(0, 0.3) - ImpreciseFraction(1, 0.2)) == ImpreciseFraction(0, -0.9)) { "0.3 - 1.2 != -0.9" }
check((ImpreciseFraction(0, 0.3) * ImpreciseFraction(0, 0.3)) == ImpreciseFraction(0, 0.09)) { "0.3 * 0.3 != 0.9 ${ImpreciseFraction(0, 0.3) * ImpreciseFraction(0, 0.3)}" }
check((ImpreciseFraction(2, 0.3) * ImpreciseFraction(2, 0.3)) == ImpreciseFraction(5, 0.29)) { "2.3 * 2.3 != 5.29 ${ImpreciseFraction(2, 0.3) * ImpreciseFraction(2, 0.3)}" }
check((ImpreciseFraction(4) / ImpreciseFraction(2)) == ImpreciseFraction(2)) { "4 / 2 != 2" }
check((ImpreciseFraction(6) / ImpreciseFraction(2)) == ImpreciseFraction(3)) { "6 / 2 != 2" }
check((ImpreciseFraction(1) / ImpreciseFraction(0, 0.25)) == ImpreciseFraction(4)) { "1 / 0.25 != 4" }
}
@Test
@DisplayName("ImpreciseFraction store/load")
fun storeLoad() {
run {
val f = ImpreciseFraction(4, 0.28)
val loaded = ImpreciseFraction.fromByteArray(f.toByteArray())
check(f == loaded) { "$f != $loaded" }
}
run {
val f = ImpreciseFraction(32748293658335L, 0.3472302174)
val loaded = ImpreciseFraction.fromByteArray(f.toByteArray())
check(f == loaded) { "$f != $loaded" }
}
}
@Test
@DisplayName("ImpreciseFraction.valueOf")
fun valueOf() {
for (i in -2100 .. 2100) {
assertEquals(ImpreciseFraction(i), ImpreciseFraction.valueOf(i))
}
for (i in -2100 .. 2100) {
assertEquals(ImpreciseFraction(i.toLong()), ImpreciseFraction.valueOf(i.toLong()))
}
}
@Test
@DisplayName("ImpreciseFraction serialization")
fun serialization() {
val output = FastByteArrayOutputStream()
val outputStream = ObjectOutputStream(output)
val val1 = ImpreciseFraction("283")
val val2 = ImpreciseFraction("0")
val val3 = ImpreciseFraction("-4")
val val4 = ImpreciseFraction("25.225")
outputStream.writeObject(val1)
outputStream.writeObject(val2)
outputStream.writeObject(val3)
outputStream.writeObject(val4)
val input = FastByteArrayInputStream(output.array, 0, output.length)
val inputStream = ObjectInputStream(input)
assertEquals(val1, inputStream.readObject())
assertEquals(val2, inputStream.readObject())
assertEquals(val3, inputStream.readObject())
assertEquals(val4, inputStream.readObject())
}
}