Compare commits

...
24 Commits
Author SHA1 Message Date
bdew e2c7940539 fixed getConcreteStack in RecipeLoader ignoring size 2014-07-15 14:01:47 +03:00
bdew 7a5982bf37 Cleanup and update changes to 1.7.2 2014-06-18 11:37:56 +03:00
bdew 5166576d30 Merge remote-tracking branch 'remotes/origin/master' into mc172 2014-06-18 11:25:59 +03:00
bdew 35be9bff77 Merge remote-tracking branch 'remotes/origin/master' into mc172 2014-05-04 15:48:48 +03:00
bdew d67bd24eda added IStackBlock for pattern matching with ItemBlocks 2014-04-30 11:18:39 +03:00
bdew a10e90a1e1 Merge remote-tracking branch 'remotes/origin/master' into mc172 2014-04-30 11:16:57 +03:00
bdew 517c3f347f Fixed build script 2014-04-30 09:33:43 +03:00
bdew ecdcdfb05f Added /dumpregistry command 2014-04-23 15:11:07 +03:00
bdew d1d3df184f Don't register custom item stacks from Machine.regBlock - not needed anymore 2014-04-23 14:09:01 +03:00
bdew 522ac5b57b Proper exception logging in RecipeLoader statements 2014-04-23 13:37:09 +03:00
bdew 7acca5475f Added NamedItem trait (which SimpleItem extends now) 2014-04-23 13:36:42 +03:00
bdew 1b86f5f7cc Merge remote-tracking branch 'remotes/origin/mc172' into mc172 2014-04-20 13:46:06 +03:00
bdew 819197cf1e Block and Item Manager should not register itemstacks by default in 1.7 since the normal block/item registry is now usable 2014-04-20 13:44:42 +03:00
bdew 1e71bf7dd9 Fixed RecipeLoader logging error 2014-04-20 13:44:10 +03:00
bdew 0549f95088 Fix project name 2014-04-14 09:50:22 +03:00
bdew 06f0007bca oops wrong version 2014-04-14 09:36:21 +03:00
bdew 54499cdb2e Update to Forge 1057 (FG 1.2) 2014-04-13 15:25:20 +03:00
bdew d80d89acf1 Merge remote-tracking branch 'remotes/origin/master' into mc172 2014-04-13 15:24:45 +03:00
bdew 78c5ec1362 Merge branch 'master' of github.com:bdew/bdlib into mc172 2014-02-27 10:06:58 +02:00
bdew 005c300d8f Added experimental network stuff 2014-02-12 17:03:34 +02:00
bdew 4754c209ae oops, i an annotation 2014-02-12 14:19:24 +02:00
bdew b89d445b17 Updated Recipe Loader for 1.7.2 changes 2014-02-12 14:18:57 +02:00
bdew 7eefbb1a31 Updated HasTE, BaseInventory and Block/Item Manager for 1.7.2 changes 2014-02-12 12:39:10 +02:00
bdew 4268019935 Initial port to MC 1.7.2 2014-02-10 14:28:05 +02:00
50 changed files with 473 additions and 262 deletions

No files matched your search

