diff --git a/README.md b/README.md index 6c30a4f..e37e606 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,12 @@ ForgeMultipart ============== An API for dynamically handling different functional parts in the one block space. + +Requirements: +The latest version of CCC-Public +Forge 7.8.0.706 (or latest git) +scala-compiler.jar (part of a standard scala installation, will need to be moved to /libs/ and linked in your IDE) +A scala compatible IDE and project (For eclipse, download the scala eclipse plugin and right click on the project -> Add Scala Nature) + +Implementation of all parts of the API should be clean and easy in Java. +The minecraft multipart mod is implemented in java as a test case. \ No newline at end of file diff --git a/codechicken/microblock/BlockMicroMaterial.scala b/codechicken/microblock/BlockMicroMaterial.scala new file mode 100644 index 0000000..0e9dc69 --- /dev/null +++ b/codechicken/microblock/BlockMicroMaterial.scala @@ -0,0 +1,107 @@ +package codechicken.microblock + +import net.minecraft.block.Block +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import net.minecraft.util.Icon +import codechicken.core.vec.Cuboid6 +import codechicken.core.lighting.LC; +import codechicken.core.lighting.LightMatrix; +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.core.render.MultiIconTransformation +import codechicken.core.render.IUVTransformation +import codechicken.microblock.MicroblockClassRegistry._ +import net.minecraft.item.Item +import net.minecraft.item.ItemStack +import codechicken.core.vec.Vector3 +import net.minecraft.entity.player.EntityPlayer +import codechicken.core.render.Vertex5 +import codechicken.core.render.UV +import net.minecraft.client.renderer.Tessellator +import codechicken.core.render.CCRenderState +import codechicken.core.vec.Rotation +import net.minecraft.tileentity.TileEntity + +class BlockMicroMaterial(val block:Block, val meta:Int = 0) extends IMicroMaterial +{ + @SideOnly(Side.CLIENT) + var icont:MultiIconTransformation = _ + + @SideOnly(Side.CLIENT) + override def loadIcons() + { + val icons = new Array[Icon](6) + for(i <- 0 until 6) + icons(i) = block.getIcon(i, meta) + icont = new MultiIconTransformation(icons) + } + + def getRenderPass = if(block.canRenderInPass(1)) 1 else 0 + + def renderMicroFace(verts:Array[Vertex5], side:Int, pos:Vector3, lightMatrix:LightMatrix, part:Microblock) + { + renderMicroFace(verts, side, pos, lightMatrix, getColour(part.tile), icont) + } + + def renderMicroFace(verts:Array[Vertex5], side:Int, pos:Vector3, lightMatrix:LightMatrix, colour:Int, uvt:IUVTransformation) + { + val uv = new UV + val t = Tessellator.instance + var i = 0 + while(i < 4) + { + if(CCRenderState.useNormals) + { + val n = Rotation.axes(side%6) + t.setNormal(n.x.toFloat, n.y.toFloat, n.z.toFloat) + } + val vert = verts(i) + if(lightMatrix != null) + { + val lc = LC.computeO(vert.vec, side) + if(CCRenderState.useModelColours) + lightMatrix.setColour(t, lc, colour) + lightMatrix.setBrightness(t, lc) + } + else + { + if(CCRenderState.useModelColours) + CCRenderState.vertexColour(colour) + } + uvt.transform(uv.set(vert.uv)) + t.addVertexWithUV(vert.vec.x+pos.x, vert.vec.y+pos.y, vert.vec.z+pos.z, uv.u, uv.v) + i+=1 + } + } + + def getColour(tile:TileEntity) = + if(tile == null) + block.getBlockColor<<8|0xFF + else + block.colorMultiplier(tile.worldObj, tile.xCoord, tile.yCoord, tile.zCoord)<<8|0xFF + + @SideOnly(Side.CLIENT) + def getBreakingIcon(side:Int) = block.getIcon(side, meta) + + def getItem = Item.itemsList(block.blockID) + + def getLocalizedName = getItem.getItemDisplayName(new ItemStack(getItem, 1, meta)) + + def getStrength(player:EntityPlayer) = player.getCurrentPlayerStrVsBlock(block, false, meta)/block.blockHardness + + def isTransparent = !block.isOpaqueCube +} + +object BlockMicroMaterial +{ + def createAndRegister(block:Block) + { + MicroMaterialRegistry.registerMaterial(new BlockMicroMaterial(block), block.getUnlocalizedName) + } + + def createAndRegister(block:Block, meta:Seq[Int]) + { + val name = block.getUnlocalizedName + meta.foreach(m => MicroMaterialRegistry.registerMaterial(new BlockMicroMaterial(block, m), name+(if(m > 0) "_"+m else ""))) + } +} \ No newline at end of file diff --git a/codechicken/microblock/CommonMicroblock.scala b/codechicken/microblock/CommonMicroblock.scala new file mode 100644 index 0000000..27bf198 --- /dev/null +++ b/codechicken/microblock/CommonMicroblock.scala @@ -0,0 +1,275 @@ +package codechicken.microblock + +import net.minecraft.nbt.NBTTagCompound +import codechicken.core.lighting.LightMatrix; +import codechicken.core.packet.PacketCustom +import codechicken.microblock.MicroMaterialRegistry._ +import codechicken.core.vec.BlockCoord +import org.lwjgl.opengl.GL11 +import codechicken.core.render.CCRenderState +import net.minecraft.world.World +import codechicken.core.vec.Cuboid6 +import codechicken.core.vec.Vector3 +import codechicken.core.lighting.LazyLightMatrix +import codechicken.multipart.TIconHitEffects +import net.minecraft.util.Icon +import net.minecraft.block.Block +import codechicken.multipart.TCuboidPart +import net.minecraft.util.MovingObjectPosition +import net.minecraft.entity.player.EntityPlayer +import codechicken.multipart.JPartialOcclusion +import codechicken.core.vec.Rotation +import codechicken.multipart.TileMultipart +import codechicken.core.render.Vertex5 +import net.minecraft.item.ItemStack +import scala.collection.mutable.ListBuffer +import codechicken.multipart.TMultiPart +import net.minecraftforge.scala.JSeq +import net.minecraftforge.scala.ScalaBridge._ + +object CommonMicroblock +{ + val face = Array[Vertex5](new Vertex5, new Vertex5, new Vertex5, new Vertex5) + + def renderHighlight(world:World, pos:BlockCoord, part:MicroblockClient) + { + GL11.glPushMatrix() + GL11.glTranslated(pos.x+0.5, pos.y+0.5, pos.z+0.5) + GL11.glScaled(1.002, 1.002, 1.002) + GL11.glTranslated(-0.5, -0.5, -0.5) + + GL11.glEnable(GL11.GL_BLEND) + GL11.glDepthMask(false) + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA) + + CCRenderState.reset() + CCRenderState.changeTexture("/terrain.png") + CCRenderState.useNormals(true) + CCRenderState.setBrightness(world, pos.x, pos.y, pos.z) + CCRenderState.setAlpha(80) + CCRenderState.useModelColours(true) + CCRenderState.startDrawing(7) + part.render(new Vector3(), null, MicroMaterialRegistry.getMaterial(part.material), part.getBounds, 0) + CCRenderState.draw() + + GL11.glDisable(GL11.GL_BLEND) + GL11.glDepthMask(true) + GL11.glPopMatrix() + } +} + +trait MicroblockClient extends Microblock with TIconHitEffects +{ +import CommonMicroblock._ + + def getBrokenIcon(side:Int):Icon = + { + val mat = MicroMaterialRegistry.getMaterial(material) + if(mat != null) + return mat.getBreakingIcon(side) + return Block.stone.getIcon(0, 0) + } + + def render(pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial, c:Cuboid6, sideMask:Int) + { + renderCuboid(pos, olm, mat, c, sideMask) + } + + def renderCuboid(pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial, c:Cuboid6, sideMask:Int) + { + val x1 = c.min.x + val x2 = c.max.x + val y1 = c.min.y + val y2 = c.max.y + val z1 = c.min.z + val z2 = c.max.z + var u1:Double = 0 + var u2:Double = 0 + var v1:Double = 0 + var v2:Double = 0 + var side = 0 + var lightMatrix:LightMatrix = null + if(olm != null) + lightMatrix = olm.lightMatrix + + if((sideMask&1) == 0) + { + u1 = x1; v1 = z1 + u2 = x2; v2 = z2 + face(0).set(x1, y1, z2, u1, v2) + face(1).set(x1, y1, z1, u1, v1) + face(2).set(x2, y1, z1, u2, v1) + face(3).set(x2, y1, z2, u2, v2) + mat.renderMicroFace(face, if(c.min.y > 0) 6 else 0, pos, lightMatrix, this) + } + + if((sideMask&2) == 0) + { + u1 = x1+2; v1 = z1 + u2 = x2+2; v2 = z2 + face(0).set(x2, y2, z2, u2, v2) + face(1).set(x2, y2, z1, u2, v1) + face(2).set(x1, y2, z1, u1, v1) + face(3).set(x1, y2, z2, u1, v2) + mat.renderMicroFace(face, if(c.max.y < 1) 7 else 1, pos, lightMatrix, this) + } + + if((sideMask&4) == 0) + { + u1 = 1-x1+4; v1 = 1-y2 + u2 = 1-x2+4; v2 = 1-y1 + face(0).set(x1, y1, z1, u1, v2) + face(1).set(x1, y2, z1, u1, v1) + face(2).set(x2, y2, z1, u2, v1) + face(3).set(x2, y1, z1, u2, v2) + mat.renderMicroFace(face, if(c.min.z > 0) 8 else 2, pos, lightMatrix, this) + } + + if((sideMask&8) == 0) + { + u1 = x1+6; v1 = 1-y2 + u2 = x2+6; v2 = 1-y1 + face(0).set(x2, y1, z2, u2, v2) + face(1).set(x2, y2, z2, u2, v1) + face(2).set(x1, y2, z2, u1, v1) + face(3).set(x1, y1, z2, u1, v2) + mat.renderMicroFace(face, if(c.max.z < 1) 9 else 3, pos, lightMatrix, this) + } + + if((sideMask&0x10) == 0) + { + u1 = z1+8; v1 = 1-y2 + u2 = z2+8; v2 = 1-y1 + face(0).set(x1, y1, z2, u2, v2) + face(1).set(x1, y2, z2, u2, v1) + face(2).set(x1, y2, z1, u1, v1) + face(3).set(x1, y1, z1, u1, v2) + mat.renderMicroFace(face, if(c.min.x > 0) 10 else 4, pos, lightMatrix, this) + } + + if((sideMask&0x20) == 0) + { + u1 = 1-z1+10; v1 = 1-y2 + u2 = 1-z2+10; v2 = 1-y1 + face(0).set(x2, y1, z1, u1, v2) + face(1).set(x2, y2, z1, u1, v1) + face(2).set(x2, y2, z2, u2, v1) + face(3).set(x2, y1, z2, u2, v2) + mat.renderMicroFace(face, if(c.max.x < 1) 11 else 5, pos, lightMatrix, this) + } + } +} + +abstract class Microblock(var shape:Byte = 0, var material:Int = 0) extends TCuboidPart +{ + def this(size:Int, shape:Int, material:Int) = this((size<<4|shape).toByte, material) + + override def getStrength(hit:MovingObjectPosition, player:EntityPlayer):Float = + { + val mat = MicroMaterialRegistry.getMaterial(material) + if(mat != null) + return mat.getStrength(player) + return super.getStrength(hit, player) + } + + override def doesTick = false + + def getSize = shape>>4 + + def getShape = shape&0xF + + def getMaterial = material + + def itemSizes():Seq[Int] = Seq() + + def itemClassID:Int = -1 + + def sizeToVolume(size:Int):Int = size + + override def getDrops():JSeq[ItemStack] = + { + var size = getSize + val items = ListBuffer[ItemStack]() + for(s <- itemSizes.reverseIterator) + { + var m = size/sizeToVolume(s) + size-=m*sizeToVolume(s) + while(m > 0) + { + val k = Math.min(m, 64) + m-=k + items+=ItemMicroPart.create(k, s|itemClassID<<8, MicroMaterialRegistry.materialName(material)) + } + } + return items + } + + override def pickItem(hit:MovingObjectPosition):ItemStack = + { + val size = getSize + for(s <- itemSizes.reverseIterator) + if(size%s == 0 && size/s >= 1) + return ItemMicroPart.create(s|itemClassID<<8, MicroMaterialRegistry.materialName(material)) + return null//unreachable + } + + override def write(packet:PacketCustom) + { + packet.writeByte(shape) + writePartID(packet, material) + } + + override def read(packet:PacketCustom) + { + shape = packet.readByte + material = readPartID(packet) + if(tile != null) + { + tile.notifyPartChange() + tile.markRender() + } + } + + override def save(tag:NBTTagCompound) + { + tag.setByte("shape", shape) + tag.setString("material", materialName(material)) + } + + override def load(tag:NBTTagCompound) + { + shape = tag.getByte("shape") + material = materialID(tag.getString("material")) + } + + def isTransparent = MicroMaterialRegistry.getMaterial(material).isTransparent +} + +trait CommonMicroblockClient extends CommonMicroblock with MicroblockClient with TMicroOcclusionClient +{ + override def renderStatic(pos:Vector3, olm:LazyLightMatrix, pass:Int) + { + val mat = MicroMaterialRegistry.getMaterial(material) + if(mat != null && pass == mat.getRenderPass) + render(pos, olm, mat, renderBounds, renderMask) + } +} + +abstract class CommonMicroblock(shape$:Byte = 0, material$:Int = 0) extends Microblock(shape$, material$) with JPartialOcclusion with TMicroOcclusion +{ + def microClass():MicroblockClass + + def getType = microClass.getName + + def getSlot = getShape + + override def getSlotMask = 1<>1)))+7 +} + +object CornerMicroClass extends MicroblockClass +{ + var aBounds:Array[Cuboid6] = new Array(256) + + for(s <- 0 until 8) + { + val rx = if((s&4) != 0) -1 else 1 + val ry = if((s&1) != 0) -1 else 1 + val rz = if((s&2) != 0) -1 else 1 + val transform = new Scale(new Vector3(rx, ry, rz), Vector3.center) + + for(t <- 1 until 8) + { + val d = t/8D + aBounds(t<<4|s) = new SelectionBox(new Cuboid6(0, 0, 0, d, d, d)) + .transform(transform).bound + } + } + + override def itemSlot = 7 + + def getName = "mcr_cnr" + + def create(client:Boolean) = + if(client) + new CornerMicroblockClient + else + new CornerMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean) = + if(client) + new CornerMicroblockClient(size, slot, material) + else + new CornerMicroblock(size, slot, material) + + def placementProperties = CornerPlacement + + override def sizeToVolume(size:Int) = (size+1)*(size+1)*(size+1) + + def getDisplayName(size:Int):String = size match + { + case 1 => "Nook" + case 2 => "Corner" + case 4 => "Notch" + } +} + +class CornerMicroblockClient(shape$:Byte = 0, material$:Int = 0) extends CornerMicroblock(shape$, material$) with CommonMicroblockClient +{ + def this(size:Int, slot:Int, material:Int) = this((size<<4|(slot-7)).toByte, material) +} + +class CornerMicroblock(shape$:Byte = 0, material$:Int = 0) extends CommonMicroblock(shape$, material$) +{ + def this(size:Int, slot:Int, material:Int) = this((size<<4|(slot-7)).toByte, material) + + def microClass = CornerMicroClass + + def getBounds = CornerMicroClass.aBounds(shape) + + override def getSlot = getShape+7 +} \ No newline at end of file diff --git a/codechicken/microblock/DefaultContent.scala b/codechicken/microblock/DefaultContent.scala new file mode 100644 index 0000000..cfb67c8 --- /dev/null +++ b/codechicken/microblock/DefaultContent.scala @@ -0,0 +1,50 @@ +package codechicken.microblock + +import net.minecraft.block.Block._ +import BlockMicroMaterial._ +import MicroMaterialRegistry._ + +object DefaultContent +{ + def load() + { + FaceMicroClass.register(0) + HollowMicroClass.register(1) + CornerMicroClass.register(2) + EdgeMicroClass.register(3) + PostMicroClass.register() + + createAndRegister(stone) + createAndRegister(dirt) + createAndRegister(cobblestone) + createAndRegister(planks, 0 to 3) + createAndRegister(wood, 0 to 3) + createAndRegister(leaves, 0 to 3) + createAndRegister(sponge) + createAndRegister(glass) + createAndRegister(blockLapis) + createAndRegister(sandStone, 0 to 2) + createAndRegister(cloth, 0 to 15) + createAndRegister(blockGold) + createAndRegister(blockIron) + createAndRegister(brick) + createAndRegister(bookShelf) + createAndRegister(cobblestoneMossy) + createAndRegister(obsidian) + createAndRegister(blockDiamond) + createAndRegister(ice) + createAndRegister(snow) + createAndRegister(blockClay) + createAndRegister(netherrack) + createAndRegister(slowSand) + createAndRegister(glowStone) + createAndRegister(stoneBrick, 0 to 3) + createAndRegister(netherBrick) + createAndRegister(whiteStone) + createAndRegister(blockEmerald) + createAndRegister(blockRedstone) + createAndRegister(blockNetherQuartz) + registerMaterial(new GrassMicroMaterial, grass.getUnlocalizedName) + registerMaterial(new TopMicroMaterial(mycelium), mycelium.getUnlocalizedName) + } +} \ No newline at end of file diff --git a/codechicken/microblock/EdgeMicroblock.scala b/codechicken/microblock/EdgeMicroblock.scala new file mode 100644 index 0000000..a34c4bd --- /dev/null +++ b/codechicken/microblock/EdgeMicroblock.scala @@ -0,0 +1,271 @@ +package codechicken.microblock + +import codechicken.core.vec.Cuboid6 +import codechicken.core.vec.Scale +import codechicken.core.vec.Vector3 +import codechicken.core.raytracer.SelectionBox +import codechicken.core.vec.TransformationList +import codechicken.core.vec.AxisCycle +import codechicken.core.vec.Rotation +import codechicken.multipart.TMultiPart +import codechicken.multipart.TNormalOcclusion +import codechicken.multipart.JPartialOcclusion +import codechicken.multipart.NormalOcclusionTest +import codechicken.multipart.TileMultipart +import codechicken.multipart.MultiPartRegistry +import codechicken.core.lighting.LazyLightMatrix +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import net.minecraftforge.scala.ScalaBridge._ +import codechicken.core.raytracer.ExtendedMOP + +object EdgePlacement extends PlacementProperties +{ + import codechicken.multipart.PartMap._ + + def microClass = EdgeMicroClass + + def placementGrid = EdgePlacementGrid + + def opposite(slot:Int, side:Int):Int = + { + if(slot < 0)//custom placement + return slot + val e = slot-15 + return 15+(packEdgeBits(e, unpackEdgeBits(e)^(1<<(side>>1)))) + } + + override def customPlacement(pmt:MicroblockPlacement):ExecutablePlacement = + { + if(pmt.size%2 == 1) return null + + val part = PostMicroClass.create(pmt.size, pmt.hit.sideHit>>1, pmt.material, pmt.world.isRemote) + if(pmt.doExpand) + { + val hpart = pmt.htile.partList(ExtendedMOP.getData[(Int, _)](pmt.hit)._1) + if(hpart.getType == PostMicroClass.getName) + { + val mpart = hpart.asInstanceOf[Microblock] + if(mpart.material == pmt.material && mpart.getSize + pmt.size < 8) + { + part.shape = ((mpart.getSize+pmt.size)<<4|mpart.getShape).toByte + return pmt.expand(mpart, part) + } + } + } + + if(pmt.slot >= 0) + return null + + if(pmt.internal && !pmt.oppMod) + return pmt.internalPlacement(pmt.htile.asInstanceOf[TileMultipart], part) + + return pmt.externalPlacement(part) + } +} + +object EdgeMicroClass extends MicroblockClass +{ + var aBounds:Array[Cuboid6] = new Array(256) + + for(s <- 0 until 12) + { + val rx = if((s&2) != 0) -1 else 1 + val rz = if((s&1) != 0) -1 else 1 + val transform = new TransformationList(new Scale(new Vector3(rx, 1, rz)), AxisCycle.cycles(s>>2)) + + for(t <- 1 until 8) + { + val d = t/8D + aBounds(t<<4|s) = new SelectionBox(new Cuboid6(0, 0, 0, d, 1, d)) + .transform(transform, Vector3.center).bound + } + } + + override def itemSlot = 15 + + def getName = "mcr_edge" + + def create(client:Boolean) = + if(client) + new EdgeMicroblockClient + else + new EdgeMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean) = + if(client) + new EdgeMicroblockClient(size, slot, material) + else + new EdgeMicroblock(size, slot, material) + + def placementProperties = EdgePlacement + + override def sizeToVolume(size:Int) = size*size + + def getDisplayName(size:Int):String = size match + { + case 1 => "Strip" + case 2 => "Post" + case 4 => "Pillar" + } +} + +class EdgeMicroblockClient(shape$:Byte = 0, material$:Int = 0) extends EdgeMicroblock(shape$, material$) with CommonMicroblockClient +{ + def this(size:Int, slot:Int, material:Int) = this((size<<4|(slot-15)).toByte, material) +} + +class EdgeMicroblock(shape$:Byte = 0, material$:Int = 0) extends CommonMicroblock(shape$, material$) +{ + def this(size:Int, slot:Int, material:Int) = this((size<<4|(slot-15)).toByte, material) + + def microClass = EdgeMicroClass + + def getBounds = EdgeMicroClass.aBounds(shape) + + override def getSlot = getShape+15 +} + +object PostMicroClass +{ + var aBounds:Array[Cuboid6] = new Array(256) + + for(s <- 0 until 3) + { + for(t <- 2 until 8 by 2) + { + val d1 = 0.5-t/16D + val d2 = 0.5+t/16D + aBounds(t<<4|s) = new SelectionBox(new Cuboid6(d1, 0, d1, d2, 1, d2)) + .transform(Rotation.sideRotations(s<<1), Vector3.center).bound + } + } + + def getName = "mcr_post" + + def create(client:Boolean) = + if(client) + new PostMicroblockClient + else + new PostMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean) = + if(client) + new PostMicroblockClient(size, slot, material) + else + new PostMicroblock(size, slot, material) + + def register() = MultiPartRegistry.registerParts((_, c:Boolean) => create(c), getName) +} + +class PostMicroblockClient(shape$:Byte = 0, material$:Int = 0) extends PostMicroblock(shape$, material$) with MicroblockClient +{ + var renderBounds1:Cuboid6 = _ + var renderBounds2:Cuboid6 = _ + + def this(size:Int, orient:Int, material:Int) = this((size<<4|orient).toByte, material) + + override def renderStatic(pos:Vector3, olm:LazyLightMatrix, pass:Int) + { + val mat = MicroMaterialRegistry.getMaterial(material) + if(mat != null && pass == mat.getRenderPass) + render(pos, olm, mat) + } + + def render(pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial) + { + renderCuboid(pos, olm, mat, renderBounds1, 0) + if(renderBounds2 != null) + renderCuboid(pos, olm, mat, renderBounds2, 0) + } + + override def onPartChanged() + { + if(tile.worldObj.isRemote) + recalcBounds() + } + + def recalcBounds() + { + renderBounds1 = getBounds.copy + renderBounds2 = null + + shrinkFace(getShape<<1) + shrinkFace(getShape<<1|1) + + tile.partList.foreach(p => + if(p.isInstanceOf[PostMicroblock] && p != this) + shrinkPost(p.asInstanceOf[PostMicroblock]) + ) + } + + def shrinkFace(fside:Int) + { + val part = tile.partMap(fside) + if(part != null && part.getType.equals("mcr_face")) + MicroOcclusion.shrink(renderBounds1, part.asInstanceOf[CommonMicroblock].getBounds, fside) + } + + def shrinkPost(post:PostMicroblock) + { + if(post == this) + return + + if(thisShrinks(post)) + { + if(renderBounds2 == null) + { + renderBounds2 = renderBounds1.copy + getShape match + { + case 0 => renderBounds2.min.y = 0.5; renderBounds1.max.y = 0.5 + case 1 => renderBounds2.min.z = 0.5; renderBounds1.max.z = 0.5 + case 2 => renderBounds2.min.x = 0.5; renderBounds1.max.x = 0.5 + } + } + MicroOcclusion.shrink(renderBounds1, post.getBounds, getShape<<1|1) + MicroOcclusion.shrink(renderBounds2, post.getBounds, getShape<<1) + } + } + + def thisShrinks(other:PostMicroblock):Boolean = + { + if(getSize != other.getSize) return getSize < other.getSize + if(isTransparent != other.isTransparent) return isTransparent + return getShape > other.getShape + } +} + +class PostMicroblock(shape$:Byte = 0, material$:Int = 0) extends Microblock(shape$, material$) with JPartialOcclusion with TNormalOcclusion +{ + def this(size:Int, orient:Int, material:Int) = this((size<<4|orient).toByte, material) + + override def getType = PostMicroClass.getName + + def getBounds = PostMicroClass.aBounds(shape) + + override def getSlotMask = 0 + + def getOcclusionBoxes = Seq(getBounds) + + def getPartialOcclusionBoxes = getOcclusionBoxes + + override def itemSizes = EdgeMicroClass.itemSizes + + override def itemClassID = EdgeMicroClass.classID + + override def sizeToVolume(size:Int) = EdgeMicroClass.sizeToVolume(size) + + override def occlusionTest(npart:TMultiPart): Boolean = + { + if(npart.isInstanceOf[PostMicroblock]) + return npart.asInstanceOf[PostMicroblock].getShape != getShape + + if(npart.getType.equals("mcr_face")) + if(npart.asInstanceOf[CommonMicroblock].getSlot>>1 == getShape) + return true + + return super.occlusionTest(npart) + } +} \ No newline at end of file diff --git a/codechicken/microblock/FaceMicroblock.scala b/codechicken/microblock/FaceMicroblock.scala new file mode 100644 index 0000000..bd3c6c0 --- /dev/null +++ b/codechicken/microblock/FaceMicroblock.scala @@ -0,0 +1,104 @@ +package codechicken.microblock + +import codechicken.core.packet.PacketCustom +import net.minecraft.nbt.NBTTagCompound +import net.minecraft.util.MovingObjectPosition +import net.minecraft.item.ItemStack +import codechicken.core.vec.Cuboid6 +import net.minecraft.entity.player.EntityPlayer +import codechicken.multipart.TCuboidPart +import codechicken.multipart.TFacePart +import codechicken.core.vec.Vector3 +import codechicken.core.raytracer.SelectionBox +import codechicken.core.vec.Rotation +import codechicken.multipart.PartMap +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.core.lighting.CCRBModel +import net.minecraft.world.World +import codechicken.core.vec.BlockCoord +import codechicken.multipart.MultipartRenderer +import codechicken.core.render.CCModel +import codechicken.multipart.TileMultipart +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import net.minecraft.block.Block +import scala.collection.immutable.Vector +import scala.collection.mutable.ListBuffer +import codechicken.multipart.BlockMultipart +import codechicken.core.lighting.LazyLightMatrix + +object FacePlacement extends PlacementProperties +{ + def microClass = FaceMicroClass + + def placementGrid = FacePlacementGrid + + def opposite(slot:Int, side:Int) = slot^1 + + override def expand(slot:Int, side:Int) = sneakOpposite(slot, side) + + override def sneakOpposite(slot:Int, side:Int) = slot == (side^1) +} + +object FaceMicroClass extends MicroblockClass +{ + var aBounds:Array[Cuboid6] = new Array(256); + + for(s <- 0 until 6) + for(t <- 1 until 8) + { + val d = t/8D + aBounds(t<<4|s) = new SelectionBox(new Cuboid6(0, 0, 0, 1, d, 1)) + .transform(Rotation.sideRotations(s), Vector3.center).bound + } + + def getName = "mcr_face" + + def create(client:Boolean) = + if(client) + new FaceMicroblockClient + else + new FaceMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean) = + if(client) + new FaceMicroblockClient(size, slot, material) + else + new FaceMicroblock(size, slot, material) + + def placementProperties = FacePlacement + + def getDisplayName(size:Int):String = size match + { + case 1 => "Cover" + case 2 => "Panel" + case 4 => "Slab" + } +} + +class FaceMicroblockClient(shape$:Byte = 0, material$:Int = 0) extends FaceMicroblock(shape$, material$) with CommonMicroblockClient +{ + def this(size:Int, shape:Int, material:Int) = this((size<<4|shape).toByte, material) + + override def render(pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial, c:Cuboid6, sideMask:Int) + { + if(isTransparent) + renderCuboid(pos, olm, mat, c, sideMask) + else + { + renderCuboid(pos, olm, mat, c, sideMask|1< 1 && side%6 < 6) + renderMicroFace(verts, side, pos, lightMatrix, colour, new TopIconTransformation(part.getBounds.max.y, sideIconT)) + } +} + +class TopMicroMaterial($block:Block, $meta:Int = 0) extends BlockMicroMaterial($block, $meta) +{ + override def renderMicroFace(verts:Array[Vertex5], side:Int, pos:Vector3, lightMatrix:LightMatrix, part:Microblock) + { + if(side%6 > 1 && side%6 < 6) + renderMicroFace(verts, side, pos, lightMatrix, getColour(part.tile), new TopIconTransformation(part.getBounds.max.y, icont)) + else + super.renderMicroFace(verts, side, pos, lightMatrix, part) + } +} \ No newline at end of file diff --git a/codechicken/microblock/HolloMicroblock.scala b/codechicken/microblock/HolloMicroblock.scala new file mode 100644 index 0000000..71c3f3b --- /dev/null +++ b/codechicken/microblock/HolloMicroblock.scala @@ -0,0 +1,230 @@ +package codechicken.microblock + +import net.minecraft.world.World +import net.minecraft.entity.player.EntityPlayer +import net.minecraft.util.MovingObjectPosition +import codechicken.multipart.TFacePart +import codechicken.core.vec.BlockCoord +import codechicken.core.vec.Cuboid6 +import codechicken.core.raytracer.SelectionBox +import codechicken.core.vec.Rotation +import codechicken.core.vec.Vector3 +import codechicken.multipart.TNormalOcclusion +import codechicken.core.lighting.LazyLightMatrix +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import net.minecraft.client.renderer.RenderBlocks +import codechicken.core.render.IconTransformation +import codechicken.core.render.RenderUtils +import codechicken.core.render.CCRenderState +import net.minecraftforge.scala.ScalaBridge._ +import net.minecraftforge.scala.JSeq + +object HollowPlacement extends PlacementProperties +{ + def microClass = HollowMicroClass + + def placementGrid = FacePlacementGrid + + def opposite(slot:Int, side:Int) = slot^1 + + override def expand(slot:Int, side:Int) = sneakOpposite(slot, side) + + override def sneakOpposite(slot:Int, side:Int) = slot == (side^1) +} + +object HollowMicroClass extends MicroblockClass +{ + var pBoxes:Array[Seq[Cuboid6]] = new Array(256) + var occBounds:Array[Cuboid6] = new Array(256) + for(s <- 0 until 6) + for(t <- 1 until 8) + { + val d = t/8D + val w1 = 1/8D + val w2 = 3/16D + pBoxes(t<<4|s) = Seq( + new SelectionBox(new Cuboid6(0, 0, 0, w1, d, 1)), + new SelectionBox(new Cuboid6(1-w1, 0, 0, 1, d, 1)), + new SelectionBox(new Cuboid6(w1, 0, 0, 1-w1, d, w1)), + new SelectionBox(new Cuboid6(w1, 0, 1-w1, 1-w1, d, 1))) + .map(_.transform(Rotation.sideRotations(s), Vector3.center).bound) + occBounds(t<<4|s) = new SelectionBox(new Cuboid6(1/8D, 0, 1/8D, 7/8D, d, 7/8D)) + .transform(Rotation.sideRotations(s), Vector3.center).bound + } + + def getName = "mcr_hllw" + + def create(client:Boolean) = + if(client) + new HollowMicroblockClient + else + new HollowMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean) = + if(client) + new HollowMicroblockClient(size, slot, material) + else + new HollowMicroblock(size, slot, material) + + def placementProperties = HollowPlacement + + def getDisplayName(size:Int) = "Hollow "+FaceMicroClass.getDisplayName(size) +} + +class HollowMicroblockClient(shape$:Byte = 0, material$:Int = 0) extends HollowMicroblock(shape$, material$) with CommonMicroblockClient +{ + renderMask |= 8<<8 + + def this(size:Int, shape:Int, material:Int) = this((size<<4|shape).toByte, material) + + override def onPartChanged() + { + super.onPartChanged() + renderMask = renderMask&0xFF | getHollowSize<<8 + } + + override def drawBreaking(renderBlocks:RenderBlocks) + { + CCRenderState.reset() + val icont = new IconTransformation(renderBlocks.overrideBlockTexture) + renderHollow(Vector3.fromTileEntity(tile), null, null, getBounds, 0, false, + (pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial, c:Cuboid6, sideMask:Int)=> + RenderUtils.renderBlock(c, sideMask, pos, icont)) + } + + override def render(pos:Vector3, olm:LazyLightMatrix, mat:IMicroMaterial, c:Cuboid6, sideMask:Int) + { + if(isTransparent) + renderHollow(pos, olm, mat, c, sideMask, false, renderCuboid) + else + { + renderHollow(pos, olm, mat, c, sideMask|1<Unit) + { + val size = renderMask >> 8 + val d1 = 0.5-size/32D + val d2 = 0.5+size/32D + val x1 = c.min.x + val x2 = c.max.x + val y1 = c.min.y + val y2 = c.max.y + val z1 = c.min.z + val z2 = c.max.z + + var faceMask = sideMask + var iMask = 0 + if(face) + faceMask = ~(1< + { + if(face) + iMask = 0x3C + f(pos, olm, mat, new Cuboid6(d1, y1, d2, d2, y2, z2), 0x3B|iMask)//-z internal + f(pos, olm, mat, new Cuboid6(d1, y1, z1, d2, y2, d1), 0x37|iMask)//+z internal + + f(pos, olm, mat, new Cuboid6(d2, y1, d1, x2, y2, d2), faceMask&0x23|0xC|iMask)//-x internal -y+y+x external + f(pos, olm, mat, new Cuboid6(x1, y1, d1, d1, y2, d2), faceMask&0x13|0xC|iMask)//+x internal -y+y-x external + + f(pos, olm, mat, new Cuboid6(x1, y1, d2, x2, y2, z2), faceMask&0x3B|4|iMask)//-y+y+z-x+x external + f(pos, olm, mat, new Cuboid6(x1, y1, z1, x2, y2, d1), faceMask&0x37|8|iMask)//-y+y-z-x+x external + } + case 2 | 3 => + { + if(face) + iMask = 0x33 + f(pos, olm, mat, new Cuboid6(d2, d1, z1, x2, d2, z2), 0x2F|iMask)//-x internal + f(pos, olm, mat, new Cuboid6(x1, d1, z1, d1, d2, z2), 0x1F|iMask)//+x internal + + f(pos, olm, mat, new Cuboid6(d1, d2, z1, d2, y2, z2), faceMask&0xE|0x30|iMask)//-y internal -z+z+y external + f(pos, olm, mat, new Cuboid6(d1, y1, z1, d2, d1, z2), faceMask&0xD|0x30|iMask)//+y internal -z+z-y external + + f(pos, olm, mat, new Cuboid6(d2, y1, z1, x2, y2, z2), faceMask&0x2F|0x10|iMask)//-z+z+x-y+y external + f(pos, olm, mat, new Cuboid6(x1, y1, z1, d1, y2, z2), faceMask&0x1F|0x20|iMask)//-z+z-x-y+y external + } + case 4 | 5 => + { + if(face) + iMask = 0xF + f(pos, olm, mat, new Cuboid6(x1, d2, d1, x2, y2, d2), 0x3E|iMask)//-y internal + f(pos, olm, mat, new Cuboid6(x1, y1, d1, x2, d1, d2), 0x3D|iMask)//+y internal + + f(pos, olm, mat, new Cuboid6(x1, d1, d2, x2, d2, z2), faceMask&0x38|3|iMask)//-z internal -x+x+z external + f(pos, olm, mat, new Cuboid6(x1, d1, z1, x2, d2, d1), faceMask&0x34|3|iMask)//+z internal -x+x-z external + + f(pos, olm, mat, new Cuboid6(x1, d2, z1, x2, y2, z2), faceMask&0x3E|1|iMask)//-x+x+y-z+z external + f(pos, olm, mat, new Cuboid6(x1, y1, z1, x2, d1, z2), faceMask&0x3D|2|iMask)//-x+x-y-z+z external + } + } + } +} + +class HollowMicroblock(shape$:Byte = 0, material$:Int = 0) extends CommonMicroblock(shape$, material$) with TFacePart with TNormalOcclusion +{ + def this(size:Int, shape:Int, material:Int) = this((size<<4|shape).toByte, material) + + def microClass = HollowMicroClass + + def getBounds:Cuboid6 = FaceMicroClass.aBounds(shape) + + override def getPartialOcclusionBoxes = HollowMicroClass.pBoxes(shape) + + def getHollowSize = + { + val part = tile.partMap(6) + if(part.isInstanceOf[IHollowConnect]) + part.asInstanceOf[IHollowConnect].getSize + else + 8 + } + + def getOcclusionBoxes:JSeq[Cuboid6] = + { + val size = getSize + val c = HollowMicroClass.occBounds(shape) + val d1 = 0.5-size/32D + val d2 = 0.5+size/32D + val x1 = c.min.x + val x2 = c.max.x + val y1 = c.min.y + val y2 = c.max.y + val z1 = c.min.z + val z2 = c.max.z + + return getSlot match + { + case 0 | 1 => + { + Seq(new Cuboid6(d2, y1, d1, x2, y2, d2), + new Cuboid6(x1, y1, d1, d1, y2, d2), + new Cuboid6(x1, y1, d2, x2, y2, z2), + new Cuboid6(x1, y1, z1, x2, y2, d1)) + } + case 2 | 3 => + { + Seq(new Cuboid6(d1, d2, z1, d2, y2, z2), + new Cuboid6(d1, y1, z1, d2, d1, z2), + new Cuboid6(d2, y1, z1, x2, y2, z2), + new Cuboid6(x1, y1, z1, d1, y2, z2)) + } + case 4 | 5 => + { + Seq(new Cuboid6(x1, d1, d2, x2, d2, z2), + new Cuboid6(x1, d1, z1, x2, d2, d1), + new Cuboid6(x1, d2, z1, x2, y2, z2), + new Cuboid6(x1, y1, z1, x2, d1, z2)) + } + } + } + + override def allowCompleteOcclusion = true + + override def solid(side:Int) = false +} \ No newline at end of file diff --git a/codechicken/microblock/IHollowConnect.java b/codechicken/microblock/IHollowConnect.java new file mode 100644 index 0000000..835c9d6 --- /dev/null +++ b/codechicken/microblock/IHollowConnect.java @@ -0,0 +1,12 @@ +package codechicken.microblock; + +/** + * Implement this on center parts that connect through hollow covers to have the covers render their hollows to fit the connection size + */ +public interface IHollowConnect +{ + /** + * @return The size (width and height) of the connection in pixels. Must be be less than 12 and more than 0 + */ + public int getSize(); +} diff --git a/codechicken/microblock/ItemMicroPart.scala b/codechicken/microblock/ItemMicroPart.scala new file mode 100644 index 0000000..f6e5ae6 --- /dev/null +++ b/codechicken/microblock/ItemMicroPart.scala @@ -0,0 +1,177 @@ +package codechicken.microblock + +import net.minecraft.item.Item +import net.minecraft.item.ItemStack +import net.minecraft.nbt.NBTTagCompound +import ItemMicroPart._ +import net.minecraftforge.client.IItemRenderer +import net.minecraftforge.client.IItemRenderer.ItemRenderType +import net.minecraftforge.client.IItemRenderer.ItemRendererHelper +import org.lwjgl.opengl.GL11 +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import net.minecraft.util.StatCollector +import java.util.List +import net.minecraft.creativetab.CreativeTabs +import codechicken.microblock.MicroblockClassRegistry._ +import codechicken.core.render.CCRenderState +import net.minecraft.client.renderer.texture.IconRegister +import codechicken.microblock.handler.MicroblockProxy +import net.minecraft.util.MovingObjectPosition +import net.minecraft.entity.player.EntityPlayer +import net.minecraft.world.World +import codechicken.core.raytracer.RayTracer +import net.minecraft.util.EnumMovingObjectType +import codechicken.core.vec.Vector3 + +class ItemMicroPart(id:Int) extends Item(id) +{ + setHasSubtypes(true) + + override def getItemDisplayName(stack:ItemStack):String = + { + val material = getMaterial(stack) + val mcrClass = MicroblockClassRegistry.getMicroClass(stack.getItemDamage) + val size = stack.getItemDamage&0xFF + if(material == null || mcrClass == null || !mcrClass.itemSizes.contains(size)) + return "Unnamed" + + return material.getLocalizedName+" "+mcrClass.getDisplayName(size) + } + + override def getSubItems(id:Int, tab:CreativeTabs, list$:List[_]) + { + val list = list$.asInstanceOf[List[ItemStack]] + for(classId <- 0 until classes.length) + { + val mcrClass = classes(classId) + if(mcrClass != null) + mcrClass.itemSizes.foreach(size => + MicroMaterialRegistry.materials_foreach((s, m) => list.add(create(classId<<8|size, s)))) + } + } + + override def registerIcons(register:IconRegister){} + + override def onItemUseFirst(item:ItemStack, player:EntityPlayer, world:World, x:Int, y:Int, z:Int, s:Int, hitX:Float, hitY:Float, hitZ:Float):Boolean = + { + if(player.isSneaking) + return useItem(item, player, world, x, y, z) && !world.isRemote + return false + } + + override def onItemUse(item:ItemStack, player:EntityPlayer, world:World, x:Int, y:Int, z:Int, s:Int, hitX:Float, hitY:Float, hitZ:Float):Boolean = + { + if(!player.isSneaking) + return useItem(item, player, world, x, y, z) + return false + } + + def useItem(item:ItemStack, player:EntityPlayer, world:World, x:Int, y:Int, z:Int):Boolean = + { + val material = getMaterialID(item) + val mcrClass = MicroblockClassRegistry.getMicroClass(item.getItemDamage) + val size = item.getItemDamage&0xFF + if(material < 0 || mcrClass == null || !mcrClass.itemSizes.contains(size)) + return false + + val hit = RayTracer.retraceBlock(world, player, x, y, z) + if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) + { + val placement = MicroblockPlacement(world, player, hit, size, material, !player.capabilities.isCreativeMode, mcrClass.placementProperties) + if(placement == null) + return false + + if(!world.isRemote) + { + placement.place(world, player, item) + if(!player.capabilities.isCreativeMode) + placement.consume(world, player, item) + } + + return true + } + + return false + } +} + +object ItemMicroPart +{ + def checkTagCompound(stack:ItemStack) + { + if(!stack.hasTagCompound()) + stack.setTagCompound(new NBTTagCompound("tag")) + } + + def create(damage:Int, material:Int):ItemStack = create(damage, MicroMaterialRegistry.materialName(material)) + + def create(damage:Int, material:String):ItemStack = create(1, damage, material) + + def create(amount:Int, damage:Int, material:String):ItemStack = + { + val stack = new ItemStack(MicroblockProxy.item, amount, damage) + checkTagCompound(stack) + stack.getTagCompound().setString("mat", material) + return stack + } + + def getMaterial(stack:ItemStack):IMicroMaterial = + { + checkTagCompound(stack) + if(!stack.getTagCompound().hasKey("mat")) + return null; + + return MicroMaterialRegistry.getMaterial(stack.getTagCompound().getString("mat")) + } + + def getMaterialID(stack:ItemStack):Int = + { + checkTagCompound(stack) + if(!stack.getTagCompound().hasKey("mat")) + return -1; + + return MicroMaterialRegistry.materialID(stack.getTagCompound().getString("mat")) + } +} + +object ItemMicroPartRenderer extends IItemRenderer +{ + def handleRenderType(item:ItemStack, t:ItemRenderType) = true + + def shouldUseRenderHelper(t:ItemRenderType, item:ItemStack, helper:ItemRendererHelper) = true + + def renderItem(t:ItemRenderType, item:ItemStack, data:Object*) + { + if(t == ItemRenderType.ENTITY) + GL11.glScaled(0.5, 0.5, 0.5); + if(t == ItemRenderType.INVENTORY || t == ItemRenderType.ENTITY) + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + + val material = getMaterial(item) + val mcrClass = MicroblockClassRegistry.getMicroClass(item.getItemDamage) + val size = item.getItemDamage&0xFF + if(material == null || mcrClass == null || !mcrClass.itemSizes.contains(size)) + return + + CCRenderState.reset() + CCRenderState.changeTexture("/terrain.png") + CCRenderState.useNormals(true) + CCRenderState.useModelColours(true) + CCRenderState.pullLightmap() + CCRenderState.startDrawing(7) + val part = mcrClass.create(size, mcrClass.itemSlot, 0, true).asInstanceOf[MicroblockClient] + part.render(new Vector3(0.5, 0.5, 0.5).subtract(part.getBounds.center), null, material, part.getBounds, 0) + CCRenderState.draw() + } + + def renderHighlight(world:World, player:EntityPlayer, stack:ItemStack, hit:MovingObjectPosition):Boolean = + { + val material = getMaterialID(stack) + val mcrClass = MicroblockClassRegistry.getMicroClass(stack.getItemDamage) + val size = stack.getItemDamage&0xFF + if(material < 0 || mcrClass == null || !mcrClass.itemSizes.contains(size)) + return false + + return mcrClass.renderHighlight(world, player, hit, size, material) + } +} \ No newline at end of file diff --git a/codechicken/microblock/MicroClass.scala b/codechicken/microblock/MicroClass.scala new file mode 100644 index 0000000..6d9422c --- /dev/null +++ b/codechicken/microblock/MicroClass.scala @@ -0,0 +1,48 @@ +package codechicken.microblock + +import codechicken.core.lighting.CCRBModel +import net.minecraft.util.MovingObjectPosition +import net.minecraft.world.World +import codechicken.core.vec.BlockCoord +import codechicken.core.vec.Vector3 +import codechicken.core.render.CCModel +import codechicken.multipart.TMultiPart +import net.minecraft.entity.player.EntityPlayer +import codechicken.multipart.TileMultipart +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side + +trait MicroblockClass +{ + var classID:Int = _ + + def getDisplayName(size:Int):String + + def itemSizes() = Seq(1, 2, 4) + + def itemSlot() = 3 + + @SideOnly(Side.CLIENT) + def renderHighlight(world:World, player:EntityPlayer, hit:MovingObjectPosition, size:Int, material:Int):Boolean = + { + placementProperties.placementGrid.render(new Vector3(hit.hitVec), hit.sideHit) + + val placement = MicroblockPlacement(world, player, hit, size, material, !player.capabilities.isCreativeMode, placementProperties) + if(placement != null) + CommonMicroblock.renderHighlight(world, placement.pos, placement.part.asInstanceOf[MicroblockClient]) + + return true + } + + def getName():String + + def create(client:Boolean):CommonMicroblock + + def create(size:Int, slot:Int, material:Int, client:Boolean):CommonMicroblock + + def sizeToVolume(size:Int) = size + + def placementProperties():PlacementProperties + + def register(id:Int) = MicroblockClassRegistry.registerMicroClass(this, id) +} \ No newline at end of file diff --git a/codechicken/microblock/MicroClassRegistry.scala b/codechicken/microblock/MicroClassRegistry.scala new file mode 100644 index 0000000..8095c65 --- /dev/null +++ b/codechicken/microblock/MicroClassRegistry.scala @@ -0,0 +1,21 @@ +package codechicken.microblock + +import codechicken.multipart.MultiPartRegistry +import codechicken.microblock.handler.MicroblockProxy + +object MicroblockClassRegistry +{ + val classes = new Array[MicroblockClass](256) + + def getMicroClass(modelId:Int) = classes(modelId>>8) + + def registerMicroClass(mcrClass:MicroblockClass, id:Int) + { + if(classes(id) != null) + throw new IllegalArgumentException("Microblock class id "+id+" is already taken by "+classes(id).getName+" when adding "+mcrClass.getName) + + classes(id) = mcrClass + mcrClass.classID = id + MultiPartRegistry.registerParts((_, c:Boolean) => mcrClass.create(c), mcrClass.getName) + } +} \ No newline at end of file diff --git a/codechicken/microblock/MicroMaterialRegistry.scala b/codechicken/microblock/MicroMaterialRegistry.scala new file mode 100644 index 0000000..c03ed60 --- /dev/null +++ b/codechicken/microblock/MicroMaterialRegistry.scala @@ -0,0 +1,118 @@ +package codechicken.microblock + +import codechicken.core.vec.Cuboid6 +import codechicken.multipart.IDWriter +import codechicken.core.lighting.LightMatrix; +import codechicken.core.packet.PacketCustom +import scala.collection.mutable.HashMap +import codechicken.core.data.MCDataOutput +import codechicken.core.data.MCDataInput +import codechicken.multipart.MultiPartRegistry +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.microblock.handler.MicroblockProxy +import codechicken.core.vec.Vector3 +import net.minecraft.util.Icon +import net.minecraft.entity.player.EntityPlayer +import codechicken.core.render.Vertex5 + +object MicroMaterialRegistry +{ + trait IMicroMaterial + { + @SideOnly(Side.CLIENT) + def getBreakingIcon(side:Int):Icon + + @SideOnly(Side.CLIENT) + def loadIcons(){} + + @SideOnly(Side.CLIENT) + def renderMicroFace(verts:Array[Vertex5], side:Int, pos:Vector3, lightMatrix:LightMatrix, part:Microblock) + + @SideOnly(Side.CLIENT) + def getRenderPass():Int + + def isTransparent():Boolean + + def getStrength(player:EntityPlayer):Float + + def getLocalizedName:String + //todo, get material properties + } + + private val typeMap:HashMap[String, IMicroMaterial] = new HashMap + private val nameMap:HashMap[String, Int] = new HashMap + private var idMap:Array[(String, IMicroMaterial)] = _ + private val idWriter = IDWriter() + + def registerMaterial(material:IMicroMaterial, name:String) + { + if(MultiPartRegistry.loaded) + throw new IllegalStateException("You must register your parts in the init methods.") + + if(typeMap.contains(name)) + throw new IllegalStateException("Material with id "+name+" is already registered.") + + System.out.println("Registered micro material: "+name) + + typeMap.put(name, material) + } + + def setupIDMap() + { + idMap = typeMap.toList.sortBy(_._1).toArray + idWriter.setMax(idMap.length) + nameMap.clear + for(i <- 0 until idMap.length) + nameMap.put(idMap(i)._1, i) + } + + def writeIDMap(packet:PacketCustom) + { + packet.writeInt(idMap.size) + idMap.foreach(e => packet.writeString(e._1)) + } + + def readIDMap(packet:PacketCustom) + { + val k = packet.readInt() + idWriter.setMax(k) + idMap = new Array(k) + for(i <- 0 until k) + { + val s = packet.readString() + val v = typeMap.get(s) + if(v.isEmpty) + throw new IllegalArgumentException("The microblock with ID "+s+" is not installed on the client");//TODO: fancy FML thingy + + idMap(i) = (s, v.get) + } + } + + def writePartID(data:MCDataOutput, id:Int) + { + idWriter.write(data, id) + } + + def readPartID(data:MCDataInput) = idWriter.read(data) + + def materialName(id:Int) = idMap(id)._1 + + def materialID(name:String):Int = + { + val v = nameMap.get(name) + if(v.isDefined) + return v.get + else + { + System.err.println("Missing mapping for part with ID: "+name) + return 0 + } + } + + def getMaterial(name:String) = typeMap.getOrElse(name, null) + + def getMaterial(id:Int) = idMap(id)._2 + + def materials_foreach(func:(String, IMicroMaterial) => Unit) = idMap.foreach(e => func(e._1, e._2)) +} \ No newline at end of file diff --git a/codechicken/microblock/MicroblockPlacement.scala b/codechicken/microblock/MicroblockPlacement.scala new file mode 100644 index 0000000..7a7239c --- /dev/null +++ b/codechicken/microblock/MicroblockPlacement.scala @@ -0,0 +1,200 @@ +package codechicken.microblock + +import net.minecraft.world.World +import net.minecraft.entity.player.EntityPlayer +import net.minecraft.util.MovingObjectPosition +import codechicken.core.vec.Vector3 +import codechicken.core.vec.BlockCoord +import codechicken.multipart.TileMultipart +import codechicken.core.vec.Rotation +import codechicken.multipart.ControlKeyModifer._ +import net.minecraft.item.ItemStack +import codechicken.microblock.handler.MicroblockProxy +import codechicken.multipart.TMultiPart +import codechicken.multipart.TileMultipartObj +import codechicken.core.raytracer.ExtendedMOP + +abstract class ExecutablePlacement(val pos:BlockCoord, val part:Microblock) +{ + def place(world:World, player:EntityPlayer, item:ItemStack) + def consume(world:World, player:EntityPlayer, item:ItemStack) +} + +class AdditionPlacement($pos:BlockCoord, $part:Microblock) extends ExecutablePlacement($pos, $part) +{ + def place(world:World, player:EntityPlayer, item:ItemStack) + { + TileMultipartObj.addPart(world, pos, part) + } + + def consume(world:World, player:EntityPlayer, item:ItemStack) + { + item.stackSize-=1 + } +} + +class ExpandingPlacement($pos:BlockCoord, $part:Microblock, opart:Microblock) extends ExecutablePlacement($pos, $part) +{ + def place(world:World, player:EntityPlayer, item:ItemStack) + { + opart.shape = part.shape + opart.tile.notifyPartChange() + opart.sendDescPacket() + } + + def consume(world:World, player:EntityPlayer, item:ItemStack) + { + item.stackSize-=1 + } +} + +abstract class PlacementProperties +{ + def opposite(slot:Int, side:Int):Int + + def sneakOpposite(slot:Int, side:Int) = true + + def expand(slot:Int, side:Int) = true + + def microClass():MicroblockClass + + def placementGrid():PlacementGrid + + def customPlacement(pmt:MicroblockPlacement):ExecutablePlacement = null +} + +object MicroblockPlacement +{ + def apply(world:World, player:EntityPlayer, hit:MovingObjectPosition, size:Int, material:Int, checkMaterial:Boolean, pp:PlacementProperties):ExecutablePlacement = + new MicroblockPlacement(world, player, hit, size, material, checkMaterial, pp)() +} + +class MicroblockPlacement(val world:World, val player:EntityPlayer, val hit:MovingObjectPosition, val size:Int, val material:Int, val checkMaterial:Boolean, val pp:PlacementProperties) +{ + val mcrClass = pp.microClass + val pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ) + val vhit = new Vector3(hit.hitVec).add(-pos.x, -pos.y, -pos.z) + val htile = TileMultipartObj.getOrConvertTile(world, pos) + val slot = pp.placementGrid.getHitSlot(vhit, hit.sideHit) + val oslot = pp.opposite(slot, hit.sideHit) + + val d = getHitDepth(vhit, hit.sideHit) + val useOppMod = pp.sneakOpposite(slot, hit.sideHit) + val oppMod = player.isControlDown + val internal = d < 1 && htile != null + val doExpand = internal && htile.loaded && !player.isSneaking && !(oppMod && useOppMod) && pp.expand(slot, hit.sideHit) + val side = hit.sideHit + + def apply():ExecutablePlacement = + { + val customPlacement = pp.customPlacement(this) + if(customPlacement != null) + return customPlacement + + if(slot < 0) + return null + + if(doExpand) + { + val hpart = htile.partList(ExtendedMOP.getData[(Int, _)](hit)._1) + if(hpart.getType == mcrClass.getName) + { + val mpart = hpart.asInstanceOf[CommonMicroblock] + if(mpart.material == material && mpart.getSize + size < 8) + return expand(mpart) + } + } + + if(internal) + { + if(!useOppMod) + return internalPlacement(htile, slot) + if((1-d)*8 < size) + { + if(htile.canAddPart(create(1, oslot, material))) + return externalPlacement(slot) + } + if(d < 0.5) + { + var ret = internalPlacement(htile, slot) + if(ret != null && !oppMod) + return ret + if(ret != null && oppMod || ret == null && !oppMod) + return internalPlacement(htile, oslot) + //sneaking + if(internalPlacement(htile, oslot) != null) + return externalPlacement(slot) + return null + } + var ret = internalPlacement(htile, oslot) + if(!oppMod) + return ret + if(ret != null) + return externalPlacement(slot) + return null + } + var ret = externalPlacement(slot) + if(ret != null && oppMod && useOppMod) + return externalPlacement(oslot) + return ret + } + + def materialCheck(sizea:Int):Boolean = + { + if(!checkMaterial) + return true + + val mUnits = mcrClass.sizeToVolume(sizea) - mcrClass.sizeToVolume(sizea+size) + var mat = 0 + player.inventory.mainInventory.foreach(item => { + if(item != null && item.itemID == MicroblockProxy.item.itemID) + { + val mcrClass = MicroblockClassRegistry.getMicroClass(item.getItemDamage) + if(ItemMicroPart.getMaterialID(item) == material) + mat+=mcrClass.sizeToVolume(item.getItemDamage&0xFF) + } + }) + return mat >= mUnits + } + + def expand(mpart:CommonMicroblock):ExecutablePlacement = expand(mpart, create(mpart.getSize+size, mpart.getSlot, mpart.material)) + + def expand(mpart:Microblock, npart:Microblock):ExecutablePlacement = + { + if(!materialCheck(mpart.getSize)) + return null + + if(mpart.tile.canReplacePart(mpart, npart)) + return new ExpandingPlacement(new BlockCoord(mpart.tile), npart, mpart) + return null + } + + def internalPlacement(htile:TileMultipart, slot:Int):ExecutablePlacement = internalPlacement(htile, create(size, slot, material)) + + def internalPlacement(htile:TileMultipart, npart:Microblock):ExecutablePlacement = + { + if(htile.canAddPart(npart)) + return new AdditionPlacement(new BlockCoord(htile), npart) + return null + } + + def externalPlacement(slot:Int):ExecutablePlacement = externalPlacement(create(size, slot, material)) + + def externalPlacement(npart:Microblock):ExecutablePlacement = + { + val pos = this.pos.copy().offset(side) + if(TileMultipartObj.canAddPart(world, pos, npart)) + return new AdditionPlacement(pos, npart) + return null + } + + def getHitDepth(vhit:Vector3, side:Int):Double = + { + var d = vhit.copy().scalarProject(Rotation.axes(side)) + if(side%2 == 0) + d+=1 + return d + } + + def create(size:Int, slot:Int, material:Int) = mcrClass.create(size, slot, material, world.isRemote) +} \ No newline at end of file diff --git a/codechicken/microblock/PlacementGrids.scala b/codechicken/microblock/PlacementGrids.scala new file mode 100644 index 0000000..ace3ff4 --- /dev/null +++ b/codechicken/microblock/PlacementGrids.scala @@ -0,0 +1,163 @@ +package codechicken.microblock + +import codechicken.core.vec.Vector3 +import org.lwjgl.opengl.GL11 +import codechicken.core.vec.BlockCoord +import codechicken.core.vec.Rotation + +trait PlacementGrid +{ + def getHitSlot(vhit:Vector3, side:Int):Int + + def render(hit:Vector3, side:Int) + + def glTransformFace(hit:Vector3, side:Int) + { + val pos = new BlockCoord(hit) + GL11.glPushMatrix() + GL11.glTranslated(pos.x+0.5, pos.y+0.5, pos.z+0.5) + Rotation.sideRotationsG(side).glRotate() + val rhit = new Vector3(pos.x+0.5, pos.y+0.5, pos.z+0.5).subtract(hit).rotate(Rotation.sideQuatsR(side^1)) + GL11.glTranslated(0, rhit.y-0.002, 0) + } +} + +object FacePlacementGrid extends PlacementGrid +{ + def render(hit:Vector3, side:Int) + { + glTransformFace(hit, side) + + GL11.glLineWidth(2) + GL11.glColor4f(0, 0, 0, 1) + GL11.glBegin(GL11.GL_LINES) + GL11.glVertex3d(-0.5, 0,-0.5) + GL11.glVertex3d(-0.5, 0, 0.5) + + GL11.glVertex3d(-0.5, 0, 0.5) + GL11.glVertex3d( 0.5, 0, 0.5) + + GL11.glVertex3d( 0.5, 0, 0.5) + GL11.glVertex3d( 0.5, 0,-0.5) + + GL11.glVertex3d( 0.5, 0,-0.5) + GL11.glVertex3d(-0.5, 0,-0.5) + + GL11.glVertex3d(0.5, 0, 0.5) + GL11.glVertex3d(0.25, 0, 0.25) + + GL11.glVertex3d(-0.5, 0, 0.5) + GL11.glVertex3d(-0.25, 0, 0.25) + + GL11.glVertex3d(0.5, 0, -0.5) + GL11.glVertex3d(0.25, 0, -0.25) + + GL11.glVertex3d(-0.5, 0, -0.5) + GL11.glVertex3d(-0.25, 0, -0.25) + + GL11.glVertex3d(-0.25, 0,-0.25) + GL11.glVertex3d(-0.25, 0, 0.25) + + GL11.glVertex3d(-0.25, 0, 0.25) + GL11.glVertex3d( 0.25, 0, 0.25) + + GL11.glVertex3d( 0.25, 0, 0.25) + GL11.glVertex3d( 0.25, 0,-0.25) + + GL11.glVertex3d( 0.25, 0,-0.25) + GL11.glVertex3d(-0.25, 0,-0.25) + GL11.glEnd(); + GL11.glPopMatrix() + } + + def getHitSlot(vhit:Vector3, side:Int):Int = + { + val s1 = (side+2)%6 + val s2 = (side+4)%6 + val u = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) + val v = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) + + if(Math.abs(u) < 4/16D && Math.abs(v) < 4/16D) + return side^1 + if(Math.abs(u) > Math.abs(v)) + return if(u > 0) s1 else s1^1 + else + return if(v > 0) s2 else s2^1 + } +} + +object CornerPlacementGrid extends PlacementGrid +{ + def render(hit:Vector3, side:Int) + { + glTransformFace(hit, side) + GL11.glLineWidth(2) + GL11.glColor4f(0, 0, 0, 1) + GL11.glBegin(GL11.GL_LINES) + + GL11.glVertex3d(-0.5, 0,-0.5) + GL11.glVertex3d(-0.5, 0, 0.5) + + GL11.glVertex3d(-0.5, 0, 0.5) + GL11.glVertex3d( 0.5, 0, 0.5) + + GL11.glVertex3d( 0.5, 0, 0.5) + GL11.glVertex3d( 0.5, 0,-0.5) + + GL11.glVertex3d( 0.5, 0,-0.5) + GL11.glVertex3d(-0.5, 0,-0.5) + + GL11.glVertex3d(0, 0,-0.5) + GL11.glVertex3d(0, 0, 0.5) + + GL11.glVertex3d(-0.5, 0, 0) + GL11.glVertex3d( 0.5, 0, 0) + + GL11.glEnd(); + GL11.glPopMatrix() + } + + def getHitSlot(vhit:Vector3, side:Int):Int = + { + val s1 = ((side&6)+3)%6 + val s2 = ((side&6)+5)%6 + val u = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) + val v = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) + + val bu = if(u >= 0) 1 else 0 + val bv = if(v >= 0) 1 else 0 + val bw = (side&1)^1 + + return 7+( + bw<<(side>>1)| + bu<<(s1>>1)| + bv<<(s2>>1)) + } +} + +object EdgePlacementGrid extends PlacementGrid +{ + def render(hit:Vector3, side:Int) = FacePlacementGrid.render(hit, side) + + def getHitSlot(vhit:Vector3, side:Int):Int = + { + val s1 = (side+2)%6 + val s2 = (side+4)%6 + val u = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s1)) + val v = vhit.copy().add(-0.5, -0.5, -0.5).scalarProject(Rotation.axes(s2)) + + if(Math.abs(u) < 4/16D && Math.abs(v) < 4/16D) + return -1 + var b = side&1 + if(Math.abs(u) > Math.abs(v)) + { + if(u < 0) b^=1 + return 15+((s2&6)<<1 | b<<1 | side&1^1) + } + else + { + if(v < 0) b^=1 + return 15+((s1&6)<<1 | (side&1^1)<<1 | b) + } + } +} \ No newline at end of file diff --git a/codechicken/microblock/TMicroOcclusion.scala b/codechicken/microblock/TMicroOcclusion.scala new file mode 100644 index 0000000..986bb17 --- /dev/null +++ b/codechicken/microblock/TMicroOcclusion.scala @@ -0,0 +1,231 @@ +package codechicken.microblock + +import codechicken.multipart.TMultiPart +import codechicken.core.vec.Cuboid6 +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.multipart.TileMultipart +import codechicken.multipart.PartMap._ + +object MicroOcclusion +{ + def shrink(renderBounds:Cuboid6, b:Cuboid6, side:Int) + { + side match + { + case -1 => + case 0 => if(renderBounds.min.y < b.max.y)renderBounds.min.y = b.max.y + case 1 => if(renderBounds.max.y > b.min.y)renderBounds.max.y = b.min.y + case 2 => if(renderBounds.min.z < b.max.z)renderBounds.min.z = b.max.z + case 3 => if(renderBounds.max.z > b.min.z)renderBounds.max.z = b.min.z + case 4 => if(renderBounds.min.x < b.max.x)renderBounds.min.x = b.max.x + case 5 => if(renderBounds.max.x > b.min.x)renderBounds.max.x = b.min.x + } + } +} + +trait TMicroOcclusionClient extends TMicroOcclusion +{ + var renderBounds:Cuboid6 = _ + var renderMask:Int = _ + + def isTransparent():Boolean + + override def onPartChanged() + { + super.onPartChanged() + recalcBounds() + } + + def recalcBounds() + { + renderBounds = getBounds.copy + if(getSlot < 6) + shrink(6) + else if(getSlot < 15) + shrink(15) + else + shrink(27) + } + + def thisShrinks(other:TMicroOcclusionClient):Boolean = + { + val shape1 = shapePriority + val shape2 = other.shapePriority + + if(shape1 != shape2)return shape1 > shape2 + if(getSlot < 6)//transparency takes precedence for covers + { + if(isTransparent != other.isTransparent) return isTransparent + if(getSize != other.getSize) return getSize < other.getSize + } + else + { + if(getSize != other.getSize) return getSize < other.getSize + if(isTransparent != other.isTransparent) return isTransparent + } + return getSlot < other.getSlot + } + + def shrinkThis(other:TMicroOcclusionClient) + { + if(thisShrinks(other)) + { + MicroOcclusion.shrink(renderBounds, other.getBounds, shrinkSide(getSlot, other.getSlot)) + } + else if(other.getSlot < 6 && !other.isTransparent)//other gets full face, we didn't shrink, flag rendermask + { + if(other.getSlot match { + case 0 => renderBounds.min.y <= 0 + case 1 => renderBounds.max.y >= 1 + case 2 => renderBounds.min.z <= 0 + case 3 => renderBounds.max.z >= 1 + case 4 => renderBounds.min.x <= 0 + case 5 => renderBounds.max.x >= 1 + }) + renderMask|=1< c2&1 + case 2 => 2|(c2&2)>>1 + case 4 => 4|(c2&4)>>2 + case _ => -1 + } + } + if(s2 < 15)//edge, other corner + { + val e1 = s1-15 + val c2 = s2-7 + val ebits = unpackEdgeBits(s1) + if((c2&edgeAxisMask(s1)) != ebits) + return -1 + + return (e1&0xC)>>1|(c2&(~ebits))>>(e1>>2) + } + //both edges + { + val e1 = s1-15 + val e2 = s2-15 + val e1bits = unpackEdgeBits(e1) + val e2bits = unpackEdgeBits(e2) + if((e1&0xC) == (e2&0xC))//same axis + { + return e1bits^e2bits match + { + case 1 => if((e2bits&1) == 0) 0 else 1 + case 2 => if((e2bits&2) == 0) 2 else 3 + case 4 => if((e2bits&4) == 0) 4 else 5 + case _ => -1 + } + } + else + { + val mask = edgeAxisMask(e1)&edgeAxisMask(e2) + if((e1bits&mask) != (e2bits&mask)) + return -1 + + return e1>>2 match + { + case 0 => if((e2bits&1) == 0) 0 else 1 + case 1 => if((e2bits&2) == 0) 2 else 3 + case 2 => if((e2bits&4) == 0) 4 else 5 + } + } + } + + throw new IllegalArgumentException("Switch Falloff") + } + + def shrink(m:Int) + { + renderMask = 0 + for(i <- 0 until m) + { + if(i != getSlot) + { + val part = tile.partMap(i) + if(part.isInstanceOf[TMicroOcclusionClient]) + shrinkThis(part.asInstanceOf[TMicroOcclusionClient]) + } + } + } +} + +trait TMicroOcclusion extends TMultiPart +{ + def getSlot():Int + def getSize():Int + def getMaterial():Int + def getBounds():Cuboid6 + + override def occlusionTest(npart:TMultiPart):Boolean = + { + if(!super.occlusionTest(npart)) + return false + + if(!npart.isInstanceOf[TMicroOcclusion]) + return true + + val mpart = npart.asInstanceOf[TMicroOcclusion] + val shape1 = shapePriority + val shape2 = mpart.shapePriority + + if(mpart.getSize + getSize > 8)//intersecting if opposite + { + if(shape1 == 0 && shape2 == 0) + if(mpart.getSlot == (getSlot^1)) + return false + + if(mpart.getMaterial != getMaterial) + { + if(shape1 == 1 && shape2 == 1) + { + val axisMask = (getSlot-7)^(mpart.getSlot-7) + if(axisMask == 3 || axisMask == 5 || axisMask == 6) + return false + } + + if(shape1 == 2 && shape2 == 1) + if(!edgeCornerOcclusionTest(this, mpart)) + return false + + if(shape1 == 1 && shape2 == 2) + if(!edgeCornerOcclusionTest(mpart, this)) + return false + + if(shape1 == 2 && shape2 == 2) + { + val e1 = getSlot-15 + val e2 = mpart.getSlot-15 + if((e1&0xC) == (e2&0xC) && ((e1&3)^(e2&3)) == 3) + return false + } + } + } + + return true + } + + def edgeCornerOcclusionTest(edge:TMicroOcclusion, corner:TMicroOcclusion):Boolean = + { + ((corner.getSlot-7)&edgeAxisMask(edge.getSlot-15)) == unpackEdgeBits(edge.getSlot-15) + } + + def shapePriority():Int = + if(getSlot < 6) + return 0 + else if(getSlot < 15) + return 1 + else + return 2 +} \ No newline at end of file diff --git a/codechicken/microblock/handler/EventHandler.scala b/codechicken/microblock/handler/EventHandler.scala new file mode 100644 index 0000000..2cb0cf5 --- /dev/null +++ b/codechicken/microblock/handler/EventHandler.scala @@ -0,0 +1,41 @@ +package codechicken.microblock.handler + +import net.minecraftforge.client.event.TextureStitchEvent +import codechicken.microblock.MicroMaterialRegistry +import net.minecraftforge.event.ForgeSubscribe +import cpw.mods.fml.common.Loader +import cpw.mods.fml.common.LoaderState +import net.minecraftforge.client.event.DrawBlockHighlightEvent +import net.minecraft.util.EnumMovingObjectType +import codechicken.microblock.ItemMicroPart +import codechicken.microblock.ItemMicroPartRenderer +import org.lwjgl.opengl.GL11 +import codechicken.core.render.RenderUtils +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side + +object MicroblockEventHandler +{ + @ForgeSubscribe + @SideOnly(Side.CLIENT) + def postTextureStitch(event:TextureStitchEvent.Post) + { + if(Loader.instance.hasReachedState(LoaderState.POSTINITIALIZATION)) + MicroMaterialRegistry.materials_foreach((s, m) => m.loadIcons()) + } + + @ForgeSubscribe + @SideOnly(Side.CLIENT) + def drawBlockHighlight(event:DrawBlockHighlightEvent) + { + if(event.currentItem != null && event.currentItem.getItem== MicroblockProxy.item && + event.target != null && event.target.typeOfHit == EnumMovingObjectType.TILE) + { + GL11.glPushMatrix() + RenderUtils.translateToWorldCoords(event.player, event.partialTicks) + if(ItemMicroPartRenderer.renderHighlight(event.player.worldObj, event.player, event.currentItem, event.target)) + event.setCanceled(true) + GL11.glPopMatrix() + } + } +} \ No newline at end of file diff --git a/codechicken/microblock/handler/ModContainer.scala b/codechicken/microblock/handler/ModContainer.scala new file mode 100644 index 0000000..ed58cb4 --- /dev/null +++ b/codechicken/microblock/handler/ModContainer.scala @@ -0,0 +1,47 @@ +package codechicken.microblock.handler; + +import cpw.mods.fml.common.Mod +import cpw.mods.fml.common.event.FMLInitializationEvent +import cpw.mods.fml.common.event.FMLPreInitializationEvent +import cpw.mods.fml.common.SidedProxy +import cpw.mods.fml.common.Mod.PreInit +import cpw.mods.fml.common.Mod.Init +import cpw.mods.fml.common.Mod.PostInit +import cpw.mods.fml.common.Mod.ServerAboutToStart +import cpw.mods.fml.common.event.FMLServerAboutToStartEvent +import cpw.mods.fml.common.network.NetworkMod +import cpw.mods.fml.common.Mod.Instance +import codechicken.microblock.MicroMaterialRegistry +import codechicken.scala.ScalaHelper +import codechicken.microblock.DefaultContent +import cpw.mods.fml.common.event.FMLPostInitializationEvent + +@Mod(name="Microblocks", version="b.0.0.0", useMetadata = false, modid = "CCMicroblock", acceptedMinecraftVersions = "[1.5.2]", dependencies="required-after:CCMultipart", modLanguage="scala") +object MicroblockMod +{ + @PreInit + def preInit(event:FMLPreInitializationEvent) + { + MicroblockProxy.preInit() + DefaultContent.load() + } + + @Init + def init(event:FMLInitializationEvent) + { + MicroblockProxy.init() + MicroMaterialRegistry.setupIDMap() + } + + @PostInit + def postInit(event:FMLPostInitializationEvent) + { + MicroblockProxy.postInit() + } + + @ServerAboutToStart + def beforeServerStart(event:FMLServerAboutToStartEvent) + { + MicroMaterialRegistry.setupIDMap() + } +} \ No newline at end of file diff --git a/codechicken/microblock/handler/Proxies.scala b/codechicken/microblock/handler/Proxies.scala new file mode 100644 index 0000000..fef6812 --- /dev/null +++ b/codechicken/microblock/handler/Proxies.scala @@ -0,0 +1,47 @@ +package codechicken.microblock.handler + +import codechicken.core.CommonUtils +import net.minecraftforge.common.MinecraftForge +import codechicken.multipart.handler.MultipartProxy._ +import codechicken.multipart.TMultiPart +import codechicken.multipart.MultiPartRegistry +import codechicken.microblock.FaceMicroblock +import codechicken.microblock.ItemMicroPart +import codechicken.microblock.MicroMaterialRegistry.IMicroMaterial +import codechicken.microblock.MicroblockClass +import net.minecraftforge.client.MinecraftForgeClient +import codechicken.microblock.ItemMicroPartRenderer +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side + +class MicroblockProxy_serverImpl +{ + var item:ItemMicroPart = _ + + def preInit() + { + item = new ItemMicroPart(config.getTag("itemMicro.id").getIntValue(24875)) + MinecraftForge.EVENT_BUS.register(MicroblockEventHandler) + } + + def init() + { + } + + def postInit() + { + } +} + +class MicroblockProxy_clientImpl extends MicroblockProxy_serverImpl +{ + @SideOnly(Side.CLIENT) + override def postInit() + { + MinecraftForgeClient.registerItemRenderer(item.itemID, ItemMicroPartRenderer) + } +} + +object MicroblockProxy extends MicroblockProxy_clientImpl +{ +} \ No newline at end of file diff --git a/codechicken/multipart/BlockMultipart.scala b/codechicken/multipart/BlockMultipart.scala new file mode 100644 index 0000000..5741e31 --- /dev/null +++ b/codechicken/multipart/BlockMultipart.scala @@ -0,0 +1,219 @@ +package codechicken.multipart + +import java.util.List +import net.minecraft.block.Block +import net.minecraft.block.material.Material +import net.minecraft.entity.Entity +import net.minecraft.util.AxisAlignedBB +import net.minecraft.world.World +import net.minecraftforge.common.ForgeDirection +import net.minecraft.util.Vec3 +import net.minecraft.util.MovingObjectPosition +import java.util.LinkedList +import codechicken.core.raytracer.IndexedCuboid6 +import codechicken.core.vec.Cuboid6 +import codechicken.core.raytracer.RayTracer +import codechicken.core.vec.Vector3 +import codechicken.core.vec.BlockCoord +import net.minecraft.entity.player.EntityPlayer +import java.util.Random +import java.util.ArrayList +import net.minecraft.item.ItemStack +import net.minecraft.client.particle.EffectRenderer +import net.minecraft.client.Minecraft +import net.minecraft.util.Icon +import net.minecraft.client.renderer.texture.IconRegister +import codechicken.core.render.TextureSpecial +import codechicken.core.render.TextureUtils +import net.minecraftforge.scala.ScalaBridge._ +import net.minecraft.world.IBlockAccess +import codechicken.core.raytracer.ExtendedMOP + +object BlockMultipart +{ + def getTile(world:IBlockAccess, x:Int, y:Int, z:Int):TileMultipart = + { + val tile = world.getBlockTileEntity(x, y, z) + if(tile.isInstanceOf[TileMultipart]) + tile.asInstanceOf[TileMultipart] + else + null + } + + def getClientTile(world:IBlockAccess, x:Int, y:Int, z:Int):TileMultipartClient = + { + val tile = world.getBlockTileEntity(x, y, z) + if(tile.isInstanceOf[TileMultipartClient]) + tile.asInstanceOf[TileMultipartClient] + else + null + } +} + +trait BlockMultipart extends Block +{ + import BlockMultipart._ + + setTickRandomly(true) + + override def hasTileEntity(meta:Int = 0) = true + + override def isBlockSolidOnSide(world:World, x:Int, y:Int, z:Int, side:ForgeDirection):Boolean = + { + val tile = getTile(world, x, y, z) + if(tile != null) tile.isSolid(side.ordinal()) else false + } + + override def onNeighborBlockChange(world:World, x:Int, y:Int, z:Int, id:Int) + { + val tile = getTile(world, x, y, z) + if(tile != null) + tile.onNeighborBlockChange(world, x, y, z, id) + } + + override def collisionRayTrace(world:World, x:Int, y:Int, z:Int, start:Vec3, end:Vec3):MovingObjectPosition = + { + val boxes:LinkedList[IndexedCuboid6] = new LinkedList; + val tile = getTile(world, x, y, z) + if(tile == null) + return null + + for(i <- 0 until tile.partList.size) + { + tile.partList(i).getSubParts.foreach { c => + boxes.add(new IndexedCuboid6((i, c.data), c.copy.add(new Vector3(x, y, z)))) + } + } + + return RayTracer.instance.rayTraceCuboids(new Vector3(start), new Vector3(end), boxes, new BlockCoord(x, y, z), this) + } + + override def removeBlockByPlayer(world:World, player:EntityPlayer, x:Int, y:Int, z:Int):Boolean = + { + val hit = RayTracer.retraceBlock(world, player, x, y, z); + if(hit == null) + return false; + + val tile = getTile(world, x, y, z) + if(tile == null) + return false + + val hitInfo:(Int, _) = ExtendedMOP.getData(hit) + if(world.isRemote) + { + tile.partList(hitInfo._1).addDestroyEffects(Minecraft.getMinecraft().effectRenderer) + return true + } + + return tile.harvestPart(hitInfo._1, !player.capabilities.isCreativeMode); + } + + override def quantityDropped(meta:Int, fortune:Int, random:Random) = 0 + + override def getBlockDropped(world:World, x:Int, y:Int, z:Int, meta:Int, fortune:Int):ArrayList[ItemStack] = + { + val ai = new ArrayList[ItemStack]() + if(world.isRemote) + return ai + + val tile = getTile(world, x, y, z) + if(tile != null) + tile.partList.foreach(part => part.getDrops.foreach(item => ai.add(item))) + return ai + } + + override def addCollisionBoxesToList(world:World, x:Int, y:Int, z:Int, ebb:AxisAlignedBB, list$:List[_], entity:Entity) + { + val list = list$.asInstanceOf[List[AxisAlignedBB]] + val tile = getTile(world, x, y, z) + if(tile != null) + { + tile.partList.foreach { part => + part.getCollisionBoxes.foreach{ c => + { + val aabb = c.toAABB().offset(x, y, z) + if(aabb.intersectsWith(ebb)) + list.add(aabb) + } + } + } + } + } + + override def addBlockHitEffects(world:World, hit:MovingObjectPosition, effectRenderer:EffectRenderer):Boolean = + { + val tile = getClientTile(world, hit.blockX, hit.blockY, hit.blockZ) + if(tile != null) + tile.partList(ExtendedMOP.getData[(Int, _)](hit)._1).addHitEffects(hit, effectRenderer) + + return true + } + + override def addBlockDestroyEffects(world:World, x:Int, y:Int, z:Int, s:Int, effectRenderer:EffectRenderer) = true + + override def renderAsNormalBlock() = false + + override def isOpaqueCube() = false + + override def getRenderType() = TileMultipartObj.renderID + + override def isAirBlock(world:World, x:Int, y:Int, z:Int) = getTile(world, x, y, z) == null || getTile(world, x, y, z).partList.isEmpty + + override def getRenderBlockPass = 1 + + override def canRenderInPass(pass:Int):Boolean = + { + MultipartRenderer.pass = pass + return true + } + + override def getPickBlock(hit:MovingObjectPosition, world:World, x:Int, y:Int, z:Int):ItemStack = + { + val tile = getTile(world, x, y, z) + if(tile != null) + { + val hitInfo:(Int, _) = ExtendedMOP.getData(hit) + return tile.partList(hitInfo._1).pickItem(hit) + } + return null + } + + override def getPlayerRelativeBlockHardness(player:EntityPlayer, world:World, x:Int, y:Int, z:Int):Float = + { + val hit = RayTracer.retraceBlock(world, player, x, y, z) + val tile = getTile(world, x, y, z) + if(hit != null && tile != null) + return tile.partList(ExtendedMOP.getData[(Int, _)](hit)._1).getStrength(hit, player)/30F; + + return 1 + } + + /** + * Kludge to set PROTECTED blockIcon to a blank icon + */ + override def registerIcons(register:IconRegister) + { + val n = getUnlocalizedName(); + val icon = TextureUtils.getBlankIcon(16, register); + setUnlocalizedName(icon.getIconName) + super.registerIcons(register) + setUnlocalizedName(n) + } + + override def getLightValue(world:IBlockAccess, x:Int, y:Int, z:Int):Int = + { + val tile = getTile(world, x, y, z) + if(tile != null) tile.getLightValue else 0 + } + + override def randomDisplayTick(world:World, x:Int, y:Int, z:Int, random:Random) + { + val tile = getClientTile(world, x, y, z) + if(tile != null) tile.randomDisplayTick(random) + } +} + +class BlockMultipartImpl(id:Int) extends Block(id, Material.rock) with BlockMultipart +{ + +} \ No newline at end of file diff --git a/codechicken/multipart/ControlKeyModifier.scala b/codechicken/multipart/ControlKeyModifier.scala new file mode 100644 index 0000000..7e9cec5 --- /dev/null +++ b/codechicken/multipart/ControlKeyModifier.scala @@ -0,0 +1,60 @@ +package codechicken.multipart + +import cpw.mods.fml.client.registry.KeyBindingRegistry.KeyHandler +import net.minecraft.client.settings.KeyBinding +import org.lwjgl.input.Keyboard +import cpw.mods.fml.common.registry.LanguageRegistry +import java.util.EnumSet +import cpw.mods.fml.common.TickType +import net.minecraft.client.Minecraft +import codechicken.core.packet.PacketCustom +import codechicken.multipart.handler.MultipartCPH +import scala.collection.mutable.HashMap +import net.minecraft.entity.player.EntityPlayer + +object ControlKeyModifer +{ + implicit def playerControlValue(p:EntityPlayer) = new ControlKeyValue(p) + + class ControlKeyValue(p:EntityPlayer) + { + def isControlDown() = map(p) + } + + val map = HashMap[EntityPlayer, Boolean]().withDefaultValue(false) +} + +object ControlKeyHandler extends KeyHandler ( + Array(new KeyBinding("key.control", Keyboard.KEY_LCONTROL)), + Array(false)) +{ + import ControlKeyModifer._ + + LanguageRegistry.instance.addStringLocalization("key.control", "Placement Modifier"); + + def keyDown(types:EnumSet[TickType], kb:KeyBinding, tickEnd:Boolean, isRepeat:Boolean) + { + if(!tickEnd && Minecraft.getMinecraft.getNetHandler != null) + { + map.put(Minecraft.getMinecraft.thePlayer, true) + val packet = new PacketCustom(MultipartCPH.channel, 1) + packet.writeBoolean(true) + packet.sendToServer() + } + } + + def keyUp(types:EnumSet[TickType], kb:KeyBinding, tickEnd:Boolean) + { + if(!tickEnd && Minecraft.getMinecraft.getNetHandler != null) + { + map.put(Minecraft.getMinecraft.thePlayer, false) + val packet = new PacketCustom(MultipartCPH.channel, 1) + packet.writeBoolean(false) + packet.sendToServer() + } + } + + def getLabel() = "Control Key Modifer"; + + def ticks() = EnumSet.of(TickType.CLIENT) +} \ No newline at end of file diff --git a/codechicken/multipart/IDWriter.scala b/codechicken/multipart/IDWriter.scala new file mode 100644 index 0000000..03a4e01 --- /dev/null +++ b/codechicken/multipart/IDWriter.scala @@ -0,0 +1,39 @@ +package codechicken.multipart + +import codechicken.core.data.MCDataOutput +import codechicken.core.data.MCDataInput + +trait IDWriter +{ + var write:(MCDataOutput, Int)=>Unit = _ + var read:(MCDataInput)=>Int = _ + + def setMax(i:Int) + { + val l = i.toLong & 0xFFFFFFFF + if(l > 0xFFFF) + { + write = (data, i) => data.writeInt(i) + read = (data) => data.readInt() + } + else if(l > 0xFF) + { + write = (data, i) => data.writeShort(i) + read = (data) => data.readUnsignedShort() + } + else + { + write = (data, i) => data.writeByte(i) + read = (data) => data.readUnsignedByte() + } + } +} + +object IDWriter +{ + def apply():IDWriter = new IDWriterImpl; +} + +class IDWriterImpl extends IDWriter +{ +} \ No newline at end of file diff --git a/codechicken/multipart/IRandomDisplayTick.scala b/codechicken/multipart/IRandomDisplayTick.scala new file mode 100644 index 0000000..96ab1fd --- /dev/null +++ b/codechicken/multipart/IRandomDisplayTick.scala @@ -0,0 +1,46 @@ +package codechicken.multipart + +import scala.collection.mutable.ArrayBuffer +import java.util.Random + +trait IRandomDisplayTick +{ + def randomDisplayTick(random:Random) +} + +trait TRandomDisplayTickTile extends TileMultipartClient +{ + var displayParts = ArrayBuffer[IRandomDisplayTick]() + + override def loadFrom(that:TileMultipart) + { + super.loadFrom(that) + if(that.isInstanceOf[TRandomDisplayTickTile]) + displayParts = that.asInstanceOf[TRandomDisplayTickTile].displayParts + } + + override def randomDisplayTick(random:Random) + { + displayParts.foreach(_.randomDisplayTick(random)) + } + + override def partAdded(part:TMultiPart) + { + super.partAdded(part) + if(part.isInstanceOf[IRandomDisplayTick]) + displayParts+=part.asInstanceOf[IRandomDisplayTick] + } + + override def partRemoved(part:TMultiPart, p:Int) + { + super.partRemoved(part, p) + if(part.isInstanceOf[IRandomDisplayTick]) + displayParts-=part.asInstanceOf[IRandomDisplayTick] + } + + override def clearParts() + { + super.clearParts() + displayParts.clear + } +} \ No newline at end of file diff --git a/codechicken/multipart/MultiPartRegistry.scala b/codechicken/multipart/MultiPartRegistry.scala new file mode 100644 index 0000000..e9cf8a4 --- /dev/null +++ b/codechicken/multipart/MultiPartRegistry.scala @@ -0,0 +1,126 @@ +package codechicken.multipart; + +import scala.collection.mutable.HashMap +import codechicken.core.packet.PacketCustom +import codechicken.core.data.MCDataOutput +import codechicken.core.data.MCDataInput +import net.minecraft.world.World +import codechicken.core.vec.BlockCoord +import scala.collection.mutable.ListBuffer + +object MultiPartRegistry +{ + trait IPartFactory + { + def createPart(name:String, client:Boolean):TMultiPart; + } + + trait IPartConverter + { + def canConvert(blockID:Int):Boolean + def convert(world:World, pos:BlockCoord):TMultiPart + } + + private val typeMap:HashMap[String, (Boolean)=>TMultiPart] = new HashMap + private val nameMap:HashMap[String, Int] = new HashMap + private var idMap:Array[(String, (Boolean)=>TMultiPart)] = _ + private val idWriter = IDWriter() + private val converters:Array[Seq[IPartConverter]] = Array.fill(4096)(Seq()) + + private var state:Int = 0 + + def registerParts(partFactory:IPartFactory, types:Array[String]) + { + registerParts(partFactory.createPart _, types:_*); + } + + def registerParts(partFactory:(String, Boolean)=>TMultiPart, types:String*) + { + if(loaded) + throw new IllegalStateException("You must register your parts in the init methods.") + state=1 + + types.foreach(s => + { + if(typeMap.contains(s)) + throw new IllegalStateException("Part with id "+s+" is already registered."); + + typeMap.put(s, (c:Boolean) => partFactory(s, c)); + }) + } + + def registerConverter(c:IPartConverter) + { + for(i <- 0 until 4096) + if(c.canConvert(i)) + converters(i) = converters(i):+c + } + + def beforeServerStart() + { + idMap = typeMap.toList.sortBy(_._1).toArray + idWriter.setMax(idMap.length) + nameMap.clear + for(i <- 0 until idMap.length) + nameMap.put(idMap(i)._1, i) + } + + def writeIDMap(packet:PacketCustom) + { + packet.writeInt(idMap.length) + idMap.foreach(e => packet.writeString(e._1)) + } + + def readIDMap(packet:PacketCustom):Seq[String] = + { + val k = packet.readInt() + idWriter.setMax(k) + idMap = new Array(k) + val missing = ListBuffer[String]() + for(i <- 0 until k) + { + val s = packet.readString() + val v = typeMap.get(s) + if(v.isEmpty) + missing+=s + else + idMap(i) = (s, v.get) + } + return missing + } + + def required = state > 0 + + def loaded = state == 2 + + def postInit(){state = 2} + + def writePartID(data:MCDataOutput, part:TMultiPart) + { + idWriter.write(data, nameMap.get(part.getType).get) + } + + def readPart(data:MCDataInput) = idMap(idWriter.read(data))._2(true) + + def createPart(name:String, client:Boolean):TMultiPart = + { + val part = typeMap.get(name) + if(part.isDefined) + return part.get(client) + else + { + System.err.println("Missing mapping for part with ID: "+name) + return null + } + } + + def convertBlock(world:World, pos:BlockCoord, id:Int):TMultiPart = + { + converters(id).foreach(c => { + val ret = c.convert(world, pos) + if(ret != null) + return ret + }) + return null + } +} diff --git a/codechicken/multipart/MultipartGenerator.scala b/codechicken/multipart/MultipartGenerator.scala new file mode 100644 index 0000000..c2c0c0c --- /dev/null +++ b/codechicken/multipart/MultipartGenerator.scala @@ -0,0 +1,254 @@ +package codechicken.multipart + +import net.minecraft.tileentity.TileEntity +import scala.collection.immutable.Map +import scala.reflect.runtime.universe._ +import scala.tools.reflect.ToolBox +import net.minecraft.world.World +import codechicken.core.vec.BlockCoord +import codechicken.multipart.handler.MultipartProxy +import cpw.mods.fml.common.FMLCommonHandler +import cpw.mods.fml.relauncher.Side + +object MultipartGenerator +{ + private var ugenid = 0 + + var mirror = scala.reflect.runtime.currentMirror + var tb = mirror.mkToolBox() + + def Apply(f:Tree, args:Tree*) = scala.reflect.runtime.universe.Apply(f, List(args:_*)) + def Apply(f:Tree, args:List[Tree]) = scala.reflect.runtime.universe.Apply(f, args) + def Invoke(s:Tree, n:TermName, args:Tree*) = Apply(Select(s, n), args:_*) + def literalUnit = Literal(Constant(())) + def PkgIdent(s:String):Tree = Ident(mirror.staticClass(s)) + + def getType(obj:Any) = mirror.classSymbol(obj.getClass).toType + + def defaultConstructor() = + DefDef( + Modifiers(), + nme.CONSTRUCTOR, //method name + List(), //type params + List(List()), //params + TypeTree(), //return type + Block( + Invoke(//body + Super(This(tpnme.EMPTY), tpnme.EMPTY), + nme.CONSTRUCTOR + ) + ) + ) + + def normalClassDef(mods:FlagSet, name:String, parents:List[String], methods:List[Tree]) = + ClassDef( + Modifiers(mods), + name, + List(), + Template( + parents.map(PkgIdent(_)), + emptyValDef, + methods + ) + ) + + def uniqueName(prefix:String):String = { + val ret = prefix+"$$"+ugenid + ugenid += 1 + return ret + } + + abstract class Generator + { + def generate():TileMultipart + } + + object SuperSet + { + val TileMultipartType = typeOf[TileMultipart] + val TileMultipartClientType = typeOf[TileMultipartClient] + def apply(types:Seq[Type], client:Boolean) = new SuperSet(types, client) + } + + class SuperSet(types:Seq[Type], client:Boolean) + { + import SuperSet._ + val set = baseType+:types.sortWith(_.toString < _.toString) + + def baseType = if(client) TileMultipartClientType else TileMultipartType + + override def equals(obj:Any) = obj match + { + case x:SuperSet => set == x.set + case _ => false + } + + override def hashCode() = set.hashCode + + def generate():TileMultipart = + { + return generatorMap.getOrElse(this, gen_sync).generate + } + + def gen_sync():Generator = tb.synchronized + { + return generatorMap.getOrElse(this, { + var gen = generator + generatorMap = generatorMap+(this->gen) + gen + }) + } + + private def generator():Generator = + { + val s = System.currentTimeMillis + val defClass = + normalClassDef( + NoFlags, + uniqueName("TileMultipart_cmp"), + set.map(_.typeSymbol.fullName).toList, + List( + defaultConstructor + ) + ) + val defGenClass = + normalClassDef( + Flag.FINAL, + uniqueName("TileMultipart_gen"), + List("codechicken.multipart.MultipartGenerator.Generator"), + List(//methods + defaultConstructor, + DefDef( + Modifiers(Flag.OVERRIDE), + "generate":TermName, + List(), + List(List()), + TypeTree(), + Invoke( + New(Ident(defClass.name)), + nme.CONSTRUCTOR + ) + ) + ) + ) + val constructGenClass = + Invoke(//return new generator instance + New(Ident(defGenClass.name)), + nme.CONSTRUCTOR + ) + + val v = tb.eval(Block(defClass, defGenClass, constructGenClass)).asInstanceOf[Generator] + val dummy = v.generate + tileTraitMap=tileTraitMap+(dummy.getClass->set.toSet) + MultipartProxy.onTileClassBuilt(dummy.getClass) + println("Generation ["+types.mkString(", ")+"] took: "+(System.currentTimeMillis-s)) + return v.asInstanceOf[Generator] + } + } + + private var generatorMap:Map[SuperSet, Generator] = Map() + private var interfaceTraitMap:Map[Type, Seq[Type]] = Map() + private var tileTraitMap:Map[Class[_], Set[Type]] = Map() + private var partTraitMap:Map[Class[_], Seq[Type]] = Map() + + SuperSet(Seq(), false).generate//default impl, boots generator + if(FMLCommonHandler.instance.getEffectiveSide == Side.CLIENT) + SuperSet(Seq(), true).generate + + private def traitsForPart(part:TMultiPart):Seq[Type] = + { + var ret = partTraitMap.getOrElse(part.getClass, null) + if(ret == null) + { + ret = getType(part).baseClasses.flatMap(s => interfaceTraitMap.getOrElse(s.asClass.toType, List())).distinct + partTraitMap = partTraitMap+(part.getClass -> ret) + } + return ret + } + + /** + * Check if part adds any new interfaces to tile, if so, replace tile with a new copy and call tile.addPart(part) + * returns true if tile was replaced + */ + private[multipart] def addPart(world:World, pos:BlockCoord, part:TMultiPart):TileMultipart = + { + var tile = TileMultipartObj.getOrConvertTile(world, pos) + + var partTraits = traitsForPart(part) + var ntile = tile + if(tile != null) + { + if(!tile.loaded) + world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block.blockID) + + val tileTraits = tileTraitMap(tile.getClass) + partTraits = partTraits.filter(!tileTraits(_)) + if(!partTraits.isEmpty) + { + ntile = SuperSet(partTraits++tileTraits, world.isRemote).generate + world.setBlockTileEntity(pos.x, pos.y, pos.z, ntile) + ntile.loadFrom(tile) + } + else if(!tile.loaded) + { + ntile.validate() + world.setBlockTileEntity(pos.x, pos.y, pos.z, ntile) + } + } + else + { + world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block.blockID) + ntile = SuperSet(partTraits, world.isRemote).generate + world.setBlockTileEntity(pos.x, pos.y, pos.z, ntile) + } + ntile.addPart(part) + return ntile + } + + /** + * Check if tile satisfies all the interfaces required by parts. If not, return a new generated copy of tile + */ + def generateCompositeTile(tile:TileEntity, parts:Seq[TMultiPart], client:Boolean):TileMultipart = + { + var partTraits = parts.flatMap(traitsForPart(_)).distinct + if(tile != null && tile.isInstanceOf[TileMultipart]) + { + var tileTraits = tileTraitMap(tile.getClass) + if(partTraits.forall(tileTraits(_)) && partTraits.size == tileTraits.size)//equal contents + return tile.asInstanceOf[TileMultipart] + + } + return SuperSet(partTraits, client).generate + } + + /** + * Check if there are any redundant interfaces on tile, if so, replace tile with new copy + */ + def partRemoved(tile:TileMultipart, part:TMultiPart):TileMultipart = + { + var partTraits = tile.partList.flatMap(traitsForPart(_)) + var testSet = partTraits.toSet + if(!traitsForPart(part).forall(testSet(_))) + { + val ntile = SuperSet(testSet.toSeq, tile.worldObj.isRemote).generate + tile.worldObj.setBlockTileEntity(tile.xCoord, tile.yCoord, tile.zCoord, ntile) + ntile.loadFrom(tile) + return ntile + } + return tile + } + + /** + * register s_trait to be applied to tiles containing parts implementing s_interface + */ + def registerTrait(s_interface:String, s_trait:String) + { + val iSymbol = mirror.staticClass(s_interface).asClass + val tSymbol = mirror.staticClass(s_trait).asClass + //TODO some checking + var reg = interfaceTraitMap.getOrElse(iSymbol.toType, Seq()) + if(!reg.contains(tSymbol.toType)) + reg = reg:+tSymbol.toType + interfaceTraitMap = interfaceTraitMap+(iSymbol.toType->reg) + } +} \ No newline at end of file diff --git a/codechicken/multipart/MultipartRenderer.scala b/codechicken/multipart/MultipartRenderer.scala new file mode 100644 index 0000000..5ed1202 --- /dev/null +++ b/codechicken/multipart/MultipartRenderer.scala @@ -0,0 +1,83 @@ +package codechicken.multipart + +import codechicken.core.lighting.LightMatrix +import codechicken.core.render.CCRenderState +import codechicken.core.vec.Cuboid6 +import codechicken.core.vec.Vector3 +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler +import cpw.mods.fml.client.registry.RenderingRegistry +import net.minecraft.block.Block +import net.minecraft.client.renderer.RenderBlocks +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer +import net.minecraft.tileentity.TileEntity +import net.minecraft.world.IBlockAccess +import codechicken.core.vec.BlockCoord +import net.minecraft.world.IWorldAccess +import net.minecraft.util.MovingObjectPosition +import net.minecraft.client.Minecraft +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.core.raytracer.ExtendedMOP +import codechicken.core.lighting.LazyLightMatrix + +@SideOnly(Side.CLIENT) +object MultipartRenderer extends TileEntitySpecialRenderer with ISimpleBlockRenderingHandler +{ + TileMultipartObj.renderID = RenderingRegistry.getNextAvailableRenderId() + private val olm = new LazyLightMatrix + + var pass:Int = 0 + + override def renderTileEntityAt(t:TileEntity, x:Double, y:Double, z:Double, f:Float) + { + var tmpart = t.asInstanceOf[TileMultipartClient] + if(tmpart.partList.isEmpty) + return + + CCRenderState.reset() + CCRenderState.pullLightmap() + CCRenderState.useNormals(true) + + val pos = new Vector3(x, y, z) + tmpart.renderDynamic(pos, f) + } + + override def getRenderId = TileMultipartObj.renderID + + override def renderWorldBlock(world:IBlockAccess, x:Int, y:Int, z:Int, block:Block, modelId:Int, renderer:RenderBlocks):Boolean = + { + var t = world.getBlockTileEntity(x, y, z) + if(!t.isInstanceOf[TileMultipartClient]) + return false + + var tmpart = t.asInstanceOf[TileMultipartClient] + if(tmpart.partList.isEmpty) + return false + + if(renderer.hasOverrideBlockTexture()) + { + val hit = Minecraft.getMinecraft().objectMouseOver + if(hit != null && hit.blockX == x && hit.blockY == y && hit.blockZ == z && ExtendedMOP.getData(hit).isInstanceOf[(_, _)]) + { + val hitInfo:(Int, _) = ExtendedMOP.getData(hit) + if(hitInfo._1.isInstanceOf[Int] && hitInfo._1 >= 0 && hitInfo._1 < tmpart.partList.size) + tmpart.partList(hitInfo._1).drawBreaking(renderer) + } + return false + } + + CCRenderState.reset() + CCRenderState.useModelColours(true) + val pos = new Vector3(x, y, z) + olm.setPos(world, x, y, z) + tmpart.renderStatic(pos, olm, pass) + return true + } + + override def renderInventoryBlock(block:Block, meta:Int, modelId:Int, renderer:RenderBlocks) + { + //TODO: pass to the super renderer. + } + + override def shouldRender3DInInventory = false +} diff --git a/codechicken/multipart/PartMap.java b/codechicken/multipart/PartMap.java new file mode 100644 index 0000000..bcd0f58 --- /dev/null +++ b/codechicken/multipart/PartMap.java @@ -0,0 +1,89 @@ +package codechicken.multipart; + +public enum PartMap +{ + BOTTOM(0), + TOP(1), + NORTH(2), + SOUTH(3), + WEST(4), + EAST(5), + CENTER(6), + CORNER_NNN(7), + CORNER_NPN(8), + CORNER_NNP(9), + CORNER_NPP(10), + CORNER_PNN(11), + CORNER_PPN(12), + CORNER_PNP(13), + CORNER_PPP(14), + EDGE_NYN(15), + EDGE_NYP(16), + EDGE_PYN(17), + EDGE_PYP(18), + EDGE_NNZ(19), + EDGE_PNZ(20), + EDGE_NPZ(21), + EDGE_PPZ(22), + EDGE_XNN(23), + EDGE_XPN(24), + EDGE_XNP(25), + EDGE_XPP(26); + + public final int i; + public final int mask; + + private PartMap(int i) + { + this.i = i; + mask = 1<>2) + { + case 0: return 6; + case 1: return 5; + case 2: return 3; + } + throw new IllegalArgumentException("Switch Falloff"); + } + + public static int unpackEdgeBits(int e) + { + switch(e>>2) + { + case 0: return (e&3)<<1; + case 1: return (e&2)>>1|(e&1)<<2; + case 2: return (e&3); + } + throw new IllegalArgumentException("Switch Falloff"); + } + + public static int packEdgeBits(int e, int bits) + { + switch(e>>2) + { + case 0: return e&0xC|bits>>1; + case 1: return e&0xC|(bits&4)>>2|(bits&1)<<1; + case 2: return e&0xC|bits&3; + } + throw new IllegalArgumentException("Switch Falloff"); + } +} diff --git a/codechicken/multipart/TCuboidPart.scala b/codechicken/multipart/TCuboidPart.scala new file mode 100644 index 0000000..e7a43ed --- /dev/null +++ b/codechicken/multipart/TCuboidPart.scala @@ -0,0 +1,28 @@ +package codechicken.multipart + +import codechicken.core.vec.Cuboid6 +import codechicken.core.raytracer.IndexedCuboid6 +import net.minecraft.client.renderer.RenderBlocks +import codechicken.core.render.CCRenderState +import codechicken.core.render.RenderUtils +import net.minecraftforge.scala.ScalaBridge._ +import codechicken.core.vec.Vector3 +import codechicken.core.render.IconTransformation +import net.minecraftforge.scala.JSeq + +abstract class JCuboidPart extends TCuboidPart + +trait TCuboidPart extends TMultiPart +{ + def getBounds:Cuboid6 + + override def getSubParts:JSeq[IndexedCuboid6] = Seq(new IndexedCuboid6(0, getBounds)) + + override def getCollisionBoxes:JSeq[Cuboid6] = Seq(getBounds) + + override def drawBreaking(renderBlocks:RenderBlocks) + { + CCRenderState.reset() + RenderUtils.renderBlock(getBounds, 0, Vector3.fromTileEntity(tile), new IconTransformation(renderBlocks.overrideBlockTexture)) + } +} \ No newline at end of file diff --git a/codechicken/multipart/TIconHitEffects.scala b/codechicken/multipart/TIconHitEffects.scala new file mode 100644 index 0000000..50c7bc9 --- /dev/null +++ b/codechicken/multipart/TIconHitEffects.scala @@ -0,0 +1,64 @@ +package codechicken.multipart + +import codechicken.core.vec.Cuboid6 +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import net.minecraft.util.Icon +import net.minecraft.util.MovingObjectPosition +import net.minecraft.client.particle.EffectRenderer +import codechicken.core.entity.EntityDigIconFX +import codechicken.core.vec.Vector3 +import codechicken.core.raytracer.ExtendedMOP + +object IconHitEffects +{ + def addHitEffects(part:JIconHitEffects, hit:MovingObjectPosition, effectRenderer:EffectRenderer) + { + EntityDigIconFX.addBlockHitEffects(part.tile.worldObj, + part.getBounds.copy.add(Vector3.fromTileEntity(part.tile)), hit.sideHit, + part.getBreakingIcon(ExtendedMOP.getData[(_, _)](hit)._2, hit.sideHit), effectRenderer) + } + + def addDestroyEffects(part:JIconHitEffects, effectRenderer:EffectRenderer) + { + addDestroyEffects(part, effectRenderer, true) + } + + def addDestroyEffects(part:JIconHitEffects, effectRenderer:EffectRenderer, scaleDensity:Boolean) + { + val icons = new Array[Icon](6) + for(i <- 0 until 6) + icons(i) = part.getBrokenIcon(i) + val bounds = + if(scaleDensity) part.getBounds.copy + else Cuboid6.full.copy + EntityDigIconFX.addBlockDestroyEffects(part.tile.worldObj, + bounds.add(Vector3.fromTileEntity(part.tile)), icons, effectRenderer) + } +} + +trait JIconHitEffects extends TMultiPart +{ + def getBounds:Cuboid6 + + @SideOnly(Side.CLIENT) + def getBreakingIcon(subPart:Any, side:Int) = getBrokenIcon(side) + + @SideOnly(Side.CLIENT) + def getBrokenIcon(side:Int):Icon +} + +trait TIconHitEffects extends JIconHitEffects +{ + @SideOnly(Side.CLIENT) + override def addHitEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer) + { + IconHitEffects.addHitEffects(this, hit, effectRenderer) + } + + @SideOnly(Side.CLIENT) + override def addDestroyEffects(effectRenderer:EffectRenderer) + { + IconHitEffects.addDestroyEffects(this, effectRenderer) + } +} \ No newline at end of file diff --git a/codechicken/multipart/TLiquidTank.scala b/codechicken/multipart/TLiquidTank.scala new file mode 100644 index 0000000..f84eaad --- /dev/null +++ b/codechicken/multipart/TLiquidTank.scala @@ -0,0 +1,98 @@ +package codechicken.multipart + +import net.minecraftforge.liquids.ITankContainer +import scala.collection.mutable.ListBuffer +import net.minecraftforge.liquids.LiquidStack +import net.minecraftforge.liquids.ILiquidTank +import net.minecraftforge.common.ForgeDirection +import codechicken.core.liquid.LiquidUtils + +trait TLiquidTank extends TileMultipart with ITankContainer +{ + var tankList = ListBuffer[ITankContainer]() + + override def partAdded(part:TMultiPart) + { + super.partAdded(part) + if(part.isInstanceOf[ITankContainer]) + tankList+=part.asInstanceOf[ITankContainer] + } + + override def partRemoved(part:TMultiPart, p:Int) + { + super.partRemoved(part, p) + if(part.isInstanceOf[ITankContainer]) + tankList-=part.asInstanceOf[ITankContainer] + } + + override def loadFrom(that:TileMultipart) + { + super.loadFrom(that) + if(that.isInstanceOf[TLiquidTank]) + tankList = that.asInstanceOf[TLiquidTank].tankList + } + + override def clearParts() + { + super.clearParts() + tankList.clear + } + + override def getTanks(dir:ForgeDirection):Array[ILiquidTank] = + { + var tankCount:Int = 0 + tankList.foreach(t => tankCount += t.getTanks(dir).length) + val tanks = new Array[ILiquidTank](tankCount) + var i = 0 + tankList.foreach(p => p.getTanks(dir).foreach(t => { + tanks(i) = t + i+=1 + })) + return tanks + } + + override def getTank(dir:ForgeDirection, liquid:LiquidStack):ILiquidTank = + { + tankList.foreach(p => { + val t = p.getTank(dir, liquid) + if(t != null) + return t//TODO: bad, slow + }) + return null + } + + override def fill(dir:ForgeDirection, liquid:LiquidStack, doFill:Boolean):Int = + { + var filled = 0 + var initial = liquid.amount + tankList.foreach(p => { + filled+=p.fill(dir, LiquidUtils.copy(liquid, initial-filled), doFill) + }) + return filled + } + + override def drain(dir:ForgeDirection, amount:Int, doDrain:Boolean):LiquidStack = + { + var drained:LiquidStack = null + tankList.foreach(p => { + val ret = p.drain(dir, amount-drained.amount, false) + if(ret != null && ret.amount > 0 && (drained == null || drained.isLiquidEqual(ret))) + { + if(doDrain) + p.drain(dir, amount-drained.amount, true) + + if(drained == null) + drained = ret + else + drained.amount+=ret.amount + } + }) + return drained + } + + override def fill(tankIndex:Int, liquid:LiquidStack, doFill:Boolean):Int = + throw new UnsupportedOperationException("Index based tank filling") + + override def drain(tankIndex:Int, maxDrain:Int, doDrain:Boolean):LiquidStack = + throw new UnsupportedOperationException("Index based tank draining") +} \ No newline at end of file diff --git a/codechicken/multipart/TMultiPart.scala b/codechicken/multipart/TMultiPart.scala new file mode 100644 index 0000000..b92ecbf --- /dev/null +++ b/codechicken/multipart/TMultiPart.scala @@ -0,0 +1,81 @@ +package codechicken.multipart + +import codechicken.core.packet.PacketCustom +import codechicken.core.vec.Cuboid6 +import codechicken.core.vec.Vector3 +import net.minecraft.entity.player.EntityPlayer +import net.minecraft.item.ItemStack +import net.minecraft.nbt.NBTTagCompound +import net.minecraft.util.MovingObjectPosition +import codechicken.core.raytracer.IndexedCuboid6 +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import net.minecraft.client.particle.EffectRenderer +import net.minecraft.util.Icon +import codechicken.core.entity.EntityDigIconFX +import net.minecraft.client.renderer.RenderBlocks +import codechicken.core.render.RenderUtils +import codechicken.core.render.IconTransformation +import codechicken.core.vec.BlockCoord +import net.minecraft.world.World +import net.minecraft.tileentity.TileEntity +import codechicken.core.render.CCRenderState +import net.minecraftforge.scala.JSeq +import net.minecraftforge.scala.ScalaBridge._ +import codechicken.core.lighting.LazyLightMatrix + +abstract class TMultiPart +{ + var tile:TileMultipart = _ + + def getTile():TileEntity = tile + + def getType:String + def bind(tile:TileMultipart) + { + TMultiPart.this.tile = tile + } + + def getSlotMask:Int = 0 + + def occlusionTest(npart:TMultiPart):Boolean = true + def getSubParts:JSeq[IndexedCuboid6] = Seq() + def getCollisionBoxes:JSeq[Cuboid6] = Seq() + + def getDrops:JSeq[ItemStack] = Seq() + def getStrength(hit:MovingObjectPosition, player:EntityPlayer):Float = 1 + def getLightValue = 0 + + @SideOnly(Side.CLIENT) + def addHitEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer){} + @SideOnly(Side.CLIENT) + def addDestroyEffects(effectRenderer:EffectRenderer){} + @SideOnly(Side.CLIENT) + def renderStatic(pos:Vector3, olm:LazyLightMatrix, pass:Int){} + @SideOnly(Side.CLIENT) + def renderDynamic(pos:Vector3, frame:Float){} + @SideOnly(Side.CLIENT) + def drawBreaking(renderBlocks:RenderBlocks){} + + def read(packet:PacketCustom){} + def write(packet:PacketCustom){} + def save(tag:NBTTagCompound){} + def load(tag:NBTTagCompound){} + + def onWorldJoin(world:World){onPartChanged()} + def onPartChanged(){} + def onNeighbourChanged(){} + + def activate(player:EntityPlayer, part:MovingObjectPosition, item:ItemStack):Boolean = false + def click(player:EntityPlayer, part:MovingObjectPosition, item:ItemStack){} + def doesTick = true + def update(){} + def pickItem(hit:MovingObjectPosition):ItemStack = null + + def sendDescPacket() = tile.sendPartDesc(this) +} + +trait TFacePart extends TMultiPart +{ + def solid(side:Int):Boolean = true +} \ No newline at end of file diff --git a/codechicken/multipart/TNormalOcclusion.scala b/codechicken/multipart/TNormalOcclusion.scala new file mode 100644 index 0000000..a796306 --- /dev/null +++ b/codechicken/multipart/TNormalOcclusion.scala @@ -0,0 +1,34 @@ +package codechicken.multipart + +import codechicken.core.vec.Cuboid6 +import net.minecraftforge.scala.JSeq +import net.minecraftforge.scala.ScalaBridge._ + +object NormalOcclusionTest +{ + def apply(boxes1:Traversable[Cuboid6], boxes2:Traversable[Cuboid6]):Boolean = + boxes1.forall(v1 => boxes2.forall(v2 => !v1.intersects(v2))) + + def apply(part1:JNormalOcclusion, part2:TMultiPart):Boolean = + { + var boxes = Seq[Cuboid6]() + if(part2.isInstanceOf[TNormalOcclusion]) + boxes = boxes++part2.asInstanceOf[JNormalOcclusion].getOcclusionBoxes + + if(part2.isInstanceOf[JPartialOcclusion]) + boxes = boxes++part2.asInstanceOf[JPartialOcclusion].getPartialOcclusionBoxes + + return NormalOcclusionTest(boxes, part1.getOcclusionBoxes) + } +} + +trait JNormalOcclusion +{ + def getOcclusionBoxes():JSeq[Cuboid6] +} + +trait TNormalOcclusion extends TMultiPart with JNormalOcclusion +{ + override def occlusionTest(npart:TMultiPart):Boolean = + NormalOcclusionTest(this, npart) && super.occlusionTest(npart) +} \ No newline at end of file diff --git a/codechicken/multipart/TPartialOcclusion.scala b/codechicken/multipart/TPartialOcclusion.scala new file mode 100644 index 0000000..f3987a1 --- /dev/null +++ b/codechicken/multipart/TPartialOcclusion.scala @@ -0,0 +1,83 @@ +package codechicken.multipart + +import codechicken.core.vec.Cuboid6 +import net.minecraftforge.scala.JSeq +import net.minecraftforge.scala.ScalaBridge._ + +trait JPartialOcclusion +{ + def getPartialOcclusionBoxes():JSeq[Cuboid6] + + def allowCompleteOcclusion = false +} + +trait TPartialOcclusionTile extends TileMultipart +{ + override def occlusionTest(parts:Seq[TMultiPart], npart:TMultiPart):Boolean = + { + if(npart.isInstanceOf[JPartialOcclusion] && !partialOcclusionTest(parts:+npart)) + return false + + return super.occlusionTest(parts, npart) + } + + def partialOcclusionTest(parts:Seq[TMultiPart]):Boolean = + { + val test = new PartialOcclusionTest(parts.length) + for(i <- 0 until parts.length) + { + val part = parts(i) + if(part.isInstanceOf[JPartialOcclusion]) + test.fill(i, part.asInstanceOf[JPartialOcclusion]) + } + return test() + } +} + +class PartialOcclusionTest(size:Int) +{ + val res = 8 + val bits = new Array[Byte](res*res*res) + val partial = new Array[Boolean](size) + + def fill(i:Int, part:JPartialOcclusion) + { + fill(i, part.getPartialOcclusionBoxes, part.allowCompleteOcclusion) + } + + def fill(i:Int, boxes:Seq[Cuboid6], complete:Boolean) + { + partial(i) = !complete + boxes.foreach(box => fill(i+1, box)) + } + + def fill(v:Int, box:Cuboid6) + { + for(x <- (box.min.x*res+0.5).toInt until (box.max.x*res+0.5).toInt) + for(y <- (box.min.y*res+0.5).toInt until (box.max.y*res+0.5).toInt) + for(z <- (box.min.z*res+0.5).toInt until (box.max.z*res+0.5).toInt) + { + val i = (x*res+y)*res+z + if(bits(i) == 0) + bits(i) = v.toByte + else + bits(i) = -1 + } + } + + def apply():Boolean = + { + val visible = new Array[Boolean](size) + bits.foreach(n => if(n > 0) visible(n-1) = true) + + var i = 0 + while(i < partial.length) + { + if(partial(i) && !visible(i)) + return false + i+=1 + } + + return true + } +} \ No newline at end of file diff --git a/codechicken/multipart/TileMultipart.scala b/codechicken/multipart/TileMultipart.scala new file mode 100644 index 0000000..2930aa7 --- /dev/null +++ b/codechicken/multipart/TileMultipart.scala @@ -0,0 +1,542 @@ +package codechicken.multipart + +import net.minecraft.tileentity.TileEntity +import scala.collection.mutable.ListBuffer +import net.minecraft.network.packet.Packet +import codechicken.core.packet.PacketCustom +import codechicken.multipart.handler.MultipartCPH +import codechicken.core.vec.BlockCoord +import net.minecraft.world.World +import java.util.List +import scala.collection.JavaConverters._ +import net.minecraft.nbt.NBTTagCompound +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.io.DataInputStream +import codechicken.core.data.MCDataInputStream +import codechicken.core.data.MCDataOutput +import codechicken.core.data.MCDataOutputStream +import net.minecraft.client.multiplayer.NetClientHandler +import codechicken.core.vec.Cuboid6 +import scala.collection.mutable.HashSet +import codechicken.multipart.handler.MultipartProxy +import net.minecraft.block.Block +import net.minecraft.item.ItemStack +import codechicken.core.inventory.InventoryUtils +import codechicken.core.vec.Vector3 +import net.minecraft.nbt.NBTTagList +import net.minecraft.client.particle.EffectRenderer +import net.minecraft.util.MovingObjectPosition +import scala.collection.mutable.ArrayBuffer +import net.minecraftforge.scala.ScalaBridge._ +import java.util.Random +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import scala.collection.mutable.Queue +import codechicken.multipart.handler.MultipartSPH +import codechicken.core.lighting.LazyLightMatrix + +trait TileMultipart extends TileEntity +{ + var partList: ArrayBuffer[TMultiPart] = ArrayBuffer() + var partMap: Array[TMultiPart] = new Array(27) + + private var doesTick = false + + def loadFrom(that:TileMultipart)//Potentially auto gen this + { + partList = that.partList + partMap = that.partMap + doesTick = that.doesTick + + partList.foreach(_.bind(this)) + } + + def jPartList():List[TMultiPart] = partList.asJava + + override def canUpdate() = doesTick//TODO: part merging true + + override def updateEntity() + { + super.updateEntity() + + TileMultipartObj.startOperation(this) + partList.foreach(_.update()) + TileMultipartObj.finishOperation(this) + } + + override def setWorldObj(world:World) + { + super.setWorldObj(world) + partList.foreach(_.onWorldJoin(world)) + } + + def loaded() = !isInvalid + + def notifyPartChange() + { + TileMultipartObj.startOperation(this) + partList.foreach(_.onPartChanged()) + TileMultipartObj.finishOperation(this) + + worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType().blockID) + worldObj.updateAllLightTypes(xCoord, yCoord, zCoord) + } + + def onNeighborBlockChange(world:World, x:Int, y:Int, z:Int, id:Int) + { + TileMultipartObj.startOperation(this) + partList.foreach(_.onNeighbourChanged()) + TileMultipartObj.finishOperation(this) + } + + def getLightValue() = partList.foldLeft(0)((l, p) => Math.max(l, p.getLightValue)) + + def markDirty() + { + worldObj.updateTileEntityChunkAndDoNothing(xCoord, yCoord, zCoord, this) + } + + def isSolid(side:Int):Boolean = + { + val part = partMap(PartMap.face(side).i) + if(part != null) part.asInstanceOf[TFacePart].solid(side) else false + } + + private def setTicking(tick:Boolean) + { + if(doesTick == tick) + return + + doesTick = tick + if(worldObj != null) + { + if(tick) + worldObj.addTileEntity(this) + else + worldObj.loadedTileEntityList.remove(this) + } + } + + def canAddPart(part:TMultiPart):Boolean = + { + if(partList.contains(part)) + return false + + val slotMask = part.getSlotMask + for(i <- 0 until partMap.length) + if((slotMask&1< part.occlusionTest(npart) && npart.occlusionTest(part)) + } + + private[multipart] def addPart(part:TMultiPart) + { + addPart_do(part) + notifyPartChange() + markDirty() + markRender() + + if(!worldObj.isRemote) + { + val packet = new PacketCustom(MultipartSPH.channel, 3) + packet.setChunkDataPacket() + packet.writeCoord(xCoord, yCoord, zCoord) + MultiPartRegistry.writePartID(packet, part) + part.write(packet) + packet.sendToChunk(worldObj, xCoord>>4, zCoord>>4) + } + } + + private[multipart] def addPart_do(part:TMultiPart) + { + if(partList.size >= 256) + throw new IllegalArgumentException("Tried to add more than 256 parts to the one tile") + + partList+=part + val mask = part.getSlotMask + for(i <- 0 until 27) + if ((mask&1< 0) + partMap(i) = part + + part.bind(this) + + if(!doesTick && part.doesTick) + setTicking(true) + + partAdded(part) + } + + def partAdded(part:TMultiPart){} + + def remPart(part:TMultiPart):TileMultipart = + { + if(TileMultipartObj.queueRemoval(this, part)) + return null + + val i = remPart_do(part) + if(!isInvalid()) + { + notifyPartChange() + markDirty() + markRender() + } + + if(!worldObj.isRemote) + { + val packet = new PacketCustom(MultipartSPH.channel, 4) + packet.setChunkDataPacket() + packet.writeCoord(xCoord, yCoord, zCoord) + packet.writeByte(i) + packet.sendToChunk(worldObj, xCoord>>4, zCoord>>4) + } + + if(!isInvalid()) + return MultipartGenerator.partRemoved(this, part) + + return null + } + + private def remPart_do(part:TMultiPart):Int = + { + val r = partList.indexOf(part) + if(r < 0) + throw new IllegalArgumentException("Tried to remove a non-existant part") + + partList-=part + for(i <- 0 until 27) + if(partMap(i) == part) + partMap(i) = null + + partRemoved(part, r) + + if(partList.isEmpty) + { + worldObj.setBlockToAir(xCoord, yCoord, zCoord) + } + else + { + if(part.doesTick && doesTick) + { + var ntick = false + partList.foreach(part => ntick |= part.doesTick) + if(!ntick) + setTicking(false) + } + } + return r + } + + def partRemoved(part:TMultiPart, p:Int){} + + private[multipart] def loadParts(parts:ListBuffer[TMultiPart]) + { + clearParts() + for(i <- 0 until partMap.length) + partMap(i) = null + parts.foreach(p => addPart_do(p)) + if(worldObj != null) + notifyPartChange() + } + + def clearParts() + { + partList.clear() + } + + override def getDescriptionPacket():Packet = + { + val packet = new PacketCustom(MultipartSPH.channel, 2); + packet.setChunkDataPacket() + + val superPacket = super.getDescriptionPacket + var partCount = partList.size + if(superPacket != null) + partCount |= 0x80 + + packet.writeByte(partCount) + if(superPacket != null) + { + packet.writeByte(superPacket.getPacketId) + superPacket.writePacketData(new DataOutputStream(new MCDataOutputStream(packet))) + } + + packet.writeCoord(xCoord, yCoord, zCoord) + partList.foreach{part => { + MultiPartRegistry.writePartID(packet, part) + part.write(packet) + }} + return packet.toPacket; + } + + def harvestPart(index:Int, drop:Boolean):Boolean = + { + val part = partList(index) + if(part == null) + return false + if(drop) + dropItems(part.getDrops) + remPart(part) + return true + } + + def dropItems(items:Seq[ItemStack]) + { + val pos = Vector3.fromTileEntityCenter(this) + items.foreach(item => InventoryUtils.dropItem(item, worldObj, pos)) + } + + def sendPartDesc(part:TMultiPart) + { + val i = partList.indexOf(part) + if(i < 0) + throw new IllegalArgumentException("Tried to send desc for non-existant part") + + val packet = new PacketCustom(MultipartSPH.channel, 5) + packet.setChunkDataPacket() + packet.writeCoord(xCoord, yCoord, zCoord) + packet.writeByte(i) + part.write(packet) + packet.sendToChunk(worldObj, xCoord>>4, zCoord>>4) + } + + def markRender() + { + worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord) + } + + override def writeToNBT(tag:NBTTagCompound) + { + super.writeToNBT(tag) + val taglist = new NBTTagList + partList.foreach { part => { + val parttag = new NBTTagCompound + parttag.setString("id", part.getType) + part.save(parttag) + taglist.appendTag(parttag) + }} + tag.setTag("parts", taglist) + } +} + +trait TileMultipartClient extends TileMultipart +{ + def renderStatic(pos:Vector3, olm:LazyLightMatrix, pass:Int) + { + partList.foreach(part => part.renderStatic(pos, olm, pass)) + } + + def renderDynamic(pos:Vector3, frame:Float) + { + partList.foreach(part => part.renderDynamic(pos, frame)) + } + + def randomDisplayTick(random:Random){} +} + +object TileMultipartObj +{ + var renderID:Int = -1 + + private var operatingTile = new ThreadLocal[TileMultipart] + private val removalQueue = Queue[TMultiPart]() + private val additionQueue = Queue[TMultiPart]() + + def startOperation(tile:TileMultipart) + { + if(operatingTile.get != null) + throw new IllegalStateException("Recursive operations not implemented") + + operatingTile.set(tile) + } + + def finishOperation(tile:TileMultipart) + { + operatingTile.remove + + if(removalQueue.isEmpty && additionQueue.isEmpty) + return + + var otile = tile + val world = tile.worldObj + val pos = new BlockCoord(tile) + while(!removalQueue.isEmpty) + otile = otile.remPart(removalQueue.dequeue) + + while(!additionQueue.isEmpty) + MultipartGenerator.addPart(world, pos, additionQueue.dequeue) + } + + def queueRemoval(tile:TileMultipart, part:TMultiPart):Boolean = + { + if(tile != operatingTile.get) + return false + + if(!removalQueue.contains(part)) + removalQueue+=part + return true + } + + def queueAddition(world:World, pos:BlockCoord, part:TMultiPart):Boolean = + { + val opt = operatingTile.get + if(opt == null || opt.worldObj != world || opt.xCoord != pos.x || opt.yCoord != pos.y || opt.zCoord != pos.z) + return false + + if(!additionQueue.contains(part)) + additionQueue+=part + + return true + } + + def getOrConvertTile(world:World, pos:BlockCoord):TileMultipart = + { + val t = world.getBlockTileEntity(pos.x, pos.y, pos.z) + if(t.isInstanceOf[TileMultipart]) + return t.asInstanceOf[TileMultipart] + + val id = world.getBlockId(pos.x, pos.y, pos.z) + val p = MultiPartRegistry.convertBlock(world, pos, id) + if(p != null) + { + val t = MultipartGenerator.generateCompositeTile(null, Seq(p), world.isRemote) + t.xCoord = pos.x + t.yCoord = pos.y + t.zCoord = pos.z + t.invalidate() + t.setWorldObj(world) + t.addPart_do(p) + return t + } + return null + } + + def canAddPart(world:World, pos:BlockCoord, part:TMultiPart):Boolean = + { + part.getCollisionBoxes.foreach{b => + if(!world.checkNoEntityCollision(b.toAABB().offset(pos.x, pos.y, pos.z))) + return false + } + + val t = getOrConvertTile(world, pos) + if(t != null) + return t.canAddPart(part) + + if(!replaceable(world, pos)) + return false + + return true + } + + def replaceable(world:World, pos:BlockCoord):Boolean = + { + val block = Block.blocksList(world.getBlockId(pos.x, pos.y, pos.z)) + return block == null || block.isAirBlock(world, pos.x, pos.y, pos.z) || block.isBlockReplaceable(world, pos.x, pos.y, pos.z) + } + + def addPart(world:World, pos:BlockCoord, part:TMultiPart):TileMultipart = + { + if(queueAddition(world, pos, part)) + return null + + return MultipartGenerator.addPart(world, pos, part) + } + + @SideOnly(Side.CLIENT) + def handleDescPacket(world:World, packet:PacketCustom, netHandler:NetClientHandler) + { + var partCount = packet.readUnsignedByte() + if((partCount & 0x80) > 0)//composite + { + val superPacket = Packet.getNewPacket(null, packet.readUnsignedByte()) + superPacket.readPacketData(new DataInputStream(new MCDataInputStream(packet))) + superPacket.processPacket(netHandler) + } + partCount &= 0x7F + + val pos = packet.readCoord + val parts = ListBuffer[TMultiPart]() + for(i <- 0 until partCount) + { + val part:TMultiPart = MultiPartRegistry.readPart(packet) + part.read(packet) + parts+=part + } + + if(parts.size == 0) + return + + val t = world.getBlockTileEntity(pos.x, pos.y, pos.z) + val tilemp = MultipartGenerator.generateCompositeTile(t, parts, true) + if(tilemp != t) + world.setBlockTileEntity(pos.x, pos.y, pos.z, tilemp) + + tilemp.loadParts(parts) + tilemp.markRender() + } + + def handlePacket(world:World, packet:PacketCustom) + { + val pos = packet.readCoord + var tilemp = BlockMultipart.getTile(world, pos.x, pos.y, pos.z) + + packet.getType() match + { + case 3 => { + val part = MultiPartRegistry.readPart(packet) + part.read(packet) + addPart(world, pos, part) + } + case 4 => if(tilemp != null) { + tilemp.remPart(tilemp.partList(packet.readUnsignedByte())) + } + case 5 => if(tilemp != null) { + tilemp.partList(packet.readUnsignedByte()).read(packet) + } + } + } + + def createFromNBT(tag:NBTTagCompound):TileMultipart = + { + val superID = tag.getString("superID") + val superClass = TileEntity.nameToClassMap.get(superID) + + val partList = tag.getTagList("parts") + val parts = ListBuffer[TMultiPart]() + + for(i <- 0 until partList.tagCount) + { + val partTag = partList.tagAt(i).asInstanceOf[NBTTagCompound] + val partID = partTag.getString("id") + val part = MultiPartRegistry.createPart(partID, false) + if(part != null) + { + part.load(partTag) + parts+=part + } + } + + if(parts.size == 0) + return null + + val tmb = MultipartGenerator.generateCompositeTile(null, parts, false) + tmb.readFromNBT(tag) + tmb.loadParts(parts) + return tmb + } +} diff --git a/codechicken/multipart/handler/EventHandler.scala b/codechicken/multipart/handler/EventHandler.scala new file mode 100644 index 0000000..4892b46 --- /dev/null +++ b/codechicken/multipart/handler/EventHandler.scala @@ -0,0 +1,45 @@ +package codechicken.multipart.handler + +import net.minecraftforge.event.tileentity.TileEntityLoadEvent +import net.minecraft.nbt.NBTTagCompound +import codechicken.multipart.TileMultipart +import net.minecraftforge.event.ForgeSubscribe +import codechicken.multipart.TileMultipartObj +import cpw.mods.fml.common.network.IConnectionHandler +import net.minecraft.network.packet.NetHandler +import net.minecraft.network.INetworkManager +import net.minecraft.network.packet.Packet1Login +import cpw.mods.fml.common.network.Player +import net.minecraft.network.NetLoginHandler +import net.minecraft.server.MinecraftServer +import codechicken.core.packet.PacketCustom +import codechicken.multipart.MultiPartRegistry + +object MultipartEventHandler extends IConnectionHandler +{ + @ForgeSubscribe + def tileEntityLoad(event:TileEntityLoadEvent) + { + val id = event.tag.getString("id"); + if(!id.equals("savedMultipart")) + return + + val t = TileMultipartObj.createFromNBT(event.tag) + if(t != null) + event.setResult(t) + } + + def connectionReceived(loginHandler:NetLoginHandler, netManager:INetworkManager):String = + { + val packet = new PacketCustom(MultipartSPH.channel, 1) + MultiPartRegistry.writeIDMap(packet) + netManager.addToSendQueue(packet.toPacket) + return null + } + + def clientLoggedIn(netHandler:NetHandler, netManager:INetworkManager, packet:Packet1Login){} + def playerLoggedIn(player:Player, netHandler:NetHandler, netManager:INetworkManager){} + def connectionOpened(netHandler:NetHandler, server:String, port:Int, netManager:INetworkManager){} + def connectionOpened(netHandler:NetHandler, server:MinecraftServer, netManager:INetworkManager){} + def connectionClosed(netManager:INetworkManager){} +} \ No newline at end of file diff --git a/codechicken/multipart/handler/ModContainer.scala b/codechicken/multipart/handler/ModContainer.scala new file mode 100644 index 0000000..920a557 --- /dev/null +++ b/codechicken/multipart/handler/ModContainer.scala @@ -0,0 +1,40 @@ +package codechicken.multipart.handler + +import cpw.mods.fml.common.network.NetworkMod +import cpw.mods.fml.common.Mod +import cpw.mods.fml.common.event.FMLPostInitializationEvent +import cpw.mods.fml.common.event.FMLPreInitializationEvent +import cpw.mods.fml.common.Mod.PreInit +import cpw.mods.fml.common.Mod.PostInit +import cpw.mods.fml.common.Mod.ServerAboutToStart +import cpw.mods.fml.common.event.FMLServerAboutToStartEvent +import codechicken.multipart.MultiPartRegistry +import cpw.mods.fml.relauncher.SideOnly +import codechicken.core.packet.PacketCustom.CustomTinyPacketHandler + +@Mod(name="Multipart API", version="b.0.0.0", useMetadata = false, modid = "CCMultipart", acceptedMinecraftVersions = "[1.5.2]", modLanguage="scala") +@NetworkMod(clientSideRequired = true, serverSideRequired = true, tinyPacketHandler=classOf[CustomTinyPacketHandler]) +object MultipartMod +{ + @PreInit + def preInit(event:FMLPreInitializationEvent) + { + MultipartProxy.preInit(event.getModConfigurationDirectory()) + } + + @PostInit + def postInit(event:FMLPostInitializationEvent) + { + if(MultiPartRegistry.required) + { + MultiPartRegistry.postInit() + MultipartProxy.postInit() + } + } + + @ServerAboutToStart + def beforeServerStart(event:FMLServerAboutToStartEvent) + { + MultiPartRegistry.beforeServerStart() + } +} \ No newline at end of file diff --git a/codechicken/multipart/handler/PacketHandlers.scala b/codechicken/multipart/handler/PacketHandlers.scala new file mode 100644 index 0000000..69a3b16 --- /dev/null +++ b/codechicken/multipart/handler/PacketHandlers.scala @@ -0,0 +1,50 @@ +package codechicken.multipart.handler + +import codechicken.core.packet.PacketCustom.ICustomPacketHandler.IClientPacketHandler +import codechicken.core.packet.PacketCustom.ICustomPacketHandler.IServerPacketHandler +import codechicken.core.packet.PacketCustom +import net.minecraft.client.multiplayer.NetClientHandler +import net.minecraft.client.Minecraft +import codechicken.multipart.MultiPartRegistry +import net.minecraft.network.NetServerHandler +import net.minecraft.entity.player.EntityPlayerMP +import codechicken.multipart.TileMultipart +import codechicken.multipart.ControlKeyModifer +import codechicken.multipart.TileMultipartObj +import net.minecraft.network.packet.Packet255KickDisconnect +import net.minecraft.server.MinecraftServer + +object MultipartCPH extends IClientPacketHandler +{ + val channel = MultipartMod; + + def handlePacket(packet:PacketCustom, netHandler:NetClientHandler, mc:Minecraft) + { + packet.getType match + { + case 1 => handlePartRegistration(packet, netHandler) + case 2 => TileMultipartObj.handleDescPacket(mc.theWorld, packet, netHandler) + case 3 | 4 | 5 => TileMultipartObj.handlePacket(mc.theWorld, packet) + } + } + + def handlePartRegistration(packet:PacketCustom, netHandler:NetClientHandler) + { + val missing = MultiPartRegistry.readIDMap(packet) + if(!missing.isEmpty) + netHandler.handleKickDisconnect(new Packet255KickDisconnect("The following multiparts are not installed on this client: "+missing.mkString(", "))) + } +} + +object MultipartSPH extends IServerPacketHandler +{ + val channel = MultipartMod; + + def handlePacket(packet:PacketCustom, netHandler:NetServerHandler, sender:EntityPlayerMP) + { + packet.getType() match + { + case 1 => ControlKeyModifer.map.put(sender, packet.readBoolean) + } + } +} diff --git a/codechicken/multipart/handler/Proxies.scala b/codechicken/multipart/handler/Proxies.scala new file mode 100644 index 0000000..7072b9b --- /dev/null +++ b/codechicken/multipart/handler/Proxies.scala @@ -0,0 +1,77 @@ +package codechicken.multipart.handler + +import codechicken.multipart.BlockMultipart +import cpw.mods.fml.common.network.PacketDispatcher +import cpw.mods.fml.client.registry.RenderingRegistry +import cpw.mods.fml.client.registry.ClientRegistry +import net.minecraft.tileentity.TileEntity +import codechicken.core.config.ConfigFile +import cpw.mods.fml.common.registry.GameRegistry +import java.io.File +import codechicken.multipart.handler.MultipartProxy._ +import codechicken.multipart.BlockMultipartImpl +import codechicken.core.CommonUtils +import codechicken.multipart.MultipartRenderer +import java.util.HashMap +import net.minecraftforge.common.MinecraftForge +import codechicken.multipart.MultipartGenerator +import cpw.mods.fml.relauncher.SideOnly +import cpw.mods.fml.relauncher.Side +import codechicken.core.packet.PacketCustom +import codechicken.multipart.TileMultipart +import cpw.mods.fml.client.registry.KeyBindingRegistry +import codechicken.multipart.ControlKeyHandler +import cpw.mods.fml.common.network.NetworkRegistry + +class MultipartProxy_serverImpl +{ + def preInit(cfgdir:File) + { + config = new ConfigFile(new File(cfgdir, "multipart.cfg")) + .setComment("Multipart API config file") + + MultipartGenerator.registerTrait("net.minecraftforge.liquids.ITankContainer", "codechicken.multipart.TLiquidTank") + MultipartGenerator.registerTrait("codechicken.multipart.JPartialOcclusion", "codechicken.multipart.TPartialOcclusionTile") + MultipartGenerator.registerTrait("codechicken.multipart.IRandomDisplayTick", "codechicken.multipart.TRandomDisplayTickTile") + } + + def postInit() + { + block = new BlockMultipartImpl(config.getTag("block.id").getIntValue(CommonUtils.getFreeBlockID(1281))) + block.setUnlocalizedName("ccmultipart") + + MinecraftForge.EVENT_BUS.register(MultipartEventHandler) + PacketCustom.assignHandler(MultipartSPH.channel, MultipartSPH) + NetworkRegistry.instance.registerConnectionHandler(MultipartEventHandler) + } + + def onTileClassBuilt(t:Class[_ <: TileEntity]) + { + TileEntity.classToNameMap.asInstanceOf[HashMap[Class[_ <: TileEntity], String]].put(t, "savedMultipart") + } +} + +class MultipartProxy_clientImpl extends MultipartProxy_serverImpl +{ + @SideOnly(Side.CLIENT) + override def postInit() + { + super.postInit() + RenderingRegistry.registerBlockHandler(MultipartRenderer); + PacketCustom.assignHandler(MultipartCPH.channel, MultipartCPH) + KeyBindingRegistry.registerKeyBinding(ControlKeyHandler) + } + + @SideOnly(Side.CLIENT) + override def onTileClassBuilt(t:Class[_ <: TileEntity]) + { + super.onTileClassBuilt(t) + ClientRegistry.bindTileEntitySpecialRenderer(t, MultipartRenderer) + } +} + +object MultipartProxy extends MultipartProxy_clientImpl +{ + var block:BlockMultipart = _ + var config:ConfigFile = _ +} \ No newline at end of file diff --git a/codechicken/multipart/minecraft/Content.java b/codechicken/multipart/minecraft/Content.java new file mode 100644 index 0000000..43a2bc6 --- /dev/null +++ b/codechicken/multipart/minecraft/Content.java @@ -0,0 +1,45 @@ +package codechicken.multipart.minecraft; + +import net.minecraft.block.Block; +import net.minecraft.world.World; +import codechicken.core.vec.BlockCoord; +import codechicken.multipart.MultiPartRegistry.IPartConverter; +import codechicken.multipart.MultiPartRegistry.IPartFactory; +import codechicken.multipart.MultiPartRegistry; +import codechicken.multipart.TMultiPart; + +public class Content implements IPartFactory, IPartConverter +{ + @Override + public TMultiPart createPart(String name, boolean client) + { + if(name.equals("mc_torch")) return client ? new TorchPartClient() : new TorchPart(); + + return null; + } + + public void init() + { + MultiPartRegistry.registerConverter(this); + MultiPartRegistry.registerParts(this, new String[]{ + "mc_torch" + }); + } + + @Override + public boolean canConvert(int blockID) + { + return blockID == Block.torchWood.blockID; + } + + @Override + public TMultiPart convert(World world, BlockCoord pos) + { + int id = world.getBlockId(pos.x, pos.y, pos.z); + int meta = world.getBlockMetadata(pos.x, pos.y, pos.z); + if(id == Block.torchWood.blockID) + return world.isRemote ? new TorchPartClient(meta) : new TorchPart(meta); + + return null; + } +} diff --git a/codechicken/multipart/minecraft/EventHandler.java b/codechicken/multipart/minecraft/EventHandler.java new file mode 100644 index 0000000..c421176 --- /dev/null +++ b/codechicken/multipart/minecraft/EventHandler.java @@ -0,0 +1,74 @@ +package codechicken.multipart.minecraft; + +import codechicken.core.packet.PacketCustom; +import codechicken.core.raytracer.RayTracer; +import codechicken.core.vec.BlockCoord; +import codechicken.core.vec.Vector3; +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TileMultipart; +import codechicken.multipart.TileMultipartObj; +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.network.packet.Packet15Place; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.ForgeSubscribe; +import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; + +public class EventHandler +{ + @ForgeSubscribe + public void playerInteract(PlayerInteractEvent event) + { + MovingObjectPosition hit = RayTracer.reTrace(event.entityPlayer.worldObj, event.entityPlayer); + if(event.action == Action.RIGHT_CLICK_BLOCK && place(event.entityPlayer, event.entityPlayer.worldObj, hit)) + event.setCanceled(true); + } + + public boolean place(EntityPlayer player, World world, MovingObjectPosition hit) + { + BlockCoord pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ).offset(hit.sideHit); + ItemStack held = player.getHeldItem(); + TileMultipart tile = TileMultipartObj.getOrConvertTile(world, pos); + if(tile == null) + return false; + + TMultiPart part = null; + if(held.itemID == Block.torchWood.blockID) + part = TorchPart.placement(world, pos, hit.sideHit); + + if(part == null) + return false; + if(tile.canAddPart(part)) + { + if(!world.isRemote) + { + TileMultipartObj.addPart(world, pos, part); + if(!player.capabilities.isCreativeMode) + { + held.stackSize--; + if (held.stackSize == 0) + { + player.inventory.mainInventory[player.inventory.currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held)); + } + } + } + else + { + player.swingItem(); + Vector3 f = new Vector3(hit.hitVec).add(-hit.blockX, -hit.blockY, -hit.blockZ); + PacketCustom.sendToServer(new Packet15Place( + hit.blockX, hit.blockY, hit.blockZ, hit.sideHit, + player.inventory.getCurrentItem(), + (float)f.x, (float)f.y, (float)f.z)); + } + return true; + } + return false; + } +} diff --git a/codechicken/multipart/minecraft/IPartMeta.java b/codechicken/multipart/minecraft/IPartMeta.java new file mode 100644 index 0000000..ad1a8fc --- /dev/null +++ b/codechicken/multipart/minecraft/IPartMeta.java @@ -0,0 +1,12 @@ +package codechicken.multipart.minecraft; + +import net.minecraft.world.World; + +public interface IPartMeta +{ + public int getMetadata(); + + public World getWorld(); + + public int getBlockId(); +} \ No newline at end of file diff --git a/codechicken/multipart/minecraft/MinecraftMultipartMod.java b/codechicken/multipart/minecraft/MinecraftMultipartMod.java new file mode 100644 index 0000000..fd72c24 --- /dev/null +++ b/codechicken/multipart/minecraft/MinecraftMultipartMod.java @@ -0,0 +1,18 @@ +package codechicken.multipart.minecraft; + +import net.minecraftforge.common.MinecraftForge; +import codechicken.core.asm.CodeChickenCorePlugin; +import cpw.mods.fml.common.Mod; +import cpw.mods.fml.common.Mod.PreInit; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; + +@Mod(name="Minecraft Multipart", version="1.0.0.0", useMetadata = false, modid = "McMultipart", acceptedMinecraftVersions=CodeChickenCorePlugin.mcVersion) +public class MinecraftMultipartMod +{ + @PreInit + public void preInit(FMLPreInitializationEvent event) + { + new Content().init(); + MinecraftForge.EVENT_BUS.register(new EventHandler()); + } +} diff --git a/codechicken/multipart/minecraft/PartMetaAccess.java b/codechicken/multipart/minecraft/PartMetaAccess.java new file mode 100644 index 0000000..96d8915 --- /dev/null +++ b/codechicken/multipart/minecraft/PartMetaAccess.java @@ -0,0 +1,124 @@ +package codechicken.multipart.minecraft; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.block.material.Material; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3Pool; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.biome.BiomeGenBase; + +public class PartMetaAccess implements IBlockAccess +{ + public IPartMeta part; + + public PartMetaAccess(IPartMeta p) + { + part = p; + } + + @Override + public int getBlockId(int i, int j, int k) + { + return part.getBlockId(); + } + + @Override + public TileEntity getBlockTileEntity(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + @SideOnly(Side.CLIENT) + public int getLightBrightnessForSkyBlocks(int i, int j, int k, int l) + { + return part.getWorld().getLightBrightnessForSkyBlocks(i, j, k, l); + } + + @Override + public int getBlockMetadata(int i, int j, int k) + { + return part.getMetadata(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getBrightness(int i, int j, int k, int l) + { + return part.getWorld().getBrightness(i, j, k, l); + } + + @Override + @SideOnly(Side.CLIENT) + public float getLightBrightness(int i, int j, int k) + { + return part.getWorld().getLightBrightness(i, j, k); + } + + @Override + public Material getBlockMaterial(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isBlockOpaqueCube(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + public boolean isBlockNormalCube(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isAirBlock(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + @SideOnly(Side.CLIENT) + public BiomeGenBase getBiomeGenForCoords(int i, int j) + { + return part.getWorld().getBiomeGenForCoords(i, j); + } + + @Override + @SideOnly(Side.CLIENT) + public int getHeight() + { + return part.getWorld().getHeight(); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean extendedLevelsInChunkCache() + { + return part.getWorld().extendedLevelsInChunkCache(); + } + + @Override + @SideOnly(Side.CLIENT) + public boolean doesBlockHaveSolidTopSurface(int i, int j, int k) + { + throw new IllegalArgumentException("Unsupported Operation"); + } + + @Override + public Vec3Pool getWorldVec3Pool() + { + return part.getWorld().getWorldVec3Pool(); + } + + @Override + public int isBlockProvidingPowerTo(int i, int j, int k, int l) + { + throw new IllegalArgumentException("Unsupported Operation"); + } +} diff --git a/codechicken/multipart/minecraft/TorchPart.java b/codechicken/multipart/minecraft/TorchPart.java new file mode 100644 index 0000000..b774f12 --- /dev/null +++ b/codechicken/multipart/minecraft/TorchPart.java @@ -0,0 +1,175 @@ +package codechicken.multipart.minecraft; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockTorch; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.scala.JSeq; +import net.minecraftforge.scala.ScalaBridge; +import codechicken.multipart.JCuboidPart; +import codechicken.multipart.JNormalOcclusion; +import codechicken.multipart.NormalOcclusionTest; +import codechicken.multipart.TMultiPart; +import codechicken.core.inventory.InventoryUtils; +import codechicken.core.packet.PacketCustom; +import codechicken.core.vec.BlockCoord; +import codechicken.core.vec.Cuboid6; +import codechicken.core.vec.Vector3; + +public class TorchPart extends JCuboidPart implements JNormalOcclusion, IPartMeta +{ + public static BlockTorch torch = (BlockTorch) Block.torchWood; + public static int[] metaSideMap = new int[]{-1, 4, 5, 2, 3, 0}; + public static int[] sideMetaMap = new int[]{5, 0, 3, 4, 1, 2}; + public byte meta; + + public TorchPart() + { + } + + public TorchPart(int meta) + { + this.meta = (byte)meta; + } + + @Override + public String getType() + { + return "mc_torch"; + } + + @Override + public void save(NBTTagCompound tag) + { + tag.setByte("meta", meta); + } + + @Override + public void load(NBTTagCompound tag) + { + meta = tag.getByte("meta"); + } + + @Override + public void write(PacketCustom packet) + { + packet.writeByte(meta); + } + + @Override + public void read(PacketCustom packet) + { + meta = packet.readByte(); + } + + @Override + public boolean occlusionTest(TMultiPart npart) + { + return NormalOcclusionTest.apply(this, npart); + } + + public JSeq getOcclusionBoxes() + { + return ScalaBridge.seq(getBounds()); + } + + @Override + public Cuboid6 getBounds() + { + double d = 0.15; + if (meta == 1) + return new Cuboid6(0, 0.2, 0.5 - d, d * 2, 0.8, 0.5 + d); + else if (meta == 2) + return new Cuboid6(1 - d * 2, 0.2, 0.5 - d, 1, 0.8, 0.5 + d); + else if (meta == 3) + return new Cuboid6(0.5 - d, 0.2, 0, 0.5 + d, 0.8, d * 2); + else if (meta == 4) + return new Cuboid6(0.5 - d, 0.2, 1 - d * 2, 0.5 + d, 0.8, 1); + else + { + d = 0.1; + return new Cuboid6(0.5 - d, 0, 0.5 - d, 0.5 + d, 0.6, 0.5 + d); + } + } + + @Override + public JSeq getCollisionBoxes() + { + return ScalaBridge.seq(); + } + + public void onNeighbourChanged() + { + TileEntity tile = getTile(); + if(!tile.worldObj.isRemote) + { + BlockCoord pos = new BlockCoord(tile).offset(metaSideMap[meta]); + if(!tile.worldObj.isBlockSolidOnSide(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(metaSideMap[meta]^1))) + drop(); + } + } + + public void drop() + { + tile().remPart(this); + InventoryUtils.dropItem(new ItemStack(torch), getTile().worldObj, Vector3.fromTileEntityCenter(getTile())); + } + + @Override + public World getWorld() + { + return getTile().worldObj; + } + + @Override + public int getMetadata() + { + return meta; + } + + @Override + public int getBlockId() + { + return torch.blockID; + } + + @Override + public int getLightValue() + { + return Block.lightValue[getBlockId()]; + } + + public static TMultiPart placement(World world, BlockCoord pos, int side) + { + if(side == 0) + return null; + pos = pos.copy().offset(side^1); + if(!world.isBlockSolidOnSide(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) + return null; + + return new TorchPart(sideMetaMap[side^1]); + } + + @Override + public JSeq getDrops() + { + return ScalaBridge.seq(new ItemStack(torch)); + } + + @Override + public ItemStack pickItem(MovingObjectPosition hit) + { + return new ItemStack(torch); + } + + @Override + public float getStrength(MovingObjectPosition hit, EntityPlayer player) + { + return torch.getPlayerRelativeBlockHardness(player, player.worldObj, hit.blockX, hit.blockY, hit.blockZ)*30; + } +} diff --git a/codechicken/multipart/minecraft/TorchPartClient.java b/codechicken/multipart/minecraft/TorchPartClient.java new file mode 100644 index 0000000..0ca82db --- /dev/null +++ b/codechicken/multipart/minecraft/TorchPartClient.java @@ -0,0 +1,96 @@ +package codechicken.multipart.minecraft; + +import java.util.Random; + +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.util.Icon; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; +import codechicken.core.vec.Vector3; +import codechicken.multipart.IRandomDisplayTick; +import codechicken.multipart.IconHitEffects; +import codechicken.multipart.JIconHitEffects; +import codechicken.core.lighting.LazyLightMatrix; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +public class TorchPartClient extends TorchPart implements IRandomDisplayTick, JIconHitEffects +{ + public TorchPartClient() + { + } + + public TorchPartClient(int meta) + { + super(meta); + } + + @Override + public void randomDisplayTick(Random random) + { + double d0 = getTile().xCoord + 0.5; + double d1 = getTile().yCoord + 0.7; + double d2 = getTile().zCoord + 0.5; + double d3 = 0.22D; + double d4 = 0.27D; + + World world = getTile().worldObj; + if (meta == 1) + { + world.spawnParticle("smoke", d0 - d4, d1 + d3, d2, 0, 0, 0); + world.spawnParticle("flame", d0 - d4, d1 + d3, d2, 0, 0, 0); + } + else if (meta == 2) + { + world.spawnParticle("smoke", d0 + d4, d1 + d3, d2, 0, 0, 0); + world.spawnParticle("flame", d0 + d4, d1 + d3, d2, 0, 0, 0); + } + else if (meta == 3) + { + world.spawnParticle("smoke", d0, d1 + d3, d2 - d4, 0, 0, 0); + world.spawnParticle("flame", d0, d1 + d3, d2 - d4, 0, 0, 0); + } + else if (meta == 4) + { + world.spawnParticle("smoke", d0, d1 + d3, d2 + d4, 0, 0, 0); + world.spawnParticle("flame", d0, d1 + d3, d2 + d4, 0, 0, 0); + } + else + { + world.spawnParticle("smoke", d0, d1, d2, 0, 0, 0); + world.spawnParticle("flame", d0, d1, d2, 0, 0, 0); + } + } + + @Override + public void renderStatic(Vector3 pos, LazyLightMatrix olm, int pass) + { + new RenderBlocks(new PartMetaAccess(this)).renderBlockTorch(torch, getTile().xCoord, getTile().yCoord, getTile().zCoord); + } + + @Override + public Icon getBreakingIcon(Object subPart, int side) + { + return torch.getIcon(0, 0); + } + + @Override + @SideOnly(Side.CLIENT) + public Icon getBrokenIcon(int side) + { + return torch.getIcon(0, 0); + } + + @Override + public void addHitEffects(MovingObjectPosition hit, EffectRenderer effectRenderer) + { + IconHitEffects.addHitEffects(this, hit, effectRenderer); + } + + @Override + public void addDestroyEffects(EffectRenderer effectRenderer) + { + IconHitEffects.addDestroyEffects(this, effectRenderer, false); + } +} diff --git a/net/minecraftforge/scala/ScalaBridge.scala b/net/minecraftforge/scala/ScalaBridge.scala new file mode 100644 index 0000000..89f1132 --- /dev/null +++ b/net/minecraftforge/scala/ScalaBridge.scala @@ -0,0 +1,29 @@ +package net.minecraftforge.scala + +import java.util.List +import java.util.Map +import scala.collection.JavaConverters._ +import codechicken.core.vec.Cuboid6 +import java.util.Collection + +object ScalaBridge +{ + implicit def wrapSeq[T](seq:Seq[T]) = new ScalaSeq[T](seq) + implicit def unwrapSeq[T](JSeq:JSeq[T]) = JSeq.seq + + def toSeq[T](c:List[T]):JSeq[T] = c.asScala + def toSeq[T](a:Array[T]):JSeq[T] = a.toSeq + + def seq[T]():JSeq[T] = Seq() + def seq[T](t1:T):JSeq[T] = Seq(t1) + def seq[T](t1:T, t2:T):JSeq[T] = Seq(t1, t2) + def seq[T](t1:T, t2:T, t3:T):JSeq[T] = Seq(t1, t2, t3) + def seq[T](t1:T, t2:T, t3:T, t4:T):JSeq[T] = Seq(t1, t2, t3, t4) +} + +class ScalaSeq[T](val seq:Seq[T]) extends JSeq[T] + +trait JSeq[T] +{ + def seq():Seq[T] +} \ No newline at end of file