Compare commits

...
41 Commits
Author SHA1 Message Date
bdew 8bbab862ab Added RecipesHelper with some shared code for config system loading 2014-10-19 17:16:59 +03:00
bdew 9e83d04487 Build with newer forge 2014-10-19 17:16:15 +03:00
bdew 9202b27340 Added renderer for covers (to allow partially showing the underlying texture) - bdew/gendustry#57 2014-10-15 12:09:08 +03:00
bdew 70ee9fabd6 Added BaseBlockRenderHandler and RenderUtils (some common code moved there) 2014-10-15 12:09:08 +03:00
bdew 78d9bed924 Merge pull request #7 from nalimleinad/mc1710
Create cs_CZ.lang
2014-10-14 13:44:19 +03:00
nalimleinad 92517cdcec Create cs_CZ.lang 2014-10-13 15:30:59 +02:00
bdew bcb8edc8a5 Improved handling of missing icons of fluids and in Texture class 2014-10-08 12:11:53 +03:00
bdew 9a837361e7 /dumpregistry will now show actual items registered in OD 2014-10-06 13:51:40 +03:00
bdew 5ae0461f10 Recipe parser/loader rework, see http://bdew.net/bacon/ for description of new format 2014-10-06 13:51:38 +03:00
bdew b3f8fb3c56 Added PlayerCache - a generic player->whatever map that auto-clears on server restart, logoff, respawn, etc. 2014-09-23 14:12:13 +03:00
bdew 023ae4d77f Added another version of Misc.asInstanceOpt that's easier to use with map, etc. 2014-09-23 14:12:13 +03:00
bdew b1e0e70fc4 Added WidgetSimpleIcon 2014-09-23 14:12:13 +03:00
bdew 5f01716310 Made network message type bound to a specific channel, this should give compile-time errors for sending messages on the wrong channel. Messages should now inherit from YourChannelObject.Message 2014-09-23 14:12:13 +03:00
bdew 0976fb4acc Merge pull request #5 from ViKaleidoscope/patch-1
Create zh_CN.lang
2014-09-19 09:25:35 +03:00
∑( ° △ °|||) 4effeafbb7 Create zh_CN.lang 2014-09-19 12:54:59 +08:00
bdew e0d3609e66 Add ability to customize on what updates DataSlotTank sends it's capacity (default unchanged - only on GUI) 2014-09-18 10:07:56 +03:00
bdew 5a1c150a03 Fixed DrawTarget.drawTextureInterpolate ignoring color parameter 2014-09-16 14:57:37 +03:00
bdew c5a7fc3d51 Fixed WidgetFluidGauge not respecting fluid color 2014-09-16 14:51:33 +03:00
bdew 9787c4836e WidgetOutputs + WidgetPowerOutput moved back to generators as it's mod-specific. WidgetRSConfig refactored from them 2014-09-16 09:44:03 +03:00
bdew cd833163af MsgOutputCfgPower/Fluid (That only had RS configuration) replaced by MsgOutputCfgRSMode 2014-09-16 09:43:13 +03:00
bdew 5a9aedb4d5 Refactoring multiblock outputs, TileOutput (&co) now has a type parameter for config object type 2014-09-04 15:54:35 +03:00
bdew 2a7bbaeb97 prevent outputs connecting back to the same structure 2014-09-03 17:37:00 +03:00
bdew 58125ee291 TileModule.getCoreAs reworked for better type safety 2014-09-03 17:36:19 +03:00
bdew d9cc8ace82 Fixed fluid config save/load 2014-09-02 17:23:36 +03:00
bdew 32617ff592 Added DataSlotInventory 2014-09-02 14:10:50 +03:00
bdew 64683a0208 Refactored output config for multiblocks, added config object for fluid outputs 2014-09-02 14:10:36 +03:00
bdew f593458511 Allow quoted strings as config keys 2014-08-31 10:44:35 +03:00
bdew e6b38472ce Ensure tanks are marked for saving when content changes 2014-08-24 09:58:51 +03:00
bdew e6c0ef2c68 Merge pull request #4 from Adaptivity/patch-1
Create ru_RU.lang
2014-08-21 13:46:48 +03:00
Anton 56110d8ec5 Create ru_RU.lang 2014-08-21 14:09:51 +04:00
bdew f000d11c54 Added ConfigSection.keys 2014-08-20 14:17:13 +03:00
bdew 913d4f48a6 Added localization file 2014-08-20 10:49:06 +03:00
bdew a25553edaf Force block update when connections change for output modules 2014-08-20 10:48:21 +03:00
bdew 82328d10ec Aded multiblock system (moved from DCM) 2014-08-14 15:13:31 +03:00
bdew 12f19fc410 BlockManager.regBlock should looke for NamedBlock trait, not SimpleBlock 2014-08-14 10:04:26 +03:00
bdew 7c275f434a bump version 2014-08-12 13:05:52 +03:00
bdew f960050f9c Added creative tabs helper 2014-08-12 12:41:23 +03:00
bdew 87dd7c34c5 Added DataSlotOption 2014-08-12 12:41:10 +03:00
bdew 9fdc6bd880 Added connected textures renderer 2014-08-11 16:51:18 +03:00
bdew 490433a7f4 Added BlockFace, HasTE can now work with BlockRef, Fixed missing copyrights 2014-08-11 16:45:01 +03:00
bdew 71bef762a6 Added BlockRef (from pressure pipes) 2014-08-07 12:46:21 +03:00
91 changed files with 2745 additions and 483 deletions

No files matched your search