+9 -8
View File
@@ -1,9 +1,10 @@
/.gradle /bin
/build
/deps
/eclipse
/out /out
/build
*.ipr /run
*.iml /deps/run
*.iws /eclipse
/.gradle
/*.iml
/*.ipr
/.idea
+12 -5
View File
@@ -1,20 +1,27 @@
buildscript { buildscript {
configurations.all {
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
repositories { repositories {
mavenCentral() mavenCentral()
maven { maven {
name = "forge" name = "forge"
url = "http://files.minecraftforge.net/maven" url = "http://files.minecraftforge.net/maven"
} }
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
} }
dependencies { dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:1.0-SNAPSHOT' classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
} }
} }
apply plugin: 'forge'
apply plugin: 'scala' apply plugin: 'scala'
apply plugin: 'forge'
version = "1.2.3" version = "1.3.0"
if (project.hasProperty('buildnum')) { if (project.hasProperty('buildnum')) {
project.version = project.version + '.' + project.buildnum project.version = project.version + '.' + project.buildnum
@@ -24,10 +31,10 @@ if (project.hasProperty('buildnum')) {
group = "net.bdew" group = "net.bdew"
archivesBaseName = "bdlib" archivesBaseName = "bdlib"
ext.versuffix = "mc164" ext.versuffix = "mc172"
minecraft { minecraft {
version = "1.6.4-9.11.1.964" version = "1.7.2-10.12.2.1126"
replace("BDLIB_VER", project.version) replace("BDLIB_VER", project.version)
} }
+1
View File
@@ -0,0 +1 @@
rootProject.name='bdlib'
+13 -4
View File
@@ -10,21 +10,30 @@
package net.bdew.lib package net.bdew.lib
import cpw.mods.fml.common.Mod import cpw.mods.fml.common.Mod
import cpw.mods.fml.common.event.FMLPreInitializationEvent import cpw.mods.fml.common.event.{FMLServerStartingEvent, FMLPreInitializationEvent}
import java.util.logging.Logger import org.apache.logging.log4j.Logger
import cpw.mods.fml.common.Mod.EventHandler import cpw.mods.fml.common.Mod.EventHandler
import net.minecraft.command.CommandHandler
@Mod(modid = "bdlib", name = "BD lib", version = "BDLIB_VER", modLanguage = "scala") @Mod(modid = "bdlib", name = "BD lib", version = "BDLIB_VER", modLanguage = "scala")
object BdLib { object BdLib {
var log: Logger = null var log: Logger = null
def logInfo(msg: String, args: Any*) = log.info(msg.format(args: _*)) def logInfo(msg: String, args: Any*) = log.info(msg.format(args: _*))
def logWarn(msg: String, args: Any*) = log.warning(msg.format(args: _*)) def logWarn(msg: String, args: Any*) = log.warn(msg.format(args: _*))
def logError(msg: String, args: Any*) = log.severe(msg.format(args: _*)) def logError(msg: String, args: Any*) = log.error(msg.format(args: _*))
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)
@EventHandler @EventHandler
def preInit(ev: FMLPreInitializationEvent) { def preInit(ev: FMLPreInitializationEvent) {
log = ev.getModLog log = ev.getModLog
log.info("bdlib BDLIB_VER loaded") log.info("bdlib BDLIB_VER loaded")
} }
@EventHandler
def serverStarting(event: FMLServerStartingEvent) {
val commandHandler = event.getServer.getCommandManager.asInstanceOf[CommandHandler]
commandHandler.registerCommand(new CommandDumpRegistry)
}
} }
@@ -0,0 +1,64 @@
/*
* 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.command.{CommandBase, ICommandSender}
import cpw.mods.fml.relauncher.FMLInjectionData
import java.io.{FileWriter, BufferedWriter, File}
import cpw.mods.fml.common.registry.GameData
import com.google.common.collect.Table
import net.minecraft.item.ItemStack
import net.minecraftforge.oredict.OreDictionary
import net.minecraftforge.fluids.FluidRegistry
class CommandDumpRegistry extends CommandBase {
def getCommandName = "dumpregistry"
override def getRequiredPermissionLevel = 2
def getCommandUsage(icommandsender: ICommandSender) = "dumpregistry"
def processCommand(sender: ICommandSender, params: Array[String]) {
val mcHome = FMLInjectionData.data()(6).asInstanceOf[File] //is there a better way to get this?
val dumpFile = new File(mcHome, "registry.dump")
val dumpWriter = new BufferedWriter(new FileWriter(dumpFile))
import scala.collection.JavaConversions._
try {
dumpWriter.write("==== BLOCKS ====\n")
dumpWriter.write(GameData.getBlockRegistry.map(GameData.getBlockRegistry.getNameForObject).toList.sorted.mkString("\n"))
dumpWriter.write("\n\n")
dumpWriter.write("==== ITEMS ====\n")
dumpWriter.write(GameData.getItemRegistry.map(GameData.getItemRegistry.getNameForObject).toList.sorted.mkString("\n"))
dumpWriter.write("\n\n")
dumpWriter.write("==== CUSTOM STACKS ====\n")
val stacksField = classOf[GameData].getDeclaredField("customItemStacks")
stacksField.setAccessible(true)
val stacksData = stacksField.get(null).asInstanceOf[Table[String, String, ItemStack]]
dumpWriter.write(stacksData.cellSet().map(x => x.getRowKey + ":" + x.getColumnKey).toList.sorted.mkString("\n"))
dumpWriter.write("\n\n")
dumpWriter.write("==== ORE DICT ====\n")
dumpWriter.write(OreDictionary.getOreNames.sorted.mkString("\n"))
dumpWriter.write("\n\n")
dumpWriter.write("==== FLUIDS ====\n")
dumpWriter.write(FluidRegistry.getRegisteredFluids.map(_._1).toList.sorted.mkString("\n"))
dumpWriter.write("\n\n")
CommandBase.notifyAdmins(sender, "Registry dumped to " + dumpFile.getCanonicalPath)
} catch {
case e: Throwable =>
CommandBase.notifyAdmins(sender, "Failed to save registry dump: " + e)
BdLib.logErrorException("Failed to save registry dump", e)
} finally {
dumpWriter.close()
}
}
}
+10 -8
View File
@@ -10,25 +10,27 @@
package net.bdew.lib package net.bdew.lib
import cpw.mods.fml.common.registry.GameRegistry import cpw.mods.fml.common.registry.GameRegistry
import net.minecraft.nbt.{NBTTagCompound, NBTTagList} import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.StatCollector import net.minecraft.util.StatCollector
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import cpw.mods.fml.common.versioning.{ArtifactVersion, VersionParser} import cpw.mods.fml.common.versioning.{ArtifactVersion, VersionParser}
import cpw.mods.fml.common.Loader import cpw.mods.fml.common.Loader
import net.minecraftforge.oredict.ShapedOreRecipe import net.minecraftforge.oredict.ShapedOreRecipe
import net.minecraft.world.biome.BiomeGenBase import net.minecraft.world.biome.BiomeGenBase
import net.minecraftforge.common.ForgeDirection
import net.minecraft.tileentity.TileEntity import net.minecraft.tileentity.TileEntity
import net.minecraftforge.common.util.ForgeDirection
object Misc { object Misc {
def iterNbtList[X](list: NBTTagList) = def iterNbtCompoundList(parent: NBTTagCompound, name: String): Iterable[NBTTagCompound] = {
for (i <- 0 until list.tagCount()) yield list.tagAt(i).asInstanceOf[X] val list = parent.getTagList(name, 10)
for (i <- 0 until list.tagCount()) yield list.getCompoundTagAt(i)
}
def getActiveModId = Loader.instance().activeModContainer().getModId def getActiveModId = Loader.instance().activeModContainer().getModId
def toLocal(s: String) = StatCollector.translateToLocal(s) def toLocal(s: String) = StatCollector.translateToLocal(s)
def toLocalF(s: String, params: Any*) = StatCollector.translateToLocal(s).format(params: _*) def toLocalF(s: String, params: Any*) = StatCollector.translateToLocal(s).format(params: _*)
def hasLocal(s: String) = StatCollector.func_94522_b(s) def hasLocal(s: String) = StatCollector.canTranslate(s)
def flattenRecipe(pattern: Seq[String], items: Map[Char, AnyRef]) = def flattenRecipe(pattern: Seq[String], items: Map[Char, AnyRef]) =
pattern ++ items.map { pattern ++ items.map {
@@ -38,7 +40,7 @@ object Misc {
def wrapTag(n: String, f: (NBTTagCompound) => Any)(t: NBTTagCompound) { def wrapTag(n: String, f: (NBTTagCompound) => Any)(t: NBTTagCompound) {
val p = t.getCompoundTag(n) val p = t.getCompoundTag(n)
f(p) f(p)
t.setCompoundTag(n, p) t.setTag(n, p)
} }
def addRecipe(result: ItemStack, pattern: Seq[String], items: Map[Char, AnyRef]) = def addRecipe(result: ItemStack, pattern: Seq[String], items: Map[Char, AnyRef]) =
@@ -57,7 +59,7 @@ object Misc {
def filterType[T](from: Iterable[_], cls: Class[T]) = from.filter(cls.isInstance).asInstanceOf[Iterable[T]] def filterType[T](from: Iterable[_], cls: Class[T]) = from.filter(cls.isInstance).asInstanceOf[Iterable[T]]
def getBiomeByName(name: String) = BiomeGenBase.biomeList.find(x => x != null && x.biomeName == name).getOrElse(null) def getBiomeByName(name: String) = BiomeGenBase.getBiomeGenArray.find(x => x != null && x.biomeName == name).getOrElse(null)
def haveModVersion(spec: String): Boolean = { def haveModVersion(spec: String): Boolean = {
val req = VersionParser.parseVersionReference(spec) val req = VersionParser.parseVersionReference(spec)
@@ -80,7 +82,7 @@ object Misc {
if (cls.isInstance(v)) Some(v.asInstanceOf[T]) else None if (cls.isInstance(v)) Some(v.asInstanceOf[T]) else None
def getNeighbourTile[T](origin: TileEntity, dir: ForgeDirection, cls: Class[T]) = def getNeighbourTile[T](origin: TileEntity, dir: ForgeDirection, cls: Class[T]) =
Option(origin.worldObj.getBlockTileEntity(origin.xCoord + dir.offsetX, Option(origin.getWorldObj.getTileEntity(origin.xCoord + dir.offsetX,
origin.yCoord + dir.offsetY, origin.zCoord + dir.offsetZ)) flatMap (asInstanceOpt(_, cls)) origin.yCoord + dir.offsetY, origin.zCoord + dir.offsetZ)) flatMap (asInstanceOpt(_, cls))
} }
+7 -6
View File
@@ -12,19 +12,20 @@ package net.bdew.lib.block
import net.minecraft.block.{ITileEntityProvider, Block} import net.minecraft.block.{ITileEntityProvider, Block}
import net.minecraft.world.{IBlockAccess, World} import net.minecraft.world.{IBlockAccess, World}
import net.minecraft.tileentity.TileEntity import net.minecraft.tileentity.TileEntity
import cpw.mods.fml.common.FMLCommonHandler import net.bdew.lib.BdLib
trait HasTE[T] extends Block with ITileEntityProvider { trait HasTE[T] extends Block with ITileEntityProvider {
val TEClass: Class[_ <: TileEntity] val TEClass: Class[_ <: TileEntity]
def createNewTileEntity(world: World): TileEntity = TEClass.newInstance()
def createNewTileEntity(world: World, meta: Int): TileEntity = TEClass.newInstance()
def getTE(w: IBlockAccess, x: Int, y: Int, z: Int): T = { def getTE(w: IBlockAccess, x: Int, y: Int, z: Int): T = {
var t = w.getBlockTileEntity(x, y, z) var t = w.getTileEntity(x, y, z)
if ((t == null) || !TEClass.isInstance(t)) { if ((t == null) || !TEClass.isInstance(t)) {
FMLCommonHandler.instance().getFMLLogger.severe("Tile entity for block %s at (%d,%d,%d) is corrupt or missing - recreating".format(this, x, y, z)) BdLib.logError("Tile entity for block %s at (%d,%d,%d) is corrupt or missing - recreating", this, x, y, z)
w match { w match {
case ww: World => case ww: World =>
t = createNewTileEntity(ww) t = createNewTileEntity(ww, w.getBlockMetadata(x, y, z))
ww.setBlockTileEntity(x, y, z, t) ww.setTileEntity(x, y, z, t)
case _ => case _ =>
sys.error("Unable to recreate TE") sys.error("Unable to recreate TE")
} }
+6 -12
View File
@@ -15,28 +15,22 @@ import cpw.mods.fml.common.registry.GameRegistry
import net.bdew.lib.block.HasTE import net.bdew.lib.block.HasTE
import net.bdew.lib.Misc import net.bdew.lib.Misc
class BlockManager(val ids: IdManager, addOldTileNames: Boolean = true) { class BlockManager() {
def this(ids: IdManager) = this(ids, true) def regBlockCls[T <: Block](blockCls: Class[T], name: String, addStack: Boolean = false): T = {
val block = blockCls.newInstance()
def regBlockCls[T <: Block](blockCls: Class[T], name: String, addStack: Boolean = true): T = {
val block = blockCls.getConstructor(classOf[Int]).newInstance(ids.getBlockId(name): Integer)
regBlock[T](block, name, addStack) regBlock[T](block, name, addStack)
} }
def regBlock[T <: Block](block: T, name: String, addStack: Boolean = true): T = { def regBlock[T <: Block](block: T, name: String, addStack: Boolean = false): T = {
GameRegistry.registerBlock(block, name) GameRegistry.registerBlock(block, name)
if (addStack) if (addStack)
GameRegistry.registerCustomItemStack(name, new ItemStack(block)) GameRegistry.registerCustomItemStack(name, new ItemStack(block))
if (block.isInstanceOf[HasTE[_]]) if (block.isInstanceOf[HasTE[_]])
if (addOldTileNames) GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass,
GameRegistry.registerTileEntityWithAlternatives(block.asInstanceOf[HasTE[_]].TEClass, "%s.%s".format(Misc.getActiveModId, name))
"%s.%s".format(Misc.getActiveModId, name), name)
else
GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass,
"%s.%s".format(Misc.getActiveModId, name))
return block return block
} }
+1 -1
View File
@@ -11,7 +11,7 @@ package net.bdew.lib.config
import net.minecraftforge.fluids.{FluidRegistry, Fluid} import net.minecraftforge.fluids.{FluidRegistry, Fluid}
class FluidManager(val ids: IdManager) { class FluidManager() {
def regFluid[T <: Fluid](fluid: T): T = { def regFluid[T <: Fluid](fluid: T): T = {
FluidRegistry.registerFluid(fluid) FluidRegistry.registerFluid(fluid)
return fluid return fluid
-46
View File
@@ -1,46 +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.config
import net.minecraft.block.Block
import net.minecraft.item.Item
import net.minecraftforge.common.Configuration
class IdManager(cfg: Configuration, itemStart: Int, blockStart: Int) {
class MyIter(start: Int, check: Array[_], offset: Int = 0) {
var now = start
def next(): Int = {
while (check(now + offset) != null) now += 1
return now
}
}
def getBlockId(name: String, comment: String) = cfg.getBlock(name, blockIds.next(), comment).getInt
def getBlockId(name: String) = cfg.getBlock(name, blockIds.next()).getInt
def getItemId(name: String, comment: String) = cfg.getItem(name, itemIds.next(), comment).getInt
def getItemId(name: String) = cfg.getItem(name, itemIds.next()).getInt
val blockIds = new MyIter(blockStart, Block.blocksList)
val itemIds = new MyIter(itemStart, Item.itemsList, 256)
// figure out what's the max id we already use, because forge is stupid
// ignore ids in the top slots as they were probably assigned to resolve conflicts
import scala.collection.JavaConverters._
val maxBlock = (cfg.getCategory(Configuration.CATEGORY_BLOCK).values().asScala.map(_.getInt).filter(_ < Block.blocksList.length - 100) ++ Seq(0)).max + 1
val maxItem = (cfg.getCategory(Configuration.CATEGORY_ITEM).values().asScala.map(_.getInt).filter(_ < Item.itemsList.length - 1000) ++ Seq(0)).max + 1
if (maxBlock > blockIds.now) blockIds.now = maxBlock
if (maxItem > itemIds.now) itemIds.now = maxItem
}
+7 -7
View File
@@ -11,19 +11,19 @@ package net.bdew.lib.config
import net.minecraft.item.{ItemStack, Item} import net.minecraft.item.{ItemStack, Item}
import cpw.mods.fml.common.registry.GameRegistry import cpw.mods.fml.common.registry.GameRegistry
import net.bdew.lib.items.SimpleItem import net.bdew.lib.items.{NamedItem, SimpleItem}
class ItemManager(val ids: IdManager) { class ItemManager() {
def regSimpleItem(name: String): SimpleItem = regItem(new SimpleItem(ids.getItemId(name), name), name) def regSimpleItem(name: String): SimpleItem = regItem(new SimpleItem(name), name)
def regItem[T <: SimpleItem](item: T): T = regItem[T](item, item.name) def regItem[T <: NamedItem](item: T): T = regItem[T](item, item.name)
def regItemCls[T <: Item](itemCls: Class[T], name: String, addStack: Boolean = true): T = { def regItemCls[T <: Item](itemCls: Class[T], name: String, addStack: Boolean = false): T = {
val item = itemCls.getConstructor(classOf[Int]).newInstance(ids.getItemId(name): Integer) val item = itemCls.newInstance()
regItem[T](item, name, addStack) regItem[T](item, name, addStack)
} }
def regItem[T <: Item](item: T, name: String, addStack: Boolean = true): T = { def regItem[T <: Item](item: T, name: String, addStack: Boolean = false): T = {
GameRegistry.registerItem(item, name) GameRegistry.registerItem(item, name)
if (addStack) if (addStack)
GameRegistry.registerCustomItemStack(name, new ItemStack(item)) GameRegistry.registerCustomItemStack(name, new ItemStack(item))
+2 -2
View File
@@ -13,12 +13,12 @@ import net.bdew.lib.recipes.gencfg.ConfigSection
import net.bdew.lib.machine.Machine import net.bdew.lib.machine.Machine
import net.bdew.lib.gui.{GuiProvider, GuiHandler} import net.bdew.lib.gui.{GuiProvider, GuiHandler}
class MachineManager(ids: IdManager, val tuning: ConfigSection, guiHandler: GuiHandler) { class MachineManager(val tuning: ConfigSection, guiHandler: GuiHandler) {
def registerMachine[R <: Machine[_]](machine: R): R = { def registerMachine[R <: Machine[_]](machine: R): R = {
machine.tuning = tuning.getSection(machine.name) machine.tuning = tuning.getSection(machine.name)
if (machine.tuning.getBoolean("Enabled")) { if (machine.tuning.getBoolean("Enabled")) {
machine.enabled = true machine.enabled = true
machine.regBlock(ids) machine.regBlock()
if (machine.isInstanceOf[GuiProvider]) if (machine.isInstanceOf[GuiProvider])
guiHandler.register(machine.asInstanceOf[GuiProvider]) guiHandler.register(machine.asInstanceOf[GuiProvider])
} }
+5 -4
View File
@@ -14,6 +14,7 @@ import net.minecraft.world.{IBlockAccess, World}
import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.EntityPlayer
import net.bdew.lib.Misc import net.bdew.lib.Misc
import net.bdew.lib.items.ItemUtils import net.bdew.lib.items.ItemUtils
import net.minecraft.block.Block
trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { trait BlockCoverable[T <: TileCoverable] extends HasTE[T] {
override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, face: Int, xoffs: Float, yoffs: Float, zoffs: Float): Boolean = { override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, face: Int, xoffs: Float, yoffs: Float, zoffs: Float): Boolean = {
@@ -52,17 +53,17 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] {
super.onBlockActivated(world, x, y, z, player, face, xoffs, yoffs, zoffs) super.onBlockActivated(world, x, y, z, player, face, xoffs, yoffs, zoffs)
} }
override def getBlockTexture(w: IBlockAccess, x: Int, y: Int, z: Int, side: Int) = override def getIcon(w: IBlockAccess, x: Int, y: Int, z: Int, side: Int) =
(for { (for {
coverStack <- Option(getTE(w, x, y, z).covers(Misc.forgeDirection(side)).cval) coverStack <- Option(getTE(w, x, y, z).covers(Misc.forgeDirection(side)).cval)
coverItem <- Option(coverStack.getItem) flatMap (Misc.asInstanceOpt(_, classOf[ItemCover])) coverItem <- Option(coverStack.getItem) flatMap (Misc.asInstanceOpt(_, classOf[ItemCover]))
} yield coverItem.getCoverIcon(coverStack) } yield coverItem.getCoverIcon(coverStack)
) getOrElse super.getBlockTexture(w, x, y, z, side) ) getOrElse super.getIcon(w, x, y, z, side)
override def breakBlock(world: World, x: Int, y: Int, z: Int, blockId: Int, meta: Int) { override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) {
if (!world.isRemote) if (!world.isRemote)
for ((dir, covOpt) <- getTE(world, x, y, z).covers; cover <- Option(covOpt.cval)) for ((dir, covOpt) <- getTE(world, x, y, z).covers; cover <- Option(covOpt.cval))
ItemUtils.throwItemAt(world, x, y, z, cover) ItemUtils.throwItemAt(world, x, y, z, cover)
super.breakBlock(world, x, y, z, blockId, meta) super.breakBlock(world, x, y, z, block, meta)
} }
} }
+3 -3
View File
@@ -10,14 +10,14 @@
package net.bdew.lib.covers package net.bdew.lib.covers
import net.minecraft.item.{ItemStack, Item} import net.minecraft.item.{ItemStack, Item}
import net.minecraftforge.common.ForgeDirection import net.minecraft.util.IIcon
import net.minecraft.util.Icon import net.minecraftforge.common.util.ForgeDirection
trait ItemCover extends Item { trait ItemCover extends Item {
/** /**
* @return Icon to render, MUST be on terrain spritesheet (0), not item! * @return Icon to render, MUST be on terrain spritesheet (0), not item!
*/ */
def getCoverIcon(stack: ItemStack): Icon def getCoverIcon(stack: ItemStack): IIcon
/** /**
* Perform tick, called on server only * Perform tick, called on server only
+1 -1
View File
@@ -10,10 +10,10 @@
package net.bdew.lib.covers package net.bdew.lib.covers
import net.bdew.lib.data.base.{UpdateKind, TileDataSlots} import net.bdew.lib.data.base.{UpdateKind, TileDataSlots}
import net.minecraftforge.common.ForgeDirection
import net.bdew.lib.data.DataSlotItemStack import net.bdew.lib.data.DataSlotItemStack
import net.bdew.lib.Misc import net.bdew.lib.Misc
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import net.minecraftforge.common.util.ForgeDirection
trait TileCoverable extends TileDataSlots { trait TileCoverable extends TileDataSlots {
val covers = (ForgeDirection.VALID_DIRECTIONS map { x => val covers = (ForgeDirection.VALID_DIRECTIONS map { x =>
@@ -10,8 +10,8 @@
package net.bdew.lib.data package net.bdew.lib.data
import net.bdew.lib.data.base.{TileDataSlots, UpdateKind, DataSlotVal} import net.bdew.lib.data.base.{TileDataSlots, UpdateKind, DataSlotVal}
import net.minecraftforge.common.ForgeDirection
import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagCompound
import net.minecraftforge.common.util.ForgeDirection
case class DataSlotDirection(name: String, parent: TileDataSlots) extends DataSlotVal[ForgeDirection] { case class DataSlotDirection(name: String, parent: TileDataSlots) extends DataSlotVal[ForgeDirection] {
var cval = ForgeDirection.UP var cval = ForgeDirection.UP
@@ -26,7 +26,7 @@ case class DataSlotItemStack(name: String, parent: TileDataSlots) extends DataSl
def save(t: NBTTagCompound, kind: UpdateKind.Value) = { def save(t: NBTTagCompound, kind: UpdateKind.Value) = {
val tag = new NBTTagCompound() val tag = new NBTTagCompound()
if (cval != null) cval.writeToNBT(tag) if (cval != null) cval.writeToNBT(tag)
t.setCompoundTag(name, tag) t.setTag(name, tag)
} }
def load(t: NBTTagCompound, kind: UpdateKind.Value) = cval = ItemStack.loadItemStackFromNBT(t.getCompoundTag(name)) def load(t: NBTTagCompound, kind: UpdateKind.Value) = cval = ItemStack.loadItemStackFromNBT(t.getCompoundTag(name))
} }
+1 -1
View File
@@ -38,7 +38,7 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w
writeToNBT(tag) writeToNBT(tag)
if (k == UpdateKind.GUI) if (k == UpdateKind.GUI)
tag.setInteger("size", getCapacity) tag.setInteger("size", getCapacity)
t.setCompoundTag(name, tag) t.setTag(name, tag)
} }
def load(t: NBTTagCompound, k: UpdateKind.Value) { def load(t: NBTTagCompound, k: UpdateKind.Value) {
@@ -21,19 +21,19 @@ trait ContainerDataSlots extends NoInvContainer {
super.addCraftingToCrafters(crafter) super.addCraftingToCrafters(crafter)
if (crafter.isInstanceOf[EntityPlayerMP]) { if (crafter.isInstanceOf[EntityPlayerMP]) {
val pkt = dataSource.getDataSlotPacket val pkt = dataSource.getDataSlotPacket
crafter.asInstanceOf[EntityPlayerMP].playerNetServerHandler.sendPacketToPlayer(pkt) crafter.asInstanceOf[EntityPlayerMP].playerNetServerHandler.sendPacket(pkt)
} }
} }
override def detectAndSendChanges() { override def detectAndSendChanges() {
super.detectAndSendChanges() super.detectAndSendChanges()
// only send updates every 10 ticks // only send updates every 10 ticks
if (dataSource.lastChange >= lastSentChange + 10 || (dataSource.lastChange > lastSentChange && lastSentChange + 10 < dataSource.worldObj.getTotalWorldTime)) { if (dataSource.lastChange >= lastSentChange + 10 || (dataSource.lastChange > lastSentChange && lastSentChange + 10 < dataSource.getWorldObj.getTotalWorldTime)) {
lastSentChange = dataSource.lastChange lastSentChange = dataSource.lastChange
val pkt = dataSource.getDataSlotPacket val pkt = dataSource.getDataSlotPacket
for (player <- players) for (player <- players)
player.playerNetServerHandler.sendPacketToPlayer(pkt) player.playerNetServerHandler.sendPacket(pkt)
} }
} }
} }
@@ -9,10 +9,11 @@
package net.bdew.lib.data.base package net.bdew.lib.data.base
import net.minecraft.network.packet.Packet132TileEntityData
import scala.collection.mutable import scala.collection.mutable
import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagCompound
import net.bdew.lib.tile.TileExtended import net.bdew.lib.tile.TileExtended
import net.minecraft.network.play.server.S35PacketUpdateTileEntity
import net.minecraft.network.Packet
trait TileDataSlots extends TileExtended { trait TileDataSlots extends TileExtended {
val dataSlots = mutable.HashMap.empty[String, DataSlot] val dataSlots = mutable.HashMap.empty[String, DataSlot]
@@ -32,7 +33,7 @@ trait TileDataSlots extends TileExtended {
if (TRACE) printf("%s: %s L<= %s\n".format(kind, n, t.getTag(n))) if (TRACE) printf("%s: %s L<= %s\n".format(kind, n, t.getTag(n)))
s.load(t, kind) s.load(t, kind)
if (kind == UpdateKind.WORLD && s.updateKind.contains(UpdateKind.RENDER)) if (kind == UpdateKind.WORLD && s.updateKind.contains(UpdateKind.RENDER))
worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord) getWorldObj.markBlockRangeForRenderUpdate(xCoord, yCoord, zCoord, xCoord, yCoord, zCoord)
} }
} }
@@ -42,20 +43,20 @@ trait TileDataSlots extends TileExtended {
handleClientUpdate.listen(doLoad(UpdateKind.WORLD, _)) handleClientUpdate.listen(doLoad(UpdateKind.WORLD, _))
def dataSlotChanged(slot: DataSlot) { def dataSlotChanged(slot: DataSlot) {
if (worldObj != null) { if (getWorldObj != null) {
if (slot.updateKind.contains(UpdateKind.GUI)) if (slot.updateKind.contains(UpdateKind.GUI))
lastChange = worldObj.getTotalWorldTime lastChange = getWorldObj.getTotalWorldTime
if (slot.updateKind.contains(UpdateKind.WORLD)) if (slot.updateKind.contains(UpdateKind.WORLD))
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord) getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
if (slot.updateKind.contains(UpdateKind.SAVE)) if (slot.updateKind.contains(UpdateKind.SAVE))
worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this) getWorldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this)
} }
} }
def getDataSlotPacket: Packet132TileEntityData = { def getDataSlotPacket: Packet = {
val tag = new NBTTagCompound() val tag = new NBTTagCompound()
doSave(UpdateKind.GUI, tag) doSave(UpdateKind.GUI, tag)
return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, ACT_GUI, tag) return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, ACT_GUI, tag)
} }
override protected def extDataPacket(id: Int, data: NBTTagCompound) { override protected def extDataPacket(id: Int, data: NBTTagCompound) {
+3 -2
View File
@@ -12,6 +12,7 @@ package net.bdew.lib.gui
import net.minecraft.client.gui.inventory.GuiContainer import net.minecraft.client.gui.inventory.GuiContainer
import net.minecraft.inventory.Container import net.minecraft.inventory.Container
import scala.collection.mutable import scala.collection.mutable
import net.minecraft.client.Minecraft
import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL11
abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) extends GuiContainer(cont) { abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) extends GuiContainer(cont) {
@@ -24,7 +25,7 @@ abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) extends GuiContai
def rect = new Rect(guiLeft, guiTop, xSize, ySize) def rect = new Rect(guiLeft, guiTop, xSize, ySize)
def getFontRenderer = fontRenderer def getFontRenderer = Minecraft.getMinecraft.fontRenderer
def getZLevel = zLevel def getZLevel = zLevel
override def initGui() { override def initGui() {
@@ -55,7 +56,7 @@ abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) extends GuiContai
import collection.JavaConversions._ import collection.JavaConversions._
if (tip.size > 0) if (tip.size > 0)
drawHoveringText(tip, x, y, fontRenderer) drawHoveringText(tip, x, y, getFontRenderer)
} }
protected def drawGuiContainerBackgroundLayer(f: Float, x: Int, y: Int) { protected def drawGuiContainerBackgroundLayer(f: Float, x: Int, y: Int) {
+2 -2
View File
@@ -24,8 +24,8 @@ class GuiHandler extends IGuiHandler {
} }
def getServerGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef = def getServerGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef =
guis(ID).getContainer(world.getBlockTileEntity(x, y, z), player) guis(ID).getContainer(world.getTileEntity(x, y, z), player)
def getClientGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef = def getClientGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef =
guis(ID).getGui(world.getBlockTileEntity(x, y, z), player) guis(ID).getGui(world.getTileEntity(x, y, z), player)
} }
+3 -3
View File
@@ -9,7 +9,7 @@
package net.bdew.lib.gui package net.bdew.lib.gui
import net.minecraft.util.{Icon, ResourceLocation} import net.minecraft.util.{IIcon, ResourceLocation}
import net.minecraft.client.Minecraft import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.texture.TextureMap import net.minecraft.client.renderer.texture.TextureMap
@@ -29,7 +29,7 @@ class InterpolatedTexture(val texture: Texture, rect: Rect) extends Texture {
def v2 = rect.y2 * (texture.v2 - texture.v1) + texture.v1 def v2 = rect.y2 * (texture.v2 - texture.v1) + texture.v1
} }
class IconWrapper(val resource: ResourceLocation, val icon: Icon) extends Texture { class IconWrapper(val resource: ResourceLocation, val icon: IIcon) extends Texture {
def u1 = icon.getMinU def u1 = icon.getMinU
def u2 = icon.getMaxU def u2 = icon.getMaxU
def v1 = icon.getMinV def v1 = icon.getMinV
@@ -55,7 +55,7 @@ object Texture {
val BLOCKS = TextureMap.locationBlocksTexture val BLOCKS = TextureMap.locationBlocksTexture
// From minecraft Icon // From minecraft Icon
def apply(res: ResourceLocation, i: Icon) = new IconWrapper(res, i) def apply(res: ResourceLocation, i: IIcon) = new IconWrapper(res, i)
// From a ResourceLocation and position, scale optional // From a ResourceLocation and position, scale optional
def apply(res: ResourceLocation, r: Rect) = new Sprite(res, r) def apply(res: ResourceLocation, r: Rect) = new Sprite(res, r)
@@ -12,12 +12,14 @@ package net.bdew.lib.gui.widgets
import net.minecraft.client.gui.GuiButton import net.minecraft.client.gui.GuiButton
import net.bdew.lib.gui.{Point, Rect} import net.bdew.lib.gui.{Point, Rect}
import net.minecraft.client.Minecraft import net.minecraft.client.Minecraft
import net.minecraft.client.audio.PositionedSoundRecord
import net.minecraft.util.ResourceLocation
class WidgetButton(val rect: Rect, text: String, clicked: WidgetButton => Unit) class WidgetButton(val rect: Rect, text: String, clicked: WidgetButton => Unit)
extends GuiButton(0, rect.x.round, rect.y.round, rect.w.round, rect.h.round, text) with Widget { extends GuiButton(0, rect.x.round, rect.y.round, rect.w.round, rect.h.round, text) with Widget {
override def mouseClicked(p: Point, button: Int) { override def mouseClicked(p: Point, button: Int) {
Minecraft.getMinecraft.sndManager.playSoundFX("random.click", 1.0F, 1.0F) Minecraft.getMinecraft.getSoundHandler.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F))
clicked(this) clicked(this)
} }
+13 -1
View File
@@ -9,7 +9,8 @@
package net.bdew.lib.items package net.bdew.lib.items
import net.minecraft.item.{Item, ItemStack} import net.minecraft.item.{ItemBlock, Item, ItemStack}
import net.minecraft.block.Block
/** /**
* Allows matching Items in ItemStacks in scala pattern matches * Allows matching Items in ItemStacks in scala pattern matches
@@ -21,3 +22,14 @@ object IStack {
else else
Some(x.getItem) Some(x.getItem)
} }
/**
* Allows matching Blocks in ItemStacks in scala pattern matches
*/
object IStackBlock {
def unapply(x: ItemStack): Option[Block] =
if (x == null || x.getItem == null || !x.getItem.isInstanceOf[ItemBlock])
None
else
Some(x.getItem.asInstanceOf[ItemBlock].field_150939_a)
}
+4 -4
View File
@@ -16,7 +16,7 @@ import net.minecraft.entity.player.EntityPlayer
import net.minecraft.inventory.{ISidedInventory, IInventory} import net.minecraft.inventory.{ISidedInventory, IInventory}
import net.bdew.lib.Misc import net.bdew.lib.Misc
import java.util.Random import java.util.Random
import net.minecraftforge.common.ForgeDirection import net.minecraftforge.common.util.ForgeDirection
object ItemUtils { object ItemUtils {
def throwItemAt(world: World, x: Int, y: Int, z: Int, stack: ItemStack) { def throwItemAt(world: World, x: Int, y: Int, z: Int, stack: ItemStack) {
@@ -39,7 +39,7 @@ object ItemUtils {
def isSameItem(stack1: ItemStack, stack2: ItemStack): Boolean = { def isSameItem(stack1: ItemStack, stack2: ItemStack): Boolean = {
if (stack1 == null || stack2 == null) if (stack1 == null || stack2 == null)
return stack1 == stack2 return stack1 == stack2
if (stack1.itemID != stack2.itemID) if (stack1.getItem != stack2.getItem)
return false return false
if (stack1.getHasSubtypes && stack2.getItemDamage != stack1.getItemDamage) if (stack1.getHasSubtypes && stack2.getItemDamage != stack1.getItemDamage)
return false return false
@@ -56,12 +56,12 @@ object ItemUtils {
if (toAdd >= stack.stackSize) { if (toAdd >= stack.stackSize) {
target.stackSize += stack.stackSize target.stackSize += stack.stackSize
stack.stackSize = 0 stack.stackSize = 0
inv.onInventoryChanged() inv.markDirty()
return null return null
} else if (toAdd > 0) { } else if (toAdd > 0) {
target.stackSize += toAdd target.stackSize += toAdd
stack.stackSize -= toAdd stack.stackSize -= toAdd
inv.onInventoryChanged() inv.markDirty()
} }
} }
+7 -3
View File
@@ -10,16 +10,20 @@
package net.bdew.lib.items package net.bdew.lib.items
import net.minecraft.item.Item import net.minecraft.item.Item
import net.minecraft.client.renderer.texture.IconRegister import net.minecraft.client.renderer.texture.IIconRegister
import cpw.mods.fml.relauncher.{Side, SideOnly} import cpw.mods.fml.relauncher.{Side, SideOnly}
import net.bdew.lib.Misc import net.bdew.lib.Misc
class SimpleItem(id: Int, val name: String) extends Item(id) { trait NamedItem extends Item {
def name: String
}
class SimpleItem(val name: String) extends Item with NamedItem {
val modId = Misc.getActiveModId val modId = Misc.getActiveModId
setUnlocalizedName(modId + "." + name) setUnlocalizedName(modId + "." + name)
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
override def registerIcons(reg: IconRegister) { override def registerIcons(reg: IIconRegister) {
itemIcon = reg.registerIcon(modId + ":" + name.toLowerCase) itemIcon = reg.registerIcon(modId + ":" + name.toLowerCase)
} }
} }
@@ -24,7 +24,7 @@ class InventoryItemAdapter(val player: EntityPlayer, val slot: Int, val size: In
def load() { def load() {
val tag = getStack.getTagCompound val tag = getStack.getTagCompound
for (nbtItem <- Misc.iterNbtList[NBTTagCompound](tag.getTagList(tagName))) { for (nbtItem <- Misc.iterNbtCompoundList(tag, "tagName")) {
val slot = nbtItem.getByte("Slot") val slot = nbtItem.getByte("Slot")
if (slot >= 0 && slot < inv.size) { if (slot >= 0 && slot < inv.size) {
inv(slot) = ItemStack.loadItemStackFromNBT(nbtItem) inv(slot) = ItemStack.loadItemStackFromNBT(nbtItem)
@@ -32,7 +32,7 @@ class InventoryItemAdapter(val player: EntityPlayer, val slot: Int, val size: In
} }
} }
def onInventoryChanged() { def markDirty() {
if (!getStack.hasTagCompound) getStack.setTagCompound(new NBTTagCompound) if (!getStack.hasTagCompound) getStack.setTagCompound(new NBTTagCompound)
val tag = getStack.getTagCompound val tag = getStack.getTagCompound
val itemList = new NBTTagList val itemList = new NBTTagList
+3 -6
View File
@@ -12,21 +12,18 @@ package net.bdew.lib.machine
import net.bdew.lib.recipes.gencfg.ConfigSection import net.bdew.lib.recipes.gencfg.ConfigSection
import net.minecraft.block.Block import net.minecraft.block.Block
import cpw.mods.fml.common.registry.GameRegistry import cpw.mods.fml.common.registry.GameRegistry
import net.minecraft.item.ItemStack
import net.bdew.lib.block.HasTE import net.bdew.lib.block.HasTE
import net.bdew.lib.config.IdManager
import net.bdew.lib.Misc import net.bdew.lib.Misc
abstract class Machine[T <: Block](val name: String, val blockConstruct: (Int) => T) { abstract class Machine[T <: Block](val name: String, blockConstruct: => T) {
var block: T = null.asInstanceOf[T] var block: T = null.asInstanceOf[T]
var tuning: ConfigSection = null var tuning: ConfigSection = null
var enabled = false var enabled = false
val modId = Misc.getActiveModId val modId = Misc.getActiveModId
def regBlock(ids: IdManager) { def regBlock() {
block = blockConstruct(ids.getBlockId(name)) block = blockConstruct
GameRegistry.registerBlock(block, name) GameRegistry.registerBlock(block, name)
GameRegistry.registerCustomItemStack(name, new ItemStack(block))
if (block.isInstanceOf[HasTE[_]]) { if (block.isInstanceOf[HasTE[_]]) {
GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass, "%s.%s".format(modId, name)) GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass, "%s.%s".format(modId, name))
} }
@@ -0,0 +1,40 @@
/*
* 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.handler.codec.MessageToMessageCodec
import cpw.mods.fml.common.network.internal.FMLProxyPacket
import net.minecraft.nbt.{CompressedStreamTools, NBTTagCompound}
import io.netty.channel.ChannelHandlerContext
import java.util
import java.io.{DataInputStream, DataOutputStream}
import io.netty.buffer.{ByteBufInputStream, ByteBufOutputStream, Unpooled}
import cpw.mods.fml.common.network.NetworkRegistry
import io.netty.channel.ChannelHandler.Sharable
import net.bdew.lib.BdLib
@Sharable
class NBTMessageToMessageCodec extends MessageToMessageCodec[FMLProxyPacket, NBTTagCompound] {
def encode(ctx: ChannelHandlerContext, msg: NBTTagCompound, out: util.List[AnyRef]) {
val buff = Unpooled.buffer()
val writer = new DataOutputStream(new ByteBufOutputStream(buff))
CompressedStreamTools.write(msg, writer)
val pkt = new FMLProxyPacket(buff, ctx.channel.attr(NetworkRegistry.FML_CHANNEL).get)
out.add(pkt)
}
def decode(ctx: ChannelHandlerContext, msg: FMLProxyPacket, out: util.List[AnyRef]) {
try {
val stream = new DataInputStream(new ByteBufInputStream(msg.payload()))
out.add(CompressedStreamTools.read(stream))
} catch {
case e: Throwable => BdLib.log.error("Error decoding packet", e)
}
}
}
+73
View File
@@ -0,0 +1,73 @@
/*
* 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.{FMLOutboundHandler, NetworkRegistry}
import cpw.mods.fml.relauncher.Side
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.entity.player.EntityPlayerMP
import io.netty.channel.{ChannelHandler, ChannelFutureListener}
class NetChannel(val name: String) {
val channels = NetworkRegistry.INSTANCE.newChannel(name, new NBTMessageToMessageCodec)
var serverHandlers = Map.empty[String, (NBTTagCompound, EntityPlayerMP) => Unit]
var clientHandlers = Map.empty[String, (NBTTagCompound) => Unit]
def regServerHandler(id: String, callable: (NBTTagCompound, EntityPlayerMP) => Unit) =
if (serverHandlers.contains(id))
sys.error("Command name already in use: %s".format(name))
else
serverHandlers += (id -> callable)
def regClientHandler(id: String, callable: (NBTTagCompound) => Unit) =
if (clientHandlers.contains(id))
sys.error("Command name already in use: %s".format(name))
else
clientHandlers += (id -> callable)
addHandler(Side.SERVER, new NetChannelServerHandler(this))
addHandler(Side.CLIENT, new NetChannelClientHandler(this))
def addHandler(side: Side, handler: ChannelHandler) {
val ch = channels.get(side)
val name = ch.findChannelHandlerNameForType(classOf[NBTMessageToMessageCodec])
ch.pipeline().addAfter(name, side + "Handler", handler)
}
def sendToAll(message: NBTTagCompound) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL)
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
}
def sendTo(message: NBTTagCompound, player: EntityPlayerMP) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER)
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player)
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
}
def sendToAllAround(message: NBTTagCompound, point: NetworkRegistry.TargetPoint) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT)
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point)
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
}
def sendToDimension(message: NBTTagCompound, dimensionId: Int) {
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION)
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(new Integer(dimensionId))
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
}
def sendToServer(message: NBTTagCompound) {
channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER)
channels.get(Side.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)
}
}
@@ -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.network
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
import net.minecraft.nbt.NBTTagCompound
import net.bdew.lib.BdLib
class NetChannelClientHandler(ch: NetChannel) extends SimpleChannelInboundHandler[NBTTagCompound] {
def channelRead0(ctx: ChannelHandlerContext, msg: NBTTagCompound) {
val cmd = msg.getString("_cmd")
ch.clientHandlers.getOrElse(cmd, {
BdLib.log.error("Unknown command: '%s' from server".format(cmd))
return
})(msg)
}
}
@@ -0,0 +1,27 @@
/*
* 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.minecraft.nbt.NBTTagCompound
import cpw.mods.fml.common.network.NetworkRegistry
import net.minecraft.network.NetHandlerPlayServer
import net.bdew.lib.BdLib
class NetChannelServerHandler(ch: NetChannel) extends SimpleChannelInboundHandler[NBTTagCompound] {
def channelRead0(ctx: ChannelHandlerContext, msg: NBTTagCompound) {
val cmd = msg.getString("_cmd")
val nh = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get.asInstanceOf[NetHandlerPlayServer].playerEntity
ch.serverHandlers.getOrElse(cmd, {
BdLib.log.error("Unknown command: '%s' from '%s'".format(cmd, nh.getCommandSenderName))
return
})(msg, nh)
}
}
+1 -1
View File
@@ -49,7 +49,7 @@ case class DataSlotPower(name: String, parent: TileDataSlots) extends DataSlot {
tag.setFloat("stored", stored) tag.setFloat("stored", stored)
if (kind == UpdateKind.GUI) if (kind == UpdateKind.GUI)
tag.setFloat("capacity", capacity) tag.setFloat("capacity", capacity)
t.setCompoundTag(name, tag) t.setTag(name, tag)
} }
def load(t: NBTTagCompound, kind: UpdateKind.Value) { def load(t: NBTTagCompound, kind: UpdateKind.Value) {
+17 -15
View File
@@ -28,31 +28,33 @@ abstract class StackRef
case class StackOreDict(id: String) extends StackRef case class StackOreDict(id: String) extends StackRef
/** /**
* Mod item reference [[cpw.mods.fml.common.registry.GameRegistry.findItemStack]] * Generic Referende
* Syntax: {modID}:{name} * Syntax: S:{modid}:{name}
* Parser: [[net.bdew.lib.recipes.RecipeParser.specModStack]] * Parser: [[net.bdew.lib.recipes.RecipeParser.specGenericStack]]
* @param mod modId of owner mod * @param mod modId of owner mod
* @param id name of the stack * @param name name of the stack
*/ */
case class StackMod(mod: String, id: String) extends StackRef case class StackGeneric(mod: String, name: String) extends StackRef
/** /**
* Vanilla block reference * Block reference
* Syntax: B:{name} [@ {meta}] * Syntax: B:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specMcBlock]] * Parser: [[net.bdew.lib.recipes.RecipeParser.specBlock]]
* @param name Unlocalized name (without "tile.") * @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage * @param meta Metadata / Damage
*/ */
case class StackMCBlock(name: String, meta: Int) extends StackRef case class StackBlock(mod: String, name: String, meta: Int) extends StackRef
/** /**
* Vanilla item reference * Item reference
* Syntax: I:{name} [@ {meta}] * Syntax: I:[{modid}:]{name} [@ {meta}]
* Parser: [[net.bdew.lib.recipes.RecipeParser.specMcItem]] * Parser: [[net.bdew.lib.recipes.RecipeParser.specItem]]
* @param name Unlocalized name (without "item.") * @param mod modId of owner mod, default is "minecraft"
* @param name Registered name
* @param meta Metadata / Damage * @param meta Metadata / Damage
*/ */
case class StackMCItem(name: String, meta: Int) extends StackRef case class StackItem(mod: String, name: String, meta: Int) extends StackRef
/** /**
* Reference to an Item/Block/ItemStack pulic static field * Reference to an Item/Block/ItemStack pulic static field
+39 -49
View File
@@ -15,8 +15,6 @@ import net.bdew.lib.{BdLib, Misc}
import net.minecraft.block.Block import net.minecraft.block.Block
import cpw.mods.fml.common.registry.GameRegistry import cpw.mods.fml.common.registry.GameRegistry
import net.minecraftforge.oredict.{ShapelessOreRecipe, OreDictionary} import net.minecraftforge.oredict.{ShapelessOreRecipe, OreDictionary}
import java.util.logging.Logger
import net.minecraft.item.crafting.FurnaceRecipes
/** /**
* Main recipe loader class * Main recipe loader class
@@ -33,9 +31,6 @@ class RecipeLoader {
*/ */
def newParser() = new RecipeParser() def newParser() = new RecipeParser()
val log: Logger = Logger.getLogger("RecipeLoader")
log.setParent(BdLib.log)
/** /**
* Current map of recipe characters to parser item references * Current map of recipe characters to parser item references
*/ */
@@ -89,7 +84,7 @@ class RecipeLoader {
val l = x.copy() val l = x.copy()
l.stackSize = cnt l.stackSize = cnt
if (meta != OreDictionary.WILDCARD_VALUE && meta != l.getItemDamage) { if (meta != OreDictionary.WILDCARD_VALUE && meta != l.getItemDamage) {
log.warning("%s requested with meta %d but specifies %d".format(source, meta, l.getItemDamage)) BdLib.logWarn("%s requested with meta %d but specifies %d", source, meta, l.getItemDamage)
l.setItemDamage(meta) l.setItemDamage(meta)
} }
return l return l
@@ -164,6 +159,8 @@ class RecipeLoader {
case _ => Seq(getConcreteStack(s)) case _ => Seq(getConcreteStack(s))
} }
def notNull[T](v: T, err: => String) = if (v == null) error(err) else v
/** /**
* Returns an ItemStack that match a reference * Returns an ItemStack that match a reference
* This is the main StackRef resolution method * This is the main StackRef resolution method
@@ -177,15 +174,15 @@ class RecipeLoader {
if (l.size == 0) error("Concrete ItemStack requested for OD entry '%s' that is empty", id) if (l.size == 0) error("Concrete ItemStack requested for OD entry '%s' that is empty", id)
val s = l.get(0).copy() val s = l.get(0).copy()
s.stackSize = cnt s.stackSize = cnt
log.info("Concrete ItemStack for OD entry '%s' -> %s".format(id, s)) BdLib.logInfo("Concrete ItemStack for OD entry '%s' -> %s", id, s)
return s return s
case StackMacro(ch) => getConcreteStack(currCharMap(ch), cnt) case StackMacro(ch) => getConcreteStack(currCharMap(ch), cnt)
case StackMod(mod, id) => case StackGeneric(mod, id) =>
val i = GameRegistry.findItemStack(mod, id, cnt) notNull(GameRegistry.findItemStack(mod, id, cnt), "Stack not found %s:%s".format(mod, id))
if (i == null) error("Item %s:%s not found", mod, id) case StackBlock(mod, id, meta) =>
i new ItemStack(notNull(GameRegistry.findBlock(mod, id), "Block not found %s:%s".format(mod, id)), cnt, meta)
case StackMCBlock(id, meta) => new ItemStack(Vanilla.blocks(id), cnt, meta) case StackItem(mod, id, meta) =>
case StackMCItem(id, meta) => new ItemStack(Vanilla.items(id), cnt, meta) new ItemStack(notNull(GameRegistry.findItem(mod, id), "Item not found %s:%s".format(mod, id)), cnt, meta)
case StackReflect(cls, field, meta) => reflectStack(cls, field, meta, cnt) case StackReflect(cls, field, meta) => reflectStack(cls, field, meta, cnt)
case StackGetter(cls, method, param, meta) => reflectStackGetter(cls, method, param, meta, cnt) case StackGetter(cls, method, param, meta) => reflectStackGetter(cls, method, param, meta, cnt)
} }
@@ -202,7 +199,7 @@ class RecipeLoader {
if (!currCharMap.contains(x)) error("Character %s is undefined", x) if (!currCharMap.contains(x)) error("Character %s is undefined", x)
val r = getRecipeComponent(currCharMap(x)) val r = getRecipeComponent(currCharMap(x))
if (r.isInstanceOf[String]) needOd = true if (r.isInstanceOf[String]) needOd = true
log.info("%s -> %s".format(x, r)) BdLib.logInfo("%s -> %s", x, r)
comp += (x -> r) comp += (x -> r)
} }
return (comp, needOd) return (comp, needOd)
@@ -215,20 +212,20 @@ class RecipeLoader {
def processStatement(s: Statement): Unit = s match { def processStatement(s: Statement): Unit = s match {
case StIfHaveMod(mod, thn, els) => case StIfHaveMod(mod, thn, els) =>
if (Misc.haveModVersion(mod)) { if (Misc.haveModVersion(mod)) {
log.info("ifMod: %s found".format(mod)) BdLib.logInfo("ifMod: %s found", mod)
processStatementsSafe(thn) processStatementsSafe(thn)
} else { } else {
log.info("ifMod: %s not found".format(mod)) BdLib.logInfo("ifMod: %s not found", mod)
processStatementsSafe(els) processStatementsSafe(els)
} }
case StClearRecipes(res) => case StClearRecipes(res) =>
log.info("Clearing recipes that produce %s".format(res)) BdLib.logInfo("Clearing recipes that produce %s", res)
delayedStatements = delayedStatements.filter({ delayedStatements = delayedStatements.filter({
x => x =>
if (x.isInstanceOf[CraftingStatement]) if (x.isInstanceOf[CraftingStatement])
if (x.asInstanceOf[CraftingStatement].result == res) { if (x.asInstanceOf[CraftingStatement].result == res) {
log.info("Removing recipe %s".format(x)) BdLib.logInfo("Removing recipe %s", x)
false false
} else true } else true
else true else true
@@ -238,7 +235,7 @@ class RecipeLoader {
delayedStatements :+= x delayedStatements :+= x
case x => case x =>
log.severe("Can't process %s - this is a programing bug!".format(x)) BdLib.logError("Can't process %s - this is a programing bug!", x)
} }
/** /**
@@ -248,19 +245,19 @@ class RecipeLoader {
def processDelayedStatement(st: DelayedStatement) = st match { def processDelayedStatement(st: DelayedStatement) = st match {
case StCharAssign(c, r) => case StCharAssign(c, r) =>
currCharMap += (c -> r) currCharMap += (c -> r)
log.info("Added %s = %s".format(c, r)) BdLib.logInfo("Added %s = %s", c, r)
case StClassMacro(id, cls) => case StClassMacro(id, cls) =>
currClassMacros += (id -> cls) currClassMacros += (id -> cls)
log.info("Added def %s = %s".format(id, cls)) BdLib.logInfo("Added def %s = %s", id, cls)
case StRecipeShaped(rec, res, cnt) => case StRecipeShaped(rec, res, cnt) =>
log.info("Adding shaped recipe %s => %s * %d".format(rec, res, cnt)) BdLib.logInfo("Adding shaped recipe %s => %s * %d", rec, res, cnt)
val (comp, needOd) = resolveRecipeComponents(rec.mkString("")) val (comp, needOd) = resolveRecipeComponents(rec.mkString(""))
val resStack = getConcreteStack(res, cnt) val resStack = getConcreteStack(res, cnt)
if (resStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { if (resStack.getItemDamage == OreDictionary.WILDCARD_VALUE) {
log.info("Result meta is unset, defaulting to 0") BdLib.logInfo("Result meta is unset, defaulting to 0")
resStack.setItemDamage(0) resStack.setItemDamage(0)
} }
@@ -269,16 +266,16 @@ class RecipeLoader {
else else
Misc.addRecipe(resStack, rec, comp) Misc.addRecipe(resStack, rec, comp)
log.info("Done... result=%s, od=%s".format(resStack, needOd)) BdLib.logInfo("Done... result=%s, od=%s", resStack, needOd)
case StRecipeShapeless(rec, res, cnt) => case StRecipeShapeless(rec, res, cnt) =>
log.info("Adding shapeless recipe %s => %s * %d".format(rec, res, cnt)) BdLib.logInfo("Adding shapeless recipe %s => %s * %d", rec, res, cnt)
val (comp, needOd) = resolveRecipeComponents(rec) val (comp, needOd) = resolveRecipeComponents(rec)
val resStack = getConcreteStack(res, cnt) val resStack = getConcreteStack(res, cnt)
val recTrans = rec.toCharArray.map(comp(_)) val recTrans = rec.toCharArray.map(comp(_))
if (resStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { if (resStack.getItemDamage == OreDictionary.WILDCARD_VALUE) {
log.info("Result meta is unset, defaulting to 0") BdLib.logInfo("Result meta is unset, defaulting to 0")
resStack.setItemDamage(0) resStack.setItemDamage(0)
} }
@@ -287,43 +284,38 @@ class RecipeLoader {
else else
GameRegistry.addShapelessRecipe(resStack, recTrans: _*) GameRegistry.addShapelessRecipe(resStack, recTrans: _*)
log.info("Done... result=%s, od=%s".format(resStack, needOd)) BdLib.logInfo("Done... result=%s, od=%s", resStack, needOd)
case StSmeltRecipe(in, out, cnt, xp) => case StSmeltRecipe(in, out, cnt, xp) =>
log.info("Adding smelting recipe %s => %s * %d (%f xp)".format(in, out, cnt, xp)) BdLib.logInfo("Adding smelting recipe %s => %s * %d (%f xp)", in, out, cnt, xp)
val outStack = getConcreteStack(out, cnt) val outStack = getConcreteStack(out, cnt)
if (outStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { if (outStack.getItemDamage == OreDictionary.WILDCARD_VALUE) {
log.info("Result meta is unset, defaulting to 0") BdLib.logInfo("Result meta is unset, defaulting to 0")
outStack.setItemDamage(0) outStack.setItemDamage(0)
} }
for (inStack <- getAllConcreteStacks(in, 1)) { for (inStack <- getAllConcreteStacks(in, 1)) {
if (inStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { GameRegistry.addSmelting(inStack, outStack, xp)
FurnaceRecipes.smelting.addSmelting(inStack.itemID, outStack, xp) BdLib.logInfo("added %s -> %s", inStack, outStack)
log.info("added %d -> %s".format(inStack.itemID, outStack))
} else {
FurnaceRecipes.smelting.addSmelting(inStack.itemID, inStack.getItemDamage, outStack, xp)
log.info("added %d@%d -> %s".format(inStack.itemID, inStack.getItemDamage, outStack))
}
} }
case StIfHaveOD(od, thn, els) => case StIfHaveOD(od, thn, els) =>
if (OreDictionary.getOres(od).size() > 0) { if (OreDictionary.getOres(od).size() > 0) {
log.info("ifOreDict: %s found".format(od)) BdLib.logInfo("ifOreDict: %s found".format(od))
processDelayedStatementsSafe(thn) processDelayedStatementsSafe(thn)
} else { } else {
log.info("ifOreDict: %s not found".format(od)) BdLib.logInfo("ifOreDict: %s not found".format(od))
processDelayedStatementsSafe(els) processDelayedStatementsSafe(els)
} }
case x => case x =>
log.severe("Can't process %s - this is a programing bug!".format(x)) BdLib.logError("Can't process %s - this is a programing bug!", x)
} }
/** /**
* Process main delayed statements list, clear the list afterwards * Process main delayed statements list, clear the list afterwards
*/ */
def processDelayedStatements() { def processDelayedStatements() {
log.info("Processing %d delayed statements".format(delayedStatements.size)) BdLib.logInfo("Processing %d delayed statements", delayedStatements.size)
processDelayedStatementsSafe(delayedStatements) processDelayedStatementsSafe(delayedStatements)
delayedStatements = List.empty delayedStatements = List.empty
} }
@@ -338,10 +330,9 @@ class RecipeLoader {
processDelayedStatement(s) processDelayedStatement(s)
} catch { } catch {
case e: StatementError => case e: StatementError =>
log.severe("Error while processing %s: %s".format(s, e.getMessage)) BdLib.logError("Error while processing %s: %s", s, e.getMessage)
case e: Throwable => case e: Throwable =>
log.severe("Error while processing %s: %s".format(s, e)) BdLib.logErrorException("Error while processing %s", e, s)
e.printStackTrace()
} }
} }
} }
@@ -356,19 +347,18 @@ class RecipeLoader {
processStatement(s) processStatement(s)
} catch { } catch {
case e: StatementError => case e: StatementError =>
log.severe("Error while processing %s: %s".format(s, e.getMessage)) BdLib.logError("Error while processing %s: %s", s, e.getMessage)
case e: Throwable => case e: Throwable =>
log.severe("Error while processing %s: %s".format(s, e)) BdLib.logErrorException("Error while processing %s", e, s)
e.printStackTrace()
} }
} }
} }
def load(f: Reader) { def load(f: Reader) {
log.info("Starting parsing") BdLib.logInfo("Starting parsing")
val r = newParser().doParse(f) val r = newParser().doParse(f)
log.info("Processing %d statements".format(r.size)) BdLib.logInfo("Processing %d statements", r.size)
processStatementsSafe(r) processStatementsSafe(r)
log.info("Done") BdLib.logInfo("Done")
} }
} }
+7 -4
View File
@@ -25,6 +25,9 @@ class RecipeParser extends JavaTokenParsers {
// Possible metadata suffix (defaults to wildcard value) // Possible metadata suffix (defaults to wildcard value)
def maybeMeta = ("@" ~> int).? ^^ (_.getOrElse(OreDictionary.WILDCARD_VALUE)) def maybeMeta = ("@" ~> int).? ^^ (_.getOrElse(OreDictionary.WILDCARD_VALUE))
// Possible modid prefix (defaults to minecraft)
def maybeModid = (str <~ ":").? ^^ (_.getOrElse("minecraft"))
// Qualified class name // Qualified class name
def clsPath = (ident <~ ".").* ~ ident def clsPath = (ident <~ ".").* ~ ident
@@ -46,9 +49,9 @@ class RecipeParser extends JavaTokenParsers {
// === Item references === // === Item references ===
def specOD = "OD" ~> ":" ~> ident ^^ StackOreDict def specOD = "OD" ~> ":" ~> ident ^^ StackOreDict
def specMcBlock = "B" ~> ":" ~> ident ~ maybeMeta ^^ { case b ~ m => StackMCBlock(b, m) } def specBlock = "B" ~> ":" ~> maybeModid ~ str ~ maybeMeta ^^ { case m ~ n ~ i => StackBlock(m, n, i) }
def specMcItem = "I" ~> ":" ~> ident ~ maybeMeta ^^ { case b ~ m => StackMCItem(b, m) } def specItem = "I" ~> ":" ~> maybeModid ~ str ~ maybeMeta ^^ { case m ~ n ~ i => StackItem(m, n, i) }
def specModStack = str ~ ":" ~ str ^^ { case m ~ c ~ n => StackMod(m, n) } def specGenericStack = "S" ~> ":" ~> str ~ ":" ~ str ^^ { case m ~ c ~ n => StackGeneric(m, n) }
def specMacro = "$" ~> recipeChar ^^ StackMacro def specMacro = "$" ~> recipeChar ^^ StackMacro
def specReflect = clsPath ~ ("[" ~> ident <~ "]") ~ maybeMeta ^^ { def specReflect = clsPath ~ ("[" ~> ident <~ "]") ~ maybeMeta ^^ {
@@ -59,7 +62,7 @@ class RecipeParser extends JavaTokenParsers {
case (p ~ cl) ~ n ~ m => StackGetter(p.mkString("."), cl, n, m) case (p ~ cl) ~ n ~ m => StackGetter(p.mkString("."), cl, n, m)
} }
def spec = specMcBlock | specMcItem | specOD | specModStack | specGetter | specReflect | specMacro def spec = specBlock | specItem | specOD | specGenericStack | specGetter | specReflect | specMacro
// Spec with possible number of items // Spec with possible number of items
def specWithCount = spec ~ ("*" ~> int).? def specWithCount = spec ~ ("*" ~> int).?
@@ -10,17 +10,18 @@
package net.bdew.lib.recipes.gencfg package net.bdew.lib.recipes.gencfg
import net.bdew.lib.recipes.{Statement, RecipeLoader} import net.bdew.lib.recipes.{Statement, RecipeLoader}
import net.bdew.lib.BdLib
trait GenericConfigLoader extends RecipeLoader { trait GenericConfigLoader extends RecipeLoader {
val cfgStore: ConfigSection val cfgStore: ConfigSection
def processConfigStatement(section: ConfigSection, s: CfgStatement): Unit = s match { def processConfigStatement(section: ConfigSection, s: CfgStatement): Unit = s match {
case CfgVal(id, v) => case CfgVal(id, v) =>
log.info("Config: %s%s = %s".format(section.pfx, id, v)) BdLib.logInfo("Config: %s%s = %s", section.pfx, id, v)
section.set(id, v) section.set(id, v)
case CfgSub(id, st) => processConfigBlock(section.getOrAddSection(id), st) case CfgSub(id, st) => processConfigBlock(section.getOrAddSection(id), st)
case x => case x =>
log.severe("Can't process %s - this is a programing bug!".format(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[CfgStatement]) = for (s <- block) processConfigStatement(view, s)
@@ -1,10 +1,10 @@
/* /*
* Copyright (c) bdew, 2013 - 2014 * Copyright (c) bdew, 2013 - 2014
* https://github.com/bdew/gendustry * https://github.com/bdew/bdlib
* *
* This mod is distributed under the terms of the Minecraft Mod Public * 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 * License 1.0, or MMPL. Please check the contents of the license located in
* https://raw.github.com/bdew/gendustry/master/MMPL-1.0.txt * https://raw.github.com/bdew/bdlib/master/MMPL-1.0.txt
*/ */
package net.bdew.lib.recipes.lootlist package net.bdew.lib.recipes.lootlist
@@ -13,6 +13,7 @@ import net.bdew.lib.recipes.gencfg.GenericConfigLoader
import net.minecraftforge.oredict.OreDictionary import net.minecraftforge.oredict.OreDictionary
import net.bdew.lib.recipes.StackRef import net.bdew.lib.recipes.StackRef
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import net.bdew.lib.BdLib
/** /**
* Loader mixin for loot lists * Loader mixin for loot lists
@@ -24,18 +25,18 @@ trait LootListLoader extends GenericConfigLoader {
try { try {
val itemStack = getConcreteStack(ref) val itemStack = getConcreteStack(ref)
if (itemStack == null) { if (itemStack == null) {
log.warning("Unable to resolve %s: null returned".format(ref)) BdLib.logWarn("Unable to resolve %s: null returned", ref)
None None
} else { } else {
if (itemStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { if (itemStack.getItemDamage == OreDictionary.WILDCARD_VALUE) {
log.info("meta/damage is unset in %s, defaulting to 0".format(ref)) BdLib.logInfo("meta/damage is unset in %s, defaulting to 0", ref)
itemStack.setItemDamage(0) itemStack.setItemDamage(0)
} }
Some((chance, itemStack)) Some((chance, itemStack))
} }
} catch { } catch {
case e: Throwable => case e: Throwable =>
log.warning("Unable to resolve %s: %s".format(ref, e.getMessage)) BdLib.logWarn("Unable to resolve %s: %s", ref, e.getMessage)
None None
} }
}).flatten }).flatten
+4 -4
View File
@@ -9,11 +9,11 @@
package net.bdew.lib.render package net.bdew.lib.render
import net.minecraft.client.renderer.texture.IconRegister import net.minecraft.client.renderer.texture.IIconRegister
import net.minecraftforge.common.MinecraftForge import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.event.ForgeSubscribe
import net.minecraftforge.client.event.TextureStitchEvent import net.minecraftforge.client.event.TextureStitchEvent
import net.bdew.lib.gui.{Texture, IconWrapper} import net.bdew.lib.gui.{Texture, IconWrapper}
import cpw.mods.fml.common.eventhandler.SubscribeEvent
/** /**
* Allows loading of texture that don't belong to specific block or item into vanilla block/item atlas * Allows loading of texture that don't belong to specific block or item into vanilla block/item atlas
@@ -38,13 +38,13 @@ class IconPreloader(kind: Int) {
implicit def entry2icon(v: TextureLoc) = v.texture.icon implicit def entry2icon(v: TextureLoc) = v.texture.icon
implicit def entry2texture(v: TextureLoc) = v.texture implicit def entry2texture(v: TextureLoc) = v.texture
def registerIcons(reg: IconRegister) {} def registerIcons(reg: IIconRegister) {}
def init() { def init() {
MinecraftForge.EVENT_BUS.register(this) MinecraftForge.EVENT_BUS.register(this)
} }
@ForgeSubscribe @SubscribeEvent
def preTextureStitch(ev: TextureStitchEvent.Pre) { def preTextureStitch(ev: TextureStitchEvent.Pre) {
if (ev.map.getTextureType == kind) { if (ev.map.getTextureType == kind) {
for (x <- icons) x.texture = Texture(sheet, ev.map.registerIcon(x.loc)) for (x <- icons) x.texture = Texture(sheet, ev.map.registerIcon(x.loc))
@@ -14,12 +14,11 @@ import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.block.Block import net.minecraft.block.Block
import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.EntityLivingBase
import net.minecraft.item.ItemStack import net.minecraft.item.ItemStack
import net.minecraft.util.Icon import net.minecraft.util.{IIcon, MathHelper}
import net.minecraft.util.MathHelper
import net.minecraft.world.IBlockAccess import net.minecraft.world.IBlockAccess
import net.minecraft.world.World import net.minecraft.world.World
import net.minecraftforge.common.ForgeDirection
import java.util.EnumSet import java.util.EnumSet
import net.minecraftforge.common.util.ForgeDirection
/** /**
* Basic logic for block rotatation * Basic logic for block rotatation
@@ -29,12 +28,12 @@ trait BaseRotateableBlock extends Block {
/** /**
* Override this method to provide your textures, also called when rendering as item * Override this method to provide your textures, also called when rendering as item
*/ */
def getIcon(meta: Int, kind: IconType.Value): Icon def getIcon(meta: Int, kind: IconType.Value): IIcon
/** /**
* Override this method to provide your textures, if you need to check other state * Override this method to provide your textures, if you need to check other state
*/ */
def getIcon(world: IBlockAccess, x: Int, y: Int, z: Int, kind: IconType.Value): Icon = getIcon(world.getBlockMetadata(x, y, z), kind) def getIcon(world: IBlockAccess, x: Int, y: Int, z: Int, kind: IconType.Value): IIcon = getIcon(world.getBlockMetadata(x, y, z), kind)
/** /**
* Set of valid rotations, default is all of them * Set of valid rotations, default is all of them
@@ -63,10 +62,10 @@ trait BaseRotateableBlock extends Block {
} }
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
override def getIcon(side: Int, meta: Int): Icon = getIcon(meta, IconType.fromSideAndDir(side, getDefaultFacing)) override def getIcon(side: Int, meta: Int): IIcon = getIcon(meta, IconType.fromSideAndDir(side, getDefaultFacing))
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
override def getBlockTexture(world: IBlockAccess, x: Int, y: Int, z: Int, side: Int): Icon = getIcon(world, x, y, z, IconType.fromSideAndDir(side, getFacing(world, x, y, z))) override def getIcon(world: IBlockAccess, x: Int, y: Int, z: Int, side: Int): IIcon = getIcon(world, x, y, z, IconType.fromSideAndDir(side, getFacing(world, x, y, z)))
override def getValidRotations(worldObj: World, x: Int, y: Int, z: Int): Array[ForgeDirection] = getValidFacings.toArray(Array.empty[ForgeDirection]) override def getValidRotations(worldObj: World, x: Int, y: Int, z: Int): Array[ForgeDirection] = getValidFacings.toArray(Array.empty[ForgeDirection])
+1 -1
View File
@@ -9,7 +9,7 @@
package net.bdew.lib.rotate package net.bdew.lib.rotate
import net.minecraftforge.common.ForgeDirection import net.minecraftforge.common.util.ForgeDirection
object IconType extends Enumeration { object IconType extends Enumeration {
val BACK = Value(0, "BACK") val BACK = Value(0, "BACK")
@@ -12,21 +12,21 @@ package net.bdew.lib.rotate
import net.minecraft.block.ITileEntityProvider import net.minecraft.block.ITileEntityProvider
import net.minecraft.world.IBlockAccess import net.minecraft.world.IBlockAccess
import net.minecraft.world.World import net.minecraft.world.World
import net.minecraftforge.common.ForgeDirection
import cpw.mods.fml.common.FMLCommonHandler import cpw.mods.fml.common.FMLCommonHandler
import net.minecraftforge.common.util.ForgeDirection
/** /**
* Stores rotation data in tile entity. The TE should implement {@link RotateableTile} * Stores rotation data in tile entity. The TE should implement {@link RotateableTile}
*/ */
trait RotateableTileBlock extends BaseRotateableBlock with ITileEntityProvider { trait RotateableTileBlock extends BaseRotateableBlock with ITileEntityProvider {
def setFacing(world: World, x: Int, y: Int, z: Int, facing: ForgeDirection) { def setFacing(world: World, x: Int, y: Int, z: Int, facing: ForgeDirection) {
world.getBlockTileEntity(x, y, z).asInstanceOf[RotateableTile].rotation := facing world.getTileEntity(x, y, z).asInstanceOf[RotateableTile].rotation := facing
} }
def getFacing(world: IBlockAccess, x: Int, y: Int, z: Int): ForgeDirection = { def getFacing(world: IBlockAccess, x: Int, y: Int, z: Int): ForgeDirection = {
val te: RotateableTile = world.getBlockTileEntity(x, y, z).asInstanceOf[RotateableTile] val te: RotateableTile = world.getTileEntity(x, y, z).asInstanceOf[RotateableTile]
if (te == null || te.rotation == null) { if (te == null || te.rotation == null) {
FMLCommonHandler.instance().getFMLLogger.warning("Failed gettig rocation for block at %d, %d, %d".format(x, y, z)) FMLCommonHandler.instance().getFMLLogger.warn("Failed getting rocation for block at %d, %d, %d".format(x, y, z))
return getDefaultFacing return getDefaultFacing
} }
return te.rotation return te.rotation
+1 -1
View File
@@ -11,7 +11,7 @@ package net.bdew.lib.tile
import net.minecraft.tileentity.TileEntity import net.minecraft.tileentity.TileEntity
import net.minecraftforge.fluids._ import net.minecraftforge.fluids._
import net.minecraftforge.common.ForgeDirection import net.minecraftforge.common.util.ForgeDirection
trait ExposeTank extends TileEntity with IFluidHandler { trait ExposeTank extends TileEntity with IFluidHandler {
def getTankFromDirection(dir: ForgeDirection): IFluidTank def getTankFromDirection(dir: ForgeDirection): IFluidTank
+8 -8
View File
@@ -11,9 +11,9 @@ package net.bdew.lib.tile
import net.minecraft.tileentity.TileEntity import net.minecraft.tileentity.TileEntity
import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagCompound
import net.minecraft.network.INetworkManager import net.minecraft.network.{NetworkManager, Packet}
import net.minecraft.network.packet.Packet132TileEntityData
import net.bdew.lib.Event import net.bdew.lib.Event
import net.minecraft.network.play.server.S35PacketUpdateTileEntity
class TileExtended extends TileEntity { class TileExtended extends TileEntity {
final val ACT_CLIENT = 1 final val ACT_CLIENT = 1
@@ -39,18 +39,18 @@ class TileExtended extends TileEntity {
persistLoad.trigger(tag) persistLoad.trigger(tag)
} }
override final def getDescriptionPacket: Packet132TileEntityData = { override final def getDescriptionPacket: Packet = {
if (!sendClientUpdate.hasListeners) return null if (!sendClientUpdate.hasListeners) return null
val tag = new NBTTagCompound val tag = new NBTTagCompound
sendClientUpdate.trigger(tag) sendClientUpdate.trigger(tag)
return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, ACT_CLIENT, tag) return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, ACT_CLIENT, tag)
} }
override final def onDataPacket(net: INetworkManager, pkt: Packet132TileEntityData) { override final def onDataPacket(net: NetworkManager, pkt: S35PacketUpdateTileEntity) {
if (pkt.actionType == ACT_CLIENT) if (pkt.func_148853_f == ACT_CLIENT)
handleClientUpdate.trigger(pkt.data) handleClientUpdate.trigger(pkt.func_148857_g)
else else
extDataPacket(pkt.actionType, pkt.data) extDataPacket(pkt.func_148853_f, pkt.func_148857_g)
} }
override final def updateEntity() { override final def updateEntity() {
@@ -18,33 +18,33 @@ trait BaseInventory extends IInventory {
def getStackInSlot(i: Int): ItemStack = inv(i) def getStackInSlot(i: Int): ItemStack = inv(i)
def getInvName = "" def getInventoryName = ""
def isInvNameLocalized = false def hasCustomInventoryName = false
def getInventoryStackLimit = 64 def getInventoryStackLimit = 64
def isUseableByPlayer(player: EntityPlayer) = true def isUseableByPlayer(player: EntityPlayer) = true
def openChest() = Unit def openInventory() {}
def closeChest() = Unit def closeInventory() {}
def isItemValidForSlot(slot: Int, stack: ItemStack) = true def isItemValidForSlot(slot: Int, stack: ItemStack) = true
def decrStackSize(slot: Int, n: Int): ItemStack = { def decrStackSize(slot: Int, n: Int): ItemStack = {
var item = inv(slot) val item = inv(slot)
if (item != null) { if (item != null) {
if (item.stackSize <= n) { if (item.stackSize <= n) {
inv(slot) = null inv(slot) = null
onInventoryChanged() markDirty()
return item return item
} else { } else {
var newstack = item.splitStack(n) val newstack = item.splitStack(n)
if (item.stackSize == 0) { if (item.stackSize == 0) {
inv(slot) = null inv(slot) = null
} }
onInventoryChanged() markDirty()
return newstack return newstack
} }
} else { } else {
@@ -55,12 +55,12 @@ trait BaseInventory extends IInventory {
def getStackInSlotOnClosing(slot: Int): ItemStack = { def getStackInSlotOnClosing(slot: Int): ItemStack = {
var tmp = inv(slot) var tmp = inv(slot)
inv(slot) = null inv(slot) = null
onInventoryChanged() markDirty()
return tmp return tmp
} }
def setInventorySlotContents(slot: Int, stack: ItemStack) = { def setInventorySlotContents(slot: Int, stack: ItemStack) = {
inv(slot) = stack inv(slot) = stack
onInventoryChanged() markDirty()
} }
} }
@@ -13,13 +13,13 @@ import net.minecraft.block.Block
import net.minecraft.world.World import net.minecraft.world.World
trait BreakableInventoryBlock extends Block { trait BreakableInventoryBlock extends Block {
override def breakBlock(world: World, x: Int, y: Int, z: Int, blockId: Int, meta: Int) { override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) {
if (!world.isRemote) { if (!world.isRemote) {
val te = world.getBlockTileEntity(x, y, z).asInstanceOf[BreakableInventoryTile] val te = world.getTileEntity(x, y, z).asInstanceOf[BreakableInventoryTile]
if (te != null) { if (te != null) {
te.dropItems() te.dropItems()
} }
} }
super.breakBlock(world, x, y, z, blockId, meta) super.breakBlock(world, x, y, z, block, meta)
} }
} }
@@ -15,9 +15,9 @@ import net.bdew.lib.items.ItemUtils
trait BreakableInventoryTile extends TileEntity with BaseInventory { trait BreakableInventoryTile extends TileEntity with BaseInventory {
def dropItems() { def dropItems() {
if (worldObj != null && !worldObj.isRemote) { if (getWorldObj != null && !getWorldObj.isRemote) {
for (stack <- inv if stack != null) { for (stack <- inv if stack != null) {
ItemUtils.throwItemAt(worldObj, xCoord, yCoord, zCoord, stack) ItemUtils.throwItemAt(getWorldObj, xCoord, yCoord, zCoord, stack)
} }
inv = new Array[ItemStack](inv.size) inv = new Array[ItemStack](inv.size)
} }
@@ -17,7 +17,7 @@ import net.bdew.lib.tile.TileExtended
trait PersistentInventoryTile extends TileExtended with BaseInventory { trait PersistentInventoryTile extends TileExtended with BaseInventory {
persistLoad.listen((tag: NBTTagCompound) => { persistLoad.listen((tag: NBTTagCompound) => {
inv = new Array[ItemStack](getSizeInventory) inv = new Array[ItemStack](getSizeInventory)
for (nbtItem <- Misc.iterNbtList[NBTTagCompound](tag.getTagList("Items"))) { for (nbtItem <- Misc.iterNbtCompoundList(tag, "Items")) {
val slot = nbtItem.getByte("Slot") val slot = nbtItem.getByte("Slot")
if (slot >= 0 && slot < inv.size) { if (slot >= 0 && slot < inv.size) {
inv(slot) = ItemStack.loadItemStackFromNBT(nbtItem) inv(slot) = ItemStack.loadItemStackFromNBT(nbtItem)