+2 -2
View File
@@ -21,7 +21,7 @@ buildscript {
apply plugin: 'scala'
apply plugin: 'forge'
version = "1.4.1"
version = "1.5.0"
if (project.hasProperty('buildnum')) {
project.version = project.version + '.' + project.buildnum
@@ -34,7 +34,7 @@ archivesBaseName = "bdlib"
ext.versuffix = "mc1710"
minecraft {
version = "1.7.10-10.13.0.1180"
version = "1.7.10-10.13.2.1231"
replace("BDLIB_VER", project.version)
}
+19
View File
@@ -0,0 +1,19 @@
bdlib.multiblock.face.north=Sever
bdlib.multiblock.face.south=Jih
bdlib.multiblock.face.east=Západ
bdlib.multiblock.face.west=Východ
bdlib.multiblock.face.up=Vršek
bdlib.multiblock.face.down=Spodek
bdlib.multiblock.disabled=Zakázáno
bdlib.multiblock.incomplete=Tento stroj není kompletní, ještě potřebuje alespoň:
bdlib.multiblock.notconnected=Nepřipojeno ke správnému stroji
bdlib.multiblock.toomanyoutputs=Připojeno příliš mnoho výstupů, nemohu získat nové připojení
bdlib.rsmode.always=Vždy ZAPNUTO
bdlib.rsmode.never=Zakázáno
bdlib.rsmode.rs_on=Povoleno při ruditovém signálu
bdlib.rsmode.rs_off=Zakázáno při ruditovém signálu
bdlib.label.empty=Prázdný
+19
View File
@@ -0,0 +1,19 @@
bdlib.multiblock.face.north=North
bdlib.multiblock.face.south=South
bdlib.multiblock.face.east=East
bdlib.multiblock.face.west=West
bdlib.multiblock.face.up=Top
bdlib.multiblock.face.down=Bottom
bdlib.multiblock.disabled=Disabled
bdlib.multiblock.incomplete=This machine is incomplete, it requires at least:
bdlib.multiblock.notconnected=Not connected to a valid machine
bdlib.multiblock.toomanyoutputs=Too many outputs connected, unable to attach new connection
bdlib.rsmode.always=Always ON
bdlib.rsmode.never=Disabled
bdlib.rsmode.rs_on=Enable on redstone
bdlib.rsmode.rs_off=Disable on redstone
bdlib.label.empty=Empty
+18
View File
@@ -0,0 +1,18 @@
bdlib.multiblock.face.north=Север
bdlib.multiblock.face.south=Юг
bdlib.multiblock.face.east=Восток
bdlib.multiblock.face.west=Запад
bdlib.multiblock.face.up=Верх
bdlib.multiblock.face.down=Низ
bdlib.multiblock.disabled=Отключено
bdlib.multiblock.incomplete=Этот механизм не завершён, ему требуется как минимум:
bdlib.multiblock.notconnected=Не подключено к верному механизму
bdlib.multiblock.toomanyoutputs=Слишком много выходов подсоединено, нельзя установить новое соединение
bdlib.rsmode.always=Всегда ВКЛ.
bdlib.rsmode.never=Отключен
bdlib.rsmode.rs_on=Включение по сигналу красного камня
bdlib.rsmode.rs_off=Отключение по сигналу красного камня
bdlib.label.empty=Пусто
+18
View File
@@ -0,0 +1,18 @@
bdlib.multiblock.face.north=北方
bdlib.multiblock.face.south=南方
bdlib.multiblock.face.east=东方
bdlib.multiblock.face.west=西方
bdlib.multiblock.face.up=顶部
bdlib.multiblock.face.down=底部
bdlib.multiblock.disabled=停用
bdlib.multiblock.incomplete=这台多方块结构机器未搭建完成, 它至少需要安装一个:
bdlib.multiblock.notconnected=未连接有效机器
bdlib.multiblock.toomanyoutputs=连接的输出接口过多, 无法连接新的接口
bdlib.rsmode.always=一直启用
bdlib.rsmode.never=一直停用
bdlib.rsmode.rs_on=接收到红石信号时启用
bdlib.rsmode.rs_off=接收到红石信号时停用
bdlib.label.empty=空
+1 -1
View File
@@ -1 +1 @@
rootProject.name='bdlib'
rootProject.name = 'bdlib'
+12 -1
View File
@@ -11,7 +11,8 @@ package net.bdew.lib
import cpw.mods.fml.common.Mod
import cpw.mods.fml.common.Mod.EventHandler
import cpw.mods.fml.common.event.{FMLPreInitializationEvent, FMLServerStartingEvent}
import cpw.mods.fml.common.event.{FMLPreInitializationEvent, FMLServerStartingEvent, FMLServerStoppingEvent}
import net.bdew.lib.multiblock.network.NetHandler
import net.minecraft.command.CommandHandler
import org.apache.logging.log4j.Logger
@@ -25,15 +26,25 @@ object BdLib {
def logWarnException(msg: String, t: Throwable, args: Any*) = log.warn(msg.format(args: _*), t)
def logErrorException(msg: String, t: Throwable, args: Any*) = log.error(msg.format(args: _*), t)
val onServerStarting = Event[FMLServerStartingEvent]
val onServerStopping = Event[FMLServerStoppingEvent]
@EventHandler
def preInit(ev: FMLPreInitializationEvent) {
log = ev.getModLog
log.info("bdlib BDLIB_VER loaded")
NetHandler.init()
}
@EventHandler
def serverStarting(event: FMLServerStartingEvent) {
val commandHandler = event.getServer.getCommandManager.asInstanceOf[CommandHandler]
commandHandler.registerCommand(new CommandDumpRegistry)
onServerStarting.trigger(event)
}
@EventHandler
def serverStopping(event: FMLServerStoppingEvent) {
onServerStopping.trigger(event)
}
}
+5
View File
@@ -10,6 +10,7 @@
package net.bdew.lib
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.texture.TextureMap
import org.lwjgl.input.Keyboard
/**
@@ -21,6 +22,10 @@ object Client {
def renderEngine = Minecraft.getMinecraft.renderEngine
def world = Minecraft.getMinecraft.theWorld
def player = Minecraft.getMinecraft.thePlayer
def textureManager = Minecraft.getMinecraft.getTextureManager
def blockMissingIcon = textureManager.getTexture(TextureMap.locationBlocksTexture).asInstanceOf[TextureMap].getAtlasSprite("missingno")
def itemMissingIcon = textureManager.getTexture(TextureMap.locationItemsTexture).asInstanceOf[TextureMap].getAtlasSprite("missingno")
def shiftDown: Boolean = {
return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54)
+6 -1
View File
@@ -46,7 +46,12 @@ class CommandDumpRegistry extends CommandBase {
dumpWriter.write("\n\n")
dumpWriter.write("==== ORE DICT ====\n")
dumpWriter.write(OreDictionary.getOreNames.sorted.mkString("\n"))
dumpWriter.write((OreDictionary.getOreNames.sorted flatMap { name =>
List(name) ++
(OreDictionary.getOres(name) map { ore =>
" - " + ore.toString
})
}).mkString("\n"))
dumpWriter.write("\n\n")
dumpWriter.write("==== FLUIDS ====\n")
@@ -0,0 +1,24 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.Item
class CreativeTabContainer {
class Tab(name: String, item: => Item) extends CreativeTabs(name) {
override def getTabIconItem = item
}
BdLib.logInfo("Loaded creative tabs for %s", Misc.getActiveModId)
def init() {}
}
+27 -2
View File
@@ -15,9 +15,10 @@ import cpw.mods.fml.common.versioning.{ArtifactVersion, VersionParser}
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.StatCollector
import net.minecraft.util.{IIcon, StatCollector}
import net.minecraft.world.biome.BiomeGenBase
import net.minecraftforge.common.util.ForgeDirection
import net.minecraftforge.fluids.{Fluid, FluidStack}
import net.minecraftforge.oredict.ShapedOreRecipe
object Misc {
@@ -64,7 +65,7 @@ object Misc {
def filterType[T](from: Iterable[_], cls: Class[T]) = from.filter(cls.isInstance).asInstanceOf[Iterable[T]]
def getBiomeByName(name: String) = BiomeGenBase.getBiomeGenArray.find(x => x != null && x.biomeName == name).getOrElse(null)
def getBiomeByName(name: String) = BiomeGenBase.getBiomeGenArray.find(x => x != null && x.biomeName == name).orNull
def haveModVersion(spec: String): Boolean = {
val req = VersionParser.parseVersionReference(spec)
@@ -86,8 +87,32 @@ object Misc {
def asInstanceOpt[T](v: Any, cls: Class[T]) =
if (cls.isInstance(v)) Some(v.asInstanceOf[T]) else None
// Same thing but in a way that's easier to use with map, etc.
def asInstanceOpt[T](cls: Class[T])(v: Any) =
if (cls.isInstance(v)) Some(v.asInstanceOf[T]) else None
def getNeighbourTile[T](origin: TileEntity, dir: ForgeDirection, cls: Class[T]) =
Option(origin.getWorldObj.getTileEntity(origin.xCoord + dir.offsetX,
origin.yCoord + dir.offsetY, origin.zCoord + dir.offsetZ)) flatMap (asInstanceOpt(_, cls))
def applyMutator[T](f: (T) => Unit, init: T): T = {
f(init)
init
}
def getFluidIcon(fs: FluidStack): IIcon =
if (fs != null && fs.getFluid != null && fs.getFluid.getIcon != null)
fs.getFluid.getIcon(fs)
else
Client.blockMissingIcon
def getFluidIcon(f: Fluid): IIcon =
if (f != null) getFluidIcon(new FluidStack(f, 1)) else Client.blockMissingIcon
def getFluidColor(fs: FluidStack): Int =
if (fs != null && fs.getFluid != null) fs.getFluid.getColor(fs) else 0xFFFFFF
def getFluidColor(f: Fluid): Int =
if (f != null) getFluidColor(new FluidStack(f, 1)) else 0xFFFFFF
}
+22
View File
@@ -0,0 +1,22 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.block
import net.minecraftforge.common.util.ForgeDirection
case class BlockFace(x: Int, y: Int, z: Int, face: ForgeDirection) {
def origin = BlockRef(x, y, z)
def target = origin.neighbour(face)
def opposite = face.getOpposite
}
object BlockFace {
def apply(bp: BlockRef, face: ForgeDirection) = new BlockFace(bp.x, bp.y, bp.z, face)
}
+59
View File
@@ -0,0 +1,59 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.block
import net.minecraft.block.Block
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.util.ForgeDirection
import scala.reflect.ClassTag
case class BlockRef(x: Int, y: Int, z: Int) {
def block(w: IBlockAccess) = Option(w.getBlock(x, y, z))
def tile(w: IBlockAccess) = Option(w.getTileEntity(x, y, z))
def meta(w: IBlockAccess) = w.getBlockMetadata(x, y, z)
def blockIs(w: IBlockAccess, other: Block) = block(w).contains(other)
def neighbour(side: ForgeDirection) = BlockRef(x + side.offsetX, y + side.offsetY, z + side.offsetZ)
def neighbours = ForgeDirection.VALID_DIRECTIONS.map(x => x -> neighbour(x)).toMap
override def toString = "(x=%d y=%d z=%d)".format(x, y, z)
def getTile[T: ClassTag](w: IBlockAccess) = tile(w) flatMap { tile =>
val cls = implicitly[ClassTag[T]].runtimeClass
if (cls.isInstance(tile))
Some(tile.asInstanceOf[T])
else None
}
def ==(tx: Int, ty: Int, tz: Int) = x == tx && y == ty && z == tz
def getBlock[T: ClassTag](w: IBlockAccess) = block(w) flatMap { block =>
val cls = implicitly[ClassTag[T]].runtimeClass
if (cls.isInstance(block))
Some(block.asInstanceOf[T])
else None
}
def writeToNBT(tag: NBTTagCompound) {
tag.setInteger("x", x)
tag.setInteger("y", y)
tag.setInteger("z", z)
}
}
object BlockRef {
def fromTile(te: TileEntity) = BlockRef(te.xCoord, te.yCoord, te.zCoord)
def fromNBT(tag: NBTTagCompound) =
BlockRef(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"))
}
+3
View File
@@ -18,6 +18,9 @@ trait HasTE[T] extends Block with ITileEntityProvider {
val TEClass: Class[_ <: TileEntity]
def createNewTileEntity(world: World, meta: Int): TileEntity = TEClass.newInstance()
def getTE(w: IBlockAccess, ref: BlockRef): T = getTE(w, ref.x, ref.y, ref.z)
def getTE(w: IBlockAccess, x: Int, y: Int, z: Int): T = {
var t = w.getTileEntity(x, y, z)
if ((t == null) || !TEClass.isInstance(t)) {
+30
View File
@@ -0,0 +1,30 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.block
import cpw.mods.fml.relauncher.{Side, SideOnly}
import net.bdew.lib.Misc
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.client.renderer.texture.IIconRegister
trait NamedBlock extends Block {
def name: String
}
class SimpleBlock(val name: String, material: Material) extends Block(material) with NamedBlock {
val modId = Misc.getActiveModId
setBlockName(modId + "." + name)
@SideOnly(Side.CLIENT)
override def registerBlockIcons(reg: IIconRegister) {
blockIcon = reg.registerIcon(modId + ":" + name.toLowerCase)
}
}
+6 -7
View File
@@ -11,20 +11,19 @@ package net.bdew.lib.config
import cpw.mods.fml.common.registry.GameRegistry
import net.bdew.lib.Misc
import net.bdew.lib.block.HasTE
import net.bdew.lib.block.{HasTE, NamedBlock}
import net.minecraft.block.Block
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.ItemStack
class BlockManager() {
def regBlockCls[T <: Block](blockCls: Class[T], name: String, addStack: Boolean = false): T = {
val block = blockCls.newInstance()
regBlock[T](block, name, addStack)
}
class BlockManager(creativeTab: CreativeTabs) {
def regBlock[T <: NamedBlock](block: T): T = regBlock(block, block.name)
def regBlock[T <: Block](block: T, name: String, addStack: Boolean = false): T = {
GameRegistry.registerBlock(block, name)
block.setCreativeTab(creativeTab)
if (addStack)
GameRegistry.registerCustomItemStack(name, new ItemStack(block))
+4 -6
View File
@@ -11,23 +11,21 @@ package net.bdew.lib.config
import cpw.mods.fml.common.registry.GameRegistry
import net.bdew.lib.items.{NamedItem, SimpleItem}
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.{Item, ItemStack}
class ItemManager() {
class ItemManager(creativeTab: CreativeTabs) {
def regSimpleItem(name: String): SimpleItem = regItem(new SimpleItem(name), name)
def regItem[T <: NamedItem](item: T): T = regItem[T](item, item.name)
def regItemCls[T <: Item](itemCls: Class[T], name: String, addStack: Boolean = false): T = {
val item = itemCls.newInstance()
regItem[T](item, name, addStack)
}
def regItem[T <: Item](item: T, name: String, addStack: Boolean = false): T = {
GameRegistry.registerItem(item, name)
item.setCreativeTab(creativeTab)
if (addStack)
GameRegistry.registerCustomItemStack(name, new ItemStack(item))
return item
}
def load() {}
}
+3 -2
View File
@@ -12,13 +12,14 @@ package net.bdew.lib.config
import net.bdew.lib.gui.{GuiHandler, GuiProvider}
import net.bdew.lib.machine.Machine
import net.bdew.lib.recipes.gencfg.ConfigSection
import net.minecraft.creativetab.CreativeTabs
class MachineManager(val tuning: ConfigSection, guiHandler: GuiHandler) {
class MachineManager(val tuning: ConfigSection, guiHandler: GuiHandler, creativeTab: CreativeTabs) {
def registerMachine[R <: Machine[_]](machine: R): R = {
machine.tuning = tuning.getSection(machine.name)
if (machine.tuning.getBoolean("Enabled")) {
machine.enabled = true
machine.regBlock()
machine.regBlock(creativeTab)
if (machine.isInstanceOf[GuiProvider])
guiHandler.register(machine.asInstanceOf[GuiProvider])
}
+11 -5
View File
@@ -9,14 +9,20 @@
package net.bdew.lib.covers
import cpw.mods.fml.relauncher.{Side, SideOnly}
import net.bdew.lib.Misc
import net.bdew.lib.block.HasTE
import net.bdew.lib.items.ItemUtils
import net.minecraft.block.Block
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.IIcon
import net.minecraft.world.{IBlockAccess, World}
import net.minecraftforge.common.util.ForgeDirection
trait BlockCoverable[T <: TileCoverable] extends HasTE[T] {
@SideOnly(Side.CLIENT)
override def getRenderType = CoverRenderer.id
override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, face: Int, xoffs: Float, yoffs: Float, zoffs: Float): Boolean = {
val te = getTE(world, x, y, z)
val side = Misc.forgeDirection(face)
@@ -53,12 +59,12 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] {
super.onBlockActivated(world, x, y, z, player, face, xoffs, yoffs, zoffs)
}
override def getIcon(w: IBlockAccess, x: Int, y: Int, z: Int, side: Int) =
(for {
coverStack <- Option(getTE(w, x, y, z).covers(Misc.forgeDirection(side)).cval)
coverItem <- Option(coverStack.getItem) flatMap (Misc.asInstanceOpt(_, classOf[ItemCover]))
def getCoverIcon(w: IBlockAccess, x: Int, y: Int, z: Int, side: ForgeDirection): Option[IIcon] =
for {
coverStack <- Option(getTE(w, x, y, z).covers(side).cval)
coverItemMaybe <- Option(coverStack.getItem)
coverItem <- Misc.asInstanceOpt(coverItemMaybe, classOf[ItemCover])
} yield coverItem.getCoverIcon(coverStack)
) getOrElse super.getIcon(w, x, y, z, side)
override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) {
if (!world.isRemote)
@@ -0,0 +1,34 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.covers
import net.bdew.lib.Misc
import net.bdew.lib.render.connected.ConnectedHelper
import net.bdew.lib.render.{BaseBlockRenderHandler, RenderUtils}
import net.minecraft.block.Block
import net.minecraft.client.renderer.RenderBlocks
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.util.ForgeDirection
object CoverRenderer extends BaseBlockRenderHandler {
override def renderInventoryBlock(block: Block, metadata: Int, modelId: Int, renderer: RenderBlocks) =
RenderUtils.renderSimpleBlockItem(block, metadata, renderer)
override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks) = {
renderer.renderStandardBlock(block, x, y, z)
for {
blockCov <- Misc.asInstanceOpt(block, classOf[BlockCoverable[_]])
face <- ForgeDirection.VALID_DIRECTIONS
icon <- blockCov.getCoverIcon(world, x, y, z, face)
if block.shouldSideBeRendered(world, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())
} ConnectedHelper.draw(face, 8).doDraw(ConnectedHelper.Vec3F(x, y, z), icon)
true
}
}
@@ -1,3 +1,12 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.data
import java.util.UUID
@@ -0,0 +1,46 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.data
import net.bdew.lib.Misc
import net.bdew.lib.data.base.{DataSlot, TileDataSlots, UpdateKind}
import net.bdew.lib.tile.inventory.BaseInventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.{NBTTagCompound, NBTTagList}
case class DataSlotInventory(name: String, parent: TileDataSlots, size: Int) extends DataSlot with BaseInventory {
setUpdate(UpdateKind.SAVE)
override def getSizeInventory = size
override def markDirty() = parent.dataSlotChanged(this)
override def load(t: NBTTagCompound, kind: UpdateKind.Value) {
inv = new Array[ItemStack](getSizeInventory)
for (nbtItem <- Misc.iterNbtCompoundList(t, name)) {
val slot = nbtItem.getByte("Slot")
if (slot >= 0 && slot < inv.size) {
inv(slot) = ItemStack.loadItemStackFromNBT(nbtItem)
}
}
}
override def save(t: NBTTagCompound, kind: UpdateKind.Value) {
val itemList = new NBTTagList
for ((item, i) <- inv.view.zipWithIndex if item != null) {
val itemNbt: NBTTagCompound = new NBTTagCompound
itemNbt.setByte("Slot", i.asInstanceOf[Byte])
item.writeToNBT(itemNbt)
itemList.appendTag(itemNbt)
}
t.setTag(name, itemList)
}
}
@@ -0,0 +1,46 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.data
import net.bdew.lib.data.base.DataSlotVal
abstract class DataSlotOption[T] extends DataSlotVal[Option[T]] {
override var cval: Option[T] = None
def set(v: T) {
if (v == null) sys.error("Null should never be used with DataSlotOption")
cval = Some(v)
}
def unset() {
cval = None
}
override def isSame(v: Option[T]) = {
if (v == null) sys.error("Null should never be used with DataSlotOption")
super.isSame(v)
}
override def :=(that: Option[T]) = {
if (that == null) sys.error("Null should never be used with DataSlotOption")
super.:=(that)
}
override def :!=(that: Option[T]) = {
if (that == null) sys.error("Null should never be used with DataSlotOption")
super.:!=(that)
}
override def :==(that: Option[T]) = {
if (that == null) sys.error("Null should never be used with DataSlotOption")
super.:==(that)
}
override def update(v: Option[T]) = {
if (v == null) sys.error("Null should never be used with DataSlotOption")
super.update(v)
}
}
+17 -2
View File
@@ -20,6 +20,8 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w
updateKind = Set(UpdateKind.GUI, UpdateKind.SAVE)
val sendCapacityOnUpdateKind = Set(UpdateKind.GUI)
def checkUpdate() {
if (!isSame(oldStack, fluid)) {
oldStack = if (fluid == null) null else fluid.copy()
@@ -36,7 +38,7 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w
def save(t: NBTTagCompound, k: UpdateKind.Value) {
val tag = new NBTTagCompound()
writeToNBT(tag)
if (k == UpdateKind.GUI)
if (sendCapacityOnUpdateKind.contains(k))
tag.setInteger("size", getCapacity)
t.setTag(name, tag)
}
@@ -45,9 +47,22 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w
setFluid(null)
val tag = t.getCompoundTag(name)
readFromNBT(tag)
if (k == UpdateKind.GUI)
if (sendCapacityOnUpdateKind.contains(k))
setCapacity(tag.getInteger("size"))
}
override def setFluid(fluid: FluidStack) = execWithChangeNotify(super.setFluid(fluid))
override def setCapacity(capacity: Int) = execWithChangeNotify(super.setCapacity(capacity))
override def drain(maxDrain: Int, doDrain: Boolean) =
if (doDrain)
execWithChangeNotify(super.drain(maxDrain, true))
else
super.drain(maxDrain, false)
override def fill(resource: FluidStack, doFill: Boolean) =
if (doFill)
execWithChangeNotify(super.fill(resource, true))
else
super.fill(resource, false)
}
case class DataSlotTank(name: String, parent: TileDataSlots, size: Int) extends DataSlotTankBase(size)
@@ -35,6 +35,12 @@ trait DataSlot {
def save(t: NBTTagCompound, kind: UpdateKind.Value)
def load(t: NBTTagCompound, kind: UpdateKind.Value)
def execWithChangeNotify[T](f: => T): T = {
val v = f
parent.dataSlotChanged(this)
v
}
def setUpdate(vals: UpdateKind.Value*): this.type = {
updateKind = vals.toSet
return this
+1 -1
View File
@@ -20,7 +20,7 @@ trait DrawTarget {
def drawTextMultiline(text: String, r: Rect, color: Color)
def drawTextureInterpolate(r: Rect, t: Texture, x1: Float, y1: Float, x2: Float, y2: Float, color: Color = Color.white) =
drawTexture(r.interpolate(x1, y1, x2, y2), Texture.interpolate(t, x1, y1, x2, y2))
drawTexture(r.interpolate(x1, y1, x2, y2), Texture.interpolate(t, x1, y1, x2, y2), color)
}
trait SimpleDrawTarget extends DrawTarget {
+8 -1
View File
@@ -9,6 +9,7 @@
package net.bdew.lib.gui
import net.bdew.lib.Client
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.util.{IIcon, ResourceLocation}
@@ -29,7 +30,13 @@ class InterpolatedTexture(val texture: Texture, rect: Rect) extends Texture {
def v2 = rect.y2 * (texture.v2 - texture.v1) + texture.v1
}
class IconWrapper(val resource: ResourceLocation, val icon: IIcon) extends Texture {
class IconWrapper(val resource: ResourceLocation, picon: IIcon) extends Texture {
val icon = if (picon == null) {
if (resource == Texture.ITEMS) Client.itemMissingIcon
else if (resource == Texture.BLOCKS) Client.blockMissingIcon
else sys.error("Attempt to create IconWrapper for null IIcon")
} else picon
def u1 = icon.getMinU
def u2 = icon.getMaxU
def v1 = icon.getMinV
@@ -0,0 +1,45 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.gui.widgets
import net.bdew.lib.gui.{Point, Rect, Texture}
import net.minecraft.client.Minecraft
import net.minecraft.client.audio.PositionedSoundRecord
import net.minecraft.util.ResourceLocation
import scala.collection.mutable
class WidgetButtonIcon(p: Point, clicked: WidgetButtonIcon => Unit, baseTex: Texture, hoverTex: Texture) extends Widget {
val rect = new Rect(p, 16, 16)
val iconRect = new Rect(p +(1, 1), 14, 14)
var icon: Texture = null
var hover: String = null
override def draw(mouse: Point) {
if (rect.contains(mouse))
parent.drawTexture(rect, hoverTex)
else
parent.drawTexture(rect, baseTex)
if (icon != null)
parent.drawTexture(iconRect, icon)
}
override def handleTooltip(p: Point, tip: mutable.MutableList[String]) {
if (hover != null && hover > "")
tip += hover
}
override def mouseClicked(p: Point, button: Int) {
Minecraft.getMinecraft.getSoundHandler.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F))
clicked(this)
}
}
@@ -13,7 +13,7 @@ import java.text.DecimalFormat
import net.bdew.lib.Misc
import net.bdew.lib.data.DataSlotTankBase
import net.bdew.lib.gui.{Point, Rect, Texture}
import net.bdew.lib.gui.{Color, Point, Rect, Texture}
import org.lwjgl.opengl.GL11
import scala.collection.mutable
@@ -35,23 +35,25 @@ class WidgetFluidGauge(val rect: Rect, overlay: Texture, dslot: DataSlotTankBase
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA)
val fstack = dslot.getFluid
if (fstack != null && fstack.getFluid.getStillIcon != null) {
val icon = Texture(Texture.BLOCKS, fstack.getFluid.getStillIcon)
if (fstack != null) {
val color = Color.fromInt(Misc.getFluidColor(fstack))
val icon = Texture(Texture.BLOCKS, Misc.getFluidIcon(fstack))
var fillHeight = if (dslot.getCapacity > 0) rect.h * fstack.amount / dslot.getCapacity else 0
var yStart: Int = 0
while (fillHeight > 0) {
if (fillHeight > 16) {
parent.drawTexture(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon)
parent.drawTexture(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon, color)
fillHeight -= 16
} else {
parent.drawTextureInterpolate(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon, 0, 1 - fillHeight / 16, 1, 1)
parent.drawTextureInterpolate(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon, 0, 1 - fillHeight / 16, 1, 1, color)
fillHeight = 0
}
yStart = yStart + 16
}
}
GL11.glColor3d(1, 1, 1)
GL11.glDisable(GL11.GL_BLEND)
parent.drawTexture(rect, overlay)
@@ -0,0 +1,16 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.gui.widgets
import net.bdew.lib.gui._
case class WidgetSimpleIcon(rect: Rect, icon: Texture) extends Widget {
override def draw(mouse: Point) = parent.drawTexture(rect, icon)
}
@@ -9,7 +9,7 @@
package net.bdew.lib.gui.widgets
import net.bdew.lib.gui.{Rect, _}
import net.bdew.lib.gui._
class WidgetSubcontainer(val rect: Rect) extends BaseWidget with WidgetContainer with SimpleDrawTarget {
def getZLevel = parent.getZLevel
+3 -1
View File
@@ -14,6 +14,7 @@ import net.bdew.lib.Misc
import net.bdew.lib.block.HasTE
import net.bdew.lib.recipes.gencfg.ConfigSection
import net.minecraft.block.Block
import net.minecraft.creativetab.CreativeTabs
abstract class Machine[T <: Block](val name: String, blockConstruct: => T) {
var block: T = null.asInstanceOf[T]
@@ -21,9 +22,10 @@ abstract class Machine[T <: Block](val name: String, blockConstruct: => T) {
var enabled = false
val modId = Misc.getActiveModId
def regBlock() {
def regBlock(creativeTab: CreativeTabs) {
block = blockConstruct
GameRegistry.registerBlock(block, name)
block.setCreativeTab(creativeTab)
if (block.isInstanceOf[HasTE[_]]) {
GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass, "%s.%s".format(modId, name))
}
@@ -0,0 +1,24 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock
import net.bdew.lib.recipes.gencfg.{ConfigSection, EntryDouble}
trait MachineCore {
var tuning: ConfigSection
def cfgSectionToMap(name: String) = tuning.getSection(name).map({
case (n, EntryDouble(v)) => n -> v.toInt
case (n, x) => sys.error("Invalid config value in section %s%s.%s = %s".format(tuning.pfx, name, n, x))
}).toMap
lazy val modules = cfgSectionToMap("Modules")
lazy val required = cfgSectionToMap("Required")
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock
import net.bdew.lib.gui.{Color, Texture}
import net.minecraft.util.IIcon
trait ResourceProvider {
// Icons for rendering, *must* be on block spritesheet
def edge: IIcon
def disabled: IIcon
def output: IIcon
def arrowTop: IIcon
def arrowRight: IIcon
def arrowBottom: IIcon
def arrowLeft: IIcon
// Textures for GUI stuff
def btBase: Texture
def btHover: Texture
def btRsOn: Texture
def btRsOff: Texture
def btEnabled: Texture
def btDisabled: Texture
val outputColors: Map[Int, Color]
val unlocalizedOutputName: Map[Int, String]
def getModuleName(s: String): String
}
+51
View File
@@ -0,0 +1,51 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock
import net.bdew.lib.block.BlockRef
import net.bdew.lib.multiblock.tile.{TileController, TileModule}
import net.minecraft.world.World
import scala.collection.mutable
object Tools {
def canConnect(world: World, core: BlockRef, kind: String): Boolean = {
val t = core.getTile[TileController](world).getOrElse(return false)
t.getNumOfMoudules(kind) < t.cfg.modules.getOrElse(kind, return false)
}
def findConnections(world: World, start: BlockRef, kind: String) =
(start.neighbours.values flatMap { case pos =>
(pos.tile(world) flatMap {
case t: TileModule => t.connected.cval
case t: TileController => Some(pos)
case _ => None
}) filter (x => canConnect(world, x, kind))
}).toList.distinct
def getAdjancedConnected(w: World, core: BlockRef, pos: BlockRef, seen: mutable.Set[BlockRef]) =
pos.neighbours.values
.filterNot(seen.contains)
.flatMap(_.getTile[TileModule](w))
.filter(x => x.connected.contains(core))
.map(_.mypos)
def findReachableModules(world: World, core: BlockRef): Set[BlockRef] = {
val seen = mutable.Set.empty[BlockRef]
val queue = mutable.Queue.empty[BlockRef]
queue ++= getAdjancedConnected(world, core, core, seen)
while (queue.size > 0) {
val current = queue.dequeue()
seen.add(current)
queue ++= getAdjancedConnected(world, core, current, seen)
}
return seen.toSet
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.block
import net.bdew.lib.block.{BlockRef, HasTE}
import net.bdew.lib.multiblock.ResourceProvider
import net.bdew.lib.multiblock.tile.TileController
import net.bdew.lib.render.connected.ConnectedTextureBlock
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.world.{IBlockAccess, World}
abstract class BlockController[T <: TileController](val name: String, material: Material, val TEClass: Class[T])
extends Block(material) with HasTE[T] with ConnectedTextureBlock {
def resources: ResourceProvider
override def edgeIcon = resources.edge
override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) {
getTE(world, x, y, z).onBreak()
super.breakBlock(world, x, y, z, block, meta)
}
override def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef) =
getTE(world, origin).modules.contains(target)
override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, meta: Int, xoffs: Float, yoffs: Float, zoffs: Float): Boolean = {
if (player.isSneaking) return false
if (world.isRemote) return true
getTE(world, x, y, z).onClick(player)
return true
}
}
@@ -0,0 +1,69 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.block
import net.bdew.lib.block.{BlockRef, HasTE}
import net.bdew.lib.multiblock.tile.TileModule
import net.bdew.lib.multiblock.{ResourceProvider, Tools}
import net.bdew.lib.render.connected.ConnectedTextureBlock
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.util.ChatComponentTranslation
import net.minecraft.world.{IBlockAccess, World}
abstract class BlockModule[T <: TileModule](val name: String, val kind: String, material: Material, val TEClass: Class[T])
extends Block(material) with HasTE[T] with ConnectedTextureBlock {
def resources: ResourceProvider
override def edgeIcon = resources.edge
override def canPlaceBlockAt(world: World, x: Int, y: Int, z: Int): Boolean =
Tools.findConnections(world, BlockRef(x, y, z), kind).size <= 1
override def onBlockPlacedBy(world: World, x: Int, y: Int, z: Int, player: EntityLivingBase, stack: ItemStack) {
getTE(world, x, y, z).tryConnect()
}
override def onNeighborBlockChange(world: World, x: Int, y: Int, z: Int, block: Block) {
getTE(world, x, y, z).tryConnect()
}
override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) {
getTE(world, x, y, z).onBreak()
super.breakBlock(world, x, y, z, block, meta)
}
override def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef) = {
val me = getTE(world, origin)
me.connected.contains(target) ||
(target.getTile[TileModule](world) exists { other =>
me.getCore.isDefined && other.getCore == me.getCore
})
}
override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, meta: Int, xoffs: Float, yoffs: Float, zoffs: Float): Boolean = {
if (player.isSneaking) return false
if (world.isRemote) return true
val te = getTE(world, x, y, z)
(for {
p <- te.connected.cval
bl <- p.block(world)
} yield {
bl.onBlockActivated(world, p.x, p.y, p.z, player, meta, 0, 0, 0)
}) getOrElse {
player.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.notconnected"))
}
true
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.block
import net.bdew.lib.block.{BlockFace, BlockRef}
import net.bdew.lib.multiblock.tile.TileOutput
import net.bdew.lib.render.connected.{BlockAdditionalRender, ConnectedHelper, FaceOverlay}
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.util.ForgeDirection
trait BlockOutput[T <: TileOutput[_]] extends BlockModule[T] with BlockAdditionalRender {
def getAdjancedFaces(face: ForgeDirection, bp: BlockRef) = {
val sides = ConnectedHelper.faceAdjanced(face)
Seq(
(BlockFace(bp, sides.top), resources.arrowTop),
(BlockFace(bp, sides.right), resources.arrowRight),
(BlockFace(bp, sides.bottom), resources.arrowBottom),
(BlockFace(bp, sides.left), resources.arrowLeft)
)
}
def getFaceOverlays(world: IBlockAccess, x: Int, y: Int, z: Int, face: ForgeDirection): List[FaceOverlay] = {
var result = List.empty[FaceOverlay]
Option(getTE(world, x, y, z)) flatMap (_.getCore) map { core =>
val bf = BlockFace(x, y, z, face)
if (core.outputFaces.contains(bf))
result :+= FaceOverlay(resources.output, resources.outputColors(core.outputFaces(bf)))
for ((bf, icon) <- getAdjancedFaces(face, bf.origin)) {
if (core.outputFaces.contains(bf))
result :+= FaceOverlay(icon, resources.outputColors(core.outputFaces(bf)))
}
}
return result
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.Misc
import net.bdew.lib.block.BlockFace
import net.bdew.lib.data.base.{DataSlot, TileDataSlots, UpdateKind}
import net.minecraft.nbt.{NBTTagCompound, NBTTagIntArray, NBTTagList}
import net.minecraftforge.common.util.ForgeDirection
case class DataSlotBlockFaceMap(name: String, parent: TileDataSlots) extends DataSlot {
val map = collection.mutable.Map.empty[BlockFace, Int]
setUpdate(UpdateKind.SAVE, UpdateKind.WORLD)
def inverted = map.map(_.swap)
def ent2arr(x: (BlockFace, Int)) = Array(x._2, x._1.x, x._1.y, x._1.z, x._1.face.ordinal())
def arr2ent(x: Array[Int]) = BlockFace(x(1), x(2), x(3), ForgeDirection.values()(x(4))) -> x(0)
def save(t: NBTTagCompound, kind: UpdateKind.Value) {
val lst = new NBTTagList()
for (x <- map) lst.appendTag(new NBTTagIntArray(ent2arr(x)))
t.setTag(name, lst)
}
def load(t: NBTTagCompound, kind: UpdateKind.Value) {
map.clear()
map ++= Misc.iterNbtIntArray(t, name) map arr2ent
}
def updated() = parent.dataSlotChanged(this)
}
object DataSlotBlockFaceMap {
import scala.language.implicitConversions
implicit def dsbfm2map(v: DataSlotBlockFaceMap) = v.map
}
@@ -0,0 +1,60 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.data.base.{DataSlot, TileDataSlots, UpdateKind}
import net.minecraft.nbt.NBTTagCompound
case class DataSlotOutputConfig(name: String, parent: TileDataSlots, slots: Int) extends DataSlot {
val map = collection.mutable.Map.empty[Int, OutputConfig]
setUpdate(UpdateKind.SAVE, UpdateKind.GUI)
def inverted = map.map(_.swap)
def save(t: NBTTagCompound, kind: UpdateKind.Value) {
for ((n, x) <- map) {
val tmp = new NBTTagCompound()
x.write(tmp)
val kind = x match {
case _: OutputConfigPower => "power"
case _: OutputConfigFluid => "fluid"
case _ => sys.error("Unknown output config kind: " + x)
}
tmp.setString("kind", kind)
t.setTag(name + "_" + n, tmp)
}
}
def load(t: NBTTagCompound, kind: UpdateKind.Value) {
map.clear()
for (i <- 0 until slots) {
if (t.hasKey(name + "_" + i)) {
val cfg = t.getCompoundTag(name + "_" + i)
val cfgObj = cfg.getString("kind") match {
case "power" => new OutputConfigPower
case "fluid" => new OutputConfigFluid
case _ => new OutputConfigInvalid
}
cfgObj.read(cfg)
map += i -> cfgObj
}
}
}
def updated() = parent.dataSlotChanged(this)
}
object DataSlotOutputConfig {
import scala.language.implicitConversions
implicit def dsbfm2map(v: DataSlotOutputConfig) = v.map
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.Misc
import net.bdew.lib.block.BlockRef
import net.bdew.lib.data.DataSlotOption
import net.bdew.lib.data.base.{TileDataSlots, UpdateKind}
import net.minecraft.nbt.NBTTagCompound
case class DataSlotPos(name: String, parent: TileDataSlots) extends DataSlotOption[BlockRef] {
setUpdate(UpdateKind.SAVE, UpdateKind.WORLD)
def save(t: NBTTagCompound, kind: UpdateKind.Value) {
cval map (x => t.setTag(name, Misc.applyMutator(x.writeToNBT, new NBTTagCompound)))
}
def load(t: NBTTagCompound, kind: UpdateKind.Value) {
cval = if (t.hasKey(name))
Some(BlockRef.fromNBT(t.getCompoundTag(name)))
else
None
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.Misc
import net.bdew.lib.block.BlockRef
import net.bdew.lib.data.base.{DataSlot, TileDataSlots, UpdateKind}
import net.minecraft.nbt.{NBTTagCompound, NBTTagList}
case class DataSlotPosSet(name: String, parent: TileDataSlots) extends DataSlot {
val set = collection.mutable.Set.empty[BlockRef]
setUpdate(UpdateKind.SAVE, UpdateKind.WORLD)
def save(t: NBTTagCompound, kind: UpdateKind.Value) {
val lst = new NBTTagList()
for (x <- set) lst.appendTag(Misc.applyMutator(x.writeToNBT, new NBTTagCompound))
t.setTag(name, lst)
}
def load(t: NBTTagCompound, kind: UpdateKind.Value) {
set.clear()
set ++= Misc.iterNbtCompoundList(t, name) map BlockRef.fromNBT
}
def updated() = parent.dataSlotChanged(this)
}
object DataSlotPosSet {
import scala.language.implicitConversions
implicit def dsps2set(v: DataSlotPosSet) = v.set
}
@@ -0,0 +1,26 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.multiblock.network.MsgOutputCfg
import net.minecraft.nbt.NBTTagCompound
import sun.reflect.generics.reflectiveObjects.NotImplementedException
abstract class OutputConfig {
def read(t: NBTTagCompound)
def write(t: NBTTagCompound)
def handleConfigPacket(m: MsgOutputCfg)
}
class OutputConfigInvalid extends OutputConfig {
def read(t: NBTTagCompound) {}
def write(t: NBTTagCompound) = throw new NotImplementedException
def handleConfigPacket(m: MsgOutputCfg) = throw new NotImplementedException
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.multiblock.network.MsgOutputCfg
import net.minecraft.nbt.NBTTagCompound
class OutputConfigFluid extends OutputConfig with OutputConfigRSControllable {
var avg = 0.0
var rsMode = RSMode.ALWAYS
final val decay = 0.5
def updateAvg(v: Double) {
avg = avg * decay + (1 - decay) * v
}
def read(t: NBTTagCompound) {
avg = t.getDouble("avg")
rsMode = RSMode(t.getInteger("rsMode"))
}
def write(t: NBTTagCompound) {
t.setDouble("avg", avg)
t.setInteger("rsMode", rsMode.id)
}
def handleConfigPacket(m: MsgOutputCfg) = m match {
case MsgOutputCfgRSMode(_, r) => rsMode = r
case _ => sys.error("Invalid output config packet %s to config %s".format(m, this))
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.multiblock.network.MsgOutputCfg
import net.minecraft.nbt.NBTTagCompound
class OutputConfigPower(var unit: String = "MJ") extends OutputConfig with OutputConfigRSControllable {
var avg = 0.0
var rsMode = RSMode.ALWAYS
final val decay = 0.5
def updateAvg(v: Double) {
avg = avg * decay + (1 - decay) * v
}
def read(t: NBTTagCompound) {
avg = t.getDouble("avg")
rsMode = RSMode(t.getInteger("rsMode"))
unit = t.getString("unit")
}
def write(t: NBTTagCompound) {
t.setDouble("avg", avg)
t.setInteger("rsMode", rsMode.id)
t.setString("unit", unit)
}
def handleConfigPacket(m: MsgOutputCfg) = m match {
case MsgOutputCfgRSMode(_, r) => rsMode = r
case _ => sys.error("Invalid output config packet %s to config %s".format(m, this))
}
}
@@ -0,0 +1,18 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.multiblock.data
import net.bdew.lib.multiblock.network.MsgOutputCfg
case class MsgOutputCfgRSMode(output: Int, rsMode: RSMode.Value) extends MsgOutputCfg
trait OutputConfigRSControllable extends OutputConfig {
var rsMode: RSMode.Value
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.data
object RSMode extends Enumeration {
val ALWAYS = Value(0, "ALWAYS")
val RS_ON = Value(1, "RS_ON")
val RS_OFF = Value(2, "RS_OFF")
val NEVER = Value(3, "NEVER")
}
@@ -0,0 +1,28 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.gui
import net.bdew.lib.gui.widgets.Widget
import net.bdew.lib.gui.{Color, Point, Rect, Texture}
import scala.collection.mutable
class WidgetInfo(val rect: Rect, icon: Texture, text: => String, tooltip: => String) extends Widget {
final val iconRect = Rect(1, 1, 8, 8)
override def handleTooltip(p: Point, tip: mutable.MutableList[String]) {
if (iconRect.contains(p) && tooltip != null) tip += tooltip
}
override def draw(mouse: Point) {
parent.drawTexture(iconRect + rect.origin, icon)
parent.drawText(text, rect.origin +(12, 1), Color.darkgray, false)
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.gui
import net.bdew.lib.Misc
import net.bdew.lib.gui.widgets.Widget
import net.bdew.lib.gui.{Point, Rect, Texture}
import net.bdew.lib.multiblock.interact.CIOutputFaces
import net.bdew.lib.render.connected.BlockAdditionalRender
import scala.collection.mutable
class WidgetOutputIcon(p: Point, te: CIOutputFaces, output: Int) extends Widget {
val rect = new Rect(p, 16, 16)
override def draw(mouse: Point) {
val faces = te.outputFaces.inverted
if (faces.isDefinedAt(output)) {
val bf = faces(output)
bf.origin.block(te.getWorldObj) map { block =>
parent.drawTexture(rect, Texture(Texture.BLOCKS, block.getIcon(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face.ordinal())))
if (block.isInstanceOf[BlockAdditionalRender]) {
for (over <- block.asInstanceOf[BlockAdditionalRender].getFaceOverlays(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face))
parent.drawTexture(rect, Texture(Texture.BLOCKS, over.icon), over.color)
}
}
} else {
parent.drawTexture(rect, Texture(Texture.BLOCKS, te.resources.disabled), te.resources.outputColors(output))
}
}
override def handleTooltip(p: Point, tip: mutable.MutableList[String]) {
val faces = te.outputFaces.inverted
tip += Misc.toLocal(te.resources.unlocalizedOutputName(output))
if (faces.isDefinedAt(output)) {
val bf = faces(output)
bf.origin.block(te.getWorldObj) map { block =>
tip += block.getLocalizedName
tip += "%d, %d, %d - %s".format(bf.x, bf.y, bf.z, Misc.toLocal("bdlib.multiblock.face." + bf.face.toString.toLowerCase))
}
} else {
tip += Misc.toLocal("bdlib.multiblock.disabled")
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.multiblock.gui
import net.bdew.lib.Misc
import net.bdew.lib.gui.widgets.{WidgetButtonIcon, WidgetSubcontainer}
import net.bdew.lib.gui.{Point, Rect}
import net.bdew.lib.multiblock.data.{MsgOutputCfgRSMode, OutputConfigRSControllable, RSMode}
import net.bdew.lib.multiblock.interact.CIOutputFaces
import net.bdew.lib.multiblock.network.NetHandler
class WidgetRSConfig(te: CIOutputFaces, output: Int, p: Point) extends WidgetSubcontainer(new Rect(p, 16, 16)) {
def cfg = te.outputConfig(output).asInstanceOf[OutputConfigRSControllable]
val bt = add(new WidgetButtonIcon(Point(0, 0), clicked, te.resources.btBase, te.resources.btHover))
val icons = Map(
RSMode.ALWAYS -> te.resources.btEnabled,
RSMode.NEVER -> te.resources.btDisabled,
RSMode.RS_ON -> te.resources.btRsOn,
RSMode.RS_OFF -> te.resources.btRsOff
)
val next = Map(
RSMode.ALWAYS -> RSMode.RS_ON,
RSMode.RS_ON -> RSMode.RS_OFF,
RSMode.RS_OFF -> RSMode.NEVER,
RSMode.NEVER -> RSMode.ALWAYS
)
override def draw(mouse: Point) {
bt.icon = icons(cfg.rsMode)
bt.hover = Misc.toLocal("bdlib.rsmode." + cfg.rsMode.toString.toLowerCase)
super.draw(mouse)
}
def clicked(b: WidgetButtonIcon) {
NetHandler.sendToServer(MsgOutputCfgRSMode(output, next(cfg.rsMode)))
}
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.interact
import net.bdew.lib.multiblock.tile.TileController
import net.minecraftforge.fluids.{Fluid, FluidStack, FluidTankInfo}
trait CIFluidInput extends TileController {
def inputFluid(resource: FluidStack, doFill: Boolean): Int
def canInputFluid(fluid: Fluid): Boolean
def getTankInfo: Array[FluidTankInfo]
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.multiblock.interact
import net.minecraftforge.fluids.{Fluid, FluidStack, FluidTankInfo}
trait CIFluidOutput extends CIOutputFaces {
def outputFluid(resource: FluidStack, doDrain: Boolean): FluidStack
def outputFluid(ammount: Int, doDrain: Boolean): FluidStack
def canOutputFluid(fluid: Fluid): Boolean
def getTankInfo: Array[FluidTankInfo]
}
@@ -0,0 +1,71 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.interact
import net.bdew.lib.block.{BlockFace, BlockRef}
import net.bdew.lib.multiblock.data._
import net.bdew.lib.multiblock.tile.{TileController, TileModule}
import net.minecraft.util.ChatComponentTranslation
import net.minecraftforge.common.util.ForgeDirection
trait CIOutputFaces extends TileController {
val maxOutputs: Int
val outputFaces = new DataSlotBlockFaceMap("outputs", this)
val outputConfig = new DataSlotOutputConfig("cfg", this, maxOutputs)
def newOutput(bp: BlockRef, face: ForgeDirection, cfg: OutputConfig): Int = {
val bf = BlockFace(bp, face)
if (outputFaces.contains(bf)) {
println("Adding already registered output??? " + bf.toString)
return outputFaces(bf)
}
val rv = outputFaces.inverted
for (i <- 0 until maxOutputs if !rv.contains(i)) {
outputFaces += (bf -> i)
outputConfig += i -> cfg
outputFaces.updated()
return i
}
val pl = getWorldObj.getClosestPlayer(bf.x, bf.y, bf.z, 10)
if (pl != null) pl.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.toomanyoutputs"))
return -1
}
serverTick.listen(doOutputs)
override def moduleRemoved(module: TileModule) {
for ((bf, n) <- outputFaces if bf.origin == module.mypos) {
outputFaces -= bf
outputConfig -= n
}
outputFaces.updated()
outputConfig.updated()
super.moduleRemoved(module)
}
def doOutputs() {
for {
(x, n) <- outputFaces
t <- x.origin.getTile[MIOutput[_]](getWorldObj)
} {
if (!outputConfig.isDefinedAt(n) || !t.outputConfigType.isInstance(outputConfig(n)))
outputConfig(n) = t.makeCfgObject(x.face)
t.doOutput(x.face, outputConfig(n).asInstanceOf[t.OCType])
}
}
def removeOutput(bp: BlockRef, face: ForgeDirection) {
val bf = BlockFace(bp, face)
outputConfig -= outputFaces(bf)
outputFaces -= bf
outputFaces.updated()
}
}
@@ -0,0 +1,14 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.interact
trait CIPowerProducer extends CIOutputFaces {
def extract(v: Float, simulate: Boolean): Float
}
@@ -0,0 +1,16 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.interact
import net.minecraft.inventory.Container
trait ContainerOutputFaces extends Container {
def te: CIOutputFaces
}
@@ -0,0 +1,23 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.interact
import net.bdew.lib.multiblock.data.OutputConfig
import net.bdew.lib.multiblock.tile.TileModule
import net.minecraftforge.common.util.ForgeDirection
trait MIOutput[T <: OutputConfig] extends TileModule {
val outputConfigType: Class[T]
type OCType = T
def doOutput(face: ForgeDirection, cfg: OCType)
def makeCfgObject(face: ForgeDirection): OutputConfig
}
@@ -0,0 +1,16 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.network
import net.bdew.lib.network.BaseMessage
abstract class MsgOutputCfg extends BaseMessage[NetHandler.type] {
val output: Int
}
@@ -0,0 +1,23 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.network
import net.bdew.lib.multiblock.interact.ContainerOutputFaces
import net.bdew.lib.network.NetChannel
import net.minecraft.entity.player.EntityPlayerMP
object NetHandler extends NetChannel("bdew.multiblock") {
regServerHandler {
case (msg: MsgOutputCfg, p: EntityPlayerMP) =>
val te = p.openContainer.asInstanceOf[ContainerOutputFaces].te
te.outputConfig(msg.output).handleConfigPacket(msg)
te.outputConfig.updated()
}
}
@@ -0,0 +1,21 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.multiblock.tile
import net.bdew.lib.multiblock.data.{OutputConfigRSControllable, RSMode}
import net.minecraft.tileentity.TileEntity
trait RSControllableOutput extends TileEntity {
def checkCanOutput(cfg: OutputConfigRSControllable): Boolean = {
if (cfg.rsMode == RSMode.ALWAYS) return true
if (cfg.rsMode == RSMode.NEVER) return false
return getWorldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord) ^ (cfg.rsMode == RSMode.RS_OFF)
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.tile
import net.bdew.lib.BdLib
import net.bdew.lib.block.BlockRef
import net.bdew.lib.data.base.{TileDataSlots, UpdateKind}
import net.bdew.lib.multiblock.block.BlockModule
import net.bdew.lib.multiblock.data.DataSlotPosSet
import net.bdew.lib.multiblock.{MachineCore, ResourceProvider, Tools}
import net.minecraft.entity.player.EntityPlayer
trait TileController extends TileDataSlots {
val modules = new DataSlotPosSet("modules", this).setUpdate(UpdateKind.WORLD, UpdateKind.SAVE, UpdateKind.RENDER)
def resources: ResourceProvider
def cfg: MachineCore
var acceptNewModules = true
var revalidateOnNextTick = true
var modulesChanged = true
lazy val mypos = BlockRef(xCoord, yCoord, zCoord)
def getNumOfMoudules(kind: String) = modules.map(_.getTile[TileModule](getWorldObj)).flatten.count(_.kind == kind)
def onModulesChanged()
def onClick(player: EntityPlayer)
def moduleConnected(module: TileModule): Boolean = {
if (acceptNewModules) {
modules.add(BlockRef(module.xCoord, module.yCoord, module.zCoord))
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
modulesChanged = true
return true
} else false
}
def moduleRemoved(module: TileModule) {
modules.remove(BlockRef(module.xCoord, module.yCoord, module.zCoord))
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
revalidateOnNextTick = true
modulesChanged = true
}
def onBreak() {
acceptNewModules = false
for (x <- modules.flatMap(_.getTile[TileModule](getWorldObj)))
x.coreRemoved()
modules.clear()
}
def validateModules() {
modules.filter(x => {
!x.getTile[TileModule](getWorldObj).isDefined || !x.getBlock[BlockModule[TileModule]](getWorldObj).isDefined
}).foreach(x => {
BdLib.logWarn("Block at %s is not a valid module, removing from machine %s at %d,%d,%d", x, this.getClass.getSimpleName, xCoord, yCoord, zCoord)
modules.remove(x)
})
val reachable = Tools.findReachableModules(getWorldObj, mypos)
val toremove = modules.filterNot(reachable.contains).flatMap(_.getTile[TileModule](getWorldObj))
acceptNewModules = false
toremove.foreach(moduleRemoved)
toremove.foreach(_.coreRemoved())
acceptNewModules = true
modulesChanged = true
modules.map(x =>
(x.getBlock[BlockModule[TileModule]](getWorldObj).orNull, x.getTile[TileModule](getWorldObj).orNull)
).filter({ case (a, b) => a.kind != b.kind }).foreach({ case (a, b) => sys.error("Type mismatch between Block/Tile Block=%s(%s) Tile=%s(%s)".format(a.kind, a, b.kind, b)) })
}
serverTick.listen(() => {
if (revalidateOnNextTick) {
revalidateOnNextTick = false
validateModules()
}
if (modulesChanged) {
modulesChanged = false
onModulesChanged()
lastChange = getWorldObj.getTotalWorldTime
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
}
})
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.tile
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.{ChatComponentTranslation, ChatStyle, EnumChatFormatting}
abstract class TileControllerGui extends TileController {
def openGui(player: EntityPlayer)
def onClick(player: EntityPlayer) = {
val missing = cfg.required.filter({ case (mod, cnt) => getNumOfMoudules(mod) < cnt })
if (missing.size > 0) {
player.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.incomplete")
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED)))
for ((mod, cnt) <- missing)
player.addChatMessage(
new ChatComponentTranslation("- %s %s", Integer.valueOf(cnt),
new ChatComponentTranslation(resources.getModuleName(mod)))
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED)))
} else openGui(player)
}
}
@@ -0,0 +1,57 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.tile
import net.bdew.lib.block.BlockRef
import net.bdew.lib.data.base.{TileDataSlots, UpdateKind}
import net.bdew.lib.multiblock.Tools
import net.bdew.lib.multiblock.data.DataSlotPos
import scala.reflect.ClassTag
trait TileModule extends TileDataSlots {
val kind: String
val connected = new DataSlotPos("connected", this).setUpdate(UpdateKind.WORLD, UpdateKind.SAVE, UpdateKind.RENDER)
def getCoreAs[T <: TileController : ClassTag] = connected flatMap (_.getTile[T](getWorldObj))
def getCore = getCoreAs[TileController]
lazy val mypos = BlockRef(xCoord, yCoord, zCoord)
def connect(target: TileController) {
if (target.moduleConnected(this)) {
connected.set(target.mypos)
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
getWorldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType)
}
}
def coreRemoved() {
connected.unset()
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
getWorldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType)
}
def onBreak() {
getCore map (_.moduleRemoved(this))
}
def tryConnect() {
if (getCore.isEmpty) {
for {
conn <- Tools.findConnections(getWorldObj, mypos, kind).headOption
core <- conn.getTile[TileController](getWorldObj)
} {
connect(core)
}
}
}
}
@@ -0,0 +1,67 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.multiblock.tile
import net.bdew.lib.Misc
import net.bdew.lib.block.BlockFace
import net.bdew.lib.multiblock.data.OutputConfig
import net.bdew.lib.multiblock.interact.{CIOutputFaces, MIOutput}
import net.minecraftforge.common.util.ForgeDirection
abstract class TileOutput[T <: OutputConfig] extends TileModule with MIOutput[T] {
override def getCore = getCoreAs[CIOutputFaces]
def makeCfgObject(face: ForgeDirection): T
var rescanFaces = false
def getCfg(dir: ForgeDirection): Option[T] =
for {
core <- getCore
onum <- core.outputFaces.get(BlockFace(mypos, dir))
cfggen <- core.outputConfig.get(onum)
cfg <- Misc.asInstanceOpt(cfggen, outputConfigType)
} yield cfg
serverTick.listen(() => {
if (rescanFaces) {
rescanFaces = false
doRescanFaces()
}
})
override def tryConnect() {
super.tryConnect()
if (connected.isDefined) rescanFaces = true
}
def canConnectoToFace(d: ForgeDirection): Boolean
def onConnectionsChanged(added: Set[ForgeDirection], removed: Set[ForgeDirection]) {}
def doRescanFaces() {
getCore map { core =>
val connections = (
ForgeDirection.VALID_DIRECTIONS
filterNot { dir => core.modules.contains(mypos.neighbour(dir)) }
filter canConnectoToFace
).toSet
val known = core.outputFaces.filter(_._1.origin == mypos).map(_._1.face).toSet
val toAdd = connections -- known
val toRemove = known -- connections
toRemove.foreach(x => core.removeOutput(mypos, x))
toAdd.foreach(x => core.newOutput(mypos, x, makeCfgObject(x)))
if (toAdd.size > 0 || toRemove.size > 0) {
onConnectionsChanged(toAdd, toRemove)
getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
}
}
}
}
@@ -9,4 +9,4 @@
package net.bdew.lib.network
abstract class Message extends Serializable
abstract class BaseMessage[CH <: NetChannel] extends Serializable
+35 -4
View File
@@ -13,18 +13,49 @@ import java.util
import cpw.mods.fml.common.network.{FMLEmbeddedChannel, FMLOutboundHandler, NetworkRegistry}
import cpw.mods.fml.relauncher.Side
import io.netty.channel.{ChannelFutureListener, ChannelHandler}
import io.netty.channel.{ChannelFutureListener, ChannelHandler, ChannelHandlerContext, SimpleChannelInboundHandler}
import net.bdew.lib.{BdLib, Misc}
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.network.NetHandlerPlayServer
class NetChannel(val name: String) {
var channels: util.EnumMap[Side, FMLEmbeddedChannel] = null
type Message = BaseMessage[this.type]
object ServerHandler extends SimpleChannelInboundHandler[Message] {
def channelRead0(ctx: ChannelHandlerContext, msg: Message) {
try {
val player = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get.asInstanceOf[NetHandlerPlayServer].playerEntity
if (serverChain.isDefinedAt(msg, player))
serverChain(msg, player)
else
BdLib.logWarn("Unable to handle message from user %s: %s", player.getDisplayName, msg)
} catch {
case e: Throwable => BdLib.logErrorException("Error handling packet", e)
}
}
}
object ClientHandler extends SimpleChannelInboundHandler[Message] {
def channelRead0(ctx: ChannelHandlerContext, msg: Message) {
try {
if (clientChain.isDefinedAt(msg))
clientChain(msg)
else
BdLib.logWarn("Unable to handle message from server: %s", msg)
} catch {
case e: Throwable => BdLib.logErrorException("Error handling packet", e)
}
}
}
def init() {
if (channels != null) sys.error("Attempted to initalize a channel twice (%s)".format(name))
channels = NetworkRegistry.INSTANCE.newChannel(name, new SerializedMessageCodec)
BdLib.logInfo("Initialized network channel '%s' for mod '%s'", name, Misc.getActiveModId)
addHandler(Side.SERVER, new NetChannelServerHandler(this))
addHandler(Side.CLIENT, new NetChannelClientHandler(this))
addHandler(Side.SERVER, ServerHandler)
addHandler(Side.CLIENT, ClientHandler)
}
var clientChain = PartialFunction.empty[Message, Unit]
@@ -38,7 +69,7 @@ class NetChannel(val name: String) {
private def addHandler(side: Side, handler: ChannelHandler) {
val ch = channels.get(side)
val name = ch.findChannelHandlerNameForType(classOf[SerializedMessageCodec])
val name = ch.findChannelHandlerNameForType(classOf[SerializedMessageCodec[this.type]])
ch.pipeline().addAfter(name, side + "Handler", handler)
}
@@ -1,26 +0,0 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.network
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
import net.bdew.lib.BdLib
class NetChannelClientHandler(ch: NetChannel) extends SimpleChannelInboundHandler[Message] {
def channelRead0(ctx: ChannelHandlerContext, msg: Message) {
try {
if (ch.clientChain.isDefinedAt(msg))
ch.clientChain(msg)
else
BdLib.logWarn("Unable to handle message from server: %s", msg)
} catch {
case e: Throwable => BdLib.logErrorException("Error handling packet", e)
}
}
}
@@ -1,29 +0,0 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.network
import cpw.mods.fml.common.network.NetworkRegistry
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
import net.bdew.lib.BdLib
import net.minecraft.network.NetHandlerPlayServer
class NetChannelServerHandler(ch: NetChannel) extends SimpleChannelInboundHandler[Message] {
def channelRead0(ctx: ChannelHandlerContext, msg: Message) {
try {
val player = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get.asInstanceOf[NetHandlerPlayServer].playerEntity
if (ch.serverChain.isDefinedAt(msg, player))
ch.serverChain(msg, player)
else
BdLib.logWarn("Unable to handle message from user %s: %s", player.getDisplayName, msg)
} catch {
case e: Throwable => BdLib.logErrorException("Error handling packet", e)
}
}
}
@@ -21,8 +21,8 @@ import io.netty.handler.codec.MessageToMessageCodec
import net.bdew.lib.BdLib
@Sharable
class SerializedMessageCodec extends MessageToMessageCodec[FMLProxyPacket, Message] {
def encode(ctx: ChannelHandlerContext, msg: Message, out: util.List[AnyRef]) {
class SerializedMessageCodec[T <: NetChannel] extends MessageToMessageCodec[FMLProxyPacket, BaseMessage[T]] {
def encode(ctx: ChannelHandlerContext, msg: BaseMessage[T], out: util.List[AnyRef]) {
val buff = Unpooled.buffer()
val writer = new ObjectOutputStream(new ByteBufOutputStream(buff))
writer.writeObject(msg)
+61
View File
@@ -0,0 +1,61 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.player
import cpw.mods.fml.common.FMLCommonHandler
import cpw.mods.fml.common.eventhandler.SubscribeEvent
import cpw.mods.fml.common.gameevent.PlayerEvent._
import net.bdew.lib.BdLib
import net.minecraft.entity.player.EntityPlayer
import scala.collection.mutable
class PlayerCache[T] extends mutable.Map[EntityPlayer, T] {
var map = Map.empty[EntityPlayer, T]
BdLib.onServerStarting.listen(x => map = map.empty)
BdLib.onServerStopping.listen(x => map = map.empty)
FMLCommonHandler.instance().bus().register(this)
def updateIfNeeded(p: EntityPlayer, v: T): Boolean = {
if (map.get(p).contains(v)) {
false
} else {
map += p -> v
true
}
}
def reset(p: EntityPlayer) {
if (map.contains(p)) map -= p
}
override def get(p: EntityPlayer) = map.get(p)
override def +=(kv: (EntityPlayer, T)) = {
map += kv
this
}
override def -=(key: EntityPlayer) = {
map -= key
this
}
override def iterator = map.iterator
@SubscribeEvent
def hadlePlayerLogout(ev: PlayerLoggedOutEvent) = reset(ev.player)
@SubscribeEvent
def hadlePlayerChangedDimension(ev: PlayerChangedDimensionEvent) = reset(ev.player)
@SubscribeEvent
def hadlePlayerRespawn(ev: PlayerRespawnEvent) = reset(ev.player)
}
-213
View File
@@ -1,213 +0,0 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.recipes
/**
* Base class for everything that can be resolved to ItemStack or recipe component
* Actual processing is in:
* * [[net.bdew.lib.recipes.RecipeLoader.getRecipeComponent]]
* * [[net.bdew.lib.recipes.RecipeLoader.getConcreteStack]]
* * [[net.bdew.lib.recipes.RecipeLoader.getAllConcreteStacks]]
*
*/
abstract class StackRef
/**
* Ore Dictionary reference
* Syntax: OD:{identifier}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specOD]]
* @param id OD entry name
*/
case class StackOreDict(id: String) extends StackRef
/**
* Generic Referende
* Syntax: S:{modid}:{name}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specGenericStack]]
* @param mod modId of owner mod
* @param name name of the stack
*/
case class StackGeneric(mod: String, name: String) extends StackRef
/**
* Block reference
* Syntax: B:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specBlock]]
* @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage
*/
case class StackBlock(mod: String, name: String, meta: Int) extends StackRef
/**
* Item reference
* Syntax: I:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specItem]]
* @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage
*/
case class StackItem(mod: String, name: String, meta: Int) extends StackRef
/**
* Reference to an Item/Block/ItemStack pulic static field
* Syntax: {path}.{to}.{class}[{field}] [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specReflect]]
* @param cls Class name
* @param field Field name
* @param meta Metadata / Damage (Ignored for ItemStacks)
*/
case class StackReflect(cls: String, field: String, meta: Int) extends StackRef
/**
* Reference to an Item/Block/ItemStack pulic static getter
* Syntax: {path}.{to}.{class}.{method}({string}) [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specGetter]]
* @param cls Class name
* @param method Method name
* @param name Parameter to getter
* @param meta Metadata / Damage (Ignored for ItemStacks)
*/
case class StackGetter(cls: String, method: String, name: String, meta: Int) extends StackRef
/**
* Macro reference to a previous definition
* Syntax: ${char}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specMacro]]
* @param id The underlying character
*/
case class StackMacro(id: Char) extends StackRef
/**
* Base class for statements
* Actual processing is in [[net.bdew.lib.recipes.RecipeLoader.processStatement]]
*/
abstract class Statement
/**
* Base class for delayed statements (executed after everything is parsed)
* Actual processing is in [[net.bdew.lib.recipes.RecipeLoader.processDelayedStatements]]
*/
abstract class DelayedStatement extends Statement
/**
* Character assignment
* Syntax: {char} = {ref}
* Parser: [[net.bdew.lib.recipes.RecipeParser.charSpec]]
* @param char Character to assign
* @param spec ItemStack Reference
*/
case class StCharAssign(char: Char, spec: StackRef) extends DelayedStatement
/**
* Define class macro
* Syntax: def {id} = {name}
* Parser: [[net.bdew.lib.recipes.RecipeParser.classMacro]]
* @param id Macro identifier
* @param cls Class name
*/
case class StClassMacro(id: String, cls: String) extends DelayedStatement
/**
* Conditional block - checks if mod is loaded
* Syntax: ifMod {string} { {statements} } [else { {statements} }]
* Parser: [[net.bdew.lib.recipes.RecipeParser.ifMod]]
* @param mod mod and version to check [[cpw.mods.fml.common.versioning.VersionParser]]
* @param thn Statements to run if present
* @param els Statements to run otherwise
*/
case class StIfHaveMod(mod: String, thn: List[Statement], els: List[Statement]) extends Statement
/**
* Conditional block - checks if api is loaded
* Syntax: ifAPI {string} { {statements} } [else { {statements} }]
* Parser: [[net.bdew.lib.recipes.RecipeParser.ifApi]]
* @param mod API modid
* @param thn Statements to run if present
* @param els Statements to run otherwise
*/
case class StIfHaveAPI(mod: String, thn: List[Statement], els: List[Statement]) extends Statement
/**
* Conditional block - checks if mod is loaded
* Can contain only delayed statements
* Syntax: ifOreDict {string} { {statements} } [else { {statements} }]
* Parser: [[net.bdew.lib.recipes.RecipeParser.ifOreDict]]
* @param id Ore Dictionary Entry
* @param thn Statements to run if present
* @param els Statements to run otherwise
*/
case class StIfHaveOD(id: String, thn: List[DelayedStatement], els: List[DelayedStatement]) extends DelayedStatement
/**
* Removes previously defined recieps for a specific result
* @param res Recipes that produce this result will be cleared
*/
case class StClearRecipes(res: StackRef) extends Statement
/**
* Base class for staments that represent a crafting recipe
*/
abstract class CraftingStatement extends DelayedStatement {
def result: StackRef
}
/**
* Shaped recipe definition
*
* Syntax:
* XXX
* XXX => {result} [* {count}]
* XXX
*
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped3x3]]
*
* Syntax:
* XX
* XX => {result} [* {count}]
*
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped2x2]]
*
* Syntax: XXX XXX XXX => {result} [* {count}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped9]]
*
* @param rec Recipe pattern
* @param result Result reference
* @param cnt Number of output items
*/
case class StRecipeShaped(rec: Seq[String], result: StackRef, cnt: Int) extends CraftingStatement
/**
* Shapeless recipe definition
* Syntax: shapeless: {characters} => {result} [* {count}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShapeless]]
*
* @param rec Recipe pattehrn
* @param result Result reference
* @param cnt Number of output items
*/
case class StRecipeShapeless(rec: String, result: StackRef, cnt: Int) extends CraftingStatement
/**
* Smelting recipe definition
* Syntax: smelt: {input} => {output}, {XP}
* Parser [[net.bdew.lib.recipes.RecipeParser.recipeSmelting]]
*
* @param in Input Stack
* @param result Output Stack
* @param cnt Output Count
* @param xp XP for smelting
*/
case class StSmeltRecipe(in: StackRef, result: StackRef, cnt: Int, xp: Float) extends CraftingStatement
/**
* Used in statement processing to abort the current statement and show an error without a stack trace
*/
class StatementError(msg: String) extends Exception(msg)
+109 -61
View File
@@ -21,7 +21,7 @@ import net.minecraftforge.oredict.{OreDictionary, ShapelessOreRecipe}
/**
* Main recipe loader class
* The input file is parsed by [[net.bdew.lib.recipes.RecipeParser]]
* Into a list of [[net.bdew.lib.recipes.Statement]] subclasses
* Into a list of [[net.bdew.lib.recipes.ConfigStatement]] subclasses
* That are then executed here
*/
@@ -49,9 +49,9 @@ class RecipeLoader {
def error(msg: String, params: Any*) = throw new StatementError(msg.format(params: _*))
/**
* List of unprocessed delayed statements
* List of unprocessed recipe statements
*/
var delayedStatements = List.empty[DelayedStatement]
var recipeStatements = List.empty[RecipeStatement]
/**
* Looks up a recipe component
@@ -67,11 +67,10 @@ class RecipeLoader {
/**
* Resolve class name if it's a macro
*/
def getRealClassName(s: String): String = {
if (s.startsWith("$")) {
return currClassMacros(s.stripPrefix("$"))
}
return s
def getRealClassName(s: String) = {
if (s.startsWith("$"))
currClassMacros(s.stripPrefix("$"))
else s
}
/**
* Sanitize items from reflection
@@ -207,62 +206,83 @@ class RecipeLoader {
return (comp, needOd)
}
/**
* Helper to remove recipes from lists
* @param list list to check
* @param res crafting result to remove
* @return cleaned list
*/
def clearStatements(list: List[RecipeStatement], res: StackRef): List[RecipeStatement] = {
list flatMap {
case x: CraftingStatement =>
if (res == x.result) {
BdLib.logInfo("Removing recipe %s", this)
None
} else Some(x)
case RsRecipes(inner) =>
Some(RsRecipes(clearStatements(inner, res)))
case RsConditional(cnd, thn, els) =>
Some(RsConditional(cnd, clearStatements(thn, res), clearStatements(els, res)))
case x => Some(x)
}
}
/**
* Checks a condition and returns the result
*/
def resolveCondition(cond: Condition): Boolean = cond match {
case CndHaveMod(mod) =>
Misc.haveModVersion(mod)
case CndHaveAPI(api) =>
ModAPIManager.INSTANCE.hasAPI(api)
case CndHaveOD(od) =>
OreDictionary.getOres(od).size() > 0
case CndNOT(cnd) => !resolveCondition(cnd)
case CndAND(c1, c2) => resolveCondition(c1) && resolveCondition(c2)
case CndOR(c1, c2) => resolveCondition(c1) || resolveCondition(c2)
case x =>
error("Can't process %s - this is a programing bug!", x)
}
/**
* Process a single statement, override this to add more statements
* @param s The statement
*/
def processStatement(s: Statement): Unit = s match {
case StIfHaveMod(mod, thn, els) =>
if (Misc.haveModVersion(mod)) {
BdLib.logInfo("ifMod: %s found", mod)
processStatementsSafe(thn)
def processConfigStatement(s: ConfigStatement): Unit = s match {
case CsConditionalConfig(cnd, thn, els) =>
if (resolveCondition(cnd)) {
BdLib.logInfo("Condition %s - TRUE", cnd)
processConfigStatementsSafe(thn)
} else {
BdLib.logInfo("ifMod: %s not found", mod)
processStatementsSafe(els)
BdLib.logInfo("Condition %s - FALSE", cnd)
processConfigStatementsSafe(els)
}
case StIfHaveAPI(mod, thn, els) =>
if (ModAPIManager.INSTANCE.hasAPI(mod)) {
BdLib.logInfo("ifAPI: %s found", mod)
processStatementsSafe(thn)
} else {
BdLib.logInfo("ifAPI: %s not found", mod)
processStatementsSafe(els)
}
case StClearRecipes(res) =>
case CsClearRecipes(res) =>
BdLib.logInfo("Clearing recipes that produce %s", res)
delayedStatements = delayedStatements.filter({
x =>
if (x.isInstanceOf[CraftingStatement])
if (x.asInstanceOf[CraftingStatement].result == res) {
BdLib.logInfo("Removing recipe %s", x)
false
} else true
else true
})
recipeStatements = clearStatements(recipeStatements, res)
case x: DelayedStatement =>
delayedStatements :+= x
case CsRecipeBlock(lst) =>
recipeStatements :+= RsRecipes(lst)
case x =>
BdLib.logError("Can't process %s - this is a programing bug!", x)
}
/**
* Process a single delayed statement
* Process a single recipe statement
* @param st The statement
*/
def processDelayedStatement(st: DelayedStatement) = st match {
case StCharAssign(c, r) =>
def processRecipeStatement(st: RecipeStatement) = st match {
case RsCharAssign(c, r) =>
currCharMap += (c -> r)
BdLib.logInfo("Added %s = %s", c, r)
case StClassMacro(id, cls) =>
case RsClassMacro(id, cls) =>
currClassMacros += (id -> cls)
BdLib.logInfo("Added def %s = %s", id, cls)
case StRecipeShaped(rec, res, cnt) =>
case RsRecipeShaped(rec, res, cnt) =>
BdLib.logInfo("Adding shaped recipe %s => %s * %d", rec, res, cnt)
val (comp, needOd) = resolveRecipeComponents(rec.mkString(""))
val resStack = getConcreteStack(res, cnt)
@@ -279,7 +299,7 @@ class RecipeLoader {
BdLib.logInfo("Done... result=%s, od=%s", resStack, needOd)
case StRecipeShapeless(rec, res, cnt) =>
case RsRecipeShapeless(rec, res, cnt) =>
BdLib.logInfo("Adding shapeless recipe %s => %s * %d", rec, res, cnt)
val (comp, needOd) = resolveRecipeComponents(rec)
val resStack = getConcreteStack(res, cnt)
@@ -297,7 +317,7 @@ class RecipeLoader {
BdLib.logInfo("Done... result=%s, od=%s", resStack, needOd)
case StSmeltRecipe(in, out, cnt, xp) =>
case RsRecipeSmelting(in, out, cnt, xp) =>
BdLib.logInfo("Adding smelting recipe %s => %s * %d (%f xp)", in, out, cnt, xp)
val outStack = getConcreteStack(out, cnt)
if (outStack.getItemDamage == OreDictionary.WILDCARD_VALUE) {
@@ -309,36 +329,64 @@ class RecipeLoader {
BdLib.logInfo("added %s -> %s", inStack, outStack)
}
case StIfHaveOD(od, thn, els) =>
if (OreDictionary.getOres(od).size() > 0) {
BdLib.logInfo("ifOreDict: %s found".format(od))
processDelayedStatementsSafe(thn)
case RsConditional(cnd, thn, els) =>
if (resolveCondition(cnd)) {
BdLib.logInfo("Condition %s - TRUE", cnd)
processRecipeStatementsInSubcontext(thn)
} else {
BdLib.logInfo("ifOreDict: %s not found".format(od))
processDelayedStatementsSafe(els)
BdLib.logInfo("Condition %s - FALSE", cnd)
processRecipeStatementsInSubcontext(els)
}
case RsRecipes(list) =>
processRecipeStatementsInSubcontext(list)
case RsRegOredict(id, spec, wildcard) =>
BdLib.logInfo("Registering ore dictionary entry: %s -> %s", spec, id)
val stack = getConcreteStack(spec)
if (wildcard) {
BdLib.logInfo("Forcing wildcard damage (was %d)", stack.getItemDamage)
stack.setItemDamage(OreDictionary.WILDCARD_VALUE)
}
BdLib.logInfo("Actual stack: %s", stack)
OreDictionary.registerOre(id, stack)
case x =>
BdLib.logError("Can't process %s - this is a programing bug!", x)
}
/**
* Process main delayed statements list, clear the list afterwards
* Processes recipe statements in a new context
* Any changes to mutable state will not persist when this method returns
*/
def processDelayedStatements() {
BdLib.logInfo("Processing %d delayed statements", delayedStatements.size)
processDelayedStatementsSafe(delayedStatements)
delayedStatements = List.empty
def processRecipeStatementsInSubcontext(list: List[RecipeStatement]) = {
val oldCharMap = currCharMap
val oldClassMacros = currClassMacros
try {
processRecipeStatementsSafe(list)
} finally {
currCharMap = oldCharMap
currClassMacros = oldClassMacros
}
}
/**
* Process a list of delayed statements and catch all exceptions
* Process main recipe statements list, clear the list afterwards
*/
def processRecipeStatements() {
BdLib.logInfo("Processing %d recipe statements", recipeStatements.size)
processRecipeStatementsSafe(recipeStatements)
recipeStatements = List.empty
}
/**
* Process a list of recipe statements and catch all exceptions
* @param list The list to process
*/
def processDelayedStatementsSafe(list: List[DelayedStatement]) {
def processRecipeStatementsSafe(list: List[RecipeStatement]) {
for (s <- list) {
try {
processDelayedStatement(s)
processRecipeStatement(s)
} catch {
case e: StatementError =>
BdLib.logError("Error while processing %s: %s", s, e.getMessage)
@@ -349,13 +397,13 @@ class RecipeLoader {
}
/**
* Process a list of statements and catch all exceptions
* Process a list of config statements and catch all exceptions
* @param r The list to process
*/
def processStatementsSafe(r: List[Statement]): Unit = {
def processConfigStatementsSafe(r: List[ConfigStatement]): Unit = {
for (s <- r) {
try {
processStatement(s)
processConfigStatement(s)
} catch {
case e: StatementError =>
BdLib.logError("Error while processing %s: %s", s, e.getMessage)
@@ -369,7 +417,7 @@ class RecipeLoader {
BdLib.logInfo("Starting parsing")
val r = newParser().doParse(f)
BdLib.logInfo("Processing %d statements", r.size)
processStatementsSafe(r)
processConfigStatementsSafe(r)
BdLib.logInfo("Done")
}
}
+55 -28
View File
@@ -68,68 +68,95 @@ class RecipeParser extends JavaTokenParsers {
// Spec with possible number of items
def specWithCount = spec ~ ("*" ~> int).?
// === Conditions ===
def cndHaveMod = "HaveMod" ~> str ^^ CndHaveMod
def cndHaveAPI = "HaveAPI" ~> str ^^ CndHaveAPI
def cndHaveOD = "HaveOD" ~> str ^^ CndHaveOD
def cndNOT = "!" ~> condition ^^ CndNOT
def cndOR = "(" ~> condition ~ "||" ~ condition <~ ")" ^^ { case c1 ~ or ~ c2 => CndOR(c1, c2) }
def cndAND = "(" ~> condition ~ "&&" ~ condition <~ ")" ^^ { case c1 ~ and ~ c2 => CndAND(c1, c2) }
def condition: Parser[Condition] = cndHaveAPI | cndHaveMod | cndHaveOD | cndNOT | cndOR | cndAND
// === Blocks ===
def recipesSubBlock = "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ RsRecipes
def recipesTopBlock = "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ CsRecipeBlock
def conditionRecipes = "if" ~> condition ~ ("{" ~> recipeStatements <~ "}") ~ ("else" ~> "{" ~> recipeStatements <~ "}").? ^^ {
case cond ~ thn ~ els => new RsConditional(cond, thn, els.getOrElse(List.empty))
}
def conditionConfig = "if" ~> condition ~ ("<<" ~> configStatements <~ ">>") ~ ("else" ~> "<<" ~> configStatements <~ ">>").? ^^ {
case cond ~ thn ~ els => new CsConditionalConfig(cond, thn, els.getOrElse(List.empty))
}
def conditionBridge = conditionRecipes ^^ { case cond => CsRecipeBlock(List(cond)) }
// === Statements ===
def charSpec = recipeChar ~ "=" ~ spec ^^ {
case ch ~ eq ~ spec => new StCharAssign(ch, spec)
case ch ~ eq ~ spec => new RsCharAssign(ch, spec)
}
def classMacro = ("def" ~> ident <~ "=") ~ clsPath ^^ {
case id ~ (p ~ cl) => StClassMacro(id, (p :+ cl).mkString("."))
}
def ifMod = ("ifMod" ~> str) ~ ("{" ~> statements <~ "}") ~ ("else" ~> "{" ~> statements <~ "}").? ^^ {
case mod ~ thn ~ els => new StIfHaveMod(mod, thn, els.getOrElse(List.empty[Statement]))
}
def ifAPI = ("ifAPI" ~> str) ~ ("{" ~> statements <~ "}") ~ ("else" ~> "{" ~> statements <~ "}").? ^^ {
case mod ~ thn ~ els => new StIfHaveAPI(mod, thn, els.getOrElse(List.empty[Statement]))
}
def ifOreDict = ("ifOreDict" ~> str) ~ ("{" ~> delayedStatements <~ "}") ~ ("else" ~> "{" ~> delayedStatements <~ "}").? ^^ {
case id ~ thn ~ els => new StIfHaveOD(id, thn, els.getOrElse(List.empty[DelayedStatement]))
case id ~ (p ~ cl) => RsClassMacro(id, (p :+ cl).mkString("."))
}
def recipeShaped3x3 = recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ~ recipeTriplet ^^ {
case r1 ~ r2 ~ (res ~ n) ~ r3 => StRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1))
case r1 ~ r2 ~ (res ~ n) ~ r3 => RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1))
}
def recipeShaped2x2 = recipeDuplet ~ recipeDuplet ~ ("=>" ~> specWithCount) ^^ {
case r1 ~ r2 ~ (res ~ n) => StRecipeShaped(Seq(r1, r2), res, n.getOrElse(1))
case r1 ~ r2 ~ (res ~ n) => RsRecipeShaped(Seq(r1, r2), res, n.getOrElse(1))
}
def recipeShaped9 = recipeTriplet ~ recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ^^ {
case r1 ~ r2 ~ r3 ~ (res ~ n) => StRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1))
case r1 ~ r2 ~ r3 ~ (res ~ n) => RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1))
}
def recipeShapeless = "shapeless" ~> ":" ~> recipeChar.+ ~ ("=>" ~> specWithCount) ^^ {
case r ~ (res ~ n) => StRecipeShapeless(r.mkString(""), res, n.getOrElse(1))
case r ~ (res ~ n) => RsRecipeShapeless(r.mkString(""), res, n.getOrElse(1))
}
def recipeSmelting = "smelt" ~> ":" ~> spec ~ ("=>" ~> specWithCount) ~ ("," ~> decimalNumber).? ^^ {
case in ~ (out ~ n) ~ xp => StSmeltRecipe(in, out, n.getOrElse(1), xp.getOrElse("0").toFloat)
def recipeSmelting = "smelt" ~> ":" ~> spec ~ ("=>" ~> specWithCount) ~ ("+" ~> decimalNumber <~ "xp").? ^^ {
case in ~ (out ~ n) ~ xp => RsRecipeSmelting(in, out, n.getOrElse(1), xp.getOrElse("0").toFloat)
}
def clearRecipes = "clearRecipes" ~> ":" ~> spec ^^ { case sp => StClearRecipes(sp) }
def regOreDict = "regOreDict" ~> ":" ~> spec ~ "@WILDCARD".? ~ ("=>" ~> str) ^^ {
case spec ~ wildcard ~ id => RsRegOredict(id, spec, wildcard.isDefined)
}
def delayedStatement: Parser[DelayedStatement] = (
def clearRecipes = "clearRecipes" ~> ":" ~> spec ^^ { case sp => CsClearRecipes(sp) }
def recipeStatement: Parser[RecipeStatement] = (
charSpec
| classMacro
| ifOreDict
| recipesSubBlock
| conditionRecipes
| recipesSubBlock
| recipeShaped3x3
| recipeShaped2x2
| recipeShaped9
| recipeShapeless
| recipeSmelting
| regOreDict
)
def statement: Parser[Statement] = delayedStatement | ifMod | ifAPI | clearRecipes
def configStatement: Parser[ConfigStatement] = (
recipesTopBlock
| clearRecipes
| conditionBridge
| conditionConfig
)
def statements = statement.*
def delayedStatements = delayedStatement.*
def configStatements = configStatement.*
def recipeStatements = recipeStatement.*
def doParse(r: Reader): List[Statement] = {
parseAll(statements, r) match {
def doParse(r: Reader): List[ConfigStatement] = {
parseAll(configStatements, r) match {
case Success(res, next) => return res
case NoSuccess(msg, next) => sys.error("Config parsing failed at %s: %s".format(next.pos, msg))
}
@@ -0,0 +1,75 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.recipes
import java.io._
import cpw.mods.fml.common.FMLCommonHandler
import net.bdew.lib.BdLib
object RecipesHelper {
/**
* Perform full loading of a set of config
* @param modName Name of the mod, used in logging an derrors
* @param listResource Resource Name of the internal config list file
* @param configDir Base path to user config giles
* @param resBaseName Base resource name for internal config files
* @param loader Loader instance
*/
def loadConfigs(modName: String, listResource: String, configDir: File, resBaseName: String, loader: RecipeLoader) {
BdLib.logInfo("Loading internal config files for mod %s", modName)
val listReader = new BufferedReader(new InputStreamReader(getClass.getResourceAsStream(listResource)))
val internals = Iterator.continually(listReader.readLine)
.takeWhile(_ != null)
.map(_.trim)
.filterNot(_.startsWith("#"))
.filterNot(_.isEmpty)
.toList
listReader.close()
val overrideDir = new File(configDir, "overrides")
if (!overrideDir.exists()) overrideDir.mkdir()
for (fileName <- internals) {
val overrideFile = new File(overrideDir, fileName)
if (overrideFile.exists()) {
tryLoadConfig(new FileReader(overrideFile), overrideFile.getCanonicalPath, modName, loader)
} else {
val resname = resBaseName + fileName
tryLoadConfig(new InputStreamReader(getClass.getResourceAsStream(resname)),
getClass.getResource(resname).toString, modName, loader)
}
}
BdLib.logInfo("Loading user config files for mod %s", modName)
for (fileName <- configDir.list().sorted if fileName.endsWith(".cfg")) {
val file = new File(configDir, fileName)
if (file.canRead)
tryLoadConfig(new FileReader(file), file.getCanonicalPath, modName, loader)
}
BdLib.logInfo("Config loading for mod %s finished", modName)
}
def tryLoadConfig(reader: Reader, path: String, modName: String, loader: RecipeLoader) {
BdLib.logInfo("Loading config: %s", path)
try {
loader.load(reader)
} catch {
case e: Throwable =>
FMLCommonHandler.instance().raiseException(e, "%s config loading failed in file %s: %s".format(modName, path, e.getMessage), true)
} finally {
reader.close()
}
}
}
@@ -0,0 +1,16 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.recipes
/**
* Used in statement processing to abort the current statement and show an error without a stack trace
*/
class StatementError(msg: String) extends Exception(msg)
-44
View File
@@ -1,44 +0,0 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.recipes
import java.lang.reflect.Modifier
import net.minecraft.block.Block
import net.minecraft.item.Item
import scala.reflect.ClassTag
object Vanilla {
// Maps of vanilla blocks and items (without tile. / item. prefixes)
lazy val blocks = mkMap[Block](_.getUnlocalizedName.stripPrefix("tile.")).withDefault(x => throw new StatementError("Block %s not found".format(x)))
lazy val items = mkMap[Item](_.getUnlocalizedName.stripPrefix("item.")).withDefault(x => throw new StatementError("Item %s not found".format(x)))
/**
* Generates the maps
* @tparam T The base class
* @param namer A function that converts objects to names
*/
private def mkMap[T](namer: T => String)(implicit t: ClassTag[T]) = {
val c = t.runtimeClass
// Grab all the fields
c.getFields.filter(x => {
// Keep only static fields that match the base Class
c.isAssignableFrom(x.getType) && Modifier.isStatic(x.getModifiers)
}).map(x => {
// Retrieve the static value
val f = x.get(null).asInstanceOf[T]
// Convert to name -> object tuples
namer(f) -> f
}).toMap // and finally to a map
}
}
@@ -0,0 +1,62 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.recipes
/**
* Represents a condition, something that can be resolved to a boolean
* Actual processing is in [[RecipeLoader.resolveCondition]]
*
* Naming convention: All subclasses are named CndFoo
*/
abstract class Condition
/**
* True if mod is present
* Syntax: HaveMod {string}
* Parser: [[RecipeParser.cndHaveMod]]
* @param mod mod id
*/
case class CndHaveMod(mod: String) extends Condition
/**
* True if API is present
* Syntax: HaveAPI {string}
* Parser: [[RecipeParser.cndHaveAPI]]
*/
case class CndHaveAPI(api: String) extends Condition
/**
* True if oredict entery is present
* Syntax: HaveOD {string}
* Parser: [[RecipeParser.cndHaveOD]]
*/
case class CndHaveOD(od: String) extends Condition
/**
* Boolean NOT
* Syntax: ! {condition}
* Parser: [[RecipeParser.cndNOT]]
*/
case class CndNOT(cnd: Condition) extends Condition
/**
* Boolean AND
* Syntax: ( {condition} && {condition} )
* Parser: [[RecipeParser.cndAND]]
*/
case class CndAND(c1: Condition, c2: Condition) extends Condition
/**
* Boolean OR
* Syntax: ( {condition} || {condition} )
* Parser: [[RecipeParser.cndOR]]
*/
case class CndOR(c1: Condition, c2: Condition) extends Condition
@@ -0,0 +1,87 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.recipes
/**
* Represents something that can be resolved to ItemStack or recipe component
* Actual processing is in:
* * [[net.bdew.lib.recipes.RecipeLoader.getRecipeComponent]]
* * [[net.bdew.lib.recipes.RecipeLoader.getConcreteStack]]
* * [[net.bdew.lib.recipes.RecipeLoader.getAllConcreteStacks]]
*
* Naming convention: All subclasses are named StackFoo
*/
abstract class StackRef
/**
* Ore Dictionary reference
* Syntax: OD:{identifier}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specOD]]
* @param id OD entry name
*/
case class StackOreDict(id: String) extends StackRef
/**
* Generic Referende
* Syntax: S:{modid}:{name}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specGenericStack]]
* @param mod modId of owner mod
* @param name name of the stack
*/
case class StackGeneric(mod: String, name: String) extends StackRef
/**
* Block reference
* Syntax: B:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specBlock]]
* @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage
*/
case class StackBlock(mod: String, name: String, meta: Int) extends StackRef
/**
* Item reference
* Syntax: I:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specItem]]
* @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage
*/
case class StackItem(mod: String, name: String, meta: Int) extends StackRef
/**
* Reference to an Item/Block/ItemStack pulic static field
* Syntax: {path}.{to}.{class}[{field}] [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specReflect]]
* @param cls Class name
* @param field Field name
* @param meta Metadata / Damage (Ignored for ItemStacks)
*/
case class StackReflect(cls: String, field: String, meta: Int) extends StackRef
/**
* Reference to an Item/Block/ItemStack pulic static getter
* Syntax: {path}.{to}.{class}.{method}({string}) [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specGetter]]
* @param cls Class name
* @param method Method name
* @param name Parameter to getter
* @param meta Metadata / Damage (Ignored for ItemStacks)
*/
case class StackGetter(cls: String, method: String, name: String, meta: Int) extends StackRef
/**
* Macro reference to a previous definition
* Syntax: ${char}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specMacro]]
* @param id The underlying character
*/
case class StackMacro(id: Char) extends StackRef
@@ -0,0 +1,43 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.recipes
/**
* Base class for config statements
* Actual processing is in [[RecipeLoader.processConfigStatement]]
*/
abstract class ConfigStatement
/**
* Block of delayed statements, used to include recipe statements in config scope (which is always top level)
* Syntax: recipes { {statements} }
* Parser: [[RecipeParser.recipesTopBlock]]
* Also used internally by the parser to bridge [[RsConditional]] to config scope in [[RecipeParser.conditionBridge]]
* @param list Statements to run
*/
case class CsRecipeBlock(list: List[RecipeStatement]) extends ConfigStatement
/**
* Conditional config block
* Syntax: if {condition} << {statements} >> [else << {statements} >>]
* Parser: [[RecipeParser.conditionConfig]]
* @param cond Condition
* @param thn Statements to run if true
* @param els Statements to run otherwise
*/
case class CsConditionalConfig(cond: Condition, thn: List[ConfigStatement], els: List[ConfigStatement]) extends ConfigStatement
/**
* Removes previously defined recieps for a specific result
* Syntax: clearRecipes: {spec}
* Parser: [[RecipeParser.clearRecipes]]
* @param res Recipes that produce this result will be cleared
*/
case class CsClearRecipes(res: StackRef) extends ConfigStatement
@@ -0,0 +1,117 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.recipes
/**
* Base class for recipe statements
* Actual processing is in [[net.bdew.lib.recipes.RecipeLoader.processRecipeStatements]]
*
* Naming convention: All subclasses are named RsFoo
*/
abstract class RecipeStatement
/**
* Character assignment
* Syntax: {char} = {ref}
* Parser: [[net.bdew.lib.recipes.RecipeParser.charSpec]]
* @param char Character to assign
* @param spec ItemStack Reference
*/
case class RsCharAssign(char: Char, spec: StackRef) extends RecipeStatement
/**
* Define class macro
* Syntax: def {id} = {name}
* Parser: [[net.bdew.lib.recipes.RecipeParser.classMacro]]
* @param id Macro identifier
* @param cls Class name
*/
case class RsClassMacro(id: String, cls: String) extends RecipeStatement
/**
* Unconditional block - allows grouping and isolation of statements
* Syntax: recipes { {statements} }
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipesSubBlock]]
* @param list Statements to run
*/
case class RsRecipes(list: List[RecipeStatement]) extends RecipeStatement
/**
* Conditional recipes block
* Syntax: if {condition} recipes { {statements} } [else { {statements} }]
* Parser: [[net.bdew.lib.recipes.RecipeParser.conditionRecipes]]
* @param cond Condition
* @param thn Statements to run if true
* @param els Statements to run otherwise
*/
case class RsConditional(cond: Condition, thn: List[RecipeStatement], els: List[RecipeStatement]) extends RecipeStatement
/**
* Base class for staments that represent a crafting recipe, that has a result
*/
abstract class CraftingStatement extends RecipeStatement {
def result: StackRef
}
/**
* Shaped recipe definition
*
* Syntax:
* XXX
* XXX => {result} [* {count}]
* XXX
*
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped3x3]]
*
* Syntax:
* XX
* XX => {result} [* {count}]
*
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped2x2]]
*
* Syntax: XXX XXX XXX => {result} [* {count}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped9]]
*
* @param rec Recipe pattern
* @param result Result reference
* @param cnt Number of output items
*/
case class RsRecipeShaped(rec: Seq[String], result: StackRef, cnt: Int) extends CraftingStatement
/**
* Shapeless recipe definition
* Syntax: shapeless: {characters} => {result} [* {count}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShapeless]]
*
* @param rec Recipe pattehrn
* @param result Result reference
* @param cnt Number of output items
*/
case class RsRecipeShapeless(rec: String, result: StackRef, cnt: Int) extends CraftingStatement
/**
* Smelting recipe definition
* Syntax: smelt: {input} => {output}, {XP}
* Parser [[net.bdew.lib.recipes.RecipeParser.recipeSmelting]]
*
* @param in Input Stack
* @param result Output Stack
* @param cnt Output Count
* @param xp XP for smelting
*/
case class RsRecipeSmelting(in: StackRef, result: StackRef, cnt: Int, xp: Float) extends CraftingStatement
/**
* Smelting recipe definition
* Syntax: regOreDict: {reference} -> {name}
* Parser [[net.bdew.lib.recipes.RecipeParser.regOreDict]]
*/
case class RsRegOredict(id: String, spec: StackRef, wildcard: Boolean) extends RecipeStatement
@@ -11,19 +11,21 @@ package net.bdew.lib.recipes.gencfg
import net.bdew.lib.gui.Color
abstract class CfgEntry
abstract class ConfigEntry
case class EntryDouble(v: Double) extends CfgEntry
case class EntryDouble(v: Double) extends ConfigEntry
case class EntryStr(v: String) extends CfgEntry
case class EntryStr(v: String) extends ConfigEntry
case class EntryNumList(v: List[Double]) extends CfgEntry
case class EntryNumList(v: List[Double]) extends ConfigEntry
case class ConfigSection(pfx: String = "") extends CfgEntry with Iterable[(String, CfgEntry)] {
var raw = Map.empty[String, CfgEntry].withDefault(x => sys.error("Config value '%s%s' is missing".format(pfx, x)))
case class ConfigSection(pfx: String = "") extends ConfigEntry with Iterable[(String, ConfigEntry)] {
var raw = Map.empty[String, ConfigEntry].withDefault(x => sys.error("Config value '%s%s' is missing".format(pfx, x)))
def iterator: Iterator[(String, CfgEntry)] = raw.iterator
def filterType[T <: CfgEntry](cls: Class[T]): Iterable[(String, T)] = raw.filter(x => cls.isInstance(x._2)).map(x => x.asInstanceOf[(String, T)])
def iterator: Iterator[(String, ConfigEntry)] = raw.iterator
def filterType[T <: ConfigEntry](cls: Class[T]): Iterable[(String, T)] = raw.filter(x => cls.isInstance(x._2)).map(x => x.asInstanceOf[(String, T)])
def keys = raw.keys
def rawget[T](id: String, t: Class[T]): T = {
val v = raw(id)
@@ -33,7 +35,7 @@ case class ConfigSection(pfx: String = "") extends CfgEntry with Iterable[(Strin
sys.error("Config value '%s%s' is of the wrong type, expected %s, got %s".format(pfx, id, t.getName, v.getClass.getName))
}
def set(id: String, v: CfgEntry) = raw += id -> v
def set(id: String, v: ConfigEntry) = raw += id -> v
def getDouble(id: String) = rawget(id, classOf[EntryDouble]).v
def getString(id: String) = rawget(id, classOf[EntryStr]).v
@@ -10,25 +10,26 @@
package net.bdew.lib.recipes.gencfg
import net.bdew.lib.BdLib
import net.bdew.lib.recipes.{RecipeLoader, Statement}
import net.bdew.lib.recipes.{ConfigStatement, RecipeLoader}
trait GenericConfigLoader extends RecipeLoader {
val cfgStore: ConfigSection
def processConfigStatement(section: ConfigSection, s: CfgStatement): Unit = s match {
def processConfigStatement(section: ConfigSection, s: CfgEntry): Unit = s match {
case CfgVal(id, v) =>
BdLib.logInfo("Config: %s%s = %s", section.pfx, id, v)
section.set(id, v)
case CfgSub(id, st) => processConfigBlock(section.getOrAddSection(id), st)
case CfgSection(id, st) => processConfigBlock(section.getOrAddSection(id), st)
case x =>
BdLib.logError("Can't process %s - this is a programing bug!", x)
}
def processConfigBlock(view: ConfigSection, block: List[CfgStatement]) = for (s <- block) processConfigStatement(view, s)
def processConfigBlock(view: ConfigSection, block: List[CfgEntry]): Unit =
for (s <- block) processConfigStatement(view, s)
override def processStatement(s: Statement) = s match {
case StCfg(id, st) => processConfigBlock(cfgStore.getOrAddSection(id), st)
case _ => super.processStatement(s)
override def processConfigStatement(s: ConfigStatement) = s match {
case CsCfgSection(id, st) => processConfigBlock(cfgStore.getOrAddSection(id), st)
case _ => super.processConfigStatement(s)
}
}
@@ -12,7 +12,7 @@ package net.bdew.lib.recipes.gencfg
import net.bdew.lib.recipes.RecipeParser
trait GenericConfigParser extends RecipeParser {
override def statement = statementCfg | super.statement
override def configStatement = statementCfg | super.configStatement
// Hex variant must come before decimalNumber, otherwise the parser breaks
def signedNumber = (
@@ -21,17 +21,21 @@ trait GenericConfigParser extends RecipeParser {
| ("-" ~> decimalNumber) ^^ { case x => -x.toDouble }
)
def cfgStatementNum = ident ~ "=" ~ signedNumber ^^ { case id ~ eq ~ n => CfgVal(id, EntryDouble(n.toDouble)) }
def cfgStatementStr = ident ~ "=" ~ str ^^ { case id ~ eq ~ s => CfgVal(id, EntryStr(s)) }
def cfgStatementNumList = ident ~ ("=" ~> "{" ~> signedNumber.* <~ "}") ^^ { case id ~ l => CfgVal(id, EntryNumList(l)) }
def cfgStatementSub = cfgBlock ^^ { case (id, st) => CfgSub(id, st) }
def cvNum = signedNumber ^^ EntryDouble
def cvStr = str ^^ EntryStr
def cvNumList = "=" ~> "{" ~> signedNumber.* <~ "}" ^^ EntryNumList
def cfgStatement = cfgStatementNum | cfgStatementStr | cfgStatementSub | cfgStatementNumList
def cfgValue = cvNum | cvStr | cvNumList
def ceSub = cfgBlock ^^ { case (id, st) => CfgSection(id, st) }
def ceAssign = str ~ "=" ~ cfgValue ^^ { case k ~ eq ~ v => CfgVal(k, v) }
def cfgEntry = ceSub | ceAssign
// A bit of type acrobatics because this is recursive (via cfgStatementSub)
// the tuple is translated into the proper class in either cfgStatementSub or cfg
def cfgBlock: Parser[(String, List[CfgStatement])] =
"cfg" ~> ident ~ ("{" ~> cfgStatement.* <~ "}") ^^ { case id ~ st => (id, st) }
def cfgBlock: Parser[(String, List[CfgEntry])] =
"cfg" ~> str ~ ("{" ~> cfgEntry.* <~ "}") ^^ { case id ~ st => (id, st) }
def statementCfg = cfgBlock ^^ { case (id, st) => StCfg(id, st) }
def statementCfg = cfgBlock ^^ { case (id, st) => CsCfgSection(id, st) }
}
@@ -9,15 +9,15 @@
package net.bdew.lib.recipes.gencfg
import net.bdew.lib.recipes.Statement
import net.bdew.lib.recipes.ConfigStatement
abstract class CfgStatement
abstract class CfgEntry
case class CfgVal(id: String, value: CfgEntry) extends CfgStatement
case class CfgVal(id: String, value: ConfigEntry) extends CfgEntry
case class CfgSub(id: String, vals: List[CfgStatement]) extends CfgStatement
case class CfgSection(id: String, vals: List[CfgEntry]) extends CfgEntry
case class StCfg(id: String, vals: List[CfgStatement]) extends Statement
case class CsCfgSection(id: String, vals: List[CfgEntry]) extends ConfigStatement
@@ -10,14 +10,14 @@
package net.bdew.lib.recipes.lootlist
import net.bdew.lib.recipes.StackRef
import net.bdew.lib.recipes.gencfg.CfgEntry
import net.bdew.lib.recipes.gencfg.ConfigEntry
/**
* Allos definition of random-weighted loot/drop lists in config sections
* Allows definition of random-weighted loot/drop lists in config sections
* @param list List on (chance percent, stack reference) pairs, resolve to
* real ItemStacks with LootListLoader.resolveLootList
*/
case class EntryLootList(list: List[(Int, StackRef)]) extends CfgEntry
case class EntryLootList(list: List[(Int, StackRef)]) extends ConfigEntry
@@ -9,17 +9,18 @@
package net.bdew.lib.recipes.lootlist
import net.bdew.lib.recipes.gencfg.{CfgVal, GenericConfigParser}
import net.bdew.lib.recipes.gencfg.GenericConfigParser
/**
* Parser mixin for loot lists
* ident: DropsList(
* ident = DropsList(
* {chance}% {stackRef}
* ...
* )
*/
trait LootListParser extends GenericConfigParser {
def dropsEntry = (wholeNumber <~ "%") ~ spec ^^ { case n ~ s => (n.toInt, s) }
def cfgDrops = ident ~ (":" ~> "DropsList" ~> "(" ~> dropsEntry.* <~ ")") ^^ { case id ~ a => CfgVal(id, EntryLootList(a)) }
override def cfgStatement = cfgDrops | super.cfgStatement
def ceDrops = "DropsList" ~> "(" ~> dropsEntry.* <~ ")" ^^ EntryLootList
override def cfgValue = ceDrops | super.cfgValue
}
@@ -0,0 +1,20 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.render
import cpw.mods.fml.client.registry.{ISimpleBlockRenderingHandler, RenderingRegistry}
abstract class BaseBlockRenderHandler extends ISimpleBlockRenderingHandler {
val id = RenderingRegistry.getNextAvailableRenderId
RenderingRegistry.registerBlockHandler(this)
override def shouldRender3DInInventory(modelId: Int) = true
override def getRenderId = id
}
+48
View File
@@ -0,0 +1,48 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://bdew.net/minecraft-mod-public-license/
*/
package net.bdew.lib.render
import net.minecraft.block.Block
import net.minecraft.client.renderer.{RenderBlocks, Tessellator}
import net.minecraftforge.common.util.ForgeDirection
import org.lwjgl.opengl.GL11
object RenderUtils {
/**
* Render a single item side
*/
def doRenderItemSide(d: ForgeDirection, r: RenderBlocks, block: Block, meta: Int) = {
val icon = r.getBlockIconFromSideAndMetadata(block, d.ordinal(), meta)
Tessellator.instance.setNormal(d.offsetX, d.offsetY, d.offsetZ)
d match {
case ForgeDirection.DOWN => r.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, icon)
case ForgeDirection.UP => r.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, icon)
case ForgeDirection.NORTH => r.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, icon)
case ForgeDirection.SOUTH => r.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, icon)
case ForgeDirection.WEST => r.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, icon)
case ForgeDirection.EAST => r.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, icon)
case _ => sys.error("Invalid side")
}
}
/**
* Render a simple block as an item (for gui, item entities etc.)
*/
def renderSimpleBlockItem(block: Block, metadata: Int, renderer: RenderBlocks) {
val T = Tessellator.instance
GL11.glTranslatef(-0.5F, -0.5F, -0.5F)
for (side <- ForgeDirection.VALID_DIRECTIONS) {
T.startDrawingQuads()
doRenderItemSide(side, renderer, block, metadata)
T.draw()
}
GL11.glTranslatef(0.5F, 0.5F, 0.5F)
}
}
@@ -0,0 +1,23 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.render.connected
import net.bdew.lib.gui.Color
import net.minecraft.util.IIcon
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.util.ForgeDirection
case class FaceOverlay(icon: IIcon, color: Color) {
def this(icon: IIcon, color: (Float, Float, Float)) = this(icon, new Color(color._1, color._2, color._3))
}
trait BlockAdditionalRender {
def getFaceOverlays(world: IBlockAccess, x: Int, y: Int, z: Int, face: ForgeDirection): List[FaceOverlay]
}
@@ -0,0 +1,121 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.render.connected
import net.bdew.lib.block.BlockRef
import net.minecraft.client.renderer.Tessellator
import net.minecraft.util.IIcon
import net.minecraftforge.common.util.ForgeDirection
object ConnectedHelper {
val edgeWidth = 1 / 16F
// Represents the rectangles of all edges/corners on a 2d pane
// 701
// 6 2
// 543
// 8 is a special case for the full face
val faceEdges = Array(
RectF(0, 1 - edgeWidth, 1, 1),
RectF(1 - edgeWidth, 1 - edgeWidth, 1, 1),
RectF(1 - edgeWidth, 0, 1, 1),
RectF(1 - edgeWidth, 0, 1, edgeWidth),
RectF(0, 0, 1, edgeWidth),
RectF(0, 0, edgeWidth, edgeWidth),
RectF(0, 0, edgeWidth, 1),
RectF(0, 1 - edgeWidth, edgeWidth, 1),
RectF(0, 0, 1, 1)
)
val faceAdjanced = (for (x <- ForgeDirection.VALID_DIRECTIONS) yield x -> new FaceAdjanced(x)).toMap
// Maps edge number + face to 3d vertices
val draw =
(for ((rect, n) <- faceEdges.zipWithIndex; face <- ForgeDirection.VALID_DIRECTIONS)
yield (face, n) -> new EdgeDraw(rect, face)).toMap
val brightnessMultiplier = Map(
ForgeDirection.UP -> 1F,
ForgeDirection.DOWN -> 0.5F,
ForgeDirection.NORTH -> 0.8F,
ForgeDirection.SOUTH -> 0.8F,
ForgeDirection.WEST -> 0.6F,
ForgeDirection.EAST -> 0.6F
)
case class Vec3F(x: Float, y: Float, z: Float) {
def *(m: Float) = Vec3F(x * m, y * m, z * m)
def +(m: Vec3F) = Vec3F(x + m.x, y + m.y, z + m.z)
def -(m: Vec3F) = Vec3F(x - m.x, y - m.y, z - m.z)
def +(d: ForgeDirection) = Vec3F(x + d.offsetX, y + d.offsetY, z + d.offsetZ)
def toInts = (x.toInt, y.toInt, z.toInt)
def asBlockRef = BlockRef(x.toInt, y.toInt, z.toInt)
}
case class RectF(x1: Float, y1: Float, x2: Float, y2: Float) {
def corners = Seq(Vec2F(x1, y1), Vec2F(x2, y1), Vec2F(x2, y2), Vec2F(x1, y2))
}
case class Vec2F(u: Float, v: Float)
case class VecPair(pos: Vec3F, tex: Vec2F)
class EdgeDraw(rect: RectF, face: ForgeDirection) {
val vertices = rect.corners map { d =>
val v = face match {
case ForgeDirection.UP => Vec3F(d.u, 1, 1 - d.v)
case ForgeDirection.DOWN => Vec3F(d.u, 0, d.v)
case ForgeDirection.NORTH => Vec3F(1 - d.u, d.v, 0)
case ForgeDirection.SOUTH => Vec3F(d.u, d.v, 1)
case ForgeDirection.EAST => Vec3F(1, d.v, 1 - d.u)
case ForgeDirection.WEST => Vec3F(0, d.v, d.u)
case _ => sys.error("Invalid face")
}
VecPair(extend(v, 0.001F), d)
}
def doDraw(pos: Vec3F, icon: IIcon) {
for (v <- vertices)
addVertextWithUV(v.pos + pos, mapToIcon(v.tex, icon))
}
}
def extend(v: Vec3F, o: Float) = Vec3F(
if (v.x == 0F) -o else if (v.x == 1F) 1 + o else v.x,
if (v.y == 0F) -o else if (v.y == 1F) 1 + o else v.y,
if (v.z == 0F) -o else if (v.z == 1F) 1 + o else v.z
)
def mapToIcon(v: Vec2F, i: IIcon) = Vec2F(i.getInterpolatedU(v.u * 16), i.getInterpolatedV((1 - v.v) * 16))
def addVertextWithUV(p: Vec3F, t: Vec2F) =
Tessellator.instance.addVertexWithUV(p.x, p.y, p.z, t.u, t.v)
class FaceAdjanced(d: ForgeDirection) {
val top = d match {
case ForgeDirection.UP => ForgeDirection.NORTH
case ForgeDirection.DOWN => ForgeDirection.SOUTH
case _ => ForgeDirection.UP
}
val right = d match {
case ForgeDirection.UP => ForgeDirection.EAST
case ForgeDirection.DOWN => ForgeDirection.EAST
case ForgeDirection.NORTH => ForgeDirection.WEST
case ForgeDirection.WEST => ForgeDirection.SOUTH
case ForgeDirection.SOUTH => ForgeDirection.EAST
case ForgeDirection.EAST => ForgeDirection.NORTH
case _ => ForgeDirection.UNKNOWN
}
val bottom = top.getOpposite
val left = right.getOpposite
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.render.connected
import net.bdew.lib.block.BlockRef
import net.bdew.lib.render.{BaseBlockRenderHandler, RenderUtils}
import net.minecraft.block.Block
import net.minecraft.client.renderer.{RenderBlocks, Tessellator}
import net.minecraft.world.IBlockAccess
import net.minecraftforge.common.util.ForgeDirection
import org.lwjgl.opengl.GL11
object ConnectedRenderer extends BaseBlockRenderHandler {
override def renderInventoryBlock(block: Block, metadata: Int, modelID: Int, renderer: RenderBlocks) {
val tessellator = Tessellator.instance
GL11.glTranslatef(-0.5F, -0.5F, -0.5F)
val edge = block.asInstanceOf[ConnectedTextureBlock].edgeIcon
for (side <- ForgeDirection.VALID_DIRECTIONS) {
tessellator.startDrawingQuads()
RenderUtils.doRenderItemSide(side, renderer, block, metadata)
ConnectedHelper.draw(side, 8).doDraw(ConnectedHelper.Vec3F(0, 0, 0), edge)
tessellator.draw()
}
GL11.glTranslatef(0.5F, 0.5F, 0.5F)
}
override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks): Boolean = {
renderer.renderStandardBlock(block, x, y, z)
val pos = ConnectedHelper.Vec3F(x, y, z)
for (face <- ForgeDirection.VALID_DIRECTIONS)
if (block.shouldSideBeRendered(world, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal()))
drawFaceEdges(world, pos, face, block.asInstanceOf[ConnectedTextureBlock])
return true
}
def drawFaceEdges(world: IBlockAccess, pos: ConnectedHelper.Vec3F, face: ForgeDirection, block: ConnectedTextureBlock) {
val edge = block.edgeIcon
val canConnect = block.canConnect(world, pos.asBlockRef, _: BlockRef)
val sides = ConnectedHelper.faceAdjanced(face)
val m = ConnectedHelper.brightnessMultiplier(face)
Tessellator.instance.setColorOpaque_F(m, m, m)
val fo = pos + face
val b = block.getMixedBrightnessForBlock(world, fo.x.toInt, fo.y.toInt, fo.z.toInt)
Tessellator.instance.setBrightness(b)
val U = !canConnect((pos + sides.top).asBlockRef)
val D = !canConnect((pos + sides.bottom).asBlockRef)
val L = !canConnect((pos + sides.left).asBlockRef)
val R = !canConnect((pos + sides.right).asBlockRef)
if (!U && !R && !canConnect((pos + sides.top + sides.right).asBlockRef))
ConnectedHelper.draw(face, 1).doDraw(pos, edge)
if (!U && !L && !canConnect((pos + sides.top + sides.left).asBlockRef))
ConnectedHelper.draw(face, 7).doDraw(pos, edge)
if (!D && !R && !canConnect((pos + sides.bottom + sides.right).asBlockRef))
ConnectedHelper.draw(face, 3).doDraw(pos, edge)
if (!D && !L && !canConnect((pos + sides.bottom + sides.left).asBlockRef))
ConnectedHelper.draw(face, 5).doDraw(pos, edge)
if (U) ConnectedHelper.draw(face, 0).doDraw(pos, edge)
if (D) ConnectedHelper.draw(face, 4).doDraw(pos, edge)
if (R) ConnectedHelper.draw(face, 2).doDraw(pos, edge)
if (L) ConnectedHelper.draw(face, 6).doDraw(pos, edge)
if (block.isInstanceOf[BlockAdditionalRender]) {
val overlays = block.asInstanceOf[BlockAdditionalRender].getFaceOverlays(world, pos.x.toInt, pos.y.toInt, pos.z.toInt, face)
for (overlay <- overlays) {
Tessellator.instance.setColorOpaque_F(overlay.color.r, overlay.color.g, overlay.color.b)
ConnectedHelper.draw(face, 8).doDraw(pos, overlay.icon)
}
}
}
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/bdlib
*
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/
package net.bdew.lib.render.connected
import net.bdew.lib.block.BlockRef
import net.minecraft.block.Block
import net.minecraft.util.IIcon
import net.minecraft.world.IBlockAccess
trait ConnectedTextureBlock extends Block {
def edgeIcon: IIcon
def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef): Boolean
override def getRenderType = ConnectedRenderer.id
}