diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 412eeda7..00000000 --- a/.gitattributes +++ /dev/null @@ -1,22 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto - -# Custom for Visual Studio -*.cs diff=csharp -*.sln merge=union -*.csproj merge=union -*.vbproj merge=union -*.fsproj merge=union -*.dbproj merge=union - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 5ebd21a1..b18cea42 100644 --- a/.gitignore +++ b/.gitignore @@ -161,3 +161,5 @@ pip-log.txt # Mac crap .DS_Store +src/cr0s/WarpDrive/client/ClientProxy.java +src/cr0s/WarpDrive/client/ClientProxy.java diff --git a/README.md b/README.md index c1d72453..1140ec77 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,6 @@ WarpDrive A warp drive mod for minecraft -See mcmod.info for credits - Minecraft forum: http://www.minecraftforum.net/topic/1938578-164-warpdrive-mod-ships-space-lasers @@ -18,7 +16,7 @@ Installation ============ 1. Download fresh build: http://kubach.tk/1.6.4/WarpDrive.zip 2. Download fresh Core build: http://kubach.tk/1.6.4/WarpDriveCore.jar -3. Install last version of IC2, Applied Energistics and Computer Craft +3. Install last version of IC2 and Computer Craft Contact Us ============= diff --git a/src/cr0s/WarpDrive/client/ClientProxy.java b/client/ClientProxy.java similarity index 74% rename from src/cr0s/WarpDrive/client/ClientProxy.java rename to client/ClientProxy.java index 06db97fc..52e12840 100644 --- a/src/cr0s/WarpDrive/client/ClientProxy.java +++ b/client/ClientProxy.java @@ -5,16 +5,18 @@ import cpw.mods.fml.client.FMLClientHandler; import cr0s.WarpDrive.CommonProxy; import cr0s.WarpDrive.FXBeam; import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -public class ClientProxy extends CommonProxy { +public class ClientProxy extends CommonProxy +{ @Override - public void registerRenderers() { + public void registerRenderers() + { } @Override - public void renderBeam(World world, Vector3 position, Vector3 target, float red, float green, float blue, int age, int energy) { - // WarpDrive.debugPrint("Rendering beam..."); + public void renderBeam(World world, Vector3 position, Vector3 target, float red, float green, float blue, int age, int energy) + { + System.out.println("Rendering beam..."); FMLClientHandler.instance().getClient().effectRenderer.addEffect(new FXBeam(world, position, target, red, green, blue, age, energy)); } } \ No newline at end of file diff --git a/src/assets/warpdrive/lang/en_US.lang b/src/assets/warpdrive/lang/en_US.lang deleted file mode 100644 index 192934fb..00000000 --- a/src/assets/warpdrive/lang/en_US.lang +++ /dev/null @@ -1,33 +0,0 @@ -item.warpdrive.crafting.Malformed.name=Bad Item -item.warpdrive.crafting.EmptyCore.name=Empty Core -item.warpdrive.crafting.TeleCore.name=Teleportation Core -item.warpdrive.crafting.WarpCore.name=Warp Core -item.warpdrive.crafting.LaserCore.name=Laser Core -item.warpdrive.crafting.ReactorCore.name=Reactor Core -item.warpdrive.crafting.InterfaceComputer.name=Computer Interface -item.warpdrive.crafting.InterfacePower.name=Power Interface - -tile.warpdrive.blocks.Air.name=Air Block -tile.warpdrive.blocks.Gas.name=Gas Block -tile.warpdrive.blocks.WarpIsolation.name=Warp-field Isolation Block -tile.warpdrive.blocks.IridiumBlock.name=Iridium Block -item.warpdrive.items.ReactorLaserFocus.name=Reactor Laser Focus -tile.warpdrive.power.Reactor.name=Enantiomorphic Reactor -tile.warpdrive.power.Laser.name=Aurbis Reactor Stabilisation Laser -tile.warpdrive.machines.WarpCore.name=Warp Drive Core -tile.warpdrive.machines.WarpProtocol.name=Warp Drive Controller -tile.warpdrive.machines.WarpRadar.name=Warp Radar -tile.warpdrive.machines.Laser.name=Laser -tile.warpdrive.machines.LaserCamera.name=Laser + Camera -tile.warpdrive.machines.LaserTreeFarm.name=Laser Tree Farm -tile.warpdrive.machines.CloakingCoil.name=Cloaking Coil -tile.warpdrive.machines.Camera.name=Camera -tile.warpdrive.machines.CloakingDeviceCore.name=Cloaking Device Core -tile.warpdrive.machines.ParticleBooster.name=Laser Particle Booster -tile.warpdrive.machines.Monitor.name=Monitor -tile.warpdrive.machines.MiningLaser.name=Mining Laser -tile.warpdrive.machines.LaserLift.name=Laser Lift -tile.warpdrive.machines.Transporter.name=Transporter -tile.warpdrive.machines.Scanner.name=Ship Scanner -tile.warpdrive.machines.AirGenerator.name=Air Generator -tile.warpdrive.machines.LaserReactorMonitor.name=Laser Reactor Monitor diff --git a/src/assets/warpdrive/lua/cloakingdevicecore/cloak1 b/src/assets/warpdrive/lua/cloakingdevicecore/cloak1 deleted file mode 100644 index 291b310c..00000000 --- a/src/assets/warpdrive/lua/cloakingdevicecore/cloak1 +++ /dev/null @@ -1,43 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end - -Side = { "bottom", "top", "back", "left", "right" } -for i = 1,5 do - if peripheral.getType(Side[i]) == "cloakingdevicecore" then - warp = peripheral.wrap(Side[i]) - break - else - warp = nil - end -end - -if warp == nil then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("No cloak core detected") -else - warp.setFieldFrequency(1337) - warp.setFieldTier(0) - warp.enableCloakingField() - if warp.isAssemblyValid() then - term.setBackgroundColor(colors.lime) - term.setTextColor(colors.blue) - term.write("Tier 1 cloak enabled") - else - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("Invalid assembly!") - term.setBackgroundColor(colors.black) - term.setTextColor(colors.white) - print() - print("In each of the 6 directions, you need to place exactly 2 Cloaking device coils, for a total of 12 coils.") - print("The 6 inner coils shall be exactly one block away from the core.") - print("The cloaking field will extend 5 blocks past the outer 6 coils.") - print("Power consumption scales with the amount of cloaked blocks.") - end -end -term.setBackgroundColor(colors.black) -term.setTextColor(colors.white) -print() diff --git a/src/assets/warpdrive/lua/cloakingdevicecore/cloak2 b/src/assets/warpdrive/lua/cloakingdevicecore/cloak2 deleted file mode 100644 index 7d5be518..00000000 --- a/src/assets/warpdrive/lua/cloakingdevicecore/cloak2 +++ /dev/null @@ -1,43 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end - -Side = { "bottom", "top", "back", "left", "right" } -for i = 1,5 do - if peripheral.getType(Side[i]) == "cloakingdevicecore" then - warp = peripheral.wrap(Side[i]) - break - else - warp = nil - end -end - -if warp == nil then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("No cloak core detected") -else - warp.setFieldFrequency(1337) - warp.setFieldTier(2) - warp.enableCloakingField() - if warp.isAssemblyValid() then - term.setBackgroundColor(colors.lime) - term.setTextColor(colors.red) - term.write("Tier 2 cloak enabled") - else - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("Invalid assembly!") - term.setBackgroundColor(colors.black) - term.setTextColor(colors.white) - print() - print("In each of the 6 directions, you need to place exactly 2 Cloaking device coils, for a total of 12 coils.") - print("The 6 inner coils shall be exactly one block away from the core.") - print("The cloaking field will extend 5 blocks past the outer 6 coils.") - print("Power consumption scales with the amount of cloaked blocks.") - end -end -term.setBackgroundColor(colors.black) -term.setTextColor(colors.white) -print() diff --git a/src/assets/warpdrive/lua/cloakingdevicecore/uncloak b/src/assets/warpdrive/lua/cloakingdevicecore/uncloak deleted file mode 100644 index 40ed58e3..00000000 --- a/src/assets/warpdrive/lua/cloakingdevicecore/uncloak +++ /dev/null @@ -1,28 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end - -Side = { "bottom", "top", "back", "left", "right" } -for i = 1,5 do - if peripheral.getType(Side[i]) == "cloakingdevicecore" then - warp = peripheral.wrap(Side[i]) - break - else - warp = nil - end -end - -if warp == nil then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("No cloak core detected") -else - warp.disableCloakingField() - term.setBackgroundColor(colors.lightGray) - term.setTextColor(colors.black) - term.write("Cloak disabled") -end -term.setBackgroundColor(colors.black) -term.setTextColor(colors.white) -print() \ No newline at end of file diff --git a/src/assets/warpdrive/lua/mininglaser/mine b/src/assets/warpdrive/lua/mininglaser/mine deleted file mode 100644 index 68cea01f..00000000 --- a/src/assets/warpdrive/lua/mininglaser/mine +++ /dev/null @@ -1,119 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end - -sides = peripheral.getNames() -mininglasers = {} -for key,side in pairs(sides) do - if peripheral.getType(side) == "mininglaser" then - print("Wrapping " .. side) - table.insert(mininglasers, peripheral.wrap(side)) - end -end - - -noExit = true -layerOffset = 1 -mineAll = true -useDeuterium = false -args = {...} -if #args > 0 then - if args[1] == "help" or args[1] == "?" then - print("Usage: mine ") - print() - print("Miner always mine below it, down to bedrock.") - print("Set layerOffset to define starting level.") - print("Power consumption will be much lower in space.") - print("Mining only ores is faster but more expensive...") - print("Use deuterium from ME system for silk touch.") - print("Mining laser can't go through forcefields.") - print("Mined chests will drop their contents.") - print() - noExit = false - else - layerOffset = tonumber( args[1] ) or 1 - end - - if #args > 1 then - if args[2] == "false" or args[2] == "0" then - mineAll = false - end - end - - if #args > 2 then - if args[3] == "true" or args[3] == "1" then - useDeuterium = true - end - end -end - -if #mininglasers == 0 then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("No mining laser detected") - - noExit = false -end -if noExit then - for key,mininglaser in pairs(mininglasers) do - if not mininglaser.isMining() then - mininglaser.offset(layerOffset) - if mineAll then - if useDeuterium then - mininglaser.quarry(useDeuterium) - else - mininglaser.quarry() - end - else - if useDeuterium then - mininglaser.mine(useDeuterium) - else - mininglaser.mine() - end - end - end - end - sleep(1) -end - -label = os.getComputerLabel() -if label then -else - label = "" .. os.getComputerID() -end - -term.setTextColor(colors.blue) -if noExit then - repeat - isMining = false - for key,mininglaser in pairs(mininglasers) do - status, energy, currentLayer, mined, total = mininglaser.state() - - term.setBackgroundColor(colors.black) - term.clear() - term.setBackgroundColor(colors.lime) - term.setCursorPos(1, 1) - term.write(label .. " - Mining laser " .. key .. " of " .. #mininglasers) - term.setBackgroundColor(colors.black) - term.setCursorPos(1, 3) - term.write("Status: " .. status .. " ") - term.setBackgroundColor(colors.black) - term.setCursorPos(1, 5) - term.write("Energy level is " .. energy .. " EU") - term.setCursorPos(1, 7) - term.write("Mined " .. mined .. " out of " .. total .. " blocks at layer " .. currentLayer .. " ") - - if mininglaser.isMining() then - sleep(1) - isMining = true - else - sleep(0.1) - end - end - until not isMining -end - -term.setBackgroundColor(colors.black) -term.setTextColor(colors.white) -print() diff --git a/src/assets/warpdrive/lua/mininglaser/stop b/src/assets/warpdrive/lua/mininglaser/stop deleted file mode 100644 index a7db2581..00000000 --- a/src/assets/warpdrive/lua/mininglaser/stop +++ /dev/null @@ -1,48 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end - -sides = peripheral.getNames() -mininglasers = {} -for key,side in pairs(sides) do - if peripheral.getType(side) == "mininglaser" then - print("Wrapping " .. side) - table.insert(mininglasers, peripheral.wrap(side)) - end -end - -label = os.getComputerLabel() -if label then -else - label = "" .. os.getComputerID() -end -term.setBackgroundColor(colors.black) -term.clear() -term.setBackgroundColor(colors.lime) -term.setCursorPos(1, 1) -term.write(label) - -if #mininglasers == 0 then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("No mining laser detected") -else - for key,mininglaser in pairs(mininglasers) do - term.setCursorPos(1, 2 + key) - if not mininglaser.isMining() then - term.setBackgroundColor(colors.red) - term.setTextColor(colors.white) - term.write("Mining laser " .. key .. " of " .. #mininglasers .. " is already stopped") - else - mininglaser.stop() - term.setBackgroundColor(colors.lime) - term.setTextColor(colors.blue) - term.write("Mining laser " .. key .. " of " .. #mininglasers .. " has been stopped") - end - end -end - -term.setBackgroundColor(colors.black) -term.setTextColor(colors.white) -print() diff --git a/src/assets/warpdrive/lua/radar/ping b/src/assets/warpdrive/lua/radar/ping deleted file mode 100644 index c3dd4cf0..00000000 --- a/src/assets/warpdrive/lua/radar/ping +++ /dev/null @@ -1,42 +0,0 @@ -side = "bottom" - -local argv = { ... } -if #argv ~= 1 then - print("Usage: scan ") - return -end - -local radius = tonumber(argv[1]) - -if radius < 1 or radius > 9999 then - print("Radius must be between 1 and 9999") - return -end - -radar = peripheral.wrap(side) - -if radar.getEnergyLevel() < radius * radius then - print("Low energy level. Sasaj") - return -end -radar.scanRadius(radius) -sleep(2) - -print("Scanning...") - -local seconds = 2 -repeat - local count = radar.getResultsCount() - sleep(1) - seconds = seconds + 1 -until count ~= nil or seconds > 10 -print("took "..seconds.." seconds") - -if count ~= nil then - for i=0, count-1 do - freq, x, y, z = radar.getResult(i) - print("Shit: "..freq.." ("..x.. " " .. y .. " " .. z .. ")") - end -else - print("Nothing is found =(") -end diff --git a/src/assets/warpdrive/lua/radar/scan b/src/assets/warpdrive/lua/radar/scan deleted file mode 100644 index f8ad2805..00000000 --- a/src/assets/warpdrive/lua/radar/scan +++ /dev/null @@ -1,101 +0,0 @@ -radar = peripheral.wrap("bottom") -radius = 500 -scale = 50 - -w, h = term.getSize() - -term.clear() - -function colorScreen(color) - for a = 2,w-1 do - for b = 1,h do - paintutils.drawPixel(a,b,color) - end - end -end - -function textOut(x, y, text, fg, bg) - term.setCursorPos(x, y) - term.setTextColor(fg) - term.setBackgroundColor(bg) - term.write(text) - local xt,yt = term.getCursorPos() - term.setCursorPos(1, yt + 1) -end - -function translateXZ(oldX, oldZ, i) - local x = radarX - oldX - local z = radarZ - oldZ - - x = x / (radius / scale) - z = z / (radius / scale) - - x = x + (w / 2) - z = z + (h / 2) - - - x = math.floor(x); - z = math.floor(z); - - return x,z -end - -function drawContact(x, y, z, name, color) - local newX, newZ = translateXZ(x, z) - - paintutils.drawPixel(newX, newZ, color) - textOut(newX - 3, newZ + 1, "[" .. name .. "]", colors.white, colors.black) -end - -function scanAndDraw() - if (radar.getEnergyLevel() < radius*radius) then - hh = math.floor(h / 2); - hw = math.floor(w / 2); - - paintutils.drawLine(hw - 5, hh - 1, hw + 5, hh - 1, colors.red); - paintutils.drawLine(hw - 5, hh, hw + 5, hh, colors.red); - textOut(hw - 4, hh,"LOW POWER", colors.white, colors.red); - paintutils.drawLine(hw - 5, hh + 1, hw + 5, hh + 1, colors.red); - sleep(1); - - return 0; - end; - radar.scanRadius(radius); - sleep(2); - - redraw(); - - numResults = radar.getResultsCount(); - - if (numResults ~= 0) then - for i = 0, numResults-1 do - freq, cx, cy, cz = radar.getResult(i); - - drawContact(cx, cy, cz, freq, colors.red) - end - end - - drawContact(radarX, radarY, radarZ, "RAD", colors.yellow); -end - -function redraw() - --shell.run("clear") - colorScreen(colors.green) - - paintutils.drawLine(1, 1, w, 1, colors.black) - - textOut(h, 1, "= Q-Radar v0.1 =", colors.white, colors.black) - - textOut(w - 3, 1, "[X]", colors.white, colors.red) - - paintutils.drawLine(1, h, w, h, colors.black); - textOut(4, h, "Energy: " .. radar.getEnergyLevel() .. " Eu | Scan radius: " .. radius, colors.white, colors.black) -end - -mrun = true -while (mrun) do - radarX, radarY, radarZ = radar.pos(); - scanAndDraw(); -end - -term.clear(); diff --git a/src/assets/warpdrive/lua/warpcontroller/startup b/src/assets/warpdrive/lua/warpcontroller/startup deleted file mode 100644 index 4f2c0b3e..00000000 --- a/src/assets/warpdrive/lua/warpcontroller/startup +++ /dev/null @@ -1,483 +0,0 @@ -if not term.isColor() then - print("Advanced computer required") - exit() -end -print("loading...") - --- set alarm side if you need this -Alarm = "top" - -Style = { - CDeflt = colors.white, - BGDeflt = colors.blue, - CTitle = colors.black, - BGTitle = colors.cyan, - CWarn = colors.white, - BGWarn = colors.red -} - -function SetColorDeflt() - term.setBackgroundColor(Style.BGDeflt) - term.setTextColor(Style.CDeflt) -end - -function SetColorTitle() - term.setBackgroundColor(Style.BGTitle) - term.setTextColor(Style.CTitle) -end - -function SetColorWarn() - term.setBackgroundColor(Style.BGWarn) - term.setTextColor(Style.CWarn) -end - -function Clear() - term.clear() - term.setCursorPos(1,1) -end - -function Show(Text) - term.write(Text) - local xt,yt = term.getCursorPos() - term.setCursorPos(1, yt+1) -end - -function ShowTitle(Text) - SetColorTitle() - term.setCursorPos(12, 1) - Show(Text) - SetColorDeflt() -end - -function ShowMenu(Text) - term.write(Text) - local xt, yt = term.getCursorPos() - for i = xt, 51 do - term.write(" ") - end - term.setCursorPos(1, yt+1) -end - -function ShowWarning(Text) - SetColorWarn() - term.setCursorPos(10, 19) - term.write(" "..Text.." ") - SetColorDeflt() -end - -function SaveData() - local file = fs.open("shipdata.txt", "w") - file.writeLine(textutils.serialize(SData)) - file.close() -end - -function ReadData() - local file = fs.open("shipdata.txt", "r") - SData = textutils.unserialize(file.readAll()) - file.close() -end - -function Explode(d, p) - local t, ll - t = {} - ll = 0 - if(#p == 1) then return {p} end - while true do - l = string.find(p ,d, ll, true) - if l ~= nil then - table.insert(t, string.sub(p, ll, l-1)) - ll = l+1 - else - table.insert(t, string.sub(p, ll)) - break - end - end - return t -end - -function ShowDirection() - if SData.Direction == 1 then - Show(" Direction = Up") - elseif SData.Direction == 2 then - Show(" Direction = Down") - elseif SData.Direction == 0 then - Show(" Direction = Front") - elseif SData.Direction == 180 then - Show(" Direction = Back") - elseif SData.Direction == 90 then - Show(" Direction = Left") - elseif SData.Direction == 255 then - Show(" Direction = Right") - end -end - -function CalcRealDistance() - if IsInHyper then - RealDistance = SData.Distance * 100 - MinimumDistance = 1 - JumpCost = (1000 * Weight) + (1000 * SData.Distance) - else - if SData.Direction == 1 or SData.Direction == 2 then - MinimumDistance = GUp + GDown - RealDistance = SData.Distance + MinimumDistance - elseif SData.Direction == 0 or SData.Direction == 180 then - MinimumDistance = GFront + GBack - RealDistance = SData.Distance + MinimumDistance - elseif SData.Direction == 90 or SData.Direction == 255 then - MinimumDistance = GLeft + GRight - RealDistance = SData.Distance + MinimumDistance - end - MinimumDistance = MinimumDistance + 1 - JumpCost = (10 * Weight) + (100 * SData.Distance) - end -end - -function CalcNewCoords(cx, cy, cz) - local res = {x=cx, y=cy, z=cz} - if SData.Direction == 1 then - res.y = res.y + RealDistance - elseif SData.Direction == 2 then - res.y = res.y - RealDistance - end - local dx = warp.get_dx() - local dz = warp.get_dz() - if dx ~= 0 then - if SData.Direction == 0 then - res.x = res.x + (RealDistance * dx) - elseif SData.Direction == 180 then - res.x = res.x - (RealDistance * dx) - elseif SData.Direction == 90 then - res.z = res.z + (RealDistance * dx) - elseif SData.Direction == 255 then - res.z = res.z - (RealDistance * dx) - end - else - if SData.Direction == 0 then - res.z = res.z + (RealDistance * dz) - elseif SData.Direction == 180 then - res.z = res.z - (RealDistance * dz) - elseif SData.Direction == 90 then - res.x = res.x + (RealDistance * dz) - elseif SData.Direction == 255 then - res.x = res.x - (RealDistance * dz) - end - end - return res -end - -function ShowInfo() - ShowTitle(Title) - Show("Core:") - Show(" x, y, z = "..X..", "..Y..", "..Z) - local energy = warp.get_energy_level() - Show(" Energy = "..math.floor(energy / 1000000).." % ("..energy.."EU)") - Show(" Attached players = "..warp.get_attached_players()) - Show("Dimensions:") - Show(" Front, Right, Up = "..GFront..", "..GRight..", "..GUp) - Show(" Back, Left, Down = "..GBack..", "..GLeft..", "..GDown) - Show(" Size = "..Weight.." blocks") - Show("Warp data:") - ShowDirection() - local dest = CalcNewCoords(X, Y, Z) - Show(" Distance = "..RealDistance.." ("..JumpCost.."EU, "..math.floor(energy/JumpCost).." jumps)") - Show(" Dest.coordinates = "..dest.x..", "..dest.y..", "..dest.z) - if SData.Summon then - Show(" Summon after = Yes") - else - Show(" Summon after = No") - end -end - -function Confirm() - ShowWarning("Are you sure? (y/n)") - local event, keycode = os.pullEvent("key") - if keycode == 21 then - return true - else - return false - end -end - -function Warp() - rs.setOutput(Alarm, false) - sleep(1) - warp.set_direction(SData.Direction) - if IsInHyper then - warp.set_mode(2) - else - warp.set_mode(1) - end - warp.do_jump() -end - -function SetDistance() - Clear() - ShowTitle("<==== Set distance ====>") - SData.Distance = 0 - CalcRealDistance() - MaximumDistance = MinimumDistance + 127 - if IsInHyper then - term.write("Distance * 100 (min "..MinimumDistance..", max "..MaximumDistance.."): ") - else - term.write("Distance (min "..MinimumDistance..", max "..MaximumDistance.."): ") - end - sleep(0.3) - SData.Distance = tonumber(read()) - if SData.Distance == nil then SData.Distance = 1 end - if SData.Distance < MinimumDistance or SData.Distance > MaximumDistance then - SData.Distance = 1 - ShowWarning("Wrong distance. Try again.") - os.pullEvent("key") - CalcRealDistance() - else - if not IsInHyper then - SData.Distance = SData.Distance - RealDistance - end - warp.set_distance(SData.Distance) - CalcRealDistance() - end -end - -function SetDirection() - local drun = true - while(drun) do - Clear() - ShowTitle("<==== Set direction ====>") - ShowDirection() - term.setCursorPos(1, 16) - SetColorTitle() - ShowMenu("Use directional keys") - ShowMenu("W/S keys for Up/Down") - ShowMenu("Enter - confirm") - SetColorDeflt() - local event, keycode = os.pullEvent("key") - if keycode == 200 then - SData.Direction = 0 - elseif keycode == 17 then - SData.Direction = 1 - elseif keycode == 203 then - SData.Direction = 90 - elseif keycode == 205 then - SData.Direction = 255 - elseif keycode == 208 then - SData.Direction = 180 - elseif keycode == 31 then - SData.Direction = 2 - elseif keycode == 28 then - drun = false - end - end -end - -function SetDimensions() - Clear() - sleep(0.3) - ShowTitle("<==== Set dimensions ====>") - term.write(" Front ("..GFront..") : ") - GFront = tonumber(read()) - term.write(" Right ("..GRight..") : ") - GRight = tonumber(read()) - term.write(" Up ("..GUp..") : ") - GUp = tonumber(read()) - term.write(" Back ("..GBack..") : ") - GBack = tonumber(read()) - term.write(" Left ("..GLeft..") : ") - GLeft = tonumber(read()) - term.write(" Down ("..GDown..") : ") - GDown = tonumber(read()) - term.write("Setting dimensions...") - warp.dim_setp(GFront, GRight, GUp) - warp.dim_setn(GBack, GLeft, GDown) - Weight = warp.get_ship_size() -end - -function Summon() - Clear() - ShowTitle("<==== Summon players ====>") - local players = Explode(",", warp.get_attached_players()) - for i = 1, #players do - Show(i..". "..players[i]) - end - SetColorTitle() - ShowMenu("Enter player number") - ShowMenu("or press enter to summon everyone") - SetColorDeflt() - sleep(0.3) - term.write(":") - local input = read() - if input == "" then - warp.summon_all() - else - input = tonumber(input) - warp.summon(input - 1) - end -end - -function JumpToBeacon() - Clear() - ShowTitle("<==== Jump to beacon ====>") - sleep(0.3) - term.write("Enter beacon frequency: ") - local freq = tostring(read()) - rs.setOutput(Alarm, true) - if Confirm() then - rs.setOutput(Alarm, false) - warp.set_mode(4) - warp.set_beacon_frequency(freq) - warp.do_jump() - end - rs.setOutput(Alarm, false) -end - -function JumpToGate() - Clear() - ShowTitle("<==== Jump to JumpGate ====>") - sleep(0.3) - term.write("Enter jumpgate name: ") - local name = tostring(read()) - rs.setOutput(Alarm, true) - if Confirm() then - rs.setOutput(Alarm, false) - warp.set_mode(6) - warp.set_target_jumpgate(name) - warp.do_jump() - end - rs.setOutput(Alarm, false) -end - -function SetShipName() - Clear() - ShowTitle("<==== Set ship name ====>") - sleep(0.3) - term.write("Enter ship name: ") - SData.Shipname = tostring(read()) - os.setComputerLabel(SData.Shipname) - warp.set_core_frequency(SData.Shipname) - SaveData() - os.reboot() -end - -if fs.exists("shipdata.txt") then - ReadData() -else - SData = { - Summon = false, - Distance = 1, - Direction = 0, - Shipname = "" - } -end - -SetColorDeflt() - -Side = { "bottom", "top", "back", "left", "right" } -for i = 1,5 do - if peripheral.getType(Side[i]) == "warpcore" then - warp = peripheral.wrap(Side[i]) - break - else - warp = nil - end -end - -if warp == nil then - ShowWarning("No warpcore controller detected") - os.pullEvent("key") - os.reboot() -end - -if SData.Shipname == "" then - SetShipName() -end - -Title = "" - -if SData.Summon then - warp.summon_all() -end - -GFront, GRight, GUp = warp.dim_getp() -GBack, GLeft, GDown = warp.dim_getn() -IsInHyper = warp.is_in_hyperspace() -repeat - X = warp.get_x() - sleep(0.3) -until X ~= nil -Y = warp.get_y() -Z = warp.get_z() -repeat - isAttached = warp.isAttached() - sleep(0.3) -until isAttached ~= false - -repeat - Weight = warp.get_ship_size() - sleep(0.3) -until Weight ~= nil - -CalcRealDistance() - -warp.set_mode(1) - -mainloop = true -while(mainloop) do - Clear() - ShowInfo() - term.setCursorPos(1, 15) - SetColorTitle() - ShowMenu("D - Dimensions, M - Toggle summon, N - Ship name") - ShowMenu("S - Set Warp Data, J - Jump, G - Jump to JumpGate") - ShowMenu("B - Jump to Beacon, H - Jump to Hyperspace") - ShowMenu("C - Summon crew, X - Shutdown WarpCore and Exit") - SetColorDeflt() - local event, keycode = os.pullEvent("key") - if keycode == 31 then - SetDirection() - SetDistance() - SaveData() - elseif keycode == 50 then - if SData.Summon then - SData.Summon = false - else - SData.Summon = true - end - SaveData() - elseif keycode == 32 then - SetDimensions() - SaveData() - elseif keycode == 36 then - rs.setOutput(Alarm, true) - if Confirm() then - Warp() - end - rs.setOutput(Alarm, false) - elseif keycode == 46 then - Summon() - elseif keycode == 48 then - JumpToBeacon() - elseif keycode == 34 then - JumpToGate() - elseif keycode == 35 then - rs.setOutput(Alarm, true) - if Confirm() then - rs.setOutput(Alarm, false) - warp.set_mode(5) - warp.do_jump() - end - rs.setOutput(Alarm, false) - elseif keycode == 45 then - mainloop = false - elseif keycode == 49 then - SetShipName() - end -end - -if SData.Summon then - SData.Summon = false - SaveData() -end -Clear() -print("wish you good") -warp.set_mode(0) -sleep(0.5) -os.shutdown() \ No newline at end of file diff --git a/src/assets/warpdrive/sound/warp_4s.ogg b/src/assets/warpdrive/sound/warp.ogg similarity index 100% rename from src/assets/warpdrive/sound/warp_4s.ogg rename to src/assets/warpdrive/sound/warp.ogg diff --git a/src/assets/warpdrive/sound/warp_10s.ogg b/src/assets/warpdrive/sound/warp_10s.ogg deleted file mode 100644 index b3a47aa5..00000000 Binary files a/src/assets/warpdrive/sound/warp_10s.ogg and /dev/null differ diff --git a/src/assets/warpdrive/sound/warp_30s.ogg b/src/assets/warpdrive/sound/warp_30s.ogg deleted file mode 100644 index 8d1029f3..00000000 Binary files a/src/assets/warpdrive/sound/warp_30s.ogg and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock0.png b/src/assets/warpdrive/textures/blocks/airBlock0.png deleted file mode 100644 index c1d1aacc..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock0.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock1.png b/src/assets/warpdrive/textures/blocks/airBlock1.png deleted file mode 100644 index c3065533..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock1.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock10.png b/src/assets/warpdrive/textures/blocks/airBlock10.png deleted file mode 100644 index 10ad0b4c..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock10.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock11.png b/src/assets/warpdrive/textures/blocks/airBlock11.png deleted file mode 100644 index 883c4094..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock11.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock12.png b/src/assets/warpdrive/textures/blocks/airBlock12.png deleted file mode 100644 index ddf4502e..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock12.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock13.png b/src/assets/warpdrive/textures/blocks/airBlock13.png deleted file mode 100644 index bcd62c55..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock13.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock14.png b/src/assets/warpdrive/textures/blocks/airBlock14.png deleted file mode 100644 index b2ce5ea2..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock14.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock15.png b/src/assets/warpdrive/textures/blocks/airBlock15.png deleted file mode 100644 index 16773b6a..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock15.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock2.png b/src/assets/warpdrive/textures/blocks/airBlock2.png deleted file mode 100644 index 8ba108ad..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock2.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock3.png b/src/assets/warpdrive/textures/blocks/airBlock3.png deleted file mode 100644 index 36f4add0..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock3.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock4.png b/src/assets/warpdrive/textures/blocks/airBlock4.png deleted file mode 100644 index 592a09e6..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock4.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock5.png b/src/assets/warpdrive/textures/blocks/airBlock5.png deleted file mode 100644 index 7c4ee870..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock5.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock6.png b/src/assets/warpdrive/textures/blocks/airBlock6.png deleted file mode 100644 index 6cb25056..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock6.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock7.png b/src/assets/warpdrive/textures/blocks/airBlock7.png deleted file mode 100644 index f1a89521..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock7.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock8.png b/src/assets/warpdrive/textures/blocks/airBlock8.png deleted file mode 100644 index 1fd6407d..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock8.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airBlock9.png b/src/assets/warpdrive/textures/blocks/airBlock9.png deleted file mode 100644 index 969fd48d..00000000 Binary files a/src/assets/warpdrive/textures/blocks/airBlock9.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/airgenTopActive.png b/src/assets/warpdrive/textures/blocks/airgenTopActive.png new file mode 100644 index 00000000..e2520225 Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/airgenTopActive.png differ diff --git a/src/assets/warpdrive/textures/blocks/camOverlay.png b/src/assets/warpdrive/textures/blocks/camOverlay.png index ca292622..fe210b30 100644 Binary files a/src/assets/warpdrive/textures/blocks/camOverlay.png and b/src/assets/warpdrive/textures/blocks/camOverlay.png differ diff --git a/src/assets/warpdrive/textures/blocks/cloakCoilTop.png b/src/assets/warpdrive/textures/blocks/cloakCoilTop.png deleted file mode 100644 index 4ffa69b0..00000000 Binary files a/src/assets/warpdrive/textures/blocks/cloakCoilTop.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/componentInterfaceComputer.psd b/src/assets/warpdrive/textures/blocks/componentInterfaceComputer.psd deleted file mode 100644 index 119bbf84..00000000 Binary files a/src/assets/warpdrive/textures/blocks/componentInterfaceComputer.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/contSideActive0.png.mcmeta b/src/assets/warpdrive/textures/blocks/contSideActive0.png.mcmeta deleted file mode 100644 index b84e69f2..00000000 --- a/src/assets/warpdrive/textures/blocks/contSideActive0.png.mcmeta +++ /dev/null @@ -1,5 +0,0 @@ -{ - "animation": { - "frametime": 4 - } -} diff --git a/src/assets/warpdrive/textures/blocks/coreSideHeated.png b/src/assets/warpdrive/textures/blocks/coreSideHeated.png deleted file mode 100644 index 7cd40f05..00000000 Binary files a/src/assets/warpdrive/textures/blocks/coreSideHeated.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/coreSideHeated.png.mcmeta b/src/assets/warpdrive/textures/blocks/coreSideHeated.png.mcmeta deleted file mode 100644 index 37d84f6a..00000000 --- a/src/assets/warpdrive/textures/blocks/coreSideHeated.png.mcmeta +++ /dev/null @@ -1,4 +0,0 @@ -{ - "animation": { - } -} \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/energy.png b/src/assets/warpdrive/textures/blocks/energy.png new file mode 100644 index 00000000..184f7faa Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_green.png b/src/assets/warpdrive/textures/blocks/energy_green.png new file mode 100644 index 00000000..076e194f Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_green.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_grey.png b/src/assets/warpdrive/textures/blocks/energy_grey.png deleted file mode 100644 index 0708fc5f..00000000 Binary files a/src/assets/warpdrive/textures/blocks/energy_grey.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/energy_orange.png b/src/assets/warpdrive/textures/blocks/energy_orange.png new file mode 100644 index 00000000..313dbfa7 Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_orange.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_red.png b/src/assets/warpdrive/textures/blocks/energy_red.png new file mode 100644 index 00000000..8996066d Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_red.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_sy.png b/src/assets/warpdrive/textures/blocks/energy_sy.png new file mode 100644 index 00000000..80393d78 Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_sy.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_violet.png b/src/assets/warpdrive/textures/blocks/energy_violet.png new file mode 100644 index 00000000..31a99f65 Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_violet.png differ diff --git a/src/assets/warpdrive/textures/blocks/energy_yellow.png b/src/assets/warpdrive/textures/blocks/energy_yellow.png new file mode 100644 index 00000000..465d8836 Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/energy_yellow.png differ diff --git a/src/assets/warpdrive/textures/blocks/laserTreeFarmSide0.png b/src/assets/warpdrive/textures/blocks/laserTreeFarmSide0.png deleted file mode 100644 index 77f23404..00000000 Binary files a/src/assets/warpdrive/textures/blocks/laserTreeFarmSide0.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/lasercamOverlay.png b/src/assets/warpdrive/textures/blocks/lasercamOverlay.png index 6000e8ab..53745518 100644 Binary files a/src/assets/warpdrive/textures/blocks/lasercamOverlay.png and b/src/assets/warpdrive/textures/blocks/lasercamOverlay.png differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaserSide0.png b/src/assets/warpdrive/textures/blocks/miningLaserSide0.png new file mode 100644 index 00000000..fad0939f Binary files /dev/null and b/src/assets/warpdrive/textures/blocks/miningLaserSide0.png differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaser_idle.png b/src/assets/warpdrive/textures/blocks/miningLaser_idle.png deleted file mode 100644 index 768a740f..00000000 Binary files a/src/assets/warpdrive/textures/blocks/miningLaser_idle.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaser_miningLowPower.png b/src/assets/warpdrive/textures/blocks/miningLaser_miningLowPower.png deleted file mode 100644 index 5336fac6..00000000 Binary files a/src/assets/warpdrive/textures/blocks/miningLaser_miningLowPower.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaser_miningPowered.png b/src/assets/warpdrive/textures/blocks/miningLaser_miningPowered.png deleted file mode 100644 index 2ed21e11..00000000 Binary files a/src/assets/warpdrive/textures/blocks/miningLaser_miningPowered.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaser_scanningLowPower.png b/src/assets/warpdrive/textures/blocks/miningLaser_scanningLowPower.png deleted file mode 100644 index 64ac3a9b..00000000 Binary files a/src/assets/warpdrive/textures/blocks/miningLaser_scanningLowPower.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/miningLaser_scanningPowered.png b/src/assets/warpdrive/textures/blocks/miningLaser_scanningPowered.png deleted file mode 100644 index b236c914..00000000 Binary files a/src/assets/warpdrive/textures/blocks/miningLaser_scanningPowered.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/powerLaserActive.png b/src/assets/warpdrive/textures/blocks/powerLaserActive.png deleted file mode 100644 index 0c3b2b59..00000000 Binary files a/src/assets/warpdrive/textures/blocks/powerLaserActive.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/powerLaserActive.png.mcmeta b/src/assets/warpdrive/textures/blocks/powerLaserActive.png.mcmeta deleted file mode 100644 index 37d84f6a..00000000 --- a/src/assets/warpdrive/textures/blocks/powerLaserActive.png.mcmeta +++ /dev/null @@ -1,4 +0,0 @@ -{ - "animation": { - } -} \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/powerLaserActive.psd b/src/assets/warpdrive/textures/blocks/powerLaserActive.psd deleted file mode 100644 index 4e8e3ecd..00000000 Binary files a/src/assets/warpdrive/textures/blocks/powerLaserActive.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/powerLaserSides.png b/src/assets/warpdrive/textures/blocks/powerLaserSides.png deleted file mode 100644 index 8b368113..00000000 Binary files a/src/assets/warpdrive/textures/blocks/powerLaserSides.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/powerLaserTopBottom.png b/src/assets/warpdrive/textures/blocks/powerLaserTopBottom.png deleted file mode 100644 index 175935b6..00000000 Binary files a/src/assets/warpdrive/textures/blocks/powerLaserTopBottom.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorMonitor.png b/src/assets/warpdrive/textures/blocks/reactorMonitor.png deleted file mode 100644 index 40d4b62a..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorMonitor.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorMonitor.psd b/src/assets/warpdrive/textures/blocks/reactorMonitor.psd deleted file mode 100644 index 65cf4f2b..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorMonitor.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide00.png b/src/assets/warpdrive/textures/blocks/reactorSide00.png deleted file mode 100644 index 28e0af45..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide00.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide00.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide00.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide00.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide01.png b/src/assets/warpdrive/textures/blocks/reactorSide01.png deleted file mode 100644 index fc97cbf8..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide01.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide01.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide01.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide01.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide02.png b/src/assets/warpdrive/textures/blocks/reactorSide02.png deleted file mode 100644 index 60a8d06c..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide02.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide02.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide02.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide02.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide03.png b/src/assets/warpdrive/textures/blocks/reactorSide03.png deleted file mode 100644 index e2052b08..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide03.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide03.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide03.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide03.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide10.png b/src/assets/warpdrive/textures/blocks/reactorSide10.png deleted file mode 100644 index 77135a3e..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide10.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide10.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide10.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide10.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide11.png b/src/assets/warpdrive/textures/blocks/reactorSide11.png deleted file mode 100644 index 30a51627..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide11.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide11.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide11.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide11.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide12.png b/src/assets/warpdrive/textures/blocks/reactorSide12.png deleted file mode 100644 index 37c69f70..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide12.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide12.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide12.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide12.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide13.png b/src/assets/warpdrive/textures/blocks/reactorSide13.png deleted file mode 100644 index bf8da829..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide13.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide13.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide13.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide13.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide20.png b/src/assets/warpdrive/textures/blocks/reactorSide20.png deleted file mode 100644 index e89b36c4..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide20.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide20.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide20.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide20.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide21.png b/src/assets/warpdrive/textures/blocks/reactorSide21.png deleted file mode 100644 index 8a2b332b..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide21.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide21.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide21.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide21.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide22.png b/src/assets/warpdrive/textures/blocks/reactorSide22.png deleted file mode 100644 index 93eef42c..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide22.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide22.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide22.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide22.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide23.png b/src/assets/warpdrive/textures/blocks/reactorSide23.png deleted file mode 100644 index a8106fd9..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide23.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide23.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide23.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide23.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide30.png b/src/assets/warpdrive/textures/blocks/reactorSide30.png deleted file mode 100644 index 7df1259e..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide30.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide30.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide30.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide30.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide31.png b/src/assets/warpdrive/textures/blocks/reactorSide31.png deleted file mode 100644 index 2a4ffd51..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide31.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide31.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide31.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide31.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide32.png b/src/assets/warpdrive/textures/blocks/reactorSide32.png deleted file mode 100644 index 2672a03f..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide32.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide32.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide32.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide32.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSide33.png b/src/assets/warpdrive/textures/blocks/reactorSide33.png deleted file mode 100644 index fe2fe2f2..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSide33.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorSide33.png.mcmeta b/src/assets/warpdrive/textures/blocks/reactorSide33.png.mcmeta deleted file mode 100644 index bd7117d0..00000000 --- a/src/assets/warpdrive/textures/blocks/reactorSide33.png.mcmeta +++ /dev/null @@ -1 +0,0 @@ -{ "animation": { "frames": [0,1,2,3,2,1] } } \ No newline at end of file diff --git a/src/assets/warpdrive/textures/blocks/reactorSideBase.psd b/src/assets/warpdrive/textures/blocks/reactorSideBase.psd deleted file mode 100644 index aaad238d..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorSideBase.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/reactorTB.png b/src/assets/warpdrive/textures/blocks/reactorTB.png deleted file mode 100644 index 01d95330..00000000 Binary files a/src/assets/warpdrive/textures/blocks/reactorTB.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/transporterBottom.png b/src/assets/warpdrive/textures/blocks/transporterBottom.png deleted file mode 100644 index a60e9279..00000000 Binary files a/src/assets/warpdrive/textures/blocks/transporterBottom.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/transporterSide.png b/src/assets/warpdrive/textures/blocks/transporterSide.png deleted file mode 100644 index 790cce4d..00000000 Binary files a/src/assets/warpdrive/textures/blocks/transporterSide.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/blocks/transporterTop.png b/src/assets/warpdrive/textures/blocks/transporterTop.png deleted file mode 100644 index f1439479..00000000 Binary files a/src/assets/warpdrive/textures/blocks/transporterTop.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentEmptyCore.PSD b/src/assets/warpdrive/textures/items/componentEmptyCore.PSD deleted file mode 100644 index fbadd94c..00000000 Binary files a/src/assets/warpdrive/textures/items/componentEmptyCore.PSD and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentEmptyCore.png b/src/assets/warpdrive/textures/items/componentEmptyCore.png deleted file mode 100644 index 6ed5d00a..00000000 Binary files a/src/assets/warpdrive/textures/items/componentEmptyCore.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentInterfaceComputer.png b/src/assets/warpdrive/textures/items/componentInterfaceComputer.png deleted file mode 100644 index eed32561..00000000 Binary files a/src/assets/warpdrive/textures/items/componentInterfaceComputer.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentInterfaceComputer.psd b/src/assets/warpdrive/textures/items/componentInterfaceComputer.psd deleted file mode 100644 index 355275af..00000000 Binary files a/src/assets/warpdrive/textures/items/componentInterfaceComputer.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentInterfacePower.png b/src/assets/warpdrive/textures/items/componentInterfacePower.png deleted file mode 100644 index d467253c..00000000 Binary files a/src/assets/warpdrive/textures/items/componentInterfacePower.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentInterfacePower.psd b/src/assets/warpdrive/textures/items/componentInterfacePower.psd deleted file mode 100644 index eedee267..00000000 Binary files a/src/assets/warpdrive/textures/items/componentInterfacePower.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentLaserCore.png b/src/assets/warpdrive/textures/items/componentLaserCore.png deleted file mode 100644 index e4c64ac2..00000000 Binary files a/src/assets/warpdrive/textures/items/componentLaserCore.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentLaserCore.psd b/src/assets/warpdrive/textures/items/componentLaserCore.psd deleted file mode 100644 index f2a96fad..00000000 Binary files a/src/assets/warpdrive/textures/items/componentLaserCore.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentReactorCore.png b/src/assets/warpdrive/textures/items/componentReactorCore.png deleted file mode 100644 index 25ac7675..00000000 Binary files a/src/assets/warpdrive/textures/items/componentReactorCore.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentReactorCore.psd b/src/assets/warpdrive/textures/items/componentReactorCore.psd deleted file mode 100644 index db3c593d..00000000 Binary files a/src/assets/warpdrive/textures/items/componentReactorCore.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentTeleCore.png b/src/assets/warpdrive/textures/items/componentTeleCore.png deleted file mode 100644 index efdde533..00000000 Binary files a/src/assets/warpdrive/textures/items/componentTeleCore.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentTeleCore.psd b/src/assets/warpdrive/textures/items/componentTeleCore.psd deleted file mode 100644 index 2ea4787c..00000000 Binary files a/src/assets/warpdrive/textures/items/componentTeleCore.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentWarpCore.png b/src/assets/warpdrive/textures/items/componentWarpCore.png deleted file mode 100644 index 674ca427..00000000 Binary files a/src/assets/warpdrive/textures/items/componentWarpCore.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/componentWarpCore.psd b/src/assets/warpdrive/textures/items/componentWarpCore.psd deleted file mode 100644 index 8f25d07d..00000000 Binary files a/src/assets/warpdrive/textures/items/componentWarpCore.psd and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/reactorFocus.png b/src/assets/warpdrive/textures/items/reactorFocus.png deleted file mode 100644 index 8059767d..00000000 Binary files a/src/assets/warpdrive/textures/items/reactorFocus.png and /dev/null differ diff --git a/src/assets/warpdrive/textures/items/reactorFocus.psd b/src/assets/warpdrive/textures/items/reactorFocus.psd deleted file mode 100644 index 4679fb30..00000000 Binary files a/src/assets/warpdrive/textures/items/reactorFocus.psd and /dev/null differ diff --git a/src/cr0s/WarpDrive/BlockAir.java b/src/cr0s/WarpDrive/BlockAir.java index 8e12a2c7..1de83d80 100644 --- a/src/cr0s/WarpDrive/BlockAir.java +++ b/src/cr0s/WarpDrive/BlockAir.java @@ -1,345 +1,288 @@ package cr0s.WarpDrive; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.Icon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockAir extends Block { - private final boolean TRANSPARENT_AIR = true; - private final boolean AIR_DEBUG = false; - private final int AIR_BLOCK_TICKS = 40; - private Icon[] iconBuffer; + private final boolean TRANSPARENT_AIR = true; - public BlockAir(int par1) { - super(par1, Material.air); - setHardness(0.0F); - setUnlocalizedName("warpdrive.blocks.Air"); - } + public BlockAir(int par1) + { + super(par1, Material.air); + } - @Override - public boolean isOpaqueCube() { - return false; - } + @Override + public boolean isOpaqueCube() + { + return false; + } - @Override - public boolean isAirBlock(World var1, int var2, int var3, int var4) { - return true; - } + @Override + public boolean isAirBlock(World var1, int var2, int var3, int var4) + { + return true; + } - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World var1, int var2, int var3, int var4) { - return null; - } + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool(World var1, int var2, int var3, int var4) + { + return null; + } - @Override - public boolean isBlockReplaceable(World var1, int var2, int var3, int var4) { - return true; - } + @Override + public boolean isBlockReplaceable(World var1, int var2, int var3, int var4) + { + return true; + } - @Override - public boolean canPlaceBlockAt(World var1, int var2, int var3, int var4) { - return true; - } + @Override + public boolean canPlaceBlockAt(World var1, int var2, int var3, int var4) + { + return true; + } - @Override - public boolean canCollideCheck(int var1, boolean var2) { - return false; - } + @Override + public boolean canCollideCheck(int var1, boolean var2) + { + return false; + } - @Override - public int getRenderBlockPass() { - return TRANSPARENT_AIR ? 1 : 0; - } + @Override + public int getRenderBlockPass() + { + return TRANSPARENT_AIR ? 1 : 0; + } - @Override - public void registerIcons(IconRegister par1IconRegister) { - if (AIR_DEBUG) { - iconBuffer = new Icon[16]; - iconBuffer[ 0] = par1IconRegister.registerIcon("warpdrive:airBlock0"); - iconBuffer[ 1] = par1IconRegister.registerIcon("warpdrive:airBlock1"); - iconBuffer[ 2] = par1IconRegister.registerIcon("warpdrive:airBlock2"); - iconBuffer[ 3] = par1IconRegister.registerIcon("warpdrive:airBlock3"); - iconBuffer[ 4] = par1IconRegister.registerIcon("warpdrive:airBlock4"); - iconBuffer[ 5] = par1IconRegister.registerIcon("warpdrive:airBlock5"); - iconBuffer[ 6] = par1IconRegister.registerIcon("warpdrive:airBlock6"); - iconBuffer[ 7] = par1IconRegister.registerIcon("warpdrive:airBlock7"); - iconBuffer[ 8] = par1IconRegister.registerIcon("warpdrive:airBlock8"); - iconBuffer[ 9] = par1IconRegister.registerIcon("warpdrive:airBlock9"); - iconBuffer[10] = par1IconRegister.registerIcon("warpdrive:airBlock10"); - iconBuffer[11] = par1IconRegister.registerIcon("warpdrive:airBlock11"); - iconBuffer[12] = par1IconRegister.registerIcon("warpdrive:airBlock12"); - iconBuffer[13] = par1IconRegister.registerIcon("warpdrive:airBlock13"); - iconBuffer[14] = par1IconRegister.registerIcon("warpdrive:airBlock14"); - iconBuffer[15] = par1IconRegister.registerIcon("warpdrive:airBlock15"); - } else { - blockIcon = par1IconRegister.registerIcon("warpdrive:airBlock"); - } - } + @Override + public void registerIcons(IconRegister par1IconRegister) + { + this.blockIcon = par1IconRegister.registerIcon("warpdrive:airBlock"); + } - @Override - public Icon getIcon(int side, int metadata) { - if (AIR_DEBUG) { - return iconBuffer[metadata]; - } else { - return blockIcon; - } - } + @Override + public int getMobilityFlag() + { + return 1; + } - @Override - public int getMobilityFlag() { - return 1; - } + @Override + public int idDropped(int var1, Random var2, int var3) + { + return -1; + } - @Override - public int idDropped(int var1, Random var2, int var3) { - return -1; - } + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 0; + } - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 0; - } + /** + * How many world ticks before ticking + */ + @Override + public int tickRate(World par1World) + { + return 20; + } - /** - * How many world ticks before ticking - */ - @Override - public int tickRate(World par1World) { - return AIR_BLOCK_TICKS; - } + /** + * Ticks the block if it's been scheduled + */ + @Override + public void updateTick(World par1World, int x, int y, int z, Random par5Random) + { + int concentration = par1World.getBlockMetadata(x, y, z); + boolean isInSpaceWorld = par1World.provider.dimensionId == WarpDrive.instance.spaceDimID || par1World.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID; - /** - * Ticks the block if it's been scheduled - */ - @Override - public void updateTick(World par1World, int x, int y, int z, Random par5Random) { - int concentration = par1World.getBlockMetadata(x, y, z); - boolean isInSpaceWorld = par1World.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID || par1World.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID; + // Remove air block to vacuum block + if (concentration <= 0 || !isInSpaceWorld) + { + //System.out.println("Killing air block"); + par1World.setBlock(x, y, z, 0, 0, 2); // replace our air block to vacuum block + } + else + { + //System.out.println("Conc: current " + concentration + " new: " + (concentration - 1) + " to spread: " + (concentration - 2)); + // Try to spread the air + spreadAirBlock(par1World, x, y, z, concentration); + } - // Remove air block to vacuum block - if (concentration <= 0 || !isInSpaceWorld) { - par1World.setBlock(x, y, z, 0, 0, 3); // replace our air block to vacuum block - } else { - // Try to spread the air - spreadAirBlock(par1World, x, y, z, concentration); - } + par1World.scheduleBlockUpdate(x, y, z, this.blockID, 20); + } - par1World.scheduleBlockUpdate(x, y, z, this.blockID, AIR_BLOCK_TICKS); - } + @Override + public boolean shouldSideBeRendered(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) + { + if (par1IBlockAccess.getBlockId(par2, par3, par4) == this.blockID) + { + return false; + } + else + { + final int i = par1IBlockAccess.getBlockId(par2, par3, par4); + boolean var6 = false; - @Override - public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { - if (AIR_DEBUG) { - return side == 0; - } - - int sideBlockID = world.getBlockId(x, y, z); - if (sideBlockID == this.blockID) { - return false; - } - return world.isAirBlock(x, y, z); - } + if (Block.blocksList[i] != null) + { + var6 = !Block.blocksList[i].isOpaqueCube(); + } - private void spreadAirBlock(World worldObj, int x, int y, int z, int concentration) { - int air_count = 1; - int empty_count = 0; - int sum_concentration = concentration; + final boolean var7 = i == 0; - // Count air in adjacent blocks - int xp_blockId = worldObj.getBlockId(x + 1, y, z); - boolean xp_isAir = WarpDriveConfig.isAirBlock(worldObj, xp_blockId, x + 1, y, z);; - int xp_concentration = (xp_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x + 1, y, z); - if (xp_isAir) { - air_count++; - if (xp_concentration > 0) { - sum_concentration += xp_concentration; - } else { - empty_count++; - } - } - int xn_blockId = worldObj.getBlockId(x - 1, y, z); - boolean xn_isAir = WarpDriveConfig.isAirBlock(worldObj, xn_blockId, x - 1, y, z); - int xn_concentration = (xn_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x - 1, y, z); - if (xn_isAir) { - air_count++; - if (xn_concentration > 0) { - sum_concentration += xn_concentration; - } else { - empty_count++; - } - } - int yp_blockId = worldObj.getBlockId(x, y + 1, z); - boolean yp_isAir = WarpDriveConfig.isAirBlock(worldObj, yp_blockId, x, y + 1, z); - int yp_concentration = (yp_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x, y + 1, z); - if (yp_isAir) { - air_count++; - if (yp_concentration > 0) { - sum_concentration += yp_concentration; - } else { - empty_count++; - } - } - int yn_blockId = worldObj.getBlockId(x, y - 1, z); - boolean yn_isAir = WarpDriveConfig.isAirBlock(worldObj, yn_blockId, x, y - 1, z); - int yn_concentration = (yn_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x, y - 1, z); - if (yn_isAir) { - air_count++; - if (yn_concentration > 0) { - sum_concentration += yn_concentration; - } else { - empty_count++; - } - } - int zp_blockId = worldObj.getBlockId(x, y, z + 1); - boolean zp_isAir = WarpDriveConfig.isAirBlock(worldObj, zp_blockId, x, y, z + 1); - int zp_concentration = (zp_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x, y, z + 1); - if (zp_isAir) { - air_count++; - if (zp_concentration > 0) { - sum_concentration += zp_concentration; - } else { - empty_count++; - } - } - int zn_blockId = worldObj.getBlockId(x, y, z - 1); - boolean zn_isAir = WarpDriveConfig.isAirBlock(worldObj, zn_blockId, x, y, z - 1); - int zn_concentration = (zn_blockId != this.blockID) ? 0 : worldObj.getBlockMetadata(x, y, z - 1); - if (zn_isAir) { - air_count++; - if (zn_concentration > 0) { - sum_concentration += zn_concentration; - } else { - empty_count++; - } - } + if ((var6 || var7) && par5 == 3 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 4 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 5 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 2 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 0 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 1 && !var6) + { + return true; + } + else + { + return false; + } + } + } - if (empty_count > 0) { - if (concentration < 8) { - sum_concentration -= empty_count; - } else if (concentration < 4) { - sum_concentration -= empty_count + (worldObj.rand.nextBoolean() ? 0 : empty_count); - } else { - sum_concentration -= 1; - } - } - if (sum_concentration < 0) sum_concentration = 0; - int mid_concentration = (int) Math.floor(sum_concentration * 1.0F / air_count); - int new_concentration = sum_concentration - mid_concentration * (air_count - 1); - if (new_concentration > 14) { - new_concentration = 14; - } - if (concentration != new_concentration) - { - if (concentration == 15) { - if ( (xp_blockId != WarpDriveConfig.airgenID) && (xn_blockId != WarpDriveConfig.airgenID) - && (yp_blockId != WarpDriveConfig.airgenID) && (yn_blockId != WarpDriveConfig.airgenID) - && (zp_blockId != WarpDriveConfig.airgenID) && (zn_blockId != WarpDriveConfig.airgenID) ) { -// WarpDrive.debugPrint("AirGenerator not found, removing air block at " + x + ", " + y + ", " + z); - worldObj.setBlockMetadataWithNotify(x, y, z, 1, 2); - } else { - // keep the block as a source -/* WarpDrive.debugPrint("15 + " - + xp_concentration + " " + xn_concentration + " " - + yp_concentration + " " + yn_concentration + " " - + zp_concentration + " " + zn_concentration + " = " + sum_concentration + " total, " + empty_count + " empty / " + air_count + " -> " + new_concentration);/**/ - } - } else { - worldObj.setBlockMetadataWithNotify(x, y, z, new_concentration, 2); - } - } - - // Check and setup air to adjacent blocks - if (xp_isAir) { - if (xp_blockId == this.blockID) { - if (xp_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x + 1, y, z, mid_concentration, 2); - } - } else { - worldObj.setBlock(x + 1, y, z, this.blockID, mid_concentration, 2); - } - } + private void spreadAirBlock(World worldObj, int x, int y, int z, int concentration) + { + if (concentration <= 0) + { + return; + } - if (xn_isAir) { - if (xn_blockId == this.blockID) { - if (xn_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x - 1, y, z, mid_concentration, 2); - } - } else { - worldObj.setBlock(x - 1, y, z, this.blockID, mid_concentration, 2); - } - } + int mid_concentration; + int block_count = 1; + mid_concentration = worldObj.getBlockMetadata(x, y, z); - if (yp_isAir) { - if (yp_blockId == this.blockID) { - if (yp_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x, y + 1, z, mid_concentration, 2); - } - } else { - worldObj.setBlock(x, y + 1, z, this.blockID, mid_concentration, 2); - } - } + // Count air in adjacent blocks + if (worldObj.isAirBlock(x + 1, y, z)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x + 1, y, z); + } - if (yn_isAir) { - if (yn_blockId == this.blockID) { - if (yn_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x, y - 1, z, mid_concentration, 2); - } - } else { - worldObj.setBlock(x, y - 1, z, this.blockID, mid_concentration, 2); - } - } + if (worldObj.isAirBlock(x - 1, y, z)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x - 1, y, z); + } - if (zp_isAir) { - if (zp_blockId == this.blockID) { - if (zp_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x, y, z + 1, mid_concentration, 2); - } - } else { - worldObj.setBlock(x, y, z + 1, this.blockID, mid_concentration, 2); - } - } + if (worldObj.isAirBlock(x, y + 1, z)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x, y + 1, z); + } - if (zn_isAir) { - if (zn_blockId == this.blockID) { - if (zn_concentration != 15) { - worldObj.setBlockMetadataWithNotify(x, y, z - 1, mid_concentration, 2); - } - } else { - worldObj.setBlock(x, y, z - 1, this.blockID, mid_concentration, 2); - } - } - } + if (worldObj.isAirBlock(x, y - 1, z)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x, y - 1, z); + } - // Used to prevent updates on chunk generation - @Override - public boolean func_82506_l() { - return false; - } + if (worldObj.isAirBlock(x, y, z + 1)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x, y, z + 1); + } - /** - * Returns if this block is collidable. Args: x, y, z - */ - @Override - public boolean isCollidable() { - return false; - } + if (worldObj.isAirBlock(x, y, z - 1)) + { + block_count++; + mid_concentration += worldObj.getBlockMetadata(x, y, z - 1); + } - @Override - public void onBlockAdded(World par1World, int par2, int par3, int par4) { - if (par1World.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID || par1World.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) { - par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World)); - } else { - par1World.setBlockToAir(par2, par3, par4); - } - } + mid_concentration = (int)Math.floor(mid_concentration / block_count); + setNewAirBlockWithConcentration(worldObj, x, y, z, mid_concentration); + + // Check and setup air to adjacent blocks + if (worldObj.isAirBlock(x + 1, y, z) && (mid_concentration > worldObj.getBlockMetadata(x + 1, y, z))) + { + setNewAirBlockWithConcentration(worldObj, x + 1, y, z, mid_concentration); + } + + if (worldObj.isAirBlock(x - 1, y, z) && (mid_concentration > worldObj.getBlockMetadata(x - 1, y, z))) + { + setNewAirBlockWithConcentration(worldObj, x - 1, y, z, mid_concentration); + } + + if (worldObj.isAirBlock(x, y + 1, z) && (mid_concentration > worldObj.getBlockMetadata(x, y + 1, z))) + { + setNewAirBlockWithConcentration(worldObj, x, y + 1, z, mid_concentration); + } + + if (worldObj.isAirBlock(x, y - 1, z) && (mid_concentration > worldObj.getBlockMetadata(x, y - 1, z))) + { + setNewAirBlockWithConcentration(worldObj, x, y - 1, z, mid_concentration); + } + + if (worldObj.isAirBlock(x, y, z + 1) && (mid_concentration > worldObj.getBlockMetadata(x, y, z + 1))) + { + setNewAirBlockWithConcentration(worldObj, x, y, z + 1, mid_concentration); + } + + if (worldObj.isAirBlock(x, y, z - 1) && (mid_concentration > worldObj.getBlockMetadata(x, y, z - 1))) + { + setNewAirBlockWithConcentration(worldObj, x, y, z - 1, mid_concentration); + } + } + + private void setNewAirBlockWithConcentration(World worldObj, int x, int y, int z, int concentration) + { + worldObj.setBlock(x, y, z, this.blockID, concentration, 2); + } + + @Override + public boolean func_82506_l() + { + return false; + } + + /** + * Returns if this block is collidable. Args: x, y, z + */ + @Override + public boolean isCollidable() + { + return false; + } + + @Override + public void onBlockAdded(World par1World, int par2, int par3, int par4) + { + if (par1World.provider.dimensionId == WarpDrive.instance.spaceDimID || par1World.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) + { + par1World.scheduleBlockUpdate(par2, par3, par4, this.blockID, this.tickRate(par1World)); + } + else + { + par1World.setBlockToAir(par2, par3, par4); + } + } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockAirGenerator.java b/src/cr0s/WarpDrive/BlockAirGenerator.java similarity index 67% rename from src/cr0s/WarpDrive/machines/BlockAirGenerator.java rename to src/cr0s/WarpDrive/BlockAirGenerator.java index 4098f102..8a304d7b 100644 --- a/src/cr0s/WarpDrive/machines/BlockAirGenerator.java +++ b/src/cr0s/WarpDrive/BlockAirGenerator.java @@ -1,13 +1,11 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; import java.util.Random; -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; @@ -25,10 +23,6 @@ public class BlockAirGenerator extends BlockContainer public BlockAirGenerator(int id, int texture, Material material) { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.AirGenerator"); } @Override @@ -42,20 +36,30 @@ public class BlockAirGenerator extends BlockContainer } @Override - public Icon getIcon(int side, int metadata) { - if (side == 0) { + public Icon getIcon(int side, int metadata) + { + if (side == 0) + { return iconBuffer[ICON_BOTTOM]; - } else if (side == 1) { - if (metadata == 0) { + } + else if (side == 1) + { + if (metadata == 0) + { return iconBuffer[ICON_INACTIVE_SIDE]; - } else { + } + else + { return iconBuffer[ICON_SIDE_ACTIVATED]; } } - if (metadata == 0) { // Inactive state - return iconBuffer[ICON_INACTIVE_SIDE]; - } else if (metadata == 1) { + if (metadata == 0) // Inactive state + { + return iconBuffer[ICON_INACTIVE_SIDE]; + } + else if (metadata == 1) + { return iconBuffer[ICON_SIDE_ACTIVATED]; } @@ -63,7 +67,8 @@ public class BlockAirGenerator extends BlockContainer } @Override - public TileEntity createNewTileEntity(World var1) { + public TileEntity createNewTileEntity(World var1) + { return new TileEntityAirGenerator(); } @@ -71,7 +76,8 @@ public class BlockAirGenerator extends BlockContainer * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -79,29 +85,36 @@ public class BlockAirGenerator extends BlockContainer * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return false; } - WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus()); - return true; + TileEntityAirGenerator gen = (TileEntityAirGenerator)par1World.getBlockTileEntity(par2, par3, par4); + + if (gen != null) + { + par5EntityPlayer.addChatMessage("[AirGen] Energy level: " + gen.getCurrentEnergyValue() + " Eu"); } - return false; + return true; } @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { + + if (te != null) + { te.invalidate(); } diff --git a/src/cr0s/WarpDrive/BlockCamera.java b/src/cr0s/WarpDrive/BlockCamera.java new file mode 100644 index 00000000..2576c2bc --- /dev/null +++ b/src/cr0s/WarpDrive/BlockCamera.java @@ -0,0 +1,64 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockCamera extends BlockContainer +{ + private Icon[] iconBuffer; + + private final int ICON_SIDE = 0; + + public BlockCamera(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[1]; + // Solid textures + iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("warpdrive:cameraSide"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + return iconBuffer[ICON_SIDE]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityCamera(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/BlockCloakingCoil.java b/src/cr0s/WarpDrive/BlockCloakingCoil.java new file mode 100644 index 00000000..db908dea --- /dev/null +++ b/src/cr0s/WarpDrive/BlockCloakingCoil.java @@ -0,0 +1,72 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Random; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockCloakingCoil extends Block +{ + private Icon[] iconBuffer; + + public BlockCloakingCoil(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[2]; + iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:cloakCoilSide"); + iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:cloakCoilSideActive"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + return iconBuffer[metadata]; + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } + + @Override + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { + TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); + + if (te != null) + { + te.invalidate(); + } + + super.breakBlock(par1World, par2, par3, par4, par5, par6); + } +} diff --git a/src/cr0s/WarpDrive/BlockCloakingDeviceCore.java b/src/cr0s/WarpDrive/BlockCloakingDeviceCore.java new file mode 100644 index 00000000..f94f4d41 --- /dev/null +++ b/src/cr0s/WarpDrive/BlockCloakingDeviceCore.java @@ -0,0 +1,98 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Random; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockCloakingDeviceCore extends BlockContainer +{ + private Icon[] iconBuffer; + + public BlockCloakingDeviceCore(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[2]; + iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:cloakingCoreInactive"); + iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:cloakingCoreActive"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + return iconBuffer[metadata]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityCloakingDeviceCore(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } + + @Override + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return false; + } + + TileEntityCloakingDeviceCore me = (TileEntityCloakingDeviceCore)par1World.getBlockTileEntity(par2, par3, par4); + + if (me != null) + { + par5EntityPlayer.addChatMessage("[CloakDeviceCore] Energy level: " + me.getCurrentEnergyValue() + " Eu"); + } + + return true; + } + + @Override + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { + TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); + + if (te != null) + { + if (((TileEntityCloakingDeviceCore)te).isEnabled) + ((TileEntityCloakingDeviceCore)te).disableCloakingField(); + + te.invalidate(); + } + + super.breakBlock(par1World, par2, par3, par4, par5, par6); + } +} diff --git a/src/cr0s/WarpDrive/BlockGas.java b/src/cr0s/WarpDrive/BlockGas.java index 74d7b4dc..003fef0a 100644 --- a/src/cr0s/WarpDrive/BlockGas.java +++ b/src/cr0s/WarpDrive/BlockGas.java @@ -1,7 +1,6 @@ package cr0s.WarpDrive; import java.util.Random; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; @@ -10,52 +9,60 @@ import net.minecraft.util.Icon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -public class BlockGas extends Block { +public class BlockGas extends Block +{ private Icon[] gasIcons; - public BlockGas(int par1) { + public BlockGas(int par1) + { super(par1, Material.air); - setHardness(0.0F); - setUnlocalizedName("warpdrive.blocks.Gas"); } @Override - public boolean isOpaqueCube() { + public boolean isOpaqueCube() + { return false; } @Override - public boolean isAirBlock(World var1, int var2, int var3, int var4) { + public boolean isAirBlock(World var1, int var2, int var3, int var4) + { return true; } @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool(World var1, int var2, int var3, int var4) { + public AxisAlignedBB getCollisionBoundingBoxFromPool(World var1, int var2, int var3, int var4) + { return null; } @Override - public boolean isBlockReplaceable(World var1, int var2, int var3, int var4) { + public boolean isBlockReplaceable(World var1, int var2, int var3, int var4) + { return true; } @Override - public boolean canPlaceBlockAt(World var1, int var2, int var3, int var4) { + public boolean canPlaceBlockAt(World var1, int var2, int var3, int var4) + { return true; } @Override - public boolean canCollideCheck(int var1, boolean var2) { + public boolean canCollideCheck(int var1, boolean var2) + { return false; } @Override - public int getRenderBlockPass() { + public int getRenderBlockPass() + { return 1; // transparency enabled } @Override - public void registerIcons(IconRegister par1IconRegister) { + public void registerIcons(IconRegister par1IconRegister) + { gasIcons = new Icon[12]; gasIcons[0] = par1IconRegister.registerIcon("warpdrive:gasBlockBlue"); gasIcons[1] = par1IconRegister.registerIcon("warpdrive:gasBlockRed"); @@ -72,17 +79,20 @@ public class BlockGas extends Block { } @Override - public Icon getIcon(int side, int metadata) { - return gasIcons[metadata % gasIcons.length]; // Lem + public Icon getIcon(int side, int metadata) + { + return gasIcons[metadata]; } @Override - public int getMobilityFlag() { + public int getMobilityFlag() + { return 1; } @Override - public int idDropped(int var1, Random var2, int var3) { + public int idDropped(int var1, Random var2, int var3) + { return -1; } @@ -90,17 +100,59 @@ public class BlockGas extends Block { * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 0; } @Override - public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) { - int sideBlockID = world.getBlockId(x, y, z); - if (sideBlockID == this.blockID) { + public boolean shouldSideBeRendered(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) + { + if (par1IBlockAccess.getBlockId(par2, par3, par4) == this.blockID) + { return false; } - return world.isAirBlock(x, y, z); + else + { + final int i = par1IBlockAccess.getBlockId(par2, par3, par4); + boolean var6 = false; + + if (Block.blocksList[i] != null) + { + var6 = !Block.blocksList[i].isOpaqueCube(); + } + + final boolean var7 = i == 0; + + if ((var6 || var7) && par5 == 3 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 4 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 5 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 2 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 0 && !var6) + { + return true; + } + else if ((var6 || var7) && par5 == 1 && !var6) + { + return true; + } + else + { + return false; + } + } } @Override @@ -113,14 +165,17 @@ public class BlockGas extends Block { * Returns if this block is collidable. Args: x, y, z */ @Override - public boolean isCollidable() { + public boolean isCollidable() + { return false; } @Override - public void onBlockAdded(World par1World, int par2, int par3, int par4) { + public void onBlockAdded(World par1World, int par2, int par3, int par4) + { // Gas blocks allow only in space - if (par1World.provider.dimensionId != WarpDriveConfig.G_SPACE_DIMENSION_ID) { + if (par1World.provider.dimensionId != WarpDrive.instance.spaceDimID) + { par1World.setBlockToAir(par2, par3, par4); } } diff --git a/src/cr0s/WarpDrive/BlockIridium.java b/src/cr0s/WarpDrive/BlockIridium.java index 0a41c72c..c560457a 100644 --- a/src/cr0s/WarpDrive/BlockIridium.java +++ b/src/cr0s/WarpDrive/BlockIridium.java @@ -4,17 +4,15 @@ import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; public class BlockIridium extends Block { public BlockIridium(int par1) { super(par1, Material.rock); - setHardness(0.8F); - setResistance(150 * 4); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.blocks.IridiumBlock"); } @Override diff --git a/src/cr0s/WarpDrive/machines/BlockLaser.java b/src/cr0s/WarpDrive/BlockLaser.java similarity index 60% rename from src/cr0s/WarpDrive/machines/BlockLaser.java rename to src/cr0s/WarpDrive/BlockLaser.java index 424b4e1a..11e93fdf 100644 --- a/src/cr0s/WarpDrive/machines/BlockLaser.java +++ b/src/cr0s/WarpDrive/BlockLaser.java @@ -1,47 +1,46 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; +import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - import java.util.Random; - -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.World; -public class BlockLaser extends BlockContainer { +public class BlockLaser extends BlockContainer +{ private Icon[] iconBuffer; private final int ICON_SIDE = 0; - public BlockLaser(int id, int texture, Material material) { + public BlockLaser(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.Laser"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { + public void registerIcons(IconRegister par1IconRegister) + { iconBuffer = new Icon[1]; // Solid textures iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("warpdrive:laserSide"); } @Override - public Icon getIcon(int side, int metadata) { + public Icon getIcon(int side, int metadata) + { return iconBuffer[ICON_SIDE]; } @Override - public TileEntity createNewTileEntity(World parWorld) { + public TileEntity createNewTileEntity(World var1) + { return new TileEntityLaser(); } @@ -49,7 +48,8 @@ public class BlockLaser extends BlockContainer { * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -57,7 +57,8 @@ public class BlockLaser extends BlockContainer { * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/BlockLaserCam.java b/src/cr0s/WarpDrive/BlockLaserCam.java new file mode 100644 index 00000000..165f403f --- /dev/null +++ b/src/cr0s/WarpDrive/BlockLaserCam.java @@ -0,0 +1,64 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockLaserCam extends BlockContainer +{ + private Icon[] iconBuffer; + + private final int ICON_SIDE = 0; + + public BlockLaserCam(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[1]; + // Solid textures + iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("warpdrive:laserSideCam"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + return iconBuffer[ICON_SIDE]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityLaser(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockLift.java b/src/cr0s/WarpDrive/BlockLift.java similarity index 65% rename from src/cr0s/WarpDrive/machines/BlockLift.java rename to src/cr0s/WarpDrive/BlockLift.java index abca2b73..dad3ac2b 100644 --- a/src/cr0s/WarpDrive/machines/BlockLift.java +++ b/src/cr0s/WarpDrive/BlockLift.java @@ -1,13 +1,11 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; import java.util.Random; -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; @@ -20,17 +18,15 @@ public class BlockLift extends BlockContainer { private Icon[] iconBuffer; - public BlockLift(int id, int texture, Material material) { + public BlockLift(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.LaserLift"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { + public void registerIcons(IconRegister par1IconRegister) + { iconBuffer = new Icon[6]; iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:liftSideOffline"); iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:liftSideUp"); @@ -41,16 +37,20 @@ public class BlockLift extends BlockContainer } @Override - public Icon getIcon(int side, int metadata) { - if (metadata > 2) { - return iconBuffer[0]; - } - if (side == 1) { + public Icon getIcon(int side, int metadata) + { + if (side == 1) + { return iconBuffer[3 + metadata]; - } else if (side == 0) { - if (metadata == 0) { + } + else if (side == 0) + { + if (metadata == 0) + { return iconBuffer[3]; - } else { + } + else + { return iconBuffer[6 - metadata]; } } @@ -59,7 +59,8 @@ public class BlockLift extends BlockContainer } @Override - public TileEntity createNewTileEntity(World var1) { + public TileEntity createNewTileEntity(World var1) + { return new TileEntityLift(); } @@ -67,7 +68,8 @@ public class BlockLift extends BlockContainer * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -75,7 +77,8 @@ public class BlockLift extends BlockContainer * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } @@ -83,24 +86,30 @@ public class BlockLift extends BlockContainer * Called upon block activation (right click on the block.) */ @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return false; } - WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus()); - return true; + TileEntityLift booster = (TileEntityLift)par1World.getBlockTileEntity(par2, par3, par4); + + if (booster != null) + { + par5EntityPlayer.addChatMessage("[Laser Lift] Energy level: " + booster.getCurrentEnergyValue()); } - return false; + return true; } @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { + + if (te != null) + { te.invalidate(); } } diff --git a/src/cr0s/WarpDrive/machines/BlockLaserTreeFarm.java b/src/cr0s/WarpDrive/BlockMiningLaser.java similarity index 55% rename from src/cr0s/WarpDrive/machines/BlockLaserTreeFarm.java rename to src/cr0s/WarpDrive/BlockMiningLaser.java index e163cd26..c90936f3 100644 --- a/src/cr0s/WarpDrive/machines/BlockLaserTreeFarm.java +++ b/src/cr0s/WarpDrive/BlockMiningLaser.java @@ -1,58 +1,61 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; +import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - import java.util.Random; - -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.World; -public class BlockLaserTreeFarm extends BlockContainer { +public class BlockMiningLaser extends BlockContainer +{ private Icon[] iconBuffer; - public BlockLaserTreeFarm(int id, int texture, Material material) { + private final int ICON_SIDE = 0; + + public BlockMiningLaser(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.LaserTreeFarm"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { + public void registerIcons(IconRegister par1IconRegister) + { iconBuffer = new Icon[2]; // Solid textures iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:particleBoosterTopBottom"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:laserTreeFarmSide0"); + iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:miningLaserSide0"); } @Override - public Icon getIcon(int side, int metadata) { - if (side == 0 || side == 1) { + public Icon getIcon(int side, int metadata) + { + if (side == 0 || side == 1) + { return iconBuffer[0]; } - return iconBuffer[1]; + return iconBuffer[metadata + 1]; } - + @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityLaserTreeFarm(); + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityMiningLaser(); } /** * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -60,7 +63,8 @@ public class BlockLaserTreeFarm extends BlockContainer { * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/BlockMonitor.java b/src/cr0s/WarpDrive/BlockMonitor.java new file mode 100644 index 00000000..7f931d37 --- /dev/null +++ b/src/cr0s/WarpDrive/BlockMonitor.java @@ -0,0 +1,112 @@ +package cr0s.WarpDrive; + +import java.util.List; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.BlockDirectional; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntityChest; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.Icon; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; + +public class BlockMonitor extends BlockContainer +{ + private Icon frontIcon; + private Icon blockIcon; + + public BlockMonitor(int id) + { + super(id, Material.iron); + } + + @SideOnly(Side.CLIENT) + + /** + * From the specified side and block metadata retrieves the blocks texture. Args: side, metadata + */ + public Icon getIcon(int side, int meta) + { + meta &= 3; + return side == 2 ? (meta == 0 ? this.frontIcon : this.blockIcon) : (side == 3 ? (meta == 2 ? this.frontIcon : this.blockIcon) : (side == 4 ? (meta == 3 ? this.frontIcon : this.blockIcon) : (side == 5 ? (meta == 1 ? this.frontIcon : this.blockIcon) : this.blockIcon))); + } + + /** + * When this method is called, your block should register all the icons it needs with the given IconRegister. This + * is the only chance you get to register icons. + */ + public void registerIcons(IconRegister reg) + { + this.frontIcon = reg.registerIcon("warpdrive:monitorFront"); + this.blockIcon = reg.registerIcon("warpdrive:monitorSide"); + } + + /** + * Called when the block is placed in the world. + */ + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack itemstack) + { + int dir = Math.round(entityliving.rotationYaw / 90.0F) & 3; + world.setBlockMetadataWithNotify(x, y, z, dir, 3); + } + + /** + * Called upon block activation (right click on the block.) + */ + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int par6, float par7, float par8, float par9) + { + if (!FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return true; + } + + // Get camera frequency + TileEntity te = world.getBlockTileEntity(x, y, z); + + if (te != null && te instanceof TileEntityMonitor) + { + int freq = ((TileEntityMonitor)te).getFrequency(); + WarpDrive.instance.cams.removeDeadCams(); + CamRegistryItem cam = WarpDrive.instance.cams.getCamByFreq(freq, world); + + if (cam == null || cam.worldObj == null || cam.worldObj != world || !WarpDrive.instance.cams.isCamAlive(cam)) + { + entityplayer.addChatMessage("[Monitor: " + freq + "] Invalid frequency or camera is too far!"); + return false; + } + else + { + // Spawn camera entity + EntityCamera e = new EntityCamera(world, cam.camPos, entityplayer); + world.spawnEntityInWorld(e); + e.setPositionAndUpdate(cam.camPos.x, cam.camPos.y, cam.camPos.z); + //e.setPositionAndRotation(camPos.x, camPos.y, camPos.z, entityplayer.rotationYaw, entityplayer.rotationPitch); + ClientCameraUtils.playerData = entityplayer; + WarpDrive.instance.overlayType = cam.type; + ClientCameraUtils.setupViewpoint(e); + } + } + + return false; + } + + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { + } + + @Override + public TileEntity createNewTileEntity(World world) + { + return new TileEntityMonitor(); + } +} diff --git a/src/cr0s/WarpDrive/BlockParticleBooster.java b/src/cr0s/WarpDrive/BlockParticleBooster.java new file mode 100644 index 00000000..8fc3e121 --- /dev/null +++ b/src/cr0s/WarpDrive/BlockParticleBooster.java @@ -0,0 +1,118 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Random; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockParticleBooster extends BlockContainer +{ + private Icon[] iconBuffer; + + public BlockParticleBooster(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[12]; + iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide0"); + iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide1"); + iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide2"); + iconBuffer[3] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide3"); + iconBuffer[4] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide4"); + iconBuffer[5] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide5"); + iconBuffer[6] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide6"); + iconBuffer[7] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide7"); + iconBuffer[8] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide8"); + iconBuffer[9] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide9"); + iconBuffer[10] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide10"); + iconBuffer[11] = par1IconRegister.registerIcon("warpdrive:particleBoosterTopBottom"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + if (side == 0 || side == 1) + { + return iconBuffer[11]; + } + + if (metadata > 10) + { + metadata = 10; + } + + return iconBuffer[metadata]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityParticleBooster(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } + + /** + * Called upon block activation (right click on the block.) + */ + @Override + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return false; + } + + TileEntityParticleBooster booster = (TileEntityParticleBooster)par1World.getBlockTileEntity(par2, par3, par4); + + if (booster != null) + { + par5EntityPlayer.addChatMessage("[Particle Booster] Energy level: " + booster.getCurrentEnergyValue()); + } + + return true; + } + + @Override + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { + TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); + + if (te != null) + { + te.invalidate(); + } + + super.breakBlock(par1World, par2, par3, par4, par5, par6); + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/BlockProtocol.java b/src/cr0s/WarpDrive/BlockProtocol.java new file mode 100644 index 00000000..e51563f6 --- /dev/null +++ b/src/cr0s/WarpDrive/BlockProtocol.java @@ -0,0 +1,117 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockProtocol extends BlockContainer +{ + private Icon[] iconBuffer; + + private final int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_TOP = 2, ICON_SIDE_ACTIVATED = 3; + //private final int ANIMATION_ + //private int currentTexture; + + public BlockProtocol(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[9]; + // Solid textures + iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("warpdrive:contSideInactive"); + iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("warpdrive:contBottom"); + iconBuffer[ICON_TOP] = par1IconRegister.registerIcon("warpdrive:contTop"); + // Animated textures + iconBuffer[ICON_SIDE_ACTIVATED] = par1IconRegister.registerIcon("warpdrive:contSideActive1"); + iconBuffer[ICON_SIDE_ACTIVATED + 1] = par1IconRegister.registerIcon("warpdrive:contSideActive2"); + iconBuffer[ICON_SIDE_ACTIVATED + 2] = par1IconRegister.registerIcon("warpdrive:contSideActive3"); + iconBuffer[ICON_SIDE_ACTIVATED + 3] = par1IconRegister.registerIcon("warpdrive:contSideActive4"); + iconBuffer[ICON_SIDE_ACTIVATED + 4] = par1IconRegister.registerIcon("warpdrive:contSideActive5"); + iconBuffer[ICON_SIDE_ACTIVATED + 5] = par1IconRegister.registerIcon("warpdrive:contSideActive6"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + if (side == 0) + { + return iconBuffer[ICON_BOTTOM]; + } + else if (side == 1) + { + return iconBuffer[ICON_TOP]; + } + + if (metadata == 0) // Inactive state + { + return iconBuffer[ICON_INACTIVE_SIDE]; + } + else if (metadata > 0) // Activated, in metadata stored mode number + { + if (ICON_SIDE_ACTIVATED + metadata - 1 < iconBuffer.length) + return iconBuffer[ICON_SIDE_ACTIVATED + metadata - 1]; + else + return iconBuffer[ICON_SIDE_ACTIVATED]; + } + else + return iconBuffer[ICON_SIDE_ACTIVATED]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityProtocol(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } + /** + * Called upon block activation (right click on the block.) + */ + @Override + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return false; + } + + TileEntityProtocol controller = (TileEntityProtocol)par1World.getBlockTileEntity(par2, par3, par4); + + if (controller != null) + { + controller.attachPlayer(par5EntityPlayer); + par5EntityPlayer.addChatMessage("[WarpCtrlr] Attached players: " + controller.getAttachedPlayersList()); + } + + return true; + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockRadar.java b/src/cr0s/WarpDrive/BlockRadar.java similarity index 56% rename from src/cr0s/WarpDrive/machines/BlockRadar.java rename to src/cr0s/WarpDrive/BlockRadar.java index f9cd6d93..7aabc33e 100644 --- a/src/cr0s/WarpDrive/machines/BlockRadar.java +++ b/src/cr0s/WarpDrive/BlockRadar.java @@ -1,13 +1,12 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; +import java.util.ArrayList; import java.util.Random; -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; @@ -20,25 +19,19 @@ public class BlockRadar extends BlockContainer { private Icon[] iconBuffer; - private final int ICON_SIDE_INACTIVE = 0; - private final int ICON_BOTTOM = 1; - private final int ICON_TOP = 2; - private final int ICON_SIDE_ACTIVATED = 3; - private final int ICON_SIDE_ACTIVATED_SCAN = 4; + private final int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_TOP = 2, ICON_SIDE_ACTIVATED = 3, ICON_SIDE_ACTIVATED_SCAN = 4; - public BlockRadar(int id, int texture, Material material) { + public BlockRadar(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.WarpRadar"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[16]; - iconBuffer[ICON_SIDE_INACTIVE] = par1IconRegister.registerIcon("warpdrive:radarSideInactive"); + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[5]; + iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("warpdrive:radarSideInactive"); iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("warpdrive:contBottom"); iconBuffer[ICON_TOP] = par1IconRegister.registerIcon("warpdrive:contTop"); iconBuffer[ICON_SIDE_ACTIVATED] = par1IconRegister.registerIcon("warpdrive:radarSideActive"); @@ -46,26 +39,36 @@ public class BlockRadar extends BlockContainer } @Override - public Icon getIcon(int side, int metadata) { - if (side == 0) { + public Icon getIcon(int side, int metadata) + { + if (side == 0) + { return iconBuffer[ICON_BOTTOM]; - } else if (side == 1) { + } + else if (side == 1) + { return iconBuffer[ICON_TOP]; } - if (metadata == 0) {// Inactive state - return iconBuffer[ICON_SIDE_INACTIVE]; - } else if (metadata == 1) { // Attached state + if (metadata == 0) // Inactive state + { + return iconBuffer[ICON_INACTIVE_SIDE]; + } + else if (metadata == 1) // Attached state + { return iconBuffer[ICON_SIDE_ACTIVATED]; - } else if (metadata == 2) { // Scanning state + } + else if (metadata == 2) // Scanning state + { return iconBuffer[ICON_SIDE_ACTIVATED_SCAN]; } - return iconBuffer[ICON_SIDE_INACTIVE]; + return null; } @Override - public TileEntity createNewTileEntity(World var1) { + public TileEntity createNewTileEntity(World var1) + { return new TileEntityRadar(); } @@ -73,7 +76,8 @@ public class BlockRadar extends BlockContainer * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -81,29 +85,36 @@ public class BlockRadar extends BlockContainer * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return false; } - WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus()); - return true; + TileEntityRadar radar = (TileEntityRadar)par1World.getBlockTileEntity(par2, par3, par4); + + if (radar != null) + { + par5EntityPlayer.addChatMessage("[Radar] Energy level: " + radar.getCurrentEnergyValue() + " Eu"); } - return false; + return true; } @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { + + if (te != null) + { te.invalidate(); } diff --git a/src/cr0s/WarpDrive/machines/BlockReactor.java b/src/cr0s/WarpDrive/BlockReactor.java similarity index 54% rename from src/cr0s/WarpDrive/machines/BlockReactor.java rename to src/cr0s/WarpDrive/BlockReactor.java index a8936fe2..83b7c4c5 100644 --- a/src/cr0s/WarpDrive/machines/BlockReactor.java +++ b/src/cr0s/WarpDrive/BlockReactor.java @@ -1,13 +1,9 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - import java.util.Random; - -import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; @@ -16,51 +12,55 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.World; -public class BlockReactor extends BlockContainer { +public class BlockReactor extends BlockContainer +{ private Icon[] iconBuffer; - private final int ICON_SIDE_INACTIVE = 0, ICON_BOTTOM = 1, ICON_TOP = 2, ICON_SIDE_ACTIVATED = 3, ICON_SIDE_HEATED = 4; + private final int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_TOP = 2, ICON_SIDE_ACTIVATED = 3; - public BlockReactor(int id, int texture, Material material) { + public BlockReactor(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.WarpCore"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[5]; - iconBuffer[ICON_SIDE_INACTIVE] = par1IconRegister.registerIcon("warpdrive:coreSideInactive"); + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[4]; + iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("warpdrive:coreSideInactive"); iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("warpdrive:coreBottom"); iconBuffer[ICON_TOP] = par1IconRegister.registerIcon("warpdrive:coreTop"); iconBuffer[ICON_SIDE_ACTIVATED] = par1IconRegister.registerIcon("warpdrive:coreSideActive"); - iconBuffer[ICON_SIDE_HEATED] = par1IconRegister.registerIcon("warpdrive:coreSideHeated"); } @Override - public Icon getIcon(int side, int metadata) { - if (side == 0) { + public Icon getIcon(int side, int metadata) + { + if (side == 0) + { return iconBuffer[ICON_BOTTOM]; - } else if (side == 1) { + } + else if (side == 1) + { return iconBuffer[ICON_TOP]; } - if (metadata == 0) { // Inactive state - return iconBuffer[ICON_SIDE_INACTIVE]; - } else if (metadata == 1) { // Activated state + if (metadata == 0) //Inactive state + { + return iconBuffer[ICON_INACTIVE_SIDE]; + } + else if (metadata == 1) // Activated state + { return iconBuffer[ICON_SIDE_ACTIVATED]; - } else if (metadata == 2) { // Heated state - return iconBuffer[ICON_SIDE_HEATED]; - } + } return null; } @Override - public TileEntity createNewTileEntity(World var1) { + public TileEntity createNewTileEntity(World var1) + { return new TileEntityReactor(); } @@ -68,7 +68,8 @@ public class BlockReactor extends BlockContainer { * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -76,7 +77,8 @@ public class BlockReactor extends BlockContainer { * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } @@ -84,30 +86,35 @@ public class BlockReactor extends BlockContainer { * Called upon block activation (right click on the block.) */ @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return false; } TileEntityReactor reactor = (TileEntityReactor)par1World.getBlockTileEntity(par2, par3, par4); - if (reactor != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(reactor.getStatus()); - return true; + if (reactor != null) + { + par5EntityPlayer.addChatMessage(reactor.getCoreState()); } - return false; + return true; } @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && te instanceof TileEntityReactor) { - WarpDrive.instance.warpCores.removeFromRegistry((TileEntityReactor)te); + + if (te != null && te instanceof TileEntityReactor) + { + WarpDrive.instance.registry.removeFromRegistry((TileEntityReactor)te); te.invalidate(); } - WarpDrive.instance.warpCores.removeDeadCores(); + WarpDrive.instance.registry.removeDeadCores(); super.breakBlock(par1World, par2, par3, par4, par5, par6); } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/BlockShipScanner.java b/src/cr0s/WarpDrive/BlockShipScanner.java new file mode 100644 index 00000000..7e69bb34 --- /dev/null +++ b/src/cr0s/WarpDrive/BlockShipScanner.java @@ -0,0 +1,106 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Random; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Icon; +import net.minecraft.world.World; + +public class BlockShipScanner extends BlockContainer +{ + private Icon[] iconBuffer; + + public BlockShipScanner(int id, int texture, Material material) + { + super(id, material); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerIcons(IconRegister par1IconRegister) + { + iconBuffer = new Icon[3]; + iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:shipScannerUp"); + iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:shipScannerSide"); + iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:contBottom"); + } + + @Override + public Icon getIcon(int side, int metadata) + { + if (side == 1) // UP + { + return iconBuffer[0]; + } + else if (side == 0) // DOWN + { + return iconBuffer[2]; + } + + return iconBuffer[1]; + } + + @Override + public TileEntity createNewTileEntity(World var1) + { + return new TileEntityShipScanner(); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + @Override + public int quantityDropped(Random par1Random) + { + return 1; + } + + /** + * Returns the ID of the items to drop on destruction. + */ + @Override + public int idDropped(int par1, Random par2Random, int par3) + { + return this.blockID; + } + + /** + * Called upon block activation (right click on the block.) + */ + @Override + public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return false; + } + + TileEntityShipScanner me = (TileEntityShipScanner)par1World.getBlockTileEntity(par2, par3, par4); + + if (me != null) + { + par5EntityPlayer.addChatMessage("[Ship Scanner] Energy level: " + me.getCurrentEnergyValue()); + } + + return true; + } + + @Override + public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) + { + TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); + + if (te != null) + { + te.invalidate(); + } + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockWarpIsolation.java b/src/cr0s/WarpDrive/BlockWarpIsolation.java similarity index 62% rename from src/cr0s/WarpDrive/machines/BlockWarpIsolation.java rename to src/cr0s/WarpDrive/BlockWarpIsolation.java index 34813f1f..efeb31ac 100644 --- a/src/cr0s/WarpDrive/machines/BlockWarpIsolation.java +++ b/src/cr0s/WarpDrive/BlockWarpIsolation.java @@ -1,36 +1,38 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; import java.util.Random; import net.minecraft.block.Block; +import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; +import net.minecraft.world.World; -public class BlockWarpIsolation extends Block { +public class BlockWarpIsolation extends Block +{ private Icon[] iconBuffer; - public BlockWarpIsolation(int id, int texture, Material material) { + public BlockWarpIsolation(int id, int texture, Material material) + { super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.blocks.WarpIsolation"); } @Override @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { + public void registerIcons(IconRegister par1IconRegister) + { iconBuffer = new Icon[1]; iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:warpIsolation"); } @Override - public Icon getIcon(int side, int metadata) { + public Icon getIcon(int side, int metadata) + { return iconBuffer[0]; } @@ -38,7 +40,8 @@ public class BlockWarpIsolation extends Block { * Returns the quantity of items to drop on block destruction. */ @Override - public int quantityDropped(Random par1Random) { + public int quantityDropped(Random par1Random) + { return 1; } @@ -46,7 +49,8 @@ public class BlockWarpIsolation extends Block { * Returns the ID of the items to drop on destruction. */ @Override - public int idDropped(int par1, Random par2Random, int par3) { + public int idDropped(int par1, Random par2Random, int par3) + { return this.blockID; } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/CamRegistry.java b/src/cr0s/WarpDrive/CamRegistry.java index 376deb29..40cb65ae 100644 --- a/src/cr0s/WarpDrive/CamRegistry.java +++ b/src/cr0s/WarpDrive/CamRegistry.java @@ -1,113 +1,72 @@ package cr0s.WarpDrive; -import java.util.Iterator; -import java.util.LinkedList; +import java.util.ArrayList; +import java.util.HashMap; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; -public class CamRegistry { - private LinkedList registry; +public class CamRegistry +{ + private ArrayList registry; - public CamRegistry() { - registry = new LinkedList(); + public CamRegistry() + { + registry = new ArrayList(); } - public CamRegistryItem getCamByFrequency(World worldObj, int frequency) { - CamRegistryItem cam = null; - for (Iterator it = registry.iterator(); it.hasNext(); ) { - cam = it.next(); - if (cam.frequency == frequency && cam.dimensionId == worldObj.provider.dimensionId) { - if (isCamAlive(worldObj, cam)) { - return cam; - } else { - WarpDrive.debugPrint("Removing 'dead' camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z + " (while searching)"); - it.remove(); - } - } - } - - // not found => dump registry - printRegistry(worldObj); - return null; - } - - public CamRegistryItem getCamByPosition(World worldObj, ChunkPosition position) { - CamRegistryItem cam = null; - for (Iterator it = registry.iterator(); it.hasNext(); ) { - cam = it.next(); - if (cam.position.x == position.x && cam.position.y == position.y && cam.position.z == position.z && cam.dimensionId == worldObj.provider.dimensionId) { - return cam; + public CamRegistryItem getCamByFreq(int frequency, World worldObj) + { + for (CamRegistryItem i : registry) + { + if (i.freq == frequency && i.worldObj == worldObj) + { + return i; } } return null; } - private static boolean isCamAlive(World worldObj, CamRegistryItem cam) { - if (worldObj.provider.dimensionId != cam.dimensionId) { - WarpDrive.debugPrint("Inconsistent worldObj with camera " + worldObj.provider.dimensionId + " vs " + cam.dimensionId); - return false; - } - - if ( (worldObj.getBlockId(cam.position.x, cam.position.y, cam.position.z) != WarpDriveConfig.camID) - && (worldObj.getBlockId(cam.position.x, cam.position.y, cam.position.z) != WarpDriveConfig.laserCamID) ) { - WarpDrive.debugPrint("Reporting a 'dead' camera in dimension " + cam.dimensionId + " at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); - return false; - } - - return true; - } - - public void removeDeadCams(World worldObj) { -// LocalProfiler.start("CamRegistry Removing dead cameras"); - - CamRegistryItem cam = null; - for (Iterator it = registry.iterator(); it.hasNext(); ) { - cam = it.next(); - if (!isCamAlive(worldObj, cam)) { - WarpDrive.debugPrint("Removing 'dead' camera in dimension " + cam.dimensionId + " at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); - it.remove(); - } - } - -// LocalProfiler.stop(); - } - - public void removeFromRegistry(World worldObj, ChunkPosition position) { - CamRegistryItem cam = getCamByPosition(worldObj, position); - if (cam != null) { - WarpDrive.debugPrint("Removing camera by request in dimension " + cam.dimensionId + " at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); - registry.remove(cam); - } - } - public void updateInRegistry(World worldObj, ChunkPosition position, int frequency, int type) { - updateInRegistry(worldObj, new CamRegistryItem(worldObj, position, frequency, type)); - } - - private void updateInRegistry(World worldObj, CamRegistryItem cam) { - removeDeadCams(worldObj); - - if (isCamAlive(worldObj, cam)) { - CamRegistryItem existingCam = getCamByPosition(worldObj, cam.position); - if (existingCam == null) { - WarpDrive.debugPrint("Adding 'live' camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z + " with frequency '" + cam.frequency + "'"); - registry.add(cam); - } else if (existingCam.frequency != cam.frequency) { - WarpDrive.debugPrint("Updating 'live' camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z + " to frequency '" + cam.frequency + "'"); - registry.add(cam); + public boolean isCamAlive(CamRegistryItem i) + { + if (i.worldObj != null) + { + if (i.worldObj.getBlockId(i.camPos.x, i.camPos.y, i.camPos.z) != WarpDriveConfig.i.camID && i.worldObj.getBlockId(i.camPos.x, i.camPos.y, i.camPos.z) != WarpDriveConfig.i.laserCamID) + { + return false; + } + + return true; + } + + return false; + } + + public void removeDeadCams() + { + for (CamRegistryItem i : registry) + { + if (!isCamAlive(i)) + { + registry.remove(i); + return; } - } else { - WarpDrive.debugPrint("Unable to update 'dead' camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); } } - public void printRegistry(World worldObj) { - System.out.println("Cameras registry for dimension " + worldObj.provider.dimensionId + ":"); - removeDeadCams(worldObj); + public void updateInRegistry(CamRegistryItem i) + { + removeDeadCams(); - for (CamRegistryItem cam : registry) { - System.out.println("- " + cam.frequency + " (" + cam.position.x + ", " + cam.position.y + ", " + cam.position.z + ")"); - } - } + if (isCamAlive(i)) + { + CamRegistryItem existingCam = this.getCamByFreq(i.freq, i.worldObj); + + if (existingCam == null) + { + registry.add(i); + } + } + } } diff --git a/src/cr0s/WarpDrive/CamRegistryItem.java b/src/cr0s/WarpDrive/CamRegistryItem.java index 05c0a7d3..b841a970 100644 --- a/src/cr0s/WarpDrive/CamRegistryItem.java +++ b/src/cr0s/WarpDrive/CamRegistryItem.java @@ -3,16 +3,23 @@ package cr0s.WarpDrive; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; -public class CamRegistryItem { - public int dimensionId = -666; - public ChunkPosition position = null; - public int frequency = -1; - public int type = 0; // 0 - basic camera, 1 - laser camera +public class CamRegistryItem +{ + public int freq; + public ChunkPosition camPos; + public World worldObj; - public CamRegistryItem(World parWorldObj, ChunkPosition parPosition, int parFrequency, int parType) { - frequency = parFrequency; - position = parPosition; - dimensionId = parWorldObj.provider.dimensionId; - type = parType; + public int type = 0; // 0 - basic cam, 1 - laser cam + public CamRegistryItem(int freq, ChunkPosition pos, World worldObj) + { + this.freq = freq; + this.camPos = pos; + this.worldObj = worldObj; + } + + public CamRegistryItem setType(int type) + { + this.type = type; + return this; } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/CameraOverlay.java b/src/cr0s/WarpDrive/CameraOverlay.java index 0876647f..eeab8ab1 100644 --- a/src/cr0s/WarpDrive/CameraOverlay.java +++ b/src/cr0s/WarpDrive/CameraOverlay.java @@ -12,56 +12,36 @@ import net.minecraftforge.event.ForgeSubscribe; public class CameraOverlay { private Minecraft mc; - private int frameCount = 0; - private static int ANIMATION_FRAMES = 200; - public CameraOverlay(Minecraft parMinecraft) { - mc = parMinecraft; - } - - private static int colorGradient(float gradient, int start, int end) { - return Math.max(0, Math.min(255, start + Math.round(gradient * (end - start)))); + public CameraOverlay(Minecraft mc) + { + this.mc = mc; } - protected void renderOverlay(int scaledWidth, int scaledHeight) { + protected void renderOverlay(int par1, int par2) + { GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_ALPHA_TEST); - try { - String text; - if (WarpDrive.instance.overlayType == 0) { - mc.getTextureManager().bindTexture(new ResourceLocation("warpdrive", "textures/blocks/camOverlay.png")); - text = "Left click to zoom / Right click to exit"; - } else { - mc.getTextureManager().bindTexture(new ResourceLocation("warpdrive", "textures/blocks/lasercamOverlay.png")); - text = "Left click to zoom / Right click to exit / Space to fire"; - } - - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV( 0.0D, scaledHeight, -90.0D, 0.0D, 1.0D); - tessellator.addVertexWithUV(scaledWidth, scaledHeight, -90.0D, 1.0D, 1.0D); - tessellator.addVertexWithUV(scaledWidth, 0.0D, -90.0D, 1.0D, 0.0D); - tessellator.addVertexWithUV( 0.0D, 0.0D, -90.0D, 0.0D, 0.0D); - tessellator.draw(); - - frameCount++; - if (frameCount >= ANIMATION_FRAMES) { - frameCount = 0; - } - float time = Math.abs(frameCount * 2.0F / ANIMATION_FRAMES - 1.0F); - int color = (colorGradient(time, 0x40, 0xA0) << 16) + (colorGradient(time, 0x80, 0x00) << 8) + colorGradient(time, 0x80, 0xFF); - mc.fontRenderer.drawString(text, (scaledWidth - mc.fontRenderer.getStringWidth(text)) / 2, 30, color, true); - if (WarpDriveConfig.debugMode) { - mc.fontRenderer.drawString(WarpDrive.instance.debugMessage, (scaledWidth - mc.fontRenderer.getStringWidth(WarpDrive.instance.debugMessage)) / 2, 40, 0xFF008F, true); - } - } catch (Exception e) { - e.printStackTrace(); + if (WarpDrive.instance.overlayType == 0) + { + this.mc.getTextureManager().bindTexture(new ResourceLocation("warpdrive", "textures/blocks/camOverlay.png")); } - + else + { + this.mc.getTextureManager().bindTexture(new ResourceLocation("warpdrive", "textures/blocks/lasercamOverlay.png")); + } + + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(0.0D, (double)par2, -90.0D, 0.0D, 1.0D); + tessellator.addVertexWithUV((double)par1, (double)par2, -90.0D, 1.0D, 1.0D); + tessellator.addVertexWithUV((double)par1, 0.0D, -90.0D, 1.0D, 0.0D); + tessellator.addVertexWithUV(0.0D, 0.0D, -90.0D, 0.0D, 0.0D); + tessellator.draw(); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_ALPHA_TEST); @@ -69,17 +49,18 @@ public class CameraOverlay } @ForgeSubscribe - public void onRender(RenderGameOverlayEvent.Pre event) { - if (WarpDrive.instance.isOverlayEnabled) { - if (event.type == ElementType.HELMET) { + public void onRender(RenderGameOverlayEvent.Pre event) + { + if (WarpDrive.instance.isOverlayEnabled) + { + if (event.type == ElementType.HELMET) + { renderOverlay(event.resolution.getScaledWidth(), event.resolution.getScaledHeight()); - } else if (event.type == ElementType.EXPERIENCE || event.type == ElementType.HOTBAR || event.type == ElementType.ARMOR - || event.type == ElementType.HEALTH || event.type == ElementType.HEALTHMOUNT || event.type == ElementType.FOOD - || event.type == ElementType.BOSSHEALTH || event.type == ElementType.TEXT || event.type == ElementType.AIR) { - // Don't render other GUI parts - if (event.isCancelable()) { - event.setCanceled(true); - } + } + else if (event.type == ElementType.EXPERIENCE || event.type == ElementType.HOTBAR || event.type == ElementType.ARMOR || event.type == ElementType.HEALTH || event.type == ElementType.HEALTHMOUNT || event.type == ElementType.FOOD || event.type == ElementType.BOSSHEALTH || event.type == ElementType.TEXT) + { + // Don't render other GUI parts + event.setCanceled(true); } } } diff --git a/src/cr0s/WarpDrive/ClientCameraUtils.java b/src/cr0s/WarpDrive/ClientCameraUtils.java index 63abec58..9fe0bf66 100644 --- a/src/cr0s/WarpDrive/ClientCameraUtils.java +++ b/src/cr0s/WarpDrive/ClientCameraUtils.java @@ -1,83 +1,42 @@ package cr0s.WarpDrive; -import org.lwjgl.input.Keyboard; - import net.minecraft.client.Minecraft; import net.minecraft.client.settings.EnumOptions; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; -public class ClientCameraUtils { - public static EntityPlayer entityPlayer; - public static int dimensionId = -666; - public static int check1_x, check1_y, check1_z, check1_blockId; - public static int check2_x, check2_y, check2_z, check2_blockId; +public class ClientCameraUtils +{ + public static EntityPlayer playerData; + public static float oldFOV; + public static float oldSens; - public static void setupViewpoint(EntityPlayer parPlayerEntity, EntityCamera entityCamera, int x1, int y1, int z1, int blockId1, int x2, int y2, int z2, int blockId2) { + public static void setupViewpoint(Entity entity) + { Minecraft mc = Minecraft.getMinecraft(); - if (parPlayerEntity == null) { - System.out.println("[WarpDrive] setupViewpoint with null player => denied"); - return; - } - if (entityCamera == null) { - System.out.println("[WarpDrive] setupViewpoint with null camera => denied"); - return; + if (entity == null) + { + System.out.println("Null"); } - entityPlayer = parPlayerEntity; - dimensionId = entityCamera.worldObj.provider.dimensionId; - check1_x = x1; - check1_y = y1; - check1_z = z1; - check1_blockId = blockId1; - check2_x = x2; - check2_y = y2; - check2_z = z2; - check2_blockId = blockId2; - - WarpDrive.debugPrint("Setting viewpoint: " + entityCamera.toString()); - mc.renderViewEntity = entityCamera; + System.out.println("Setting viewpoint: " + entity.toString()); + mc.renderViewEntity = (EntityLivingBase)entity; mc.gameSettings.thirdPersonView = 0; + oldFOV = mc.gameSettings.fovSetting; + oldSens = mc.gameSettings.mouseSensitivity; WarpDrive.instance.isOverlayEnabled = true; - - Keyboard.enableRepeatEvents(true); } - public static void resetViewpoint() { + public static void resetCam() + { Minecraft mc = Minecraft.getMinecraft(); - if (entityPlayer != null) { - mc.renderViewEntity = entityPlayer; - entityPlayer = null; - WarpDrive.debugPrint("Resetting viewpoint"); - } else { - System.out.println("[WarpDrive] reseting viewpoint with invalid player entity ?!?"); - } - - Keyboard.enableRepeatEvents(false); - - WarpDrive.instance.isOverlayEnabled = false; + mc.renderViewEntity = playerData; + playerData = null; mc.gameSettings.thirdPersonView = 0; - mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, WarpDrive.normalFOV); - mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, WarpDrive.normalSensitivity); - - entityPlayer = null; - dimensionId = -666; - } - - public static boolean isValidContext(World worldObj) { - if (worldObj == null || worldObj.provider.dimensionId != dimensionId) { - return false; - } - if (worldObj.getBlockId(check1_x, check1_y, check1_z) != check1_blockId) { - System.out.println("[WarpDrive] checking viewpoint, found invalid block1 at (" + check1_x + ", " + check1_y + ", " + check1_z + ")"); - return false; - } - if (worldObj.getBlockId(check2_x, check2_y, check2_z) != check2_blockId) { - System.out.println("[WarpDrive] checking viewpoint, found invalid block2 at (" + check2_x + ", " + check2_y + ", " + check2_z + ")"); - return false; - } - return true; + mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, oldFOV); + mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, oldSens); + WarpDrive.instance.isOverlayEnabled = false; } } diff --git a/src/cr0s/WarpDrive/ClientProxy.java b/src/cr0s/WarpDrive/ClientProxy.java new file mode 100644 index 00000000..92d94cb8 --- /dev/null +++ b/src/cr0s/WarpDrive/ClientProxy.java @@ -0,0 +1,20 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.client.FMLClientHandler; +import net.minecraft.world.World; +import net.minecraftforge.client.MinecraftForgeClient; + +public class ClientProxy extends CommonProxy +{ + @Override + public void registerRenderers() + { + } + + @Override + public void renderBeam(World world, Vector3 position, Vector3 target, float red, float green, float blue, int age, int energy) + { + //System.out.println("Rendering beam..."); + FMLClientHandler.instance().getClient().effectRenderer.addEffect(new FXBeam(world, position, target, red, green, blue, age, energy)); + } +} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/CloakChunkWatcher.java b/src/cr0s/WarpDrive/CloakChunkWatcher.java index 2273610d..0c23f044 100644 --- a/src/cr0s/WarpDrive/CloakChunkWatcher.java +++ b/src/cr0s/WarpDrive/CloakChunkWatcher.java @@ -1,35 +1,26 @@ package cr0s.WarpDrive; import java.util.ArrayList; -import cr0s.WarpDrive.CloakedArea; +import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.packet.Packet56MapChunks; import net.minecraft.world.ChunkCoordIntPair; +import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.world.ChunkWatchEvent; -public class CloakChunkWatcher { +public class CloakChunkWatcher +{ @ForgeSubscribe public void chunkLoaded(ChunkWatchEvent event) { EntityPlayerMP p = event.player; ChunkCoordIntPair chunk = event.chunk; - - // Check chunk for locating in cloaked areas ArrayList cloaks = WarpDrive.instance.cloaks.getCloaksForPoint(p.worldObj.provider.dimensionId, chunk.getCenterXPos(), 0, chunk.getCenterZPosition(), true); if (cloaks.size() == 0) return; - - //Chunk c = p.worldObj.getChunkFromChunkCoords(chunk.chunkXPos, chunk.chunkZPos); - for (CloakedArea area : cloaks) { + for (CloakedArea area : cloaks) area.sendCloakPacketToPlayer(p, false); - } - - /*List list = new ArrayList(); - list.add(c); - - // Send obscured chunk - System.out.println("[Cloak] Sending to player " + p.username + " obscured chunk at (" + chunk.chunkXPos + "; " + chunk.chunkZPos + ")"); - ((EntityPlayerMP)p).playerNetServerHandler.sendPacketToPlayer(new Packet56MapChunks(list));*/ - } } diff --git a/src/cr0s/WarpDrive/CloakManager.java b/src/cr0s/WarpDrive/CloakManager.java index 907ed1d0..c06e4027 100644 --- a/src/cr0s/WarpDrive/CloakManager.java +++ b/src/cr0s/WarpDrive/CloakManager.java @@ -6,7 +6,10 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.FMLNetworkHandler; +import cpw.mods.fml.relauncher.Side; +import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLeashKnot; import net.minecraft.entity.EntityLivingBase; @@ -42,7 +45,9 @@ import net.minecraft.network.packet.Packet24MobSpawn; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.network.packet.Packet25EntityPainting; import net.minecraft.network.packet.Packet26EntityExpOrb; +import net.minecraft.network.packet.Packet56MapChunks; import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.World; @@ -55,22 +60,22 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; * */ -public class CloakManager { - - private LinkedList cloaks; +public class CloakManager +{ + private ArrayList cloaks; public CloakManager() { - this.cloaks = new LinkedList(); + this.cloaks = new ArrayList(); } public boolean isInCloak(int dimensionID, int x, int y, int z, boolean chunk) { - for (int i = 0; i < this.cloaks.size(); i++) { - if (this.cloaks.get(i).dimensionId != dimensionID) + for (int i = 0; i < this.cloaks.size(); i++){ + if (this.cloaks.get(i).world == null || this.cloaks.get(i).world.provider.dimensionId != dimensionID) continue; AxisAlignedBB axisalignedbb = this.cloaks.get(i).aabb; - if (axisalignedbb.minX <= x && axisalignedbb.maxX >= x && (chunk || (axisalignedbb.minY <= y && axisalignedbb.maxY >= y)) && axisalignedbb.minZ <= z && axisalignedbb.maxZ >= z) { + if (axisalignedbb.minX <= (double) x && axisalignedbb.maxX >= (double) x && (chunk || (axisalignedbb.minY <= (double) y && axisalignedbb.maxY >= (double) y)) && axisalignedbb.minZ <= (double) z && axisalignedbb.maxZ >= (double) z) { return true; } } @@ -81,31 +86,39 @@ public class CloakManager { public ArrayList getCloaksForPoint(int dimensionID, int x, int y, int z, boolean chunk) { ArrayList res = new ArrayList(); - for (int i = 0; i < this.cloaks.size(); i++) { - if (this.cloaks.get(i).dimensionId != dimensionID) + for (int i = 0; i < this.cloaks.size(); i++){ + if (this.cloaks.get(i).world == null || this.cloaks.get(i).world.provider.dimensionId != dimensionID) continue; AxisAlignedBB axisalignedbb = this.cloaks.get(i).aabb; - if (axisalignedbb.minX <= x && axisalignedbb.maxX >= x && (chunk || (axisalignedbb.minY <= y && axisalignedbb.maxY >= y)) && axisalignedbb.minZ <= z && axisalignedbb.maxZ >= z) { + //System.outprint("[Cloak] checking (" + x + "; " + y + "; " + z + ") -> " + this.cloaks.get(i).aabb); + if (axisalignedbb.minX <= (double) x && axisalignedbb.maxX >= (double) x && (chunk || (axisalignedbb.minY <= (double) y && axisalignedbb.maxY >= (double) y)) && axisalignedbb.minZ <= (double) z && axisalignedbb.maxZ >= (double) z) { res.add(cloaks.get(i)); - } + //System.outprintln(": YES"); + }// else + //System.outprintln(": NO"); } return res; } - public boolean isAreaExists(World worldObj, int x, int y, int z) { - return (getCloakedArea(worldObj, x, y, z) != null); + public boolean isAreaExists(int frequency) { + for (int i = 0; i < this.cloaks.size(); i++){ + if (this.cloaks.get(i).frequency == frequency) + return true; + } + + return false; } - public void addCloakedAreaWorld(World worldObj, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int x, int y, int z, byte tier) { - cloaks.add(new CloakedArea(worldObj, x, y, z, AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ), tier)); + public void addCloakedAreaWorld(World worldObj, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int frequency, byte tier) { + cloaks.add(new CloakedArea(worldObj, frequency, AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ), tier)); } - public void removeCloakedArea(World worldObj, int x, int y, int z) { + public void removeCloakedArea(int frequency) { int index = 0; for (int i = 0; i < this.cloaks.size(); i++){ - if (this.cloaks.get(i).coreX == x && this.cloaks.get(i).coreY == y && this.cloaks.get(i).coreZ == z && this.cloaks.get(i).dimensionId == worldObj.provider.dimensionId) { + if (this.cloaks.get(i).frequency == frequency) { this.cloaks.get(i).sendCloakPacketToPlayersEx(true); // send info about collapsing cloaking field index = i; break; @@ -115,121 +128,216 @@ public class CloakManager { cloaks.remove(index); } - public CloakedArea getCloakedArea(World worldObj, int x, int y, int z) { + public CloakedArea getCloakedArea(int frequency) { for (CloakedArea area : this.cloaks) { - if (area.coreX == x && area.coreY == y && area.coreZ == z && area.dimensionId == worldObj.provider.dimensionId) + if (area.frequency == frequency) return area; } return null; } - public void checkPlayerLeftArea(EntityPlayer player) { + public void playerEnteringCloakedArea(CloakedArea area, EntityPlayer player) { + area.playersInArea.add(player); + revealChunksToPlayer(area, player); + revealEntityToPlayer(area, player); + area.sendCloakPacketToPlayer(player, false); + } + + public void revealEntityToPlayer(CloakedArea area, EntityPlayer p) { + List list = p.worldObj.getEntitiesWithinAABBExcludingEntity(p, area.aabb); + + for (Entity e : list) { + ((EntityPlayerMP)p).playerNetServerHandler.sendPacketToPlayer(getPacketForThisEntity(e)); + } + } + + public void checkPlayerLeavedArea(EntityPlayer p) { for (CloakedArea area : this.cloaks) { - if (!area.isEntityWithinArea(player) && area.isPlayerInArea(player.username)) { - area.removePlayer(player.username); + if (!area.isPlayerWithinArea(p) && area.isPlayerInArea(p)) { + area.removePlayerFromArea(p); //System.outprintln("[Cloak] Player " + p.username + " has leaved cloaked area " + area.frequency); - MinecraftServer.getServer().getConfigurationManager().sendToAllNearExcept(player, player.posX, player.posY, player.posZ, 100, player.worldObj.provider.dimensionId, getPacketForThisEntity(player)); - area.sendCloakPacketToPlayer(player, false); + MinecraftServer.getServer().getConfigurationManager().sendToAllNearExcept(p, p.posX, p.posY, p.posZ, 100, p.worldObj.provider.dimensionId, getPacketForThisEntity(p)); + area.sendCloakPacketToPlayer(p, false); } } } - public static Packet getPacketForThisEntity(Entity e) { - if (e.isDead) { - e.worldObj.getWorldLogAgent().logWarning("Fetching addPacket for removed entity"); - } + public void revealChunksToPlayer(CloakedArea area, EntityPlayer p) { + //System.outprintln("[Cloak] Revealing cloaked chunks in area " + area.frequency + " to player " + p.username); + for (int x = (int)area.aabb.minX; x < (int)area.aabb.maxX; x++) + for (int z = (int)area.aabb.minZ; z < (int)area.aabb.maxZ; z++) + for (int y = (int)area.aabb.minY; y < (int)area.aabb.maxY; y++) { + if (p.worldObj.getBlockId(x, y, z) != 0) + p.worldObj.markBlockForUpdate(x, y, z); + } + /*ArrayList chunksToSend = new ArrayList(); + + for (int x = (int)area.aabb.minX >> 4; x <= (int)area.aabb.maxX >> 4; x++) + for (int z = (int)area.aabb.minZ >> 4; z <= (int)area.aabb.maxZ >> 4; z++) { + chunksToSend.add(p.worldObj.getChunkFromChunkCoords(x, z)); + } + + //System.outprintln("[Cloak] Sending " + chunksToSend.size() + " chunks to player " + p.username); + ((EntityPlayerMP)p).playerNetServerHandler.sendPacketToPlayer(new Packet56MapChunks(chunksToSend)); + + //System.outprintln("[Cloak] Sending decloak packet to player " + p.username); + area.sendCloakPacketToPlayer(p, true); // decloak = true + */ + } + + private Packet getPacketForThisEntity(Entity e) + { + if (e.isDead) + { + e.worldObj.getWorldLogAgent().logWarning("Fetching addPacket for removed entity"); + } - Packet pkt = FMLNetworkHandler.getEntitySpawningPacket(e); - if (pkt != null) { - return pkt; - } + Packet pkt = FMLNetworkHandler.getEntitySpawningPacket(e); - if (e instanceof EntityItem) { - return new Packet23VehicleSpawn(e, 2, 1); - } else if (e instanceof EntityPlayerMP) { - return new Packet20NamedEntitySpawn((EntityPlayer)e); - } else if (e instanceof EntityMinecart) { - EntityMinecart entityminecart = (EntityMinecart)e; - return new Packet23VehicleSpawn(e, 10, entityminecart.getMinecartType()); - } else if (e instanceof EntityBoat) { - return new Packet23VehicleSpawn(e, 1); - } else if (!(e instanceof IAnimals) && !(e instanceof EntityDragon)) { - if (e instanceof EntityFishHook) { - EntityPlayer entityplayer = ((EntityFishHook)e).angler; - return new Packet23VehicleSpawn(e, 90, entityplayer != null ? entityplayer.entityId : e.entityId); - } else if (e instanceof EntityArrow) { - Entity entity = ((EntityArrow)e).shootingEntity; - return new Packet23VehicleSpawn(e, 60, entity != null ? entity.entityId : e.entityId); - } else if (e instanceof EntitySnowball) { - return new Packet23VehicleSpawn(e, 61); - } else if (e instanceof EntityPotion) { - return new Packet23VehicleSpawn(e, 73, ((EntityPotion)e).getPotionDamage()); - } else if (e instanceof EntityExpBottle) { - return new Packet23VehicleSpawn(e, 75); - } else if (e instanceof EntityEnderPearl) { - return new Packet23VehicleSpawn(e, 65); - } else if (e instanceof EntityEnderEye) { - return new Packet23VehicleSpawn(e, 72); - } else if (e instanceof EntityFireworkRocket) { - return new Packet23VehicleSpawn(e, 76); - } else { - Packet23VehicleSpawn packet23vehiclespawn; + if (pkt != null) + { + return pkt; + } - if (e instanceof EntityFireball) { - EntityFireball entityfireball = (EntityFireball)e; - packet23vehiclespawn = null; - byte b0 = 63; + if (e instanceof EntityItem) + { + return new Packet23VehicleSpawn(e, 2, 1); + } + else if (e instanceof EntityPlayerMP) + { + return new Packet20NamedEntitySpawn((EntityPlayer)e); + } + else if (e instanceof EntityMinecart) + { + EntityMinecart entityminecart = (EntityMinecart)e; + return new Packet23VehicleSpawn(e, 10, entityminecart.getMinecartType()); + } + else if (e instanceof EntityBoat) + { + return new Packet23VehicleSpawn(e, 1); + } + else if (!(e instanceof IAnimals) && !(e instanceof EntityDragon)) + { + if (e instanceof EntityFishHook) + { + EntityPlayer entityplayer = ((EntityFishHook)e).angler; + return new Packet23VehicleSpawn(e, 90, entityplayer != null ? entityplayer.entityId : e.entityId); + } + else if (e instanceof EntityArrow) + { + Entity entity = ((EntityArrow)e).shootingEntity; + return new Packet23VehicleSpawn(e, 60, entity != null ? entity.entityId : e.entityId); + } + else if (e instanceof EntitySnowball) + { + return new Packet23VehicleSpawn(e, 61); + } + else if (e instanceof EntityPotion) + { + return new Packet23VehicleSpawn(e, 73, ((EntityPotion)e).getPotionDamage()); + } + else if (e instanceof EntityExpBottle) + { + return new Packet23VehicleSpawn(e, 75); + } + else if (e instanceof EntityEnderPearl) + { + return new Packet23VehicleSpawn(e, 65); + } + else if (e instanceof EntityEnderEye) + { + return new Packet23VehicleSpawn(e, 72); + } + else if (e instanceof EntityFireworkRocket) + { + return new Packet23VehicleSpawn(e, 76); + } + else + { + Packet23VehicleSpawn packet23vehiclespawn; - if (e instanceof EntitySmallFireball) { - b0 = 64; - } else if (e instanceof EntityWitherSkull) { - b0 = 66; - } + if (e instanceof EntityFireball) + { + EntityFireball entityfireball = (EntityFireball)e; + packet23vehiclespawn = null; + byte b0 = 63; - if (entityfireball.shootingEntity != null) { - packet23vehiclespawn = new Packet23VehicleSpawn(e, b0, ((EntityFireball)e).shootingEntity.entityId); - } else { - packet23vehiclespawn = new Packet23VehicleSpawn(e, b0, 0); - } + if (e instanceof EntitySmallFireball) + { + b0 = 64; + } + else if (e instanceof EntityWitherSkull) + { + b0 = 66; + } - packet23vehiclespawn.speedX = (int)(entityfireball.accelerationX * 8000.0D); - packet23vehiclespawn.speedY = (int)(entityfireball.accelerationY * 8000.0D); - packet23vehiclespawn.speedZ = (int)(entityfireball.accelerationZ * 8000.0D); - return packet23vehiclespawn; - } else if (e instanceof EntityEgg) { - return new Packet23VehicleSpawn(e, 62); - } else if (e instanceof EntityTNTPrimed) { - return new Packet23VehicleSpawn(e, 50); - } else if (e instanceof EntityEnderCrystal) { - return new Packet23VehicleSpawn(e, 51); - } else if (e instanceof EntityFallingSand) { - EntityFallingSand entityfallingsand = (EntityFallingSand)e; - return new Packet23VehicleSpawn(e, 70, entityfallingsand.blockID | entityfallingsand.metadata << 16); - } else if (e instanceof EntityPainting) { - return new Packet25EntityPainting((EntityPainting)e); - } else if (e instanceof EntityItemFrame) { - EntityItemFrame entityitemframe = (EntityItemFrame)e; - packet23vehiclespawn = new Packet23VehicleSpawn(e, 71, entityitemframe.hangingDirection); - packet23vehiclespawn.xPosition = MathHelper.floor_float(entityitemframe.xPosition * 32); - packet23vehiclespawn.yPosition = MathHelper.floor_float(entityitemframe.yPosition * 32); - packet23vehiclespawn.zPosition = MathHelper.floor_float(entityitemframe.zPosition * 32); - return packet23vehiclespawn; - } else if (e instanceof EntityLeashKnot) { - EntityLeashKnot entityleashknot = (EntityLeashKnot)e; - packet23vehiclespawn = new Packet23VehicleSpawn(e, 77); - packet23vehiclespawn.xPosition = MathHelper.floor_float(entityleashknot.xPosition * 32); - packet23vehiclespawn.yPosition = MathHelper.floor_float(entityleashknot.yPosition * 32); - packet23vehiclespawn.zPosition = MathHelper.floor_float(entityleashknot.zPosition * 32); - return packet23vehiclespawn; - } else if (e instanceof EntityXPOrb) { - return new Packet26EntityExpOrb((EntityXPOrb)e); - } else { - throw new IllegalArgumentException("Don\'t know how to add " + e.getClass() + "!"); - } - } - } else { - return new Packet24MobSpawn((EntityLivingBase)e); - } - } + if (entityfireball.shootingEntity != null) + { + packet23vehiclespawn = new Packet23VehicleSpawn(e, b0, ((EntityFireball)e).shootingEntity.entityId); + } + else + { + packet23vehiclespawn = new Packet23VehicleSpawn(e, b0, 0); + } + + packet23vehiclespawn.speedX = (int)(entityfireball.accelerationX * 8000.0D); + packet23vehiclespawn.speedY = (int)(entityfireball.accelerationY * 8000.0D); + packet23vehiclespawn.speedZ = (int)(entityfireball.accelerationZ * 8000.0D); + return packet23vehiclespawn; + } + else if (e instanceof EntityEgg) + { + return new Packet23VehicleSpawn(e, 62); + } + else if (e instanceof EntityTNTPrimed) + { + return new Packet23VehicleSpawn(e, 50); + } + else if (e instanceof EntityEnderCrystal) + { + return new Packet23VehicleSpawn(e, 51); + } + else if (e instanceof EntityFallingSand) + { + EntityFallingSand entityfallingsand = (EntityFallingSand)e; + return new Packet23VehicleSpawn(e, 70, entityfallingsand.blockID | entityfallingsand.metadata << 16); + } + else if (e instanceof EntityPainting) + { + return new Packet25EntityPainting((EntityPainting)e); + } + else if (e instanceof EntityItemFrame) + { + EntityItemFrame entityitemframe = (EntityItemFrame)e; + packet23vehiclespawn = new Packet23VehicleSpawn(e, 71, entityitemframe.hangingDirection); + packet23vehiclespawn.xPosition = MathHelper.floor_float((float)(entityitemframe.xPosition * 32)); + packet23vehiclespawn.yPosition = MathHelper.floor_float((float)(entityitemframe.yPosition * 32)); + packet23vehiclespawn.zPosition = MathHelper.floor_float((float)(entityitemframe.zPosition * 32)); + return packet23vehiclespawn; + } + else if (e instanceof EntityLeashKnot) + { + EntityLeashKnot entityleashknot = (EntityLeashKnot)e; + packet23vehiclespawn = new Packet23VehicleSpawn(e, 77); + packet23vehiclespawn.xPosition = MathHelper.floor_float((float)(entityleashknot.xPosition * 32)); + packet23vehiclespawn.yPosition = MathHelper.floor_float((float)(entityleashknot.yPosition * 32)); + packet23vehiclespawn.zPosition = MathHelper.floor_float((float)(entityleashknot.zPosition * 32)); + return packet23vehiclespawn; + } + else if (e instanceof EntityXPOrb) + { + return new Packet26EntityExpOrb((EntityXPOrb)e); + } + else + { + throw new IllegalArgumentException("Don\'t know how to add " + e.getClass() + "!"); + } + } + } + else + { + return new Packet24MobSpawn((EntityLivingBase)e); + } + } } diff --git a/src/cr0s/WarpDrive/CloakedArea.java b/src/cr0s/WarpDrive/CloakedArea.java index b90f7245..dbae7818 100644 --- a/src/cr0s/WarpDrive/CloakedArea.java +++ b/src/cr0s/WarpDrive/CloakedArea.java @@ -17,63 +17,57 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -public class CloakedArea { - public int dimensionId = -666; - public int coreX, coreY, coreZ; +public class CloakedArea +{ + public int frequency; public AxisAlignedBB aabb; - private LinkedList playersInArea; + public LinkedList playersInArea; public byte tier = 0; + public World world = null; - public boolean isPlayerInArea(String username) { - for (String playerInArea : playersInArea) { + public boolean isPlayerInArea(EntityPlayer player) { + for (EntityPlayer p : this.playersInArea) { //System.outprintln("[Cloak] Checking player: " + p.username + "(" + p.entityId + ")" + " =? " + player.username + " (" + p.entityId + ")"); - if (playerInArea.equals(username)) + if (p.username.equals(player.username)) return true; } - + return false; } - public void removePlayer(String username) { - for (int i = 0; i < playersInArea.size(); i++) { - if (playersInArea.get(i).equals(username)) { - playersInArea.remove(i); + public void removePlayerFromArea(EntityPlayer p) { + for (int i = 0; i < this.playersInArea.size(); i++) { + if (this.playersInArea.get(i).username.equals(p.username)) { + this.playersInArea.remove(i); return; } - } + } } - public void addPlayer(String username) { - if (!isPlayerInArea(username)) { - playersInArea.add(username); - } + public boolean isPlayerWithinArea(EntityPlayer player) { + return (aabb.minX <= player.posX && aabb.maxX >= player.posX && aabb.minY <= player.posY && aabb.maxY >= player.posY && aabb.minZ <= player.posZ && aabb.maxZ >= player.posZ); } - - public boolean isEntityWithinArea(Entity entity) { - return (aabb.minX <= entity.posX && aabb.maxX >= entity.posX && aabb.minY <= entity.posY && aabb.maxY >= entity.posY && aabb.minZ <= entity.posZ && aabb.maxZ >= entity.posZ); - } - - public CloakedArea(World worldObj, int x, int y, int z, AxisAlignedBB aabb, byte tier) { - this.coreX = x; - this.coreY = y; - this.coreZ = z; + + public CloakedArea(World worldObj, int frequency, AxisAlignedBB aabb, byte tier) { + this.frequency = frequency; this.aabb = aabb; this.tier = tier; - this.playersInArea = new LinkedList(); + this.playersInArea = new LinkedList(); - if (worldObj == null || aabb == null) { + if (worldObj == null || aabb == null) + return; + + this.world = worldObj; + + if (this.world == null) return; - } - this.dimensionId = worldObj.provider.dimensionId; - try { - // Add all players currently inside the field + // Added all players, who inside the field List list = worldObj.getEntitiesWithinAABB(EntityPlayerMP.class, this.aabb); for (Entity e : list) { - if (e instanceof EntityPlayer) { - addPlayer(((EntityPlayer)e).username); - } + if (e instanceof EntityPlayer) + this.playersInArea.add((EntityPlayer)e); } } catch (Exception e) { e.printStackTrace(); @@ -98,33 +92,36 @@ public class CloakedArea { double midY = this.aabb.minY + (Math.abs(this.aabb.maxY - this.aabb.minY) / 2); double midZ = this.aabb.minZ + (Math.abs(this.aabb.maxZ - this.aabb.minZ) / 2); - for (int j = 0; j < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); j++) { - EntityPlayerMP entityPlayerMP = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(j); + for (int j = 0; j < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); ++j) + { + EntityPlayerMP entityplayermp = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(j); - if (entityPlayerMP.dimension == dimensionId) { - double d4 = midX - entityPlayerMP.posX; - double d5 = midY - entityPlayerMP.posY; - double d6 = midZ - entityPlayerMP.posZ; + if (entityplayermp.dimension == this.world.provider.dimensionId) + { + double d4 = midX - entityplayermp.posX; + double d5 = midY - entityplayermp.posY; + double d6 = midZ - entityplayermp.posZ; - if (Math.abs(d4) < RADIUS && Math.abs(d5) < RADIUS && Math.abs(d6) < RADIUS) { + if (d4 * d4 + d5 * d5 + d6 * d6 < RADIUS * RADIUS) + { if (decloak) { - revealChunksToPlayer(entityPlayerMP); - revealEntityToPlayer(entityPlayerMP); + WarpDrive.instance.cloaks.revealChunksToPlayer(this, (EntityPlayer)entityplayermp); + WarpDrive.instance.cloaks.revealEntityToPlayer(this, (EntityPlayer)entityplayermp); } - if (!isEntityWithinArea(entityPlayerMP) && !decloak) { - sendCloakPacketToPlayer(entityPlayerMP, false); - } else if (decloak) { - sendCloakPacketToPlayer(entityPlayerMP, true); + if (!isPlayerWithinArea((EntityPlayer)entityplayermp) && !decloak) + sendCloakPacketToPlayer((EntityPlayer)entityplayermp, false); + else if (decloak) { + sendCloakPacketToPlayer((EntityPlayer)entityplayermp, true); } } } - } + } } public void sendCloakPacketToPlayer(EntityPlayer player, boolean decloak) { //System.outprintln("[Cloak] Sending cloak packet to player " + player.username); - if (isPlayerInArea(player.username)) { + if (isPlayerInArea(player)) { //System.outprintln("[Cloak] Player " + player.username + " is inside cloaking field"); return; } @@ -132,7 +129,8 @@ public class CloakedArea { ByteArrayOutputStream bos = new ByteArrayOutputStream(8); DataOutputStream outputStream = new DataOutputStream(bos); - try { + try + { outputStream.writeInt((int) this.aabb.minX); outputStream.writeInt((int) this.aabb.minY); outputStream.writeInt((int) this.aabb.minZ); @@ -144,15 +142,17 @@ public class CloakedArea { outputStream.writeBoolean(decloak); outputStream.writeByte(this.tier); - } catch (Exception ex) { + } + catch (Exception ex) + { ex.printStackTrace(); } - + Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "WarpDriveCloaks"; packet.data = bos.toByteArray(); packet.length = bos.size(); - + ((EntityPlayerMP)player).playerNetServerHandler.sendPacketToPlayer(packet); } @@ -186,6 +186,9 @@ public class CloakedArea { extendedblockstorage = storageArrays[y >> 4] = new ExtendedBlockStorage(y >> 4 << 4, !c.worldObj.provider.hasNoSky); } + + int j2 = c.xPosition * 16 + x; + int k2 = c.zPosition * 16 + z; extendedblockstorage.setExtBlockID(x, y & 15, z, blockId); if (extendedblockstorage.getExtBlockID(x, y & 15, z) != blockId) @@ -199,46 +202,5 @@ public class CloakedArea { return true; } } - } - - public void playerEnteringCloakedArea(EntityPlayer player) { - addPlayer(player.username); - revealChunksToPlayer(player); - revealEntityToPlayer(player); - sendCloakPacketToPlayer(player, false); - } - - public void revealChunksToPlayer(EntityPlayer p) { - //System.outprintln("[Cloak] Revealing cloaked chunks in area " + area.frequency + " to player " + p.username); - for (int x = (int)aabb.minX; x <= (int)aabb.maxX; x++) { - for (int z = (int)aabb.minZ; z <= (int)aabb.maxZ; z++) { - for (int y = (int)aabb.minY; y <= (int)aabb.maxY; y++) { - if (p.worldObj.getBlockId(x, y, z) != 0) { - p.worldObj.markBlockForUpdate(x, y, z); - } - } - } - } - /*ArrayList chunksToSend = new ArrayList(); - - for (int x = (int)aabb.minX >> 4; x <= (int)aabb.maxX >> 4; x++) - for (int z = (int)aabb.minZ >> 4; z <= (int)aabb.maxZ >> 4; z++) { - chunksToSend.add(p.worldObj.getChunkFromChunkCoords(x, z)); - } - - //System.outprintln("[Cloak] Sending " + chunksToSend.size() + " chunks to player " + p.username); - ((EntityPlayerMP)p).playerNetServerHandler.sendPacketToPlayer(new Packet56MapChunks(chunksToSend)); - - //System.outprintln("[Cloak] Sending decloak packet to player " + p.username); - area.sendCloakPacketToPlayer(p, true); // decloak = true - */ - } - - public void revealEntityToPlayer(EntityPlayer p) { - List list = p.worldObj.getEntitiesWithinAABBExcludingEntity(p, aabb); - - for (Entity e : list) { - ((EntityPlayerMP)p).playerNetServerHandler.sendPacketToPlayer(CloakManager.getPacketForThisEntity(e)); - } - } + } } diff --git a/src/cr0s/WarpDrive/CommonProxy.java b/src/cr0s/WarpDrive/CommonProxy.java index 6cdacb9c..272c2ca2 100644 --- a/src/cr0s/WarpDrive/CommonProxy.java +++ b/src/cr0s/WarpDrive/CommonProxy.java @@ -1,5 +1,8 @@ package cr0s.WarpDrive; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; + import net.minecraft.world.World; import cpw.mods.fml.common.registry.EntityRegistry; @@ -7,10 +10,10 @@ public class CommonProxy { public void registerEntities() { - EntityRegistry.registerModEntity(EntityJump.class, "EntityJump", 240, WarpDrive.instance, 80, 1, false); // Lem - EntityRegistry.registerModEntity(EntitySphereGen.class, "EntitySphereGenerator", 241, WarpDrive.instance, 200, 1, false); // Lem - EntityRegistry.registerModEntity(EntityStarCore.class, "EntityStarCore", 242, WarpDrive.instance, 300, 1, false); // Lem - EntityRegistry.registerModEntity(EntityCamera.class, "EntityCamera", 243, WarpDrive.instance, 300, 1, false); // Lem + EntityRegistry.registerModEntity(EntityJump.class, "EntityJump", 1, WarpDrive.instance, 80, 1, false); + EntityRegistry.registerModEntity(EntitySphereGen.class, "EntitySphereGenerator", 1, WarpDrive.instance, 200, 1, false); + EntityRegistry.registerModEntity(EntityStarCore.class, "EntityStarCore", 1, WarpDrive.instance, 300, 1, false); + EntityRegistry.registerModEntity(EntityCamera.class, "EntityCamera", 1, WarpDrive.instance, 300, 1, false); } public void registerRenderers() diff --git a/src/cr0s/WarpDrive/DebugCommand.java b/src/cr0s/WarpDrive/DebugCommand.java deleted file mode 100644 index 452dc050..00000000 --- a/src/cr0s/WarpDrive/DebugCommand.java +++ /dev/null @@ -1,150 +0,0 @@ -package cr0s.WarpDrive; - -import cpw.mods.fml.common.FMLCommonHandler; -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.DimensionManager; - -/* -* /wdebug -*/ - -public class DebugCommand extends CommandBase -{ - @Override - public String getCommandName() - { - return "wdebug"; - } - - @Override - public int getRequiredPermissionLevel() - { - return 2; - } - - @Override - public String getCommandUsage(ICommandSender par1ICommandSender) - { - return "/" + getCommandName() + " ...\n" - + "dimension: 0/world, 2/space, 3/hyperspace\n" - + "coordinates: x,y,z\n" - + "action: I(nvalidate), V(alidate), A(set air), R(emoveEntity), P(setBlock), S(etEntity)"; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] params) - { - EntityPlayerMP player = (EntityPlayerMP)icommandsender; - if(params.length > 6 ) - { - int dim, x, y, z, blockId, metadata; - String actions; - try - { - String par = params[0].toLowerCase(); - if (par.equals("world") || par.equals("overworld") || par.equals("0")) - { - dim = 0; - } - else if (par.equals("nether") || par.equals("thenether") || par.equals("-1")) - { - dim = -1; - } - else if (par.equals("s") || par.equals("space")) - { - dim = WarpDriveConfig.G_SPACE_DIMENSION_ID; - } - else if (par.equals("h") || par.equals("hyper") || par.equals("hyperspace")) - { - dim = WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID; - } - else - { - dim = Integer.parseInt(par); - } - - x = Integer.parseInt(params[1]); - y = Integer.parseInt(params[2]); - z = Integer.parseInt(params[3]); - blockId = Integer.parseInt(params[4]); - metadata = Integer.parseInt(params[5]); - actions = params[6]; - } - catch (Exception e) - { - e.printStackTrace(); - player.addChatMessage(getCommandUsage(icommandsender)); - return; - } - - notifyAdmins(icommandsender, "/" + getCommandName() + " " + dim + " " + x + "," + y + "," + z + " " + blockId + ":" + metadata + " " + actions); - World worldObj = DimensionManager.getWorld(dim); - TileEntity te = worldObj.getBlockTileEntity(x, y, z); - notifyAdmins(icommandsender, "[" + getCommandName() + "] In dimension " + worldObj.getProviderName() + " - " + worldObj.getWorldInfo().getWorldName() + ", Current block is " + worldObj.getBlockId(x, y, z) + ":" + worldObj.getBlockMetadata(x, y, z) + ", tile entity is " + ((te == null) ? "undefined" : "defined")); - String side = FMLCommonHandler.instance().getEffectiveSide().isClient() ? "Client":"Server"; - - // I(nvalidate), V(alidate), A(set air), R(emoveEntity), P(setBlock), S(etEntity) - boolean bReturn = false; - for (char ch: actions.toUpperCase().toCharArray()) { - switch (ch) { - case 'I': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": invalidating"); - if (te != null) { - te.invalidate(); - } - break; - case 'V': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": validating"); - if (te != null) { - te.validate(); - } - break; - case 'A': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": setting to Air"); - bReturn = worldObj.setBlockToAir(x, y, z); - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn); - break; - case 'R': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": remove entity"); - worldObj.removeBlockTileEntity(x, y, z); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set block " + x + ", " + y + ", " + z + " to " + blockId + ":" + metadata); - bReturn = worldObj.setBlock(x, y, z, blockId, metadata, ch - '0'); - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn); - break; - case 'P': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set block " + x + ", " + y + ", " + z + " to " + blockId + ":" + metadata); - bReturn = worldObj.setBlock(x, y, z, blockId, metadata, 2); - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": returned " + bReturn); - break; - case 'S': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": set entity"); - worldObj.setBlockTileEntity(x, y, z, te); - break; - case 'C': - notifyAdmins(icommandsender, "[" + getCommandName() + "] " + side + ": update containing block info"); - if (te != null) { - te.updateContainingBlockInfo(); - } - break; - } - } - } - else - { - player.addChatMessage(getCommandUsage(icommandsender)); - } - } -} diff --git a/src/cr0s/WarpDrive/EntityCamera.java b/src/cr0s/WarpDrive/EntityCamera.java index 0bf3dcf1..0c3f2389 100644 --- a/src/cr0s/WarpDrive/EntityCamera.java +++ b/src/cr0s/WarpDrive/EntityCamera.java @@ -2,24 +2,35 @@ package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.PacketDispatcher; +import cpw.mods.fml.relauncher.Side; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; +import java.util.List; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.Display; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.settings.EnumOptions; -import net.minecraft.client.settings.GameSettings; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.ChatMessageComponent; +import net.minecraft.util.ChunkCoordinates; +import net.minecraft.util.DamageSource; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; +import net.minecraft.entity.player.EntityPlayer; public final class EntityCamera extends EntityLivingBase { @@ -27,165 +38,145 @@ public final class EntityCamera extends EntityLivingBase public int yCoord; public int zCoord; + private int ticks = 0; private EntityPlayer player; private Minecraft mc = Minecraft.getMinecraft(); + private int dx, dy, dz; - private int dx = 0, dy = 0, dz = 0; private int zoomNumber = 0; - private int closeWaitTicks = 0; - private int zoomWaitTicks = 0; - private int fireWaitTicks = 0; - private boolean isActive = true; - private int bootUpTicks = 20; + private int waitTicks = 2; + private int fireWaitTicks = 2; + + private float oldFOV; + private float oldSens; - public EntityCamera(World world) { - super(world); - // TODO Auto-generated constructor stub - } - private boolean isCentered = true; - public EntityCamera(World world, ChunkPosition pos, EntityPlayer player) { + public EntityCamera(World world, ChunkPosition pos, EntityPlayer player) + { super(world); this.setInvisible(true); int x = pos.x; int y = pos.y; int z = pos.z; this.xCoord = x; - this.posX = x; + this.posX = (double) x; this.yCoord = y; - this.posY = y; + this.posY = (double) y; this.zCoord = z; - this.posZ = z; + this.posZ = (double) z; this.player = player; } - - private void closeCamera() { - if (!isActive) { - return; - } - - ClientCameraUtils.resetViewpoint(); - worldObj.removeEntity(this); - isActive = false; - } - + @Override - public void onEntityUpdate() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - if (player == null || player.isDead) { - WarpDrive.debugPrint("" + this + " Player is null or dead, closing camera..."); - closeCamera(); - return; - } - if (!ClientCameraUtils.isValidContext(worldObj)) { - WarpDrive.debugPrint("" + this + " Invalid context, closing camera..."); - closeCamera(); - return; - } - - int blockID = worldObj.getBlockId(xCoord, yCoord, zCoord); + public void onEntityUpdate() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { mc.renderViewEntity.rotationYaw = player.rotationYaw; - //mc.renderViewEntity.rotationYawHead = player.rotationYawHead; mc.renderViewEntity.rotationPitch = player.rotationPitch; - WarpDrive.instance.debugMessage = "Mouse " + Mouse.isButtonDown(0) + " " + Mouse.isButtonDown(1) + " " + Mouse.isButtonDown(2) + " " + Mouse.isButtonDown(3) - + "\nBackspace " + Keyboard.isKeyDown(Keyboard.KEY_BACKSLASH) + " Space " + Keyboard.isKeyDown(Keyboard.KEY_SPACE) + " Shift " + ""; // Perform zoom - if (Mouse.isButtonDown(0)) {// FIXME merge: main is using right click with Mouse.isButtonDown(1), branch is using left click - zoomWaitTicks++; - if (zoomWaitTicks >= 2) { - zoomWaitTicks = 0; - zoom(); + if (Mouse.isButtonDown(1) && waitTicks-- <= 0) + { + waitTicks = 4; + zoom(); + } + + if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) + { + ClientCameraUtils.resetCam(); + this.setDead(); + } + else if (Mouse.isButtonDown(0) && fireWaitTicks-- <= 0) + { + fireWaitTicks = 1; + + // Make a shoot with camera-laser + if (worldObj.getBlockId(xCoord, yCoord, zCoord) == WarpDriveConfig.i.laserCamID) + { + sendTargetPacket(); + } + } + else + { + if (Keyboard.isKeyDown(Keyboard.KEY_DOWN) && (dy != -2)) + { + dy = -1; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_UP) && (dy != 2)) + { + dy = 2; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_A) && (dz != -1)) + { + dz = -1; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_D) && (dz != 1)) + { + dz = 1; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_W) && (dx != 1)) + { + dx = 1; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_S) && (dx != -1)) + { + dx = -1; + } + else if (Keyboard.isKeyDown(Keyboard.KEY_C)) //centering view + { + isCentered = !isCentered; + return; } - } else { - zoomWaitTicks = 0; } - if (bootUpTicks > 0) { - bootUpTicks--; - } else { - if (Mouse.isButtonDown(1)) { - closeWaitTicks++; - if (closeWaitTicks >= 2) { - closeWaitTicks = 0; - closeCamera(); - } - } else { - closeWaitTicks = 0; - } - } - - if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {// FIXME merge: main is using left click with Mouse.isButtonDown(0), branch is using space bar - fireWaitTicks++; - if (fireWaitTicks >= 2) { - fireWaitTicks = 0; - - // Make a shoot with camera-laser - if (blockID == WarpDriveConfig.laserCamID) { - sendTargetPacket(); - } - } - } else { - fireWaitTicks = 0; - } - - GameSettings gamesettings = mc.gameSettings; - if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { - dy = -1; - } else if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { - dy = 2; - } else if (Keyboard.isKeyDown(gamesettings.keyBindLeft.keyCode)) { - dz = -1; - } else if (Keyboard.isKeyDown(gamesettings.keyBindRight.keyCode)) { - dz = 1; - } else if (Keyboard.isKeyDown(gamesettings.keyBindForward.keyCode)) { - dx = 1; - } else if (Keyboard.isKeyDown(gamesettings.keyBindBack.keyCode)) { - dx = -1; - } else if (Keyboard.isKeyDown(Keyboard.KEY_C)) { // centering view - dx = 0; - dy = 0; - dz = 0; - isCentered = !isCentered; - return; - } - - if (isCentered) { - setPosition(xCoord + 0.5D, yCoord + 0.75D, zCoord + 0.5D); + if (isCentered) + { + this.setPosition(xCoord + 0.5, yCoord + 0.75, zCoord + 0.5); } else { - setPosition(xCoord + dx, yCoord + dy, zCoord + dz); - } + this.setPosition(xCoord + dx, yCoord + dy, zCoord + dz); + } + + } } - @Override - public void onUpdate() { - super.onUpdate(); - this.motionX = this.motionY = this.motionZ = 0.0D; - } - - public void zoom() { - if (zoomNumber == 0) { + public void zoom() + { + if (zoomNumber == 0) + { + this.oldFOV = mc.gameSettings.fovSetting; + this.oldSens = mc.gameSettings.mouseSensitivity; mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, -0.75F); mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, 0.4F); - } else if (zoomNumber == 1) { + ++zoomNumber; + } + else if (zoomNumber == 1) + { mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, -1.25F); mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, 0.3F); - } else if (zoomNumber == 2) { + ++zoomNumber; + } + else if (zoomNumber == 2) + { mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, -1.6F); mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, 0.15F); - } else if (zoomNumber == 3) { - mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, WarpDrive.normalFOV); - mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, WarpDrive.normalSensitivity); + zoomNumber = 3; + } + else if (zoomNumber == 3) + { + mc.gameSettings.setOptionFloatValue(EnumOptions.FOV, this.oldFOV); + mc.gameSettings.setOptionFloatValue(EnumOptions.SENSITIVITY, this.oldSens); + zoomNumber = 0; } - zoomNumber = (zoomNumber + 1) % 4; } @Override - public boolean shouldRenderInPass(int pass) { + public boolean shouldRenderInPass(int pass) + { return false; } @@ -199,52 +190,68 @@ public final class EntityCamera extends EntityLivingBase @Override public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - xCoord = nbttagcompound.getInteger("x"); - yCoord = nbttagcompound.getInteger("y"); - zCoord = nbttagcompound.getInteger("z"); + this.xCoord = nbttagcompound.getInteger("x"); + this.yCoord = nbttagcompound.getInteger("y"); + this.zCoord = nbttagcompound.getInteger("z"); } + /*@Override + protected void entityInit() { + }*/ + @Override public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("x", xCoord); - nbttagcompound.setInteger("y", yCoord); - nbttagcompound.setInteger("z", zCoord); + nbttagcompound.setInteger("x", this.xCoord); + nbttagcompound.setInteger("y", this.yCoord); + nbttagcompound.setInteger("z", this.zCoord); } @Override - public ItemStack getHeldItem() { + public ItemStack getHeldItem() + { return null; } @Override - public ItemStack getCurrentItemOrArmor(int i) { + public ItemStack getCurrentItemOrArmor(int i) + { return null; } @Override - public void setCurrentItemOrArmor(int i, ItemStack itemstack) { + public void setCurrentItemOrArmor(int i, ItemStack itemstack) + { } @Override - public ItemStack[] getLastActiveItems() { + public ItemStack[] getLastActiveItems() + { return null; } - // Camera orientation refresh to server packet - public void sendTargetPacket() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + // Camera frequency refresh to clients packet + public void sendTargetPacket() + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.CLIENT) + { ByteArrayOutputStream bos = new ByteArrayOutputStream(8); DataOutputStream outputStream = new DataOutputStream(bos); - try { + try + { + // Write source vector outputStream.writeInt(xCoord); outputStream.writeInt(yCoord); outputStream.writeInt(zCoord); outputStream.writeFloat(mc.renderViewEntity.rotationYaw); outputStream.writeFloat(mc.renderViewEntity.rotationPitch); - } catch (Exception e) { - e.printStackTrace(); + } + catch (Exception ex) + { + ex.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); @@ -252,7 +259,6 @@ public final class EntityCamera extends EntityLivingBase packet.data = bos.toByteArray(); packet.length = bos.size(); PacketDispatcher.sendPacketToServer(packet); - WarpDrive.debugPrint("" + this + " Packet '" + packet.channel + "' sent (" + xCoord + ", " + yCoord + ", " + zCoord + ") yawn " + mc.renderViewEntity.rotationYaw + " pitch " + mc.renderViewEntity.rotationPitch); } } @@ -270,4 +276,4 @@ public final class EntityCamera extends EntityLivingBase public ChunkCoordinates getPlayerCoordinates() { return new ChunkCoordinates(xCoord, yCoord, zCoord); }*/ -} \ No newline at end of file +} diff --git a/src/cr0s/WarpDrive/EntityJump.java b/src/cr0s/WarpDrive/EntityJump.java index 9a4cf5b5..64055e2c 100644 --- a/src/cr0s/WarpDrive/EntityJump.java +++ b/src/cr0s/WarpDrive/EntityJump.java @@ -1,8 +1,9 @@ package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.machines.TileEntityReactor; -import dan200.computercraft.api.peripheral.IPeripheral; +import dan200.computer.api.IPeripheral; +import dan200.turtle.api.ITurtleAccess; +import dan200.turtle.api.TurtleSide; import ic2.api.network.NetworkHelper; import java.lang.reflect.Method; @@ -40,13 +41,17 @@ public class EntityJump extends Entity private int moveY; private int moveZ; - private int xCoord; - private int yCoord; - private int zCoord; - private int dx; - private int dz; - private int distance; - private int direction; + public int xCoord; + public int yCoord; + public int zCoord; + public int distance; + public int dir; + public int shipLeft; + public int shipRight; + public int shipFront; + public int shipBack; + public int shipDown; + public int shipUp; public int shipLength; public int maxX; public int maxZ; @@ -54,182 +59,161 @@ public class EntityJump extends Entity public int minX; public int minZ; public int minY; + public int dx; + public int dz; - private boolean isHyperspaceJump; + public int mode; - private World targetWorld; + public World targetWorld; private Ticket sourceWorldTicket; private Ticket targetWorldTicket; - private boolean collisionDetected = false; - private ArrayList collisionAtSource; - private ArrayList collisionAtTarget; - private float collisionStrength = 0; - + // Collision point coordinates + public int blowX, blowY, blowZ; + boolean needToExplode = false; public boolean on = false; - private JumpBlock ship[]; - private TileEntityReactor reactor; + public boolean bedrockOnShip = false; + public JumpBlock ship[]; + public TileEntityReactor reactor; - private final static int STATE_IDLE = 0; - private final static int STATE_JUMPING = 1; - private final static int STATE_REMOVING = 2; - private int state = STATE_IDLE; - private int currentIndexInShip = 0; + public final static int STATE_IDLE = 0; + public final static int STATE_JUMPING = 1; + public final static int STATE_REMOVING = 2; + int state = STATE_IDLE; + int currentIndexInShip = 0; private final int BLOCKS_PER_TICK = 3500; private List entitiesOnShip; private List ASTurbines; - private boolean betweenWorlds; + AxisAlignedBB axisalignedbb; - private int destX, destY, destZ; - private boolean isCoordJump; + private boolean fromSpace, toSpace, betweenWorlds; + public boolean toHyperSpace, fromHyperSpace; + private boolean isInHyperSpace; - private long msCounter = 0; - private int ticks = 0; + int destX, destY, destZ; + boolean isCoordJump; + + long msCounter = 0; public EntityJump(World world) { super(world); targetWorld = worldObj; - WarpDrive.debugPrint("" + this + " Entity created (empty) in dimension " + worldObj.getProviderName() + " - " + worldObj.getWorldInfo().getWorldName() - + " " + (FMLCommonHandler.instance().getEffectiveSide().isClient() ? "Client":"Server")); + System.out.println("[JE@" + this + "] Entity created (empty)"); } - public EntityJump(World world, int x, int y, int z, int _dx, int _dz, TileEntityReactor _reactor, - boolean _isHyperspaceJump, int _distance, int _direction, boolean _isCoordJump, int _destX, int _destY, int _destZ) { + public EntityJump(World world, int x, int y, int z, int _dist, int _direction, int _dx, int _dz, TileEntityReactor parReactor) + { super(world); - this.posX = x + 0.5D; - this.posY = y + 0.5D; - this.posZ = z + 0.5D; this.xCoord = x; + this.posX = (double) x; this.yCoord = y; + this.posY = (double) y; this.zCoord = z; + this.posZ = (double) z; + this.distance = _dist; + this.dir = _direction; + shipLeft = shipRight = shipFront = shipBack = shipDown = shipUp = shipLength = 0; this.dx = _dx; this.dz = _dz; - this.reactor = _reactor; - this.isHyperspaceJump = _isHyperspaceJump; - this.distance = _distance; - this.direction = _direction; - this.isCoordJump = _isCoordJump; - this.destX = _destX; - this.destY = _destY; - this.destZ = _destZ; - - // set by reactor maxX = maxZ = maxY = minX = minZ = minY = 0; - shipLength = 0; - - // set when preparing jump - targetWorld = null; - - WarpDrive.debugPrint("" + this + " Entity created"); + targetWorld = worldObj; + System.out.println("[JE@" + this + "] Entity created"); + this.reactor = parReactor; } - public void killEntity(String reason) { - if (!on) { + public void killEntity(String reason) + { + if (!on) + { return; } on = false; + System.out.println("[JE@" + this + "] Killing jump entity..."); - if (reason == null || reason.isEmpty()) { - WarpDrive.debugPrint("" + this + " Killing jump entity..."); - } else { - WarpDrive.debugPrint("" + this + " Killing jump entity... (" + reason + ")"); + if (!reason.isEmpty()) + { + System.out.println("[JUMP] Killed: " + reason); } -// unlockWorlds(); + unlockWorlds(); unforceChunks(); worldObj.removeEntity(this); } - + @Override - public boolean isEntityInvulnerable() { - return true; - } - - @Override - public void onUpdate() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public void onUpdate() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return; } - if (!on) { - System.out.println("" + this + " Removing from onUpdate..."); + if (!on) + { worldObj.removeEntity(this); return; } - if (minY < 0 || maxY > 256) { - String msg = "Invalid Y coordinate(s), check ship dimensions..."; - messageToAllPlayersOnShip(msg); - killEntity(msg); + if (minY < 0 || maxY > 256) + { + killEntity("Y-coord error!"); return; } - ticks++; - if (state == STATE_IDLE) { - WarpDrive.debugPrint("" + this + " Preparing to jump..."); + if (state == STATE_IDLE) + { + System.out.println("[JE] Preparing to jump..."); prepareToJump(); - if (on) { - state = STATE_JUMPING; - } - } else if (state == STATE_JUMPING) { - if (currentIndexInShip < ship.length - 1) { - //moveEntities(true); - moveShip(); - } else { + state = STATE_JUMPING; + } + else if (state == STATE_JUMPING) + { + if (currentIndexInShip >= ship.length - 1) + { moveEntities(false); currentIndexInShip = 0; state = STATE_REMOVING; } - } else if (state == STATE_REMOVING) { + else + { + //moveEntities(true); + moveShip(); + } + } + else if (state == STATE_REMOVING) + { ASTurbines = new ArrayList(); removeShip(); - if (currentIndexInShip >= ship.length - 1) { + if (currentIndexInShip >= ship.length - 1) + { finishJump(); + FixASTurbines(); state = STATE_IDLE; } - } else { - String msg = "Invalid state, aborting jump..."; - messageToAllPlayersOnShip(msg); - killEntity(msg); - return; } } - private boolean forceChunks(StringBuilder reason) + private void forceChunks() { - LocalProfiler.start("EntityJump.forceChunks"); - WarpDrive.debugPrint("" + this + " Forcing chunks in " + worldObj.provider.getDimensionName() + " and " + targetWorld.provider.getDimensionName()); - sourceWorldTicket = ForgeChunkManager.requestTicket(WarpDrive.instance, worldObj, Type.NORMAL); // Type.ENTITY); - if (sourceWorldTicket == null) { - reason.append("Chunkloading rejected in S:" + worldObj.getWorldInfo().getWorldName() + ". Aborting."); - return false; - } + System.out.println("[JE@" + this + "] Forcing chunks"); + sourceWorldTicket = ForgeChunkManager.requestTicket(WarpDrive.instance, worldObj, Type.ENTITY); targetWorldTicket = ForgeChunkManager.requestTicket(WarpDrive.instance, targetWorld, Type.NORMAL); - if (targetWorldTicket == null) { - reason.append("Chunkloading rejected in T:" + worldObj.getWorldInfo().getWorldName() + ". Aborting."); - return false; - } -// sourceWorldTicket.bindEntity(this); + sourceWorldTicket.bindEntity(this); int x1 = minX >> 4; int x2 = maxX >> 4; int z1 = minZ >> 4; int z2 = maxZ >> 4; - int chunkCount = 0; + for (int x = x1; x <= x2; x++) { for (int z = z1; z <= z2; z++) { - chunkCount++; - if (chunkCount > sourceWorldTicket.getMaxChunkListDepth()) { - reason.append("Ship is extending over too many chunks, max is S:" + sourceWorldTicket.getMaxChunkListDepth() + ". Aborting."); - return false; - } ForgeChunkManager.forceChunk(sourceWorldTicket, new ChunkCoordIntPair(x, z)); } } @@ -238,283 +222,283 @@ public class EntityJump extends Entity x2 = (maxX + moveX) >> 4; z1 = (minZ + moveZ) >> 4; z2 = (maxZ + moveZ) >> 4; - chunkCount = 0; + for (int x = x1; x <= x2; x++) { for (int z = z1; z <= z2; z++) { - chunkCount++; - if (chunkCount > targetWorldTicket.getMaxChunkListDepth()) { - reason.append("Ship is extending over too many chunks, max is T:" + sourceWorldTicket.getMaxChunkListDepth() + ". Aborting."); - return false; - } ForgeChunkManager.forceChunk(targetWorldTicket, new ChunkCoordIntPair(x, z)); } } - LocalProfiler.stop(); - return true; } private void unforceChunks() { - LocalProfiler.start("EntityJump.unforceChunks"); - WarpDrive.debugPrint("" + this + " Unforcing chunks"); + System.out.println("[JE@" + this + "] Unforcing chunks"); - int x1, x2, z1, z2; - if (sourceWorldTicket != null) { - x1 = minX >> 4; - x2 = maxX >> 4; - z1 = minZ >> 4; - z2 = maxZ >> 4; - for (int x = x1; x <= x2; x++) { - for (int z = z1; z <= z2; z++) { - ForgeChunkManager.unforceChunk(sourceWorldTicket, new ChunkCoordIntPair(x, z)); - } - } - ForgeChunkManager.releaseTicket(sourceWorldTicket); - sourceWorldTicket = null; + if (sourceWorldTicket == null || targetWorldTicket == null) + { + return; } - if (targetWorldTicket != null) { - x1 = (minX + moveX) >> 4; - x2 = (maxX + moveX) >> 4; - z1 = (minZ + moveZ) >> 4; - z2 = (maxZ + moveZ) >> 4; - for (int x = x1; x <= x2; x++) { - for (int z = z1; z <= z2; z++) { - ForgeChunkManager.unforceChunk(targetWorldTicket, new ChunkCoordIntPair(x, z)); - } + int x1 = minX >> 4; + int x2 = maxX >> 4; + int z1 = minZ >> 4; + int z2 = maxZ >> 4; + + for (int x = x1; x <= x2; x++) + { + for (int z = z1; z <= z2; z++) + { + ForgeChunkManager.unforceChunk(sourceWorldTicket, new ChunkCoordIntPair(x, z)); } - ForgeChunkManager.releaseTicket(targetWorldTicket); - targetWorldTicket = null; } - - LocalProfiler.stop(); + + x1 = (minX + moveX) >> 4; + x2 = (maxX + moveX) >> 4; + z1 = (minZ + moveZ) >> 4; + z2 = (maxZ + moveZ) >> 4; + + for (int x = x1; x <= x2; x++) + { + for (int z = z1; z <= z2; z++) + { + ForgeChunkManager.unforceChunk(targetWorldTicket, new ChunkCoordIntPair(x, z)); + } + } + + ForgeChunkManager.releaseTicket(sourceWorldTicket); + ForgeChunkManager.releaseTicket(targetWorldTicket); + sourceWorldTicket = null; + targetWorldTicket = null; } - private void messageToAllPlayersOnShip(String msg) { - if (entitiesOnShip == null) { - reactor.messageToAllPlayersOnShip(msg); - } else { - System.out.println("" + this + " messageToAllPlayersOnShip: " + msg); - for (MovingEntity me : entitiesOnShip) { - if (me.entity instanceof EntityPlayer) { - ((EntityPlayer)me.entity).addChatMessage("[" + ((reactor != null && reactor.coreFrequency.length() > 0) ? reactor.coreFrequency : "WarpCore") + "] " + msg); - } - } + public void lockWorlds() + { + System.out.println("[JE@" + this + "] Locking worlds..."); + targetWorld.isRemote = true; + + // When warping between dimensions is need to lock both worlds + if (targetWorld.provider.dimensionId != worldObj.provider.dimensionId) + { + worldObj.isRemote = true; } } - public static String getDirectionLabel(int direction) { - switch (direction) { - case -1: return "UP"; - case -2: return "DOWN"; - case 0: return "FRONT"; - case 180: return "BACK"; - case 90: return "LEFT"; - case 255: return "RIGHT"; - default: return direction + " degrees"; + public void unlockWorlds() + { + System.out.println("[JE@" + this + "] Unlocking worlds.."); + targetWorld.isRemote = false; + + if (targetWorld.provider.dimensionId != worldObj.provider.dimensionId) + { + worldObj.isRemote = false; } } - - private void prepareToJump() { - StringBuilder reason = new StringBuilder(); + public void messageToAllPlayersOnShip(String msg) + { + if (entitiesOnShip != null) + for (MovingEntity me : entitiesOnShip) + if (me.entity instanceof EntityPlayer) + ((EntityPlayer)me.entity).addChatMessage("[WarpCore] " + msg); + } + + public void prepareToJump() + { LocalProfiler.start("EntityJump.prepareToJump"); - boolean isInSpace = (worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID); - boolean isInHyperSpace = (worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID); + isInHyperSpace = (worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID); + toSpace = (dir == -1 && (maxY + distance > 255) && worldObj.provider.dimensionId == 0); + fromSpace = (dir == -2 && (minY - distance < 0) && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID); + betweenWorlds = fromSpace || toSpace || toHyperSpace || fromHyperSpace; - boolean toSpace = (direction == -1) && (maxY + distance > 255) && (!isInSpace) && (!isInHyperSpace); - boolean fromSpace = (direction == -2) && (minY - distance < 0) && isInSpace; - betweenWorlds = fromSpace || toSpace || isHyperspaceJump; - moveX = moveY = moveZ = 0; - - TransitionPlane overworld = new TransitionPlane(0, 0, 0, 5000, 5000, 0, 0); - Vector3 exit; //FIXME - if (toSpace) { - if (worldObj.provider.dimensionId == overworld.dimensionId) { - if (!overworld.isValidToSpace(new Vector3(this))) {// invalid transition, cancel transition - LocalProfiler.stop(); - String msg = "Ship is outside worldborder, unable to transition to space!"; - messageToAllPlayersOnShip(msg); - killEntity(msg); - return; - } - moveX = overworld.spaceCenterX - overworld.dimensionCenterX; - moveZ = overworld.spaceCenterZ - overworld.dimensionCenterZ; - } else { - moveX = 0; - moveZ = 0; - } - targetWorld = DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID); - } else if (fromSpace) { - if (!overworld.isValidFromSpace(new Vector3(this))) {// invalid transition, cancel transition - LocalProfiler.stop(); - String msg = "Ship is outside worldborder, unable to transition from space!"; - messageToAllPlayersOnShip(msg); - killEntity(msg); - return; - } - moveX = overworld.dimensionCenterX - overworld.spaceCenterX; - moveZ = overworld.dimensionCenterZ - overworld.spaceCenterZ; - targetWorld = DimensionManager.getWorld(0); - } else if (isHyperspaceJump && isInHyperSpace) { - targetWorld = DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID); - } else if (isHyperspaceJump && isInSpace) { - targetWorld = DimensionManager.getWorld(WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID); - } else { - targetWorld = worldObj; + if (toSpace || fromHyperSpace) + { + targetWorld = DimensionManager.getWorld(WarpDrive.instance.spaceDimID); } + else if (fromSpace) + { + targetWorld = DimensionManager.getWorld(0); + } + else if (toHyperSpace) + { + targetWorld = DimensionManager.getWorld(WarpDrive.instance.hyperSpaceDimID); + } + else + { + targetWorld = this.worldObj; + } + + axisalignedbb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); // FIXME //turnOffModems(); // Calculate jump vector - if (isCoordJump) { + if (isCoordJump) + { moveX = destX - xCoord; moveZ = destZ - zCoord; moveY = destY - yCoord; - distance = 0; // FIXME: check collision in straight path, starting with getPossibleJumpDistance() ? - } else if (isHyperspaceJump) { distance = 0; - } else { - if (toSpace) { - // enter space at current altitude - moveY = 0; - } else if (fromSpace) { - // re-enter atmosphere at max altitude - moveY = 245 - maxY; - } else { + } + else if (toHyperSpace || fromHyperSpace) + { + moveX = moveY = moveZ = 0; + distance = 0; + } + else + { + if (betweenWorlds) + { + moveX = moveY = 0; + + if (fromSpace) + { + moveY = 245 - maxY; + } + + if (toSpace) + { + moveY = 0; + } + } + else + { // Do not check in long jumps - if (distance < 256) { + if (distance < 256) + { distance = getPossibleJumpDistance(); } - int movementVector[] = getVector(direction); + if (distance <= shipLength) + { + killEntity("Not enough space for jump."); + messageToAllPlayersOnShip("Not enough space for jump!"); + LocalProfiler.stop(); + return; + } + + int movementVector[] = getVector(dir); moveX = movementVector[0] * distance; moveY = movementVector[1] * distance; moveZ = movementVector[2] * distance; - if ((maxY + moveY) > 255) { + if ((maxY + moveY) > 255) + { moveY = 255 - maxY; } - if ((minY + moveY) < 5) { + if ((minY + moveY) < 5) + { moveY = 5 - minY; } } } - if (betweenWorlds) { - WarpDrive.debugPrint("" + this + " Worlds: " + worldObj.provider.getDimensionName() + " -> " + targetWorld.provider.getDimensionName()); + if (betweenWorlds) + { + System.out.println("[JE] Worlds: " + worldObj.provider.getDimensionName() + " -> " + targetWorld.provider.getDimensionName()); } - - // Validate positions aren't overlapping - if (!betweenWorlds) { - if ( Math.abs(moveX) <= (maxX - minX + 1) && Math.abs(moveY) <= (maxY - minY + 1) && Math.abs(moveZ) <= (maxZ - minZ + 1) ) { - // render fake explosions - doCollisionDamage(false); - // cancel jump - LocalProfiler.stop(); - String msg = "Not enough space for jump!"; - messageToAllPlayersOnShip(msg); - killEntity(msg); - return; + forceChunks(); + lockWorlds(); + saveEntities(axisalignedbb); + System.out.println("[JE] Saved " + entitiesOnShip.size() + " entities from ship"); + + if (!isCoordJump && !(toHyperSpace || fromHyperSpace)) + { + if (dir != -2 && dir != -1) + { + messageToAllPlayersOnShip("Jumping in direction " + dir + " degrees to distance " + distance + " blocks "); + } + else if (dir == -1) + { + messageToAllPlayersOnShip("Jumping UP to distance " + distance + " blocks "); + } + else if (dir == -2) + { + messageToAllPlayersOnShip("Jumping DOWN to distance " + distance + " blocks "); } } - - if (!forceChunks(reason)) { - String msg = reason.toString(); - killEntity(msg); - messageToAllPlayersOnShip(msg); - LocalProfiler.stop(); - return; - } -// lockWorlds(); - saveEntities(); - WarpDrive.debugPrint("" + this + " Saved " + entitiesOnShip.size() + " entities from ship"); - - if (isHyperspaceJump && isInSpace) { + else if (toHyperSpace) + { messageToAllPlayersOnShip("Entering HYPERSPACE..."); - } else if (isHyperspaceJump && isInHyperSpace) { - messageToAllPlayersOnShip("Leaving HYPERSPACE.."); - } else if (isCoordJump) { - messageToAllPlayersOnShip("Jumping to coordinates (" + destX + "; " + yCoord + "; " + destZ + ")!"); - } else { - messageToAllPlayersOnShip("Jumping " + getDirectionLabel(direction) + " by " + distance + " blocks"); + } + else if (fromHyperSpace) + { + messageToAllPlayersOnShip("Leaving HYPERSPACE"); + } + else if (isCoordJump) + { + messageToAllPlayersOnShip("Jumping by coordinates to (" + destX + "; " + yCoord + "; " + destZ + ")!"); } - // validate ship content - int shipVolume = getRealShipVolume_checkBedrock(reason); - if (shipVolume == -1) { - String msg = reason.toString(); - killEntity(msg); - messageToAllPlayersOnShip(msg); + bedrockOnShip = false; + int shipSize = getRealShipSize(); // sets bedrockOnShip + + if (bedrockOnShip) + { + killEntity("Bedrock is on the ship. Aborting."); + messageToAllPlayersOnShip("Bedrock is on the ship. Aborting."); LocalProfiler.stop(); return; } - saveShip(shipVolume); + saveShip(shipSize); this.currentIndexInShip = 0; msCounter = System.currentTimeMillis(); LocalProfiler.stop(); - WarpDrive.debugPrint("Removing TE duplicates: tileEntities in target world before jump: " + targetWorld.loadedTileEntityList.size()); + System.out.println("Removing TE duplicates. Size before jump: " + targetWorld.loadedTileEntityList.size()); } /** * Finish jump: move entities, unlock worlds and delete self */ - private void finishJump() { - WarpDrive.debugPrint("" + this + " Jump done in " + ((System.currentTimeMillis() - msCounter) / 1000F) + " seconds and " + ticks + " ticks"); + public void finishJump() + { + System.out.println("[JE] Finished. Jump took " + ((System.currentTimeMillis() - msCounter) / 1000F) + " seconds"); //FIXME TileEntity duplication workaround - WarpDrive.debugPrint("Removing TE duplicates: tileEntities in target world after jump, before cleanup: " + targetWorld.loadedTileEntityList.size()); + System.out.println("Removing TE duplicates. Size before: " + targetWorld.loadedTileEntityList.size()); LocalProfiler.start("EntityJump.removeDuplicates()"); - try { + try + { targetWorld.loadedTileEntityList = this.removeDuplicates(targetWorld.loadedTileEntityList); - } catch (Exception e) { - WarpDrive.debugPrint("TE Duplicates removing exception: " + e.getMessage()); } - FixASTurbines(); - doCollisionDamage(true); + catch (Exception e) + { + System.out.println("TE Duplicates removing exception: " + e.getMessage()); + } LocalProfiler.stop(); - WarpDrive.debugPrint("Removing TE duplicates: tileEntities in target world after jump, after cleanup: " + targetWorld.loadedTileEntityList.size()); - killEntity("Jump done"); + System.out.println("Removing TE duplicates. Size after: " + targetWorld.loadedTileEntityList.size()); + killEntity(""); } /** * Removing ship from world * */ - private void removeShip() { + public void removeShip() + { LocalProfiler.start("EntityJump.removeShip"); int blocksToMove = Math.min(BLOCKS_PER_TICK, ship.length - currentIndexInShip); - WarpDrive.debugPrint("" + this + " Removing ship blocks " + currentIndexInShip + " to " + (currentIndexInShip + blocksToMove - 1) + " / " + (ship.length - 1)); + System.out.println("[JE] Removing ship part: " + currentIndexInShip + "/" + ship.length + " [btm: " + blocksToMove + "]"); TileEntity te; Class c; - for (int index = 0; index < blocksToMove; index++) { - if (currentIndexInShip >= ship.length) { + for (int index = 0; index < blocksToMove; index++) + { + if (currentIndexInShip >= ship.length) break; - } - JumpBlock jb = ship[ship.length - currentIndexInShip - 1]; - if (jb == null) { - WarpDrive.debugPrint("" + this + " Removing ship part: unexpected null found at ship[" + currentIndexInShip + "]"); - currentIndexInShip++; - continue; - } - - if (jb.blockTileEntity != null) { - // WarpDrive.debugPrint("Removing tile entity at " + jb.x + ", " + jb.y + ", " + jb.z); + JumpBlock jb = ship[currentIndexInShip]; + if (jb != null && jb.blockTileEntity != null) worldObj.removeBlockTileEntity(jb.x, jb.y, jb.z); - } - worldObj.setBlock(jb.x, jb.y, jb.z, 0, 0, 2); - - te = targetWorld.getBlockTileEntity(jb.x + moveX, jb.y + moveY, jb.z + moveZ); - if (te != null) { + te = worldObj.getBlockTileEntity(jb.x + moveX, jb.y + moveY, jb.z + moveZ); + if (te != null) + { c = te.getClass(); - if (c.getName().equals("atomicscience.jiqi.TTurbine")) { + if (c.getName().equals("atomicscience.jiqi.TTurbine")) try { if (c.getField("shiDa").getBoolean(te)) @@ -524,36 +508,27 @@ public class EntityJump extends Entity { e.printStackTrace(); } - } else if (te instanceof TileEntityReactor) { - WarpDrive.instance.warpCores.removeFromRegistry((TileEntityReactor)te); - } - c = c.getSuperclass(); - if (c.getName().equals("ic2.core.block.wiring.TileEntityElectricBlock") || c.getName().equals("ic2.core.block.TileEntityBlock") || c.getName().contains("ic2.core.block.generator")) { + if (c.getName().equals("ic2.core.block.wiring.TileEntityElectricBlock") || c.getName().equals("ic2.core.block.TileEntityBlock") || c.getName().contains("ic2.core.block.generator")) + { try { Method method; - method = c.getDeclaredMethod("onUnloaded", (Class[])null); - method.invoke(te, (Object[])null); - method = c.getDeclaredMethod("onLoaded", (Class[])null); - method.invoke(te, (Class)null); - } - catch (Exception e) - { - e.printStackTrace(); + method = c.getDeclaredMethod("onUnloaded", null); + method.invoke(te, null); + method = c.getDeclaredMethod("onLoaded", null); + method.invoke(te, null); } + catch (Exception e) {} te.updateContainingBlockInfo(); try { NetworkHelper.updateTileEntityField(te, "facing"); } - catch (Exception e) - { - e.printStackTrace(); - } + catch (Exception e) {} } } - + worldObj.setBlockToAir(jb.x, jb.y, jb.z); currentIndexInShip++; } LocalProfiler.stop(); @@ -564,12 +539,14 @@ public class EntityJump extends Entity * * @param shipSize */ - private void saveShip(int shipSize) { + public void saveShip(int shipSize) + { LocalProfiler.start("EntityJump.saveShip"); ship = new JumpBlock[shipSize]; - if (ship == null) { - killEntity("Unable to allocate memory (ship is null!)"); + if (ship == null) + { + killEntity("ship is null!"); LocalProfiler.stop(); return; } @@ -599,7 +576,7 @@ public class EntityJump extends Entity int blockID = worldObj.getBlockId(x, y, z); // Skip air blocks - if (worldObj.isAirBlock(x, y, z) && (blockID != WarpDriveConfig.airID)) + if (blockID == 0 || blockID == WarpDriveConfig.i.gasID) { continue; } @@ -607,11 +584,6 @@ public class EntityJump extends Entity int blockMeta = worldObj.getBlockMetadata(x, y, z); TileEntity tileentity = worldObj.getBlockTileEntity(x, y, z); ship[index] = new JumpBlock(blockID, blockMeta, tileentity, x, y, z); - if (ship[index] == null) - { - WarpDrive.debugPrint("" + this + " Unable to allocate memory (ship[" + index + "] is null!)"); - } - index++; } } @@ -619,20 +591,23 @@ public class EntityJump extends Entity } } - WarpDrive.debugPrint("" + this + " Ship saved as " + ship.length + " blocks"); + System.out.println((new StringBuilder()).append("[JUMP] Ship saved: ").append((new StringBuilder()).append(ship.length).append(" blocks")).toString()); LocalProfiler.stop(); } /** *Ship moving */ - private void moveShip() { + public void moveShip() + { LocalProfiler.start("EntityJump.moveShip"); int blocksToMove = Math.min(BLOCKS_PER_TICK, ship.length - currentIndexInShip); - WarpDrive.debugPrint("" + this + " Moving ship blocks " + currentIndexInShip + " to " + (currentIndexInShip + blocksToMove - 1) + " / " + (ship.length - 1)); + System.out.println("[JE] Moving ship part: " + currentIndexInShip + "/" + ship.length + " [btm: " + blocksToMove + "]"); - for (int index = 0; index < blocksToMove; index++) { - if (currentIndexInShip >= ship.length) { + for (int index = 0; index < blocksToMove; index++) + { + if (currentIndexInShip >= ship.length) + { break; } @@ -648,199 +623,80 @@ public class EntityJump extends Entity * * @return possible jump distance or -1 */ - private int getPossibleJumpDistance() { - WarpDrive.debugPrint("" + this + " Calculating possible jump distance..."); + public int getPossibleJumpDistance() + { + System.out.println("[JUMP] Calculating possible jump distance..."); int testDistance = this.distance; int blowPoints = 0; - collisionDetected = false; - - CheckMovementResult result = null; - while (testDistance >= 0) { - // Is there enough space in destination point? - result = checkMovement(testDistance, false); - if (result == null) { + while (testDistance >= 0) + { + // Is there enough space in destination point? + boolean canJump = checkMovement(testDistance); + + if (canJump) + { break; } - - if (result.isCollision) { - blowPoints++; - } + + blowPoints++; testDistance--; } - - if (distance != testDistance) { - WarpDrive.debugPrint("" + this + " Jump distance adjusted to " + testDistance + " after " + blowPoints + " collisions"); - } - // Register explosion(s) at collision point - if (blowPoints > WarpDriveConfig.WC_COLLISION_TOLERANCE_BLOCKS) { - result = checkMovement(Math.max(1, testDistance + 1), true); - if (result != null) { - /* - * Strength scaling: - * Creeper = 3 or 6 - * Wither skull = 1 - * Wither boom = 5 - * Endercrystal = 6 - * TNTcart = 4 to 11.5 - * TNT = 4 - */ - float massCorrection = 0.5F + (float)Math.sqrt( - Math.min(1.0D, Math.max(0.0D, reactor.shipVolume - WarpDriveConfig.WC_MAX_SHIP_VOLUME_ON_SURFACE) / WarpDriveConfig.WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE)); - collisionDetected = true; - collisionStrength = (4.0F + blowPoints - WarpDriveConfig.WC_COLLISION_TOLERANCE_BLOCKS) * massCorrection; - collisionAtSource = result.atSource; - collisionAtTarget = result.atTarget; - WarpDrive.debugPrint("" + this + " Reporting " + collisionAtTarget.size() + " collisions coordinates " - + blowPoints + " blowPoints with massCorrection of " + String.format("%.2f", massCorrection) + " => strength " + String.format("%.2f", collisionStrength) ); - } else { - System.out.println("WarpDrive error: unable to compute collision points, ignoring..."); - } + // Make an explosion in collision point + if (blowPoints > 5 && (this.dir != -1 && this.dir != -2)) + { + messageToAllPlayersOnShip(" [COLLISION] at (" + blowX + "; " + blowY + "; " + blowZ + ")"); + worldObj.createExplosion((Entity) null, blowX, blowY, blowZ, Math.min(4F * 30, 4F * (distance / 2)), true); } return testDistance; } - - private void doCollisionDamage(boolean atTarget) { - if (!collisionDetected) { - WarpDrive.debugPrint("" + this + " doCollisionDamage No collision detected..."); - return; - } - ArrayList collisionPoints = atTarget ? collisionAtTarget : collisionAtSource; - Vector3 min = collisionPoints.get(0); - Vector3 max = collisionPoints.get(0); - for (Vector3 v : collisionPoints) { - if (min.x > v.x) { - min.x = v.x; - } else if (max.x < v.x) { - max.x = v.x; - } - if (min.y > v.y) { - min.y = v.y; - } else if (max.y < v.y) { - max.y = v.y; - } - if (min.z > v.z) { - min.z = v.z; - } else if (max.z < v.z) { - max.z = v.z; - } - } - - // inform players on board - double rx = Math.round(min.x + worldObj.rand.nextInt( Math.max(1, (int) (max.x - min.x)) )); - double ry = Math.round(min.y + worldObj.rand.nextInt( Math.max(1, (int) (max.y - min.y)) )); - double rz = Math.round(min.z + worldObj.rand.nextInt( Math.max(1, (int) (max.z - min.z)) )); -// WarpDrive.debugPrint("doCollisionDamage msg " + rx + ", " + ry + ", " + rz + " atTarget " + atTarget + " min " + min + " max " + max); - messageToAllPlayersOnShip("Ship collision detected around " + (int)rx + ", " + (int)ry + ", " + (int)rz + ". Damage report pending..."); - - // randomize if too many collision points - int nbExplosions = Math.min(5, collisionPoints.size()); - WarpDrive.debugPrint("doCollisionDamage nbExplosions " + nbExplosions + "/" + collisionPoints.size()); - for (int i = 0; i < nbExplosions; i++) { - // get location - Vector3 current; - if (nbExplosions < collisionPoints.size()) { - WarpDrive.debugPrint("doCollisionDamage random #" + i); - current = collisionPoints.get(worldObj.rand.nextInt(collisionPoints.size())); - } else { - WarpDrive.debugPrint("doCollisionDamage get " + i); - current = collisionPoints.get(i); - } - - // compute explosion strength with a jitter, at least 1 TNT - float strength = Math.max(4.0F, collisionStrength / nbExplosions - 2.0F + 2.0F * worldObj.rand.nextFloat()); - - (atTarget ? targetWorld : worldObj).newExplosion((Entity) null, current.x, current.y, current.z, strength, atTarget, atTarget); - WarpDrive.debugPrint("doCollisionDamage explosion at " + current.x + ", " + current.y + ", " + current.z + " with strength " + strength); - } - } - private int getRealShipVolume_checkBedrock(StringBuilder reason) { - LocalProfiler.start("EntityJump.getRealShipVolume_checkBedrock"); - int shipVolume = 0; - - for (int x = minX; x <= maxX; x++) { - for (int z = minZ; z <= maxZ; z++) { - for (int y = minY; y <= maxY; y++) { - int blockID = worldObj.getBlockId(x, y, z); - - // Skipping vanilla air & WarpDrive gas blocks, keep WarpDrive air block - if (worldObj.isAirBlock(x, y, z) && (blockID != WarpDriveConfig.airID)) {// whitelist - continue; - } - - shipVolume++; - - /* - Item item = Item.itemsList[blockID]; - if (item == null) - WarpDrive.debugPrint("Block(" + x + ", " + y + ", " + z + ") is undefined#" + blockID + ":" + worldObj.getBlockMetadata(x, y, z)); - else - WarpDrive.debugPrint("Block(" + x + ", " + y + ", " + z + ") is " + item.getUnlocalizedName() + ":" + worldObj.getBlockMetadata(x, y, z)); - /**/ - - if ((blockID == Block.bedrock.blockID) || (blockID == 2702)) {// Blacklist - reason.append("Bedrock detected onboard at " + x + ", " + y + ", " + z + ". Aborting."); - LocalProfiler.stop(); - return -1; - } - } - } - } - - // Lem: abort jump if blocks with TE are connecting to the ship (avoid crash when splitting multi-blocks) - for (int x = minX - 1; x <= maxX + 1; x++) { - boolean xBorder = (x == minX - 1) || (x == maxX + 1); - for (int z = minZ - 1; z <= maxZ + 1; z++) { - boolean zBorder = (z == minZ - 1) || (z == maxZ + 1); - for (int y = minY - 1; y <= maxY + 1; y++) { - boolean yBorder = (y == minY - 1) || (y == maxY + 1); - if ((y < 0) || (y > 255)) - continue; - if (!(xBorder || yBorder || zBorder)) - continue; + public int getRealShipSize() + { + LocalProfiler.start("EntityJump.getRealShipSize"); + int shipSize = 0; + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + for (int y = minY; y <= maxY; y++) + { int blockID = worldObj.getBlockId(x, y, z); // Skipping air blocks - if (worldObj.isAirBlock(x, y, z)) { + if (blockID == 0 || blockID == WarpDriveConfig.i.gasID) + { continue; } - // Skipping unmovable blocks - if ((blockID == Block.bedrock.blockID) || (blockID == 2702)) {// Blacklist - continue; + shipSize++; + + if (blockID == Block.bedrock.blockID) + { + bedrockOnShip = true; + LocalProfiler.stop(); + return shipSize; } - - TileEntity te = worldObj.getBlockTileEntity(x, y, z); - if (te == null) { - continue; - } - - reason.append("Ship snagged at " + x + ", " + y + ", " + z + ". Damage report pending..."); - worldObj.createExplosion((Entity) null, x, y, z, Math.min(4F * 30, 4F * (shipVolume / 50)), false); - LocalProfiler.stop(); - return -1; } } } LocalProfiler.stop(); - return shipVolume; + return shipSize; } - - private void saveEntities() { + public void saveEntities(AxisAlignedBB axisalignedbb) + { entitiesOnShip = new ArrayList(); - - AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX + 0.99D, maxY + 0.99D, maxZ + 0.99D); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); - - for (Object o : list) { - if (o == null || !(o instanceof Entity) || (o instanceof EntityJump)) { + + for (Object o : list) + { + if (o == null || !(o instanceof Entity) || (o instanceof EntityJump)) + { continue; } @@ -849,17 +705,19 @@ public class EntityJump extends Entity entitiesOnShip.add(movingEntity); } } - - private boolean moveEntities(boolean restorePositions) { - WarpDrive.debugPrint("" + this + " Moving entities"); - LocalProfiler.start("EntityJump.moveEntities"); + public boolean moveEntities(boolean restorePositions) + { + System.out.println("[JE] Moving entities"); - if (entitiesOnShip != null) { - for (MovingEntity me : entitiesOnShip) { + if (entitiesOnShip != null) + { + for (MovingEntity me : entitiesOnShip) + { Entity entity = me.entity; - if (entity == null) { + if (entity == null) + { continue; } @@ -870,43 +728,48 @@ public class EntityJump extends Entity double newEntityY; double newEntityZ; - if (restorePositions) { + if (restorePositions) + { newEntityX = oldEntityX; newEntityY = oldEntityY; newEntityZ = oldEntityZ; - } else { + } + else + { newEntityX = oldEntityX + moveX; newEntityY = oldEntityY + moveY; newEntityZ = oldEntityZ + moveZ; } - //WarpDrive.debugPrint("Entity moving: old (" + oldEntityX + " " + oldEntityY + " " + oldEntityZ + ") -> new (" + newEntityX + " " + newEntityY + " " + newEntityZ); + //System.out.println("Entity moving: old (" + oldEntityX + " " + oldEntityY + " " + oldEntityZ + ") -> new (" + newEntityX + " " + newEntityY + " " + newEntityZ); // Travel to another dimension if needed - if (betweenWorlds && !restorePositions) { + if (betweenWorlds && !restorePositions) + { MinecraftServer server = MinecraftServer.getServer(); WorldServer from = server.worldServerForDimension(worldObj.provider.dimensionId); WorldServer to = server.worldServerForDimension(targetWorld.provider.dimensionId); SpaceTeleporter teleporter = new SpaceTeleporter(to, 0, MathHelper.floor_double(newEntityX), MathHelper.floor_double(newEntityY), MathHelper.floor_double(newEntityZ)); - if (entity instanceof EntityPlayerMP) { + if (entity instanceof EntityPlayerMP) + { EntityPlayerMP player = (EntityPlayerMP) entity; server.getConfigurationManager().transferPlayerToDimension(player, targetWorld.provider.dimensionId, teleporter); - } else { + } + else + { server.getConfigurationManager().transferEntityToWorld(entity, worldObj.provider.dimensionId, from, to, teleporter); } } // Update position - if (entity instanceof EntityPlayerMP) { + if (entity instanceof EntityPlayerMP) + { EntityPlayerMP player = (EntityPlayerMP) entity; + ChunkCoordinates bedLocation = player.getBedLocation(); - ChunkCoordinates bedLocation = player.getBedLocation(player.worldObj.provider.dimensionId); - - if (bedLocation != null - && minX <= bedLocation.posX && maxX >= bedLocation.posX - && minY <= bedLocation.posY && maxY >= bedLocation.posY - && minZ <= bedLocation.posZ && maxZ >= bedLocation.posZ) { + if (bedLocation != null && testBB(axisalignedbb, bedLocation.posX, bedLocation.posY, bedLocation.posZ)) + { bedLocation.posX = bedLocation.posX + moveX; bedLocation.posY = bedLocation.posY + moveY; bedLocation.posZ = bedLocation.posZ + moveZ; @@ -914,17 +777,21 @@ public class EntityJump extends Entity } player.setPositionAndUpdate(newEntityX, newEntityY, newEntityZ); - } else { + } + else + { entity.setPosition(newEntityX, newEntityY, newEntityZ); } } } - LocalProfiler.stop(); return true; } - + public boolean testBB(AxisAlignedBB axisalignedbb, int x, int y, int z) + { + return axisalignedbb.minX <= (double) x && axisalignedbb.maxX >= (double) x && axisalignedbb.minY <= (double) y && axisalignedbb.maxY >= (double) y && axisalignedbb.minZ <= (double) z && axisalignedbb.maxZ >= (double) z; + } public int[] getVector(int i) { @@ -966,92 +833,76 @@ public class EntityJump extends Entity return v; } - class CheckMovementResult { - public ArrayList atSource; - public ArrayList atTarget; - public boolean isCollision = false; - public String reason = ""; - - CheckMovementResult() { - this.atSource = new ArrayList(1); - this.atTarget = new ArrayList(1); - this.isCollision = false; - this.reason = "Unknown reason"; - } - - public void add(double sx, double sy, double sz, double tx, double ty, double tz, boolean pisCollision, String preason) { - atSource.add(new Vector3(sx, sy, sz)); - atTarget.add(new Vector3(tx, ty, tz)); - isCollision = isCollision || pisCollision; - reason = preason; - WarpDrive.debugPrint("CheckMovementResult " + sx + ", " + sy + ", " + sz + " -> " + tx + ", " + ty + ", " + tz + " " + isCollision + " '" + reason + "'"); - } - }; - private CheckMovementResult checkMovement(int testDistance, boolean fullCollisionDetails) { - CheckMovementResult result = new CheckMovementResult(); - if ((direction == -1 && maxY + testDistance > 255) && !betweenWorlds) { - result.add(xCoord, maxY + testDistance, zCoord, xCoord + 0.5D, maxY + testDistance + 1.0D, zCoord + 0.5D, - false, "Reactor will blow due +high limit"); - return result; + public boolean checkMovement(int testDistance) + { + if ((dir == -1 && maxY + testDistance > 255) && !toSpace) + { + System.out.println("[JUMP] Reactor will blow due +high limit"); + return false; } - if ((direction == -2 && minY - testDistance <= 8) && !betweenWorlds) { - result.add(xCoord, minY - testDistance, zCoord, xCoord + 0.5D, maxY - testDistance, zCoord + 0.5D, - false, "Reactor will blow due -low limit"); - return result; + if ((dir == -2 && minY - testDistance <= 8) && !fromSpace) + { + blowY = minY - testDistance; + blowX = xCoord; + blowZ = zCoord; + System.out.println("[JUMP] Reactor will blow due -low limit"); + return false; } - int movementVector[] = getVector(direction); - int lmoveX = movementVector[0] * testDistance; - int lmoveY = movementVector[1] * testDistance; - int lmoveZ = movementVector[2] * testDistance; - - int x, y, z, newX, newY, newZ, blockOnShipID, blockID; - for (y = minY; y <= maxY; y++) { - newY = y + lmoveY; - for (x = minX; x <= maxX; x++) { - newX = x + lmoveX; - for (z = minZ; z <= maxZ; z++) { - newZ = z + lmoveZ; + int movementVector[] = getVector(dir); + // TODO: Disasm, plz fix it. Local variable hiding class global field + int moveX = movementVector[0] * testDistance; + int moveY = movementVector[1] * testDistance; + int moveZ = movementVector[2] * testDistance; - blockID = worldObj.getBlockId(newX, newY, newZ); - if ((blockID == Block.bedrock.blockID) || (blockID == 2702)) {// Blacklist - result.add(x, y, z, - newX + 0.5D - movementVector[0] * 1.0D, - newY + 0.5D - movementVector[1] * 1.0D, - newZ + 0.5D - movementVector[2] * 1.0D, - true, "Unpassable block " + blockID + " detected at destination (" + newX + ";" + newY + ";" + newZ + ")"); - if (!fullCollisionDetails) { - return result; - } + for (int y = minY; y <= maxY; y++) + { + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + int newX = x + moveX; + int newY = y + moveY; + int newZ = z + moveZ; + + if (isBlockInShip(newX, newY, newZ)) + { + continue; } - blockOnShipID = worldObj.getBlockId(x, y, z); - if (blockOnShipID != 0 && blockID != 0 && blockID != WarpDriveConfig.airID && blockID != WarpDriveConfig.gasID && blockID != 18) { - result.add(x, y, z, - newX + 0.5D + movementVector[0] * 0.1D, - newY + 0.5D + movementVector[1] * 0.1D, - newZ + 0.5D + movementVector[2] * 0.1D, - true, "Obstacle block #" + blockID + " detected at (" + newX + ", " + newY + ", " + newZ + ")"); - if (!fullCollisionDetails) { - return result; - } + int blockID = worldObj.getBlockId(newX, newY, newZ); + int blockOnShipID = worldObj.getBlockId(x, y, z); + + if (blockOnShipID == Block.bedrock.blockID) + { + return false; + } + + if (blockOnShipID != 0 && blockID != 0 && blockID != WarpDriveConfig.i.airID && blockID != WarpDriveConfig.i.gasID && blockID != 18) + { + blowX = x; + blowY = y; + blowZ = z; + System.out.println((new StringBuilder()).append("[JUMP] Reactor will blow due BlockID ").append((new StringBuilder()).append(blockID).append(" at (").append(newX).append(";").append(newY).append(";").append(newZ).append(")").toString()).toString()); + return false; } } } } - if (fullCollisionDetails && result.isCollision) { - return result; - } else { - return null; - } + return true; } -/* + + public boolean isBlockInShip(int x, int y, int z) + { + return x >= minX && x <= maxX && y >= minY && y <= maxY && z >= minZ && z <= maxZ; + } + private void turnOffModem(IPeripheral p) { // FIXME - if (p.getType() == "modem") { + /*if (p.getType() == "modem") { String[] methods = p.getMethodNames(); for(int i = 0; i < methods.length; i++) { if (methods[i] == "closeAll") { @@ -1063,17 +914,17 @@ public class EntityJump extends Entity return; } } - } + }*/ } private void turnOffModems() { // FIXME - for (int x = minX; x <= maxX; x++) { + /*for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { for (int y = minY; y <= maxY; y++) { int blockID = worldObj.getBlockId(x, y, z); - if (blockID == 0 || blockID == WarpDriveConfig.airID || blockID == WarpDriveConfig.gasID) { + if (blockID == 0 || blockID == WarpDriveConfig.i.airID || blockID == WarpDriveConfig.i.gasID) { continue; } @@ -1093,16 +944,17 @@ public class EntityJump extends Entity } } } - } - }/**/ + }*/ + } - private boolean moveBlockSimple(int indexInShip) + public boolean moveBlockSimple(int indexInShip) { try { JumpBlock shipBlock = ship[indexInShip]; - if (shipBlock == null) { + if (shipBlock == null) + { return false; } @@ -1117,42 +969,29 @@ public class EntityJump extends Entity mySetBlock(targetWorld, newX, newY, newZ, blockID, blockMeta, 2); // Re-schedule air blocks update - if (blockID == WarpDriveConfig.airID) { + if (blockID == WarpDriveConfig.i.airID) + { targetWorld.markBlockForUpdate(newX, newY, newZ); targetWorld.scheduleBlockUpdate(newX, newY, newZ, blockID, 40 + targetWorld.rand.nextInt(20)); } NBTTagCompound oldnbt = new NBTTagCompound(); - boolean unlockToValidate = false; - // 145 Anvil, 146 Trapped chest, 149 inactive redstone comparator, 156 Quartz stair, 159 Stained clay + if (shipBlock.blockTileEntity != null && blockID != 159 && blockID != 149 && blockID != 156 && blockID != 146 && blockID != 145) { shipBlock.blockTileEntity.writeToNBT(oldnbt); oldnbt.setInteger("x", newX); oldnbt.setInteger("y", newY); oldnbt.setInteger("z", newZ); - - if (oldnbt.hasKey("mainX") && oldnbt.hasKey("mainY") && oldnbt.hasKey("mainZ")) // Mekanism 6.0.4.44 - { - WarpDrive.debugPrint("[JUMP] moveBlockSimple: TileEntity from Mekanism detected"); - oldnbt.setInteger("mainX", oldnbt.getInteger("mainX") + moveX); - oldnbt.setInteger("mainY", oldnbt.getInteger("mainY") + moveY); - oldnbt.setInteger("mainZ", oldnbt.getInteger("mainZ") + moveZ); - unlockToValidate = true; - } else if (oldnbt.hasKey("id") && oldnbt.getString("id") == "savedMultipart") - { - WarpDrive.debugPrint("[JUMP] moveBlockSimple: TileEntity from Forge multipart detected at " + oldX + ", " + oldY + ", " + oldZ); - unlockToValidate = true; - } else { -// WarpDrive.debugPrint("[JUMP] moveBlockSimple: TileEntity from other detected"); - } TileEntity newTileEntity = null; - if (blockID == WarpDriveConfig.CC_Computer || blockID == WarpDriveConfig.CC_peripheral || blockID == WarpDriveConfig.CCT_Turtle || blockID == WarpDriveConfig.CCT_Upgraded || blockID == WarpDriveConfig.CCT_Advanced) + if (blockID == WarpDriveConfig.i.CC_Computer || blockID == WarpDriveConfig.i.CC_peripheral || blockID == WarpDriveConfig.i.CCT_Turtle || blockID == WarpDriveConfig.i.CCT_Upgraded || blockID == WarpDriveConfig.i.CCT_Advanced) { newTileEntity = TileEntity.createAndLoadEntity(oldnbt); newTileEntity.invalidate(); } - else if (blockID == WarpDriveConfig.AS_Turbine) + else if (blockID == WarpDriveConfig.i.GT_Machine) + newTileEntity = TileEntity.createAndLoadEntity(oldnbt); + else if (blockID == WarpDriveConfig.i.AS_Turbine) { if (oldnbt.hasKey("zhuYao")) { @@ -1164,22 +1003,19 @@ public class EntityJump extends Entity } newTileEntity = TileEntity.createAndLoadEntity(oldnbt); } - - if (newTileEntity == null) - newTileEntity = TileEntity.createAndLoadEntity(oldnbt); - - newTileEntity.worldObj = targetWorld; - if (unlockToValidate) - { -// targetWorld.isRemote = false; - newTileEntity.validate(); -// targetWorld.isRemote = true; - } else { - newTileEntity.validate(); + newTileEntity = targetWorld.getBlockTileEntity(newX, newY, newZ); + if (newTileEntity == null) + { + System.out.println("[EJ] Error moving tileEntity! TE is null"); + return false; + } + newTileEntity.invalidate(); + newTileEntity.readFromNBT(oldnbt); } - + newTileEntity.worldObj = targetWorld; + newTileEntity.validate(); worldObj.removeBlockTileEntity(oldX, oldY, oldZ); targetWorld.setBlockTileEntity(newX, newY, newZ, newTileEntity); } @@ -1187,14 +1023,13 @@ public class EntityJump extends Entity catch (Exception exception) { exception.printStackTrace(); - WarpDrive.debugPrint("[JUMP] moveBlockSimple exception Idx " + indexInShip); return false; } return true; } - private static ArrayList removeDuplicates(List l) + public ArrayList removeDuplicates(List l) { Set s = new TreeSet(new Comparator() { @@ -1203,7 +1038,7 @@ public class EntityJump extends Entity { if (o1.xCoord == o2.xCoord && o1.yCoord == o2.yCoord && o1.zCoord == o2.zCoord) { - WarpDrive.debugPrint("Removed duplicated TE: " + o1 + ", " + o2); + System.out.println("Removed duplicated TE: " + o1 + ", " + o2); return 0; } else @@ -1219,23 +1054,23 @@ public class EntityJump extends Entity @Override protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { - //WarpDrive.debugPrint("" + this + " readEntityFromNBT()"); + //System.out.println("[JE@"+this+"] readEntityFromNBT()"); } @Override protected void entityInit() { - //WarpDrive.debugPrint("" + this + " entityInit()"); + //System.out.println("[JE@"+this+"] entityInit()"); } @Override protected void writeEntityToNBT(NBTTagCompound var1) { - //WarpDrive.debugPrint("" + this + " writeEntityToNBT()"); + //System.out.println("[JE@"+this+"] writeEntityToNBT()"); } // Own implementation of setting blocks without light recalculation in optimization purposes - private boolean mySetBlock(World w, int x, int y, int z, int blockId, int blockMeta, int par6) + public boolean mySetBlock(World w, int x, int y, int z, int blockId, int blockMeta, int par6) { if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { @@ -1260,7 +1095,7 @@ public class EntityJump extends Entity } } - private boolean myChunkSBIDWMT(Chunk c, int x, int y, int z, int blockId, int blockMeta) + public boolean myChunkSBIDWMT(Chunk c, int x, int y, int z, int blockId, int blockMeta) { int j1 = z << 4 | x; @@ -1376,33 +1211,13 @@ public class EntityJump extends Entity try { c = t.getClass(); - Method method = c.getDeclaredMethod("bianDa", (Class[])null); - method.invoke(t, (Object[])null); - method.invoke(t, (Object[])null); + Method method = c.getDeclaredMethod("bianDa", null); + method.invoke(t, null); + method.invoke(t, null); } catch (Exception e) { e.printStackTrace(); } } - - public void setMinMaxes(int minXV,int maxXV,int minYV,int maxYV,int minZV,int maxZV) - { - minX = minXV; - maxX = maxXV; - minY = minYV; - maxY = maxYV; - minZ = minZV; - maxZ = maxZV; - } - - @Override - public String toString() { - return String.format("%s/%d \'%s\' @ \'%s\' %.2f, %.2f, %.2f", new Object[] { - getClass().getSimpleName(), - Integer.valueOf(entityId), - reactor == null ? "~NULL~" : reactor.coreFrequency, - worldObj == null ? "~NULL~" : worldObj.getWorldInfo().getWorldName(), - Double.valueOf(posX), Double.valueOf(posY), Double.valueOf(posZ)}); - } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/EntitySphereGen.java b/src/cr0s/WarpDrive/EntitySphereGen.java index 51127987..6c88825d 100644 --- a/src/cr0s/WarpDrive/EntitySphereGen.java +++ b/src/cr0s/WarpDrive/EntitySphereGen.java @@ -1,8 +1,13 @@ package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.Loader; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.util.ArrayList; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -11,35 +16,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -/* -2014-06-07 21:41:45 [Infos] [STDOUT] Generating star (class 0) at -579 257 1162 -2014-06-07 21:41:45 [Infos] [Minecraft-Client] [CHAT] /generate: generating star at -579, 257, 1162 -2014-06-07 21:41:45 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:41:45 [Infos] [STDOUT] [ESG] Saved 310248 blocks -2014-06-07 21:41:45 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 95.646ms, total: 95.646ms -2014-06-07 21:41:45 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:41:45 [Infos] [STDOUT] [ESG] Saved 23706 blocks -2014-06-07 21:41:45 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 15.427ms, total: 15.427ms -2014-06-07 21:42:03 [Infos] [STDOUT] Generating star (class 1) at -554 257 1045 -2014-06-07 21:42:03 [Infos] [Minecraft-Client] [CHAT] /generate: generating star at -554, 257, 1045 -2014-06-07 21:42:03 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:42:03 [Infos] [STDOUT] [ESG] Saved 1099136 blocks -2014-06-07 21:42:03 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 37.404ms, total: 37.404ms -2014-06-07 21:42:03 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:42:03 [Infos] [STDOUT] [ESG] Saved 50646 blocks -2014-06-07 21:42:03 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 34.369ms, total: 34.369ms - -2014-06-07 21:42:39 [Infos] [STDOUT] Generating star (class 2) at -404 257 978 -2014-06-07 21:42:39 [Infos] [Minecraft-Client] [CHAT] /generate: generating star at -404, 257, 978 -2014-06-07 21:42:39 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:42:39 [Infos] [STDOUT] [ESG] Saved 2144432 blocks -2014-06-07 21:42:39 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 85.523ms, total: 85.523ms -2014-06-07 21:42:39 [Infos] [STDOUT] [ESG] Saving blocks... -2014-06-07 21:42:40 [Infos] [STDOUT] [ESG] Saved 76699 blocks -2014-06-07 21:42:40 [Infos] [STDOUT] [PROF] {EntitySphereGen.saveSphereBlocks} self: 9.286ms, total: 9.286ms - - */ public final class EntitySphereGen extends Entity { public int xCoord; @@ -47,76 +24,77 @@ public final class EntitySphereGen extends Entity public int zCoord; private int radius; - private int[] defaultBlock; + private int[] block; + public int[] defaultBlock; private boolean hollow; - private boolean fillingSphere; // new sphere blocks does not replace existing blocks (for gases & moons) - private boolean generateOres; // generate random surface blocks (ores) or fixed blockID - private int gasColor; + private boolean fillingSphere; // new sphere blocks does not replace existing blocks (for gases) + private boolean surfaceSphere; // generate random surface blocks or fixed blockID - private final int BLOCKS_PER_TICK = 5000; + private final int BLOCKS_PER_TICK = 10000; private final int STATE_SAVING = 0; private final int STATE_SETUP = 1; - private final int STATE_DELETE = 2; - private final int STATE_STOP = 3; + private final int STATE_STOP = 2; + private final int STATE_DELETE = 3; private int state = STATE_DELETE; - private int ticksDelay = 0; private int currentIndex = 0; - private int pregenSize = 0; private ArrayList blocks; - public EntitySphereGen(World world) { + public EntitySphereGen(World world) + { super(world); +System.out.println("ZLO EntitySphereGen THE FUCK create"); } - public EntitySphereGen(World world, int x, int y, int z, int radius, int blockID, int blockMeta, boolean hollow, boolean fillingSphere, boolean generateOres) { + public EntitySphereGen(World world, int x, int y, int z, int radius, int blockID, int blockMeta, boolean hollow, boolean fillingSphere) + { super(world); this.xCoord = x; - this.posX = x; + this.posX = (double) x; this.yCoord = y; - this.posY = y; + this.posY = (double) y; this.zCoord = z; - this.posZ = z; + this.posZ = (double) z; this.radius = radius; this.hollow = hollow; this.fillingSphere = fillingSphere; - this.generateOres = generateOres; - this.gasColor = worldObj.rand.nextInt(12); + this.surfaceSphere = (blockID == 0); this.state = STATE_SAVING; - this.pregenSize = (int)Math.ceil(Math.PI * 4.0F / 3.0F * Math.pow(radius + 1, 3)); - blocks = new ArrayList(this.pregenSize); - this.defaultBlock = new int[] {blockID, blockMeta}; - this.ticksDelay = world.rand.nextInt(60); + blocks = new ArrayList(); + if (surfaceSphere) + defaultBlock = WarpDriveConfig.i.getDefaultSurfaceBlock(world.rand, world.rand.nextInt(10) > 8, true); + else + this.block = new int[] {blockID, blockMeta}; } - public void killEntity() { + public void killEntity() + { this.state = STATE_STOP; worldObj.removeEntity(this); } @Override - public void onUpdate() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public void onUpdate() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { return; } - - if (ticksDelay > 0) { - ticksDelay--; - return; - } - - switch (this.state) { + + switch (this.state) + { case STATE_SAVING: - tickScheduleBlocks(); + System.out.println("[ESG] Saving blocks..."); + saveSphereBlocks(); this.state = STATE_SETUP; break; case STATE_SETUP: if (currentIndex >= blocks.size() - 1) this.state = STATE_DELETE; else - tickPlaceBlocks(); + setupBlocksTick(); break; case STATE_DELETE: currentIndex = 0; @@ -125,12 +103,15 @@ public final class EntitySphereGen extends Entity } } - private void tickPlaceBlocks() { + private void setupBlocksTick() + { + LocalProfiler.start("EntitySphereGen.setupBlocksTick"); int blocksToMove = Math.min(BLOCKS_PER_TICK, blocks.size() - currentIndex); -// LocalProfiler.start("[EntitySphereGen] Placing blocks: " + currentIndex + "/" + blocks.size()); + System.out.println("[ESG] Setting up blocks: " + currentIndex + "/" + blocks.size() + " [bts: " + blocksToMove + "]"); int notifyFlag; - for (int index = 0; index < blocksToMove; index++) { + for (int index = 0; index < blocksToMove; index++) + { if (currentIndex >= blocks.size()) break; notifyFlag = (currentIndex % 1000 == 0 ? 2 : 0); @@ -139,105 +120,98 @@ public final class EntitySphereGen extends Entity currentIndex++; } -// LocalProfiler.stop(); + LocalProfiler.stop(); } - private void tickScheduleBlocks() { -// LocalProfiler.start("EntitySphereGen.tickScheduleBlocks"); + private void saveSphereBlocks() + { radius += 0.5D; // Radius from center of block double radiusSq = radius * radius; // Optimization to avoid square roots double radius1Sq = (radius - 1.0D) * (radius - 1.0D); // for hollow sphere int ceilRadius = (int) Math.ceil(radius); // Pass the cube and check points for sphere equation x^2 + y^2 + z^2 = r^2 - int[] block = defaultBlock; - for (int x = 0; x <= ceilRadius; x++) { - double x2 = (x + 0.5D) * (x + 0.5D); - for (int y = 0; y <= ceilRadius; y++) { - double y2 = (y + 0.5D) * (y + 0.5D); - for (int z = 0; z <= ceilRadius; z++) { - double z2 = (z + 0.5D) * (z + 0.5D); - double dSq = x2 + y2 + z2; // Distance from current position to center - + for (int x = 0; x <= ceilRadius; x++) + { + for (int y = 0; y <= ceilRadius; y++) + { + for (int z = 0; z <= ceilRadius; z++) + { + double dSq = lengthSq(x, y, z); // Distance from current position to center + // Skip too far blocks if (dSq > radiusSq) continue; // Hollow sphere condition - if ((hollow) && ((dSq < radius1Sq) || ((lengthSq(x + 1.5D, y + 0.5D, z + 0.5D) <= radiusSq) && (lengthSq(x + 0.5D, y + 1.5D, z + 0.5D) <= radiusSq) && (lengthSq(x + 0.5D, y + 0.5D, z + 1.5D) <= radiusSq)))) + if ((hollow) && ((dSq < radius1Sq) || ((lengthSq(x + 1, y, z) <= radiusSq) && (lengthSq(x, y + 1, z) <= radiusSq) && (lengthSq(x, y, z + 1) <= radiusSq)))) continue; - - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); // Add blocks to memory addBlock(new JumpBlock(block[0], block[1], xCoord + x, yCoord + y, zCoord + z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord - x, yCoord + y, zCoord + z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord + x, yCoord - y, zCoord + z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord + x, yCoord + y, zCoord - z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord - x, yCoord - y, zCoord + z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord + x, yCoord - y, zCoord - z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord - x, yCoord + y, zCoord - z)); - if (generateOres) - block = WarpDriveConfig.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); + if (surfaceSphere) + block = WarpDriveConfig.i.getRandomSurfaceBlock(worldObj.rand, defaultBlock[0], defaultBlock[1], true); addBlock(new JumpBlock(block[0], block[1], xCoord - x, yCoord - y, zCoord - z)); } } } - if (blocks != null) { - WarpDrive.debugPrint("[EntitySphereGen] Saved " + blocks.size() + " blocks (estimated to " + pregenSize + ")"); - } -// LocalProfiler.stop(); + if (blocks != null) + System.out.println("[ESG] Saved " + blocks.size() + " blocks"); } - private void addBlock(JumpBlock jb) { - if (blocks == null) - return; - // Replace water with random gas (ship in moon) - if (worldObj.getBlockId(jb.x, jb.y, jb.z) == Block.leaves.blockID) { - if (worldObj.rand.nextInt(50) != 1) - { - jb.blockID = WarpDriveConfig.gasID; - jb.blockMeta = gasColor; - } - blocks.add(jb); - return; - } - // Do not replace existing blocks if fillingSphere is true + private void addBlock(JumpBlock jb) + { + // Do not replace exitsting blocks if fillingSphere is true if (fillingSphere && !worldObj.isAirBlock(jb.x, jb.y, jb.z)) return; + if (blocks == null) + return; blocks.add(jb); } - private static double lengthSq(double x, double y, double z) { + private static double lengthSq(double x, double y, double z) + { return (x * x) + (y * y) + (z * z); } @Override - protected void readEntityFromNBT(NBTTagCompound tag) { + protected void readEntityFromNBT(NBTTagCompound tag) + { } @Override - protected void entityInit() { + protected void entityInit() + { } @Override - protected void writeEntityToNBT(NBTTagCompound tag) { + protected void writeEntityToNBT(NBTTagCompound tag) + { } - // Own implementation of setting blocks without light recalculation in optimization purposes - private static boolean mySetBlock(World w, int x, int y, int z, int blockId, int blockMeta, int par6) { - if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { + // Own implementation of setting blocks withow light recalculation in optimization purposes + public boolean mySetBlock(World w, int x, int y, int z, int blockId, int blockMeta, int par6) + { + if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) + { if (y < 0) return false; else if (y >= 256) @@ -245,12 +219,13 @@ public final class EntitySphereGen extends Entity w.markBlockForUpdate(x, y, z); Chunk chunk = w.getChunkFromChunkCoords(x >> 4, z >> 4); return myChunkSBIDWMT(chunk, x & 15, y, z & 15, blockId, blockMeta); - } else { - return false; } + else + return false; } - private static boolean myChunkSBIDWMT(Chunk c, int x, int y, int z, int blockId, int blockMeta) { + public boolean myChunkSBIDWMT(Chunk c, int x, int y, int z, int blockId, int blockMeta) + { int j1 = z << 4 | x; if (y >= c.precipitationHeightMap[j1] - 1) c.precipitationHeightMap[j1] = -999; @@ -290,9 +265,4 @@ public final class EntitySphereGen extends Entity c.isModified = true; return true; } - - @Override - public boolean shouldRenderInPass(int pass) { - return false; - } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/EntityStarCore.java b/src/cr0s/WarpDrive/EntityStarCore.java index 37513e4c..2831e553 100644 --- a/src/cr0s/WarpDrive/EntityStarCore.java +++ b/src/cr0s/WarpDrive/EntityStarCore.java @@ -6,7 +6,6 @@ import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; @@ -23,7 +22,6 @@ public final class EntityStarCore extends Entity private final int KILL_RADIUS = 60; private final int BURN_RADIUS = 200; //private final int ROCKET_INTERCEPT_RADIUS = 100; //disabled - private boolean isLogged = false; private final int ENTITY_ACTION_INTERVAL = 10; // ticks @@ -38,38 +36,58 @@ public final class EntityStarCore extends Entity { super(world); this.xCoord = x; - this.posX = x; + this.posX = (double) x; this.yCoord = y; - this.posY = y; + this.posY = (double) y; this.zCoord = z; - this.posZ = z; + this.posZ = (double) z; this.radius = radius; } private void actionToEntitiesNearStar() { - int xmax, ymax, zmax; + int xmax, ymax, zmax, x1, x2, z1, z2; int xmin, ymin, zmin; - final int MAX_RANGE = this.radius + KILL_RADIUS + BURN_RADIUS;// + ROCKET_INTERCEPT_RADIUS; - final int KILL_RANGESQ = (this.radius + KILL_RADIUS) * (this.radius + KILL_RADIUS); - final int BURN_RANGESQ = (this.radius + KILL_RADIUS + BURN_RADIUS) * (this.radius + KILL_RADIUS + BURN_RADIUS); - xmin = xCoord - MAX_RANGE; - xmax = xCoord + MAX_RANGE; + final int CUBE_SIDE = this.radius + KILL_RADIUS + BURN_RADIUS;// + ROCKET_INTERCEPT_RADIUS; + x1 = xCoord + CUBE_SIDE; + x2 = xCoord - CUBE_SIDE; - zmin = zCoord - MAX_RANGE; - zmax = zCoord + MAX_RANGE; + if (x1 < x2) + { + xmin = x1; + xmax = x2; + } + else + { + xmin = x2; + xmax = x1; + } - ymin = yCoord - MAX_RANGE; - ymax = yCoord + MAX_RANGE; + z1 = zCoord + CUBE_SIDE; + z2 = zCoord - CUBE_SIDE; + + if (z1 < z2) + { + zmin = z1; + zmax = z2; + } + else + { + zmin = z2; + zmax = z1; + } + + ymax = yCoord + CUBE_SIDE; + ymin = yCoord - CUBE_SIDE; AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(xmin, ymin, zmin, xmax, ymax, zmax); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, aabb); - if (!isLogged) - { - isLogged = true; - WarpDrive.debugPrint(this + ": Capture range: " + MAX_RANGE - + " X: " + xmin + " to " + xmax + " Y: " + ymin + " to " + ymax + " Z: " + zmin + " to " + zmax); - } + /*System.out.println("-"); + System.out.println("Coordinates: (" + xCoord + "; " + yCoord + "; " + zCoord + "). Cube side: " + CUBE_SIDE); + System.out.println("[" + this + "] X: " + xmin + " -> " + xmax); + System.out.println("[" + this + "] Y: " + ymin + " -> " + ymax); + System.out.println("[" + this + "] Z: " + zmin + " -> " + zmax); + */ for (Object o : list) { if (o == null || !(o instanceof Entity)) @@ -82,22 +100,15 @@ public final class EntityStarCore extends Entity EntityLivingBase entity = (EntityLivingBase)o; //System.out.println("Found: " + entity.getEntityName() + " distance: " + entity.getDistanceToEntity(this)); - if (entity.getDistanceSqToEntity(this) <= KILL_RANGESQ) + if (entity.getDistanceToEntity(this) <= (this.radius + KILL_RADIUS)) { // 100% kill, ignores any protection entity.attackEntityFrom(DamageSource.onFire, 9000); } - else if (entity.getDistanceSqToEntity(this) <= BURN_RANGESQ) + else if (entity.getDistanceToEntity(this) <= (this.radius + BURN_RADIUS)) { - if (entity instanceof EntityPlayer) - { - EntityPlayer player = (EntityPlayer)entity; - if (player.capabilities.isCreativeMode) - continue; - } // burn entity to 100 seconds - if (!entity.isImmuneToFire()) - entity.setFire(100); + entity.setFire(100); entity.attackEntityFrom(DamageSource.onFire, 1); } }/* else { // Intercept ICBM rocket and kill diff --git a/src/cr0s/WarpDrive/FXBeam.java b/src/cr0s/WarpDrive/FXBeam.java index 24f58023..cc84f312 100644 --- a/src/cr0s/WarpDrive/FXBeam.java +++ b/src/cr0s/WarpDrive/FXBeam.java @@ -1,6 +1,7 @@ package cr0s.WarpDrive; import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.EntityLivingBase; @@ -57,8 +58,29 @@ public class FXBeam extends EntityFX this.particleMaxAge = age; this.energy = energy; - if (red == 1 && green == 0 && blue == 0) { - TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_grey.png"); + if (red == 1 && green == 0 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_red.png"); + } + else if (red == 0 && green == 1 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_green.png"); + } + else if (red == 0 && green == 0 && blue == 1) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy.png"); + } + else if (red == 1 && green == 1 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_yellow.png"); + } + else if (red == 1 && green == 0.5 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_orange.png"); + } + else if (red == 0.5 && green == 0 && blue == 0.5) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_violet.png"); } /** @@ -100,8 +122,31 @@ public class FXBeam extends EntityFX this.particleMaxAge = age; this.energy = energy; - TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_grey.png"); - + if (red == 1 && green == 0 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_red.png"); + } + else if (red == 0 && green == 1 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_green.png"); + } + else if (red == 0 && green == 0 && blue == 1) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy.png"); + } + else if (red == 1 && green == 1 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_yellow.png"); + } + else if (red == 1 && green == 0.5 && blue == 0) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_orange.png"); + } + else if (red == 0.5 && green == 0 && blue == 0.5) + { + TEXTURE = new ResourceLocation("warpdrive", "textures/blocks/energy_violet.png"); + } + /** * Sets the particle age based on distance. */ diff --git a/src/cr0s/WarpDrive/GenerateCommand.java b/src/cr0s/WarpDrive/GenerateCommand.java index 99b0d212..dd7cddc1 100644 --- a/src/cr0s/WarpDrive/GenerateCommand.java +++ b/src/cr0s/WarpDrive/GenerateCommand.java @@ -1,6 +1,5 @@ package cr0s.WarpDrive; -import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; @@ -29,64 +28,71 @@ public class GenerateCommand extends CommandBase @Override public String getCommandUsage(ICommandSender par1ICommandSender) { - return "/" + getCommandName() + " \nPossible structures: moon, ship, asteroid, astfield, gascloud, star , jumpgate "; + return "/" + getCommandName() + " \nPossible structures: moon, ship, asteroid, astfield, gascloud, star, jumpgate "; } @Override public void processCommand(ICommandSender icommandsender, String[] params) { EntityPlayerMP player = (EntityPlayerMP)icommandsender; - if(params.length > 0) + String struct = params[0]; + + // Reject command, if player is not in space + if (player.dimension != WarpDrive.instance.spaceDimID && (!"ship".equals(struct))) { - String struct = params[0]; - - // Reject command, if player is not in space - if (player.dimension != WarpDriveConfig.G_SPACE_DIMENSION_ID && (!"ship".equals(struct))) - { - player.addChatMessage("* generate: this structure is only allowed in space!"); - return; - } - - int x = MathHelper.floor_double(player.posX); - int y = MathHelper.floor_double(player.posY); - int z = MathHelper.floor_double(player.posZ); - - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - if (struct.equals("moon")) { - notifyAdmins(icommandsender, "/generate: generating moon at " + x + ", " + (y - 16) + ", " + z, new Object[0]); - WarpDrive.instance.spaceWorldGenerator.generateMoon(player.worldObj, x, y - 16, z); - } else if (struct.equals("ship")) { - notifyAdmins(icommandsender, "/generate: generating NPC ship at " + x + ", " + y + ", " + z, new Object[0]); - new WorldGenSmallShip(false).generate(player.worldObj, player.worldObj.rand, x, y, z); - } else if (struct.equals("asteroid")) { - notifyAdmins(icommandsender, "/generate: generating asteroid at " + x + ", " + (y - 10) + ", " + z, new Object[0]); - WarpDrive.instance.spaceWorldGenerator.generateRandomAsteroid(player.worldObj, x, y - 10, z, 6, 11); - } else if (struct.equals("astfield")) { - notifyAdmins(icommandsender, "/generate: generating asteroid field at " + x + ", " + y + ", " + z, new Object[0]); - WarpDrive.instance.spaceWorldGenerator.generateAsteroidField(player.worldObj, x, y, z); - } else if (struct.equals("gascloud")) { - notifyAdmins(icommandsender, "/generate: generating gas cloud at " + x + ", " + y + ", " + z, new Object[0]); - WarpDrive.instance.spaceWorldGenerator.generateGasCloudOfColor(player.worldObj, x, y, z, 15, 20, player.worldObj.rand.nextInt(12)); - } else if (struct.equals("star")) { - notifyAdmins(icommandsender, "/generate: generating star at " + x + ", " + y + ", " + z, new Object[0]); - Integer type = (params.length > 1) ? Integer.parseInt(params[1]) : -1; // Lem - WarpDrive.instance.spaceWorldGenerator.generateStar(player.worldObj, x, y, z, type); // Lem - } else if (struct.equals("jumpgate")) { - if (params.length == 2) { - notifyAdmins(icommandsender, "/generate: creating jumpgate at " + x + ", " + y + ", " + z, new Object[0]); - - if (WarpDrive.instance.jumpGates.addGate(params[1], x, y, z)) { - JumpGateGenerator.generate(player.worldObj, x, Math.min(y,255-JumpGateGenerator.GATE_SIZE_HALF - 1), z); - } else { - notifyAdmins(icommandsender, "/generate: jumpgate '" + params[1] + "' already exists.", new Object[0]); - } - } - } else { - player.addChatMessage(getCommandUsage(icommandsender)); - } - } - } else { - player.addChatMessage(getCommandUsage(icommandsender)); + player.addChatMessage("* generate: this structure generation allowed only in space!"); + return; + } + + int x = MathHelper.floor_double(player.posX); + int y = MathHelper.floor_double(player.posY); + int z = MathHelper.floor_double(player.posZ); + + if (struct.equals("moon")) + { + notifyAdmins(icommandsender, "/generate: generating moon at " + x + ", " + (y - 16) + ", " + z, new Object[0]); + WarpDrive.instance.spaceWorldGenerator.generateMoon(player.worldObj, x, y - 16, z); + } + else if (struct.equals("ship")) + { + notifyAdmins(icommandsender, "/generate: generating NPC ship at " + x + ", " + y + ", " + z, new Object[0]); + new WorldGenSmallShip(false).generate(player.worldObj, player.worldObj.rand, x, y, z); + } + else if (struct.equals("asteroid")) + { + notifyAdmins(icommandsender, "/generate: generating asteroid at " + x + ", " + (y - 10) + ", " + z, new Object[0]); + WarpDrive.instance.spaceWorldGenerator.generateAsteroid(player.worldObj, x, y - 10, z, 6, 11); + } + else if (struct.equals("astfield")) + { + notifyAdmins(icommandsender, "/generate: generating asteroid field at " + x + ", " + y + ", " + z, new Object[0]); + WarpDrive.instance.spaceWorldGenerator.generateAsteroidField(player.worldObj, x, y, z); + } + else if (struct.equals("gascloud")) + { + notifyAdmins(icommandsender, "/generate: generating gas cloud at " + x + ", " + y + ", " + z, new Object[0]); + WarpDrive.instance.spaceWorldGenerator.generateGasCloudOfColor(player.worldObj, x, y, z, 15, 20, player.worldObj.rand.nextInt(12)); + } + else if (struct.equals("star")) + { + notifyAdmins(icommandsender, "/generate: generating star at " + x + ", " + y + ", " + z, new Object[0]); + WarpDrive.instance.spaceWorldGenerator.generateStar(player.worldObj, x, y, z); + } + else if (struct.equals("jumpgate")) + { + if (params.length == 2) + { + notifyAdmins(icommandsender, "/generate: creating jumpgate at " + x + ", " + y + ", " + z, new Object[0]); + + if (WarpDrive.instance.jumpGates.addGate(params[1], x, y, z)) + { + JumpGateGenerator.generate(player.worldObj, x, y, z); + } + else + { + notifyAdmins(icommandsender, "/generate: jumpgate '" + params[1] + "' already exists.", new Object[0]); + } + } } } } diff --git a/src/cr0s/WarpDrive/GravityManager.java b/src/cr0s/WarpDrive/GravityManager.java index 34d0adbb..3674f794 100644 --- a/src/cr0s/WarpDrive/GravityManager.java +++ b/src/cr0s/WarpDrive/GravityManager.java @@ -1,6 +1,7 @@ package cr0s.WarpDrive; import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; @@ -8,104 +9,79 @@ import net.minecraft.util.MathHelper; public class GravityManager { - private static double OVERWORLD_ENTITY_GRAVITY = 0.080000000000000002D; // Default value from Vanilla - private static double OVERWORLD_ITEM_GRAVITY = 0.039999999105930328D; // Default value from Vanilla - private static double OVERWORLD_ITEM_GRAVITY2 = 0.9800000190734863D; // Default value from Vanilla - private static double HYPERSPACE_FIELD_ENTITY_GRAVITY = 0.035D; - private static double HYPERSPACE_VOID_ENTITY_JITTER = 0.005D; - private static double SPACE_FIELD_ENTITY_GRAVITY = 0.025D; // Lem 0.08D - private static double SPACE_FIELD_ITEM_GRAVITY = 0.02D; // Lem 0.04D - private static double SPACE_FIELD_ITEM_GRAVITY2 = 0.60D; // Lem 0.9800000190734863D - private static double SPACE_VOID_GRAVITY = 0.001D; // Lem 0.0001D - private static double SPACE_VOID_GRAVITY_JETPACKSNEAK = 0.02D; // Lem 0.01D - private static double SPACE_VOID_GRAVITY_RAWSNEAK = 0.005D; // Lem 0.01D 0.001 = no mvt + private static double SPACE_GRAVITY = 0.0001D; + private static double SPACE_GRAVITY_SNEAK = 0.01D; public static double getGravityForEntity(EntityLivingBase entity) { // Is entity in space or hyper-space? - boolean inSpace = entity.worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID; - boolean inHyperspace = entity.worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID; - // entity.ticksExisted + boolean inSpace = entity.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID || entity.worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID; - if (inSpace || inHyperspace) + if (inSpace) { boolean insideGravField = isEntityInGraviField(entity); - + if (insideGravField) { - if (inSpace) - return SPACE_FIELD_ENTITY_GRAVITY; - else - return HYPERSPACE_FIELD_ENTITY_GRAVITY; + return 0.08D; } else { - double jitter = (entity.rand.nextDouble() - 0.5D) * 2.0D * HYPERSPACE_VOID_ENTITY_JITTER; - if (inSpace) - jitter = 0.0D; if (entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer)entity; if (player.isSneaking()) { - if (player.getCurrentArmor(2) != null && WarpDriveConfig.Jetpacks.contains(player.getCurrentArmor(2).itemID)) + if (player.getCurrentArmor(2) != null && WarpDriveConfig.i.Jetpacks.contains(player.getCurrentArmor(2).itemID)) { - return SPACE_VOID_GRAVITY_JETPACKSNEAK; + return SPACE_GRAVITY_SNEAK; } - else - { - return SPACE_VOID_GRAVITY_RAWSNEAK; - } - } - else - { - // FIXME: compensate jetpack } } - return SPACE_VOID_GRAVITY + jitter; + return SPACE_GRAVITY; } } - return OVERWORLD_ENTITY_GRAVITY; + return 0.08D; } public static double getItemGravity(EntityItem entity) { - if (entity.worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID || entity.worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) + if (entity.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID || entity.worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) { if (isEntityInGraviField(entity)) { - return SPACE_FIELD_ITEM_GRAVITY; + return 0.03999999910593033D; } else { - return SPACE_VOID_GRAVITY; + return SPACE_GRAVITY; } } else { - return OVERWORLD_ITEM_GRAVITY; // On Earth + return 0.03999999910593033D; // On Earth } } public static double getItemGravity2(EntityItem entity) { - if (entity.worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID || entity.worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) + if (entity.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID || entity.worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) { if (isEntityInGraviField(entity)) { - return SPACE_FIELD_ITEM_GRAVITY2; + return 0.9800000190734863D; } else { - return SPACE_VOID_GRAVITY; + return SPACE_GRAVITY; } } else { - return OVERWORLD_ITEM_GRAVITY2; + return 0.9800000190734863D; } } diff --git a/src/cr0s/WarpDrive/HyperSpaceGenerator.java b/src/cr0s/WarpDrive/HyperSpaceGenerator.java index b2a21e7e..c1f75fcb 100644 --- a/src/cr0s/WarpDrive/HyperSpaceGenerator.java +++ b/src/cr0s/WarpDrive/HyperSpaceGenerator.java @@ -31,7 +31,7 @@ public class HyperSpaceGenerator extends ChunkProviderGenerate implements IChunk @Override public Chunk provideChunk(int par1, int par2) { - this.rand.setSeed(par1 * 341873128712L + par2 * 132897987541L); + this.rand.setSeed((long) par1 * 341873128712L + (long) par2 * 132897987541L); byte[] var3 = new byte[32768]; generateTerrain(par1, par2, var3); //this.caveGenerator.generate(this, this.worldObj, par1, par2, var3); diff --git a/src/cr0s/WarpDrive/HyperSpaceProvider.java b/src/cr0s/WarpDrive/HyperSpaceProvider.java index 7505b557..0df37d31 100644 --- a/src/cr0s/WarpDrive/HyperSpaceProvider.java +++ b/src/cr0s/WarpDrive/HyperSpaceProvider.java @@ -100,7 +100,7 @@ public class HyperSpaceProvider extends WorldProvider for (int var2 = 0; var2 <= 15; ++var2) { - float var3 = 1.0F - var2 / 15.0F; + float var3 = 1.0F - (float)var2 / 15.0F; this.lightBrightnessTable[var2] = (1.0F - var3) / (var3 * 3.0F + 1.0F) * (1.0F - var1) + var1; } } @@ -124,14 +124,14 @@ public class HyperSpaceProvider extends WorldProvider { setCloudRenderer(new CloudRenderBlank()); setSkyRenderer(new CloudRenderBlank()); - return this.worldObj.getWorldVec3Pool().getVecFromPool(1.0D, 0.0D, 0.0D); + return this.worldObj.getWorldVec3Pool().getVecFromPool((double) 1, (double) 0, (double) 0); } @SideOnly(Side.CLIENT) @Override public Vec3 getFogColor(float par1, float par2) { - return this.worldObj.getWorldVec3Pool().getVecFromPool(0.1D, 0.0D, 0.0D); + return this.worldObj.getWorldVec3Pool().getVecFromPool((double) 0.1, (double) 0, (double) 0); } @SideOnly(Side.CLIENT) @@ -150,7 +150,7 @@ public class HyperSpaceProvider extends WorldProvider @Override public int getRespawnDimension(EntityPlayerMP player) { - return WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID; + return WarpDrive.instance.hyperSpaceDimID; } @Override @@ -190,8 +190,8 @@ public class HyperSpaceProvider extends WorldProvider worldObj.setBlock(var5.posX, var5.posY + 1, var5.posZ - 1, Block.glass.blockID, 0, 2); worldObj.setBlock(var5.posX, var5.posY + 2, var5.posZ - 1, Block.glass.blockID, 0, 2); worldObj.setBlock(var5.posX, var5.posY + 3, var5.posZ, Block.glass.blockID, 0, 2); - worldObj.setBlock(var5.posX, var5.posY, var5.posZ, WarpDriveConfig.airID, 15, 2); - worldObj.setBlock(var5.posX, var5.posY + 1, var5.posZ, WarpDriveConfig.airID, 15, 2); + worldObj.setBlock(var5.posX, var5.posY, var5.posZ, WarpDriveConfig.i.airID, 15, 2); + worldObj.setBlock(var5.posX, var5.posY + 1, var5.posZ, WarpDriveConfig.i.airID, 15, 2); } return var5; diff --git a/src/cr0s/WarpDrive/HyperSpaceWorldGenerator.java b/src/cr0s/WarpDrive/HyperSpaceWorldGenerator.java index 74fccd91..46169fde 100644 --- a/src/cr0s/WarpDrive/HyperSpaceWorldGenerator.java +++ b/src/cr0s/WarpDrive/HyperSpaceWorldGenerator.java @@ -1,9 +1,7 @@ package cr0s.WarpDrive; import cpw.mods.fml.common.IWorldGenerator; - import java.util.Random; - import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; @@ -24,7 +22,7 @@ public class HyperSpaceWorldGenerator implements IWorldGenerator @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { - if (world.provider.dimensionId != WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) + if (world.provider.dimensionId != WarpDrive.instance.hyperSpaceDimID) { // ... } diff --git a/src/cr0s/WarpDrive/InvisibleCommand.java b/src/cr0s/WarpDrive/InvisibleCommand.java index a06f051c..8ad020aa 100644 --- a/src/cr0s/WarpDrive/InvisibleCommand.java +++ b/src/cr0s/WarpDrive/InvisibleCommand.java @@ -4,6 +4,8 @@ import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; +import net.minecraft.util.MathHelper; +import net.minecraft.world.WorldServer; public class InvisibleCommand extends CommandBase { @@ -23,6 +25,8 @@ public class InvisibleCommand extends CommandBase public void processCommand(ICommandSender icommandsender, String[] astring) { EntityPlayerMP player = (EntityPlayerMP)icommandsender; + MinecraftServer server = MinecraftServer.getServer(); + int targetDim = WarpDrive.instance.spaceDimID; if (astring.length >= 1) { diff --git a/src/cr0s/WarpDrive/JumpGatesRegistry.java b/src/cr0s/WarpDrive/JumpGatesRegistry.java index 1db0f86e..87c570ad 100644 --- a/src/cr0s/WarpDrive/JumpGatesRegistry.java +++ b/src/cr0s/WarpDrive/JumpGatesRegistry.java @@ -9,49 +9,52 @@ import java.io.PrintWriter; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.MathHelper; +import net.minecraft.client.Minecraft; -public final class JumpGatesRegistry { +public final class JumpGatesRegistry +{ private File db; private ArrayList gates = new ArrayList(); //@SideOnly(Side.CLIENT) - public JumpGatesRegistry() { - db = new File("gates.txt"); - System.out.println("Gates.txt file: " + db); - - if (db != null && !db.exists()) { - try { - db.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - try { + public JumpGatesRegistry() + { + db = MinecraftServer.getServer().getFile("gates.txt"); + + try + { loadGates(); - } catch (IOException ex) { + } + catch (IOException ex) + { Logger.getLogger(JumpGatesRegistry.class.getName()).log(Level.SEVERE, null, ex); } } - public void saveGates() throws IOException { + public void saveGates() throws IOException + { PrintWriter out = new PrintWriter(new FileWriter(db)); // Write each string in the array on a separate line - for (JumpGate jg : gates) { + for (JumpGate jg : gates) + { out.println(jg); } out.close(); } - public void loadGates() throws IOException { + public void loadGates() throws IOException + { System.out.println("[JUMP GATES] Loading jump gates from gates.txt..."); BufferedReader bufferedreader; bufferedreader = new BufferedReader(new FileReader(db)); String s1; - while ((s1 = bufferedreader.readLine()) != null) { + while ((s1 = bufferedreader.readLine()) != null) + { gates.add(new JumpGate(s1)); } @@ -59,31 +62,39 @@ public final class JumpGatesRegistry { System.out.println("[JUMP GATES] Loaded " + gates.size() + " jump gates."); } - public void addGate(JumpGate jg) { + public void addGate(JumpGate jg) + { gates.add(jg); } - public boolean addGate(String name, int x, int y, int z) { + public boolean addGate(String name, int x, int y, int z) + { // Gate already exists - if (findGateByName(name) != null) { + if (findGateByName(name) != null) + { return false; } addGate(new JumpGate(name, x, y, z)); - try { + try + { saveGates(); - } catch (IOException ex) { + } + catch (IOException ex) + { Logger.getLogger(JumpGatesRegistry.class.getName()).log(Level.SEVERE, null, ex); } return true; } - public void removeGate(String name) { + public void removeGate(String name) + { JumpGate jg; - for (int i = 0; i < gates.size(); i++) { + for (int i = 0; i < gates.size(); i++) + { jg = gates.get(i); if (jg.name.equalsIgnoreCase(name)) @@ -93,16 +104,22 @@ public final class JumpGatesRegistry { } } - try { + try + { saveGates(); - } catch (IOException ex) { + } + catch (IOException ex) + { Logger.getLogger(JumpGatesRegistry.class.getName()).log(Level.SEVERE, null, ex); } } - public JumpGate findGateByName(String name) { - for (JumpGate jg : gates) { - if (jg.name.equalsIgnoreCase(name)) { + public JumpGate findGateByName(String name) + { + for (JumpGate jg : gates) + { + if (jg.name.equalsIgnoreCase(name)) + { return jg; } } @@ -110,37 +127,36 @@ public final class JumpGatesRegistry { return null; } - public String jumpGatesList() { + public String jumpGatesList() + { String result = ""; - for (JumpGate jg : gates) { + for (JumpGate jg : gates) + { result += jg.toNiceString() + "\n"; } return result; } - - public String commaList() { - String result = ""; - for (JumpGate jg : gates) { - result += jg.toNiceString() + ","; - } - return result; - } - public JumpGate findNearestGate(int x, int y, int z) { -// WarpDrive.debugPrint(jumpGatesList()); - double minDistance2 = -1; + public JumpGate findNearestGate(int x, int y, int z) + { + System.out.println(jumpGatesList()); + double minDistance = -1; JumpGate res = null; - for (JumpGate jg : gates) { - double dX = jg.xCoord - x; - double dY = jg.yCoord - y; - double dZ = jg.zCoord - z; - double distance2 = dX * dX + dY * dY + dZ * dZ; + for (JumpGate jg : gates) + { + double d3 = jg.xCoord - x; + double d4 = jg.yCoord - y; + double d5 = jg.zCoord - z; + double distance = MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5); + System.out.println("Checking gate: " + jg.name + ", distance: " + distance); - if ((minDistance2 == -1) || (distance2 < minDistance2)) { - minDistance2 = distance2; + if (minDistance == -1 || distance < minDistance) + { + System.out.println("Setting " + jg.name + " as nearest"); + minDistance = distance; res = jg; } } diff --git a/src/cr0s/WarpDrive/JumpgateCommand.java b/src/cr0s/WarpDrive/JumpgateCommand.java deleted file mode 100644 index 44632926..00000000 --- a/src/cr0s/WarpDrive/JumpgateCommand.java +++ /dev/null @@ -1,33 +0,0 @@ -package cr0s.WarpDrive; - -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; - -public class JumpgateCommand extends CommandBase -{ - @Override - public int getRequiredPermissionLevel() - { - return 4; - } - - @Override - public String getCommandName() - { - return "jumpgates"; - } - - @Override - public String getCommandUsage(ICommandSender icommandsender) - { - return "Lists jumpgates"; - } - - @Override - public void processCommand(ICommandSender icommandsender, String[] astring) - { - EntityPlayerMP player = (EntityPlayerMP)icommandsender; - player.addChatMessage(WarpDrive.instance.jumpGates.commaList()); - } -} diff --git a/src/cr0s/WarpDrive/MetaRotations$1.java b/src/cr0s/WarpDrive/MetaRotations$1.java index 3e4a7321..ef8e684a 100644 --- a/src/cr0s/WarpDrive/MetaRotations$1.java +++ b/src/cr0s/WarpDrive/MetaRotations$1.java @@ -12,8 +12,7 @@ class MetaRotations$1 implements FilenameFilter this.this$0 = var1; } - @Override - public boolean accept(File f, String name) + public boolean accept(File f, String name) { return name.endsWith(".mrot"); } diff --git a/src/cr0s/WarpDrive/MetaRotations.java b/src/cr0s/WarpDrive/MetaRotations.java index 98698387..aef3148a 100644 --- a/src/cr0s/WarpDrive/MetaRotations.java +++ b/src/cr0s/WarpDrive/MetaRotations.java @@ -6,16 +6,24 @@ import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MathHelper; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import ic2.api.network.NetworkHelper; public class MetaRotations { private File metaRotationsDirectory; - public Map metaRotationMap = new HashMap(); + public Map metaRotationMap = new HashMap(); public int getRotatedMeta(int block, int meta, int rotate) { @@ -25,7 +33,7 @@ public class MetaRotations } else { - BlockMetaRotation rotation = metaRotationMap.get(Integer.valueOf(block)); + BlockMetaRotation rotation = (BlockMetaRotation)this.metaRotationMap.get(Integer.valueOf(block)); return rotation == null ? meta : rotation.getRotatedMeta(meta, rotate); } } @@ -237,8 +245,7 @@ public class MetaRotations reader.close(); } - public static int rotate90(int type, int parData) { - int data = parData; + public static int rotate90(int type, int data) { switch (type) { case BlockID.MINECART_TRACKS: switch (data) { @@ -399,19 +406,23 @@ public class MetaRotations } public static short rotateIC2MachineFacing90Reverse(short facing) { - switch(facing) // 3 5 2 4 + switch(facing) // 3 5 2 4 { case 3: - return 5; + facing = 5; + break; case 5: - return 2; + facing = 2; + break; case 2: - return 4; + facing = 4; + break; case 4: - return 3; + facing = 3; + break; } return facing; } @@ -431,16 +442,20 @@ public class MetaRotations switch(facing) // 0 4 2 1 { case 0: - return 4; + facing = 4; + break; case 4: - return 2; + facing = 2; + break; case 2: - return 1; + facing = 1; + break; case 1: - return 0; + facing = 0; + break; } return facing; @@ -450,16 +465,20 @@ public class MetaRotations switch(facing) // 3 5 2 4 { case 3: - return 5; + facing = 5; + break; case 5: - return 2; + facing = 2; + break; case 2: - return 4; + facing = 4; + break; case 4: - return 3; + facing = 3; + break; } return facing; @@ -474,7 +493,8 @@ public class MetaRotations } public static int rotateCCBlock90Reverse(int dir) { - switch(dir) { + switch(dir) + { case 4: return 3; case 3: @@ -491,7 +511,8 @@ public class MetaRotations public static int rotateComputer90Reverse(int meta) { int typeMeta = meta & 0x8; - switch(meta - typeMeta) { + switch(meta - typeMeta) + { case 4: return typeMeta + 3; case 3: @@ -513,8 +534,7 @@ public class MetaRotations * @param data * @return */ - public static int rotate90Reverse(int type, int parData) { - int data = parData; + public static int rotate90Reverse(int type, int data) { switch (type) { case BlockID.MINECART_TRACKS: switch (data) { diff --git a/src/cr0s/WarpDrive/PacketHandler.java b/src/cr0s/WarpDrive/PacketHandler.java index a265eed3..508a02fd 100644 --- a/src/cr0s/WarpDrive/PacketHandler.java +++ b/src/cr0s/WarpDrive/PacketHandler.java @@ -5,18 +5,18 @@ import java.io.DataInputStream; import java.io.IOException; import java.util.List; +import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; +import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; import cpw.mods.fml.common.network.IPacketHandler; import cpw.mods.fml.common.network.Player; -import cr0s.WarpDrive.machines.TileEntityCamera; -import cr0s.WarpDrive.machines.TileEntityLaser; -import cr0s.WarpDrive.machines.TileEntityMonitor; import net.minecraft.client.multiplayer.WorldClient; public class PacketHandler implements IPacketHandler @@ -42,142 +42,192 @@ public class PacketHandler implements IPacketHandler } } - public static void handleCloak(Packet250CustomPayload packet, EntityPlayer player) { - DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); + public void handleCloak(Packet250CustomPayload packet, EntityPlayer player) { + DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); - try { - // Read cloaked area parameters - int minX = inputStream.readInt(); - int minY = inputStream.readInt(); - int minZ = inputStream.readInt(); - - int maxX = inputStream.readInt(); - int maxY = inputStream.readInt(); - int maxZ = inputStream.readInt(); - - boolean decloak = inputStream.readBoolean(); - - byte tier = inputStream.readByte(); - - //WarpDrive.debugPrint("[Cloak Packet] Received " + ((decloak) ? "DEcloaked" : "cloaked") + "area: (" + minX + "; " + minY + "; " + minZ + ") -> (" + maxX + "; " + maxY + "; " + maxZ + ")"); - - if (minX <= player.posX && maxX >= player.posY && minY <= player.posZ && maxY >= player.posX && minZ <= player.posY && maxZ >= player.posZ) - return; - + try + { + // Read cloaked area parameters + int minX = inputStream.readInt(); + int minY = inputStream.readInt(); + int minZ = inputStream.readInt(); + + int maxX = inputStream.readInt(); + int maxY = inputStream.readInt(); + int maxZ = inputStream.readInt(); + + boolean decloak = inputStream.readBoolean(); + + byte tier = inputStream.readByte(); + + int w = Math.abs(maxX - minX); + int h = Math.abs(maxY - minY); + int l = Math.abs(maxZ - minZ); + + //(-2099; 208; 423) -> (-2069; 243; 453) + // + int size = w * h * l; + + //System.out.println("[Cloak Packet] Received " + ((decloak) ? "DEcloaked" : "cloaked") + "area: (" + minX + "; " + minY + "; " + minZ + ") -> (" + maxX + "; " + maxY + "; " + maxZ + ")"); + + if (minX <= player.chunkCoordX && maxX >= player.chunkCoordY && minY <= player.chunkCoordY && maxY >= player.chunkCoordY && minZ <= player.chunkCoordZ && maxZ >= player.chunkCoordZ) + return; + // Hide the area - if (!decloak) { - //WarpDrive.debugPrint("[Cloak Packet] Removing " + size + " blocks..."); - - // Now hide the blocks within area - World worldObj = player.worldObj; - int cloakBlockID = (tier == 1) ? WarpDriveConfig.gasID : 0; - int cloakBlockMetadata = (tier == 1) ? 5 : 0; - for (int y = minY; y <= maxY; y++) { - for (int x = minX; x <= maxX; x++) { - for(int z = minZ; z <= maxZ; z++) { - if (worldObj.getBlockId(x, y, z) != 0) { - worldObj.setBlock(x, y, z, cloakBlockID, cloakBlockMetadata, 4); - } - } - } + if (!decloak) + { + //System.out.println("[Cloak Packet] Removing " + size + " blocks..."); + + // Now hide the blocks within area + World worldObj = player.worldObj; + for (int y = minY; y <= maxY; y++) + for (int x = minX; x <= maxX; x++) + for(int z = minZ; z <= maxZ; z++) + if (worldObj.getBlockId(x, y, z) != 0) + worldObj.setBlock(x, y, z, (tier == 1) ? WarpDriveConfig.i.gasID : 0, 5, 4); + + //System.out.println("[Cloak Packet] Removing entity..."); + // Hide any entities inside area + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(player, aabb); + for (Entity e : list) + { + worldObj.removeEntity(e); + ((WorldClient)worldObj).removeEntityFromWorld(e.entityId); } - - //WarpDrive.debugPrint("[Cloak Packet] Removing entity..."); - // Hide any entities inside area - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(player, aabb); - for (Entity e : list) { - worldObj.removeEntity(e); - ((WorldClient)worldObj).removeEntityFromWorld(e.entityId); - } - } else { // reveal the area - player.worldObj.markBlockRangeForRenderUpdate(minX + 1, minY + 1, minZ + 1, maxX + 1, maxY + 1, maxZ + 1); - - // Make some graphics - int numLasers = 80 + player.worldObj.rand.nextInt(50); - - double centerX = (minX + maxX) / 2.0D; - double centerY = (minY + maxY) / 2.0D; - double centerZ = (minZ + maxZ) / 2.0D; - double radiusX = (maxX - minX) / 2.0D + 5.0D; - double radiusY = (maxY - minY) / 2.0D + 5.0D; - double radiusZ = (maxZ - minZ) / 2.0D + 5.0D; - - for (int i = 0; i < numLasers; i++) { - WarpDrive.proxy.renderBeam(player.worldObj, - new Vector3( - centerX + radiusX * player.worldObj.rand.nextGaussian(), - centerY + radiusY * player.worldObj.rand.nextGaussian(), - centerZ + radiusZ * player.worldObj.rand.nextGaussian()), - new Vector3( - centerX + radiusX * player.worldObj.rand.nextGaussian(), - centerY + radiusY * player.worldObj.rand.nextGaussian(), - centerZ + radiusZ * player.worldObj.rand.nextGaussian()), - player.worldObj.rand.nextFloat(), player.worldObj.rand.nextFloat(), player.worldObj.rand.nextFloat(), - 60 + player.worldObj.rand.nextInt(60), 100); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void handleLaserTargeting(Packet250CustomPayload packet, EntityPlayer player) - { - DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); + } + else + { // reveal the area + player.worldObj.markBlockRangeForRenderUpdate(minX, minY, minZ, maxX, maxY, maxZ); + + // Make some graphics + int numLasers = 25 + player.worldObj.rand.nextInt(300); + + for (int i = 0; i < numLasers; i++) + { + int randX1 = minX + player.worldObj.rand.nextInt(maxX - minX); + int randX2 = minX + player.worldObj.rand.nextInt(maxX - minX); + + int randY1 = minY + player.worldObj.rand.nextInt(maxY - minY); + int randY2 = minY + player.worldObj.rand.nextInt(maxY - minY); + + int randZ1 = minZ + player.worldObj.rand.nextInt(maxZ - minZ); + int randZ2 = minZ + player.worldObj.rand.nextInt(maxZ - minZ); + + float r = 0, g = 0, b = 0; + + switch (player.worldObj.rand.nextInt(6)) + { + case 0: + r = 1.0f; + g = b = 0; + break; + case 1: + r = b = 0; + g = 1.0f; + break; + case 2: + r = g = 0; + b = 1.0f; + break; + case 3: + r = b = 0.5f; + g = 0; + break; + case 4: + r = g = 1.0f; + b = 0; + break; + case 5: + r = 1.0f; + b = 0.5f; + g = 0f; + } + WarpDrive.proxy.renderBeam(player.worldObj, new Vector3(randX1, randY1, randZ1), new Vector3(randX2, randY2, randZ2), r, g, b, 10, 100); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } - try - { - int x = inputStream.readInt(); - int y = inputStream.readInt(); - int z = inputStream.readInt(); - float yaw = inputStream.readFloat(); - float pitch = inputStream.readFloat(); - WarpDrive.debugPrint("Received target packet: (" + x + "; " + y + "; " + z + ") yaw: " + yaw + " pitch: " + pitch); - TileEntity te = player.worldObj.getBlockTileEntity(x, y, z); - if (te != null && te instanceof TileEntityLaser) { - TileEntityLaser laser = (TileEntityLaser)te; - laser.yaw = yaw; - laser.pitch = pitch; - laser.delayTicks = 0; - laser.isEmitting = true; - } - } - catch (Exception e) - { - e.printStackTrace(); - } + public void handleLaserTargeting(Packet250CustomPayload packet, EntityPlayer player) + { + DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); + + try + { + int x = inputStream.readInt(); + int y = inputStream.readInt(); + int z = inputStream.readInt(); + float yaw = inputStream.readFloat(); + float pitch = inputStream.readFloat(); + System.out.println("Got target packet: (" + x + "; " + y + "; " + z + ") | yaw: " + yaw + " | pitch: " + pitch); + TileEntity te = player.worldObj.getBlockTileEntity(x, y, z); + + if (te != null) + { + System.out.println("TE is NULL"); + + if (te instanceof TileEntityLaser) + { + TileEntityLaser l = (TileEntityLaser)te; + l.yaw = yaw; + l.pitch = pitch; + l.delayTicks = 0; + l.isEmitting = true; + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } } - public static void handleFreqUpdate(Packet250CustomPayload packet, EntityPlayer player) { - DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); + public void handleFreqUpdate(Packet250CustomPayload packet, EntityPlayer player) + { + DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); - try { - int x = inputStream.readInt(); - int y = inputStream.readInt(); - int z = inputStream.readInt(); - int frequency = inputStream.readInt(); -// WarpDrive.debugPrint("Received frequency packet: (" + x + ", " + y + ", " + z + ") frequency '" + frequency + "'"); - TileEntity te = player.worldObj.getBlockTileEntity(x, y, z); - if (te != null) { - if (te instanceof TileEntityMonitor) { - ((TileEntityMonitor)te).setFrequency(frequency); - } else if (te instanceof TileEntityCamera) { - ((TileEntityCamera)te).setFrequency(frequency); - } else if (te instanceof TileEntityLaser) { - ((TileEntityLaser)te).setCameraFrequency(frequency); - } - } - } - catch (Exception e) - { - e.printStackTrace(); - } - } + try + { + int x = inputStream.readInt(); + int y = inputStream.readInt(); + int z = inputStream.readInt(); + int freq = inputStream.readInt(); + //System.out.println("Got freq packet: (" + x + "; " + y + "; " + z + ") | freq: " + freq); + TileEntity te = player.worldObj.getBlockTileEntity(x, y, z); + + if (te != null) + { + if (te instanceof TileEntityMonitor) + { + ((TileEntityMonitor)te).setFrequency(freq); + } + else if (te instanceof TileEntityCamera) + { + ((TileEntityCamera)te).setFrequency(freq); + WarpDrive.instance.cams.updateInRegistry(new CamRegistryItem(freq, new ChunkPosition(x, y, z), player.worldObj).setType(0)); + } + else if (te instanceof TileEntityLaser) + { + ((TileEntityLaser)te).camFreq = freq; + WarpDrive.instance.cams.updateInRegistry(new CamRegistryItem(freq, new ChunkPosition(x, y, z), player.worldObj).setType(1)); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } private void handleBeam(Packet250CustomPayload packet, EntityPlayer player) { DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data)); + int dimID; Vector3 source, target; double sx, sy, sz; double tx, ty, tz; @@ -207,15 +257,24 @@ public class PacketHandler implements IPacketHandler // Read energy value energy = inputStream.readInt(); - // Render beam -// WarpDrive.debugPrint("Received beam packet from " + source + " to " + target + " as RGB " + r + " " + g + " " + b + " age " + age +" energy " + energy); + // Render beam + /*System.out.println("sx: " + sx + " sy: " + sy + " sz: " + sz); + System.out.println("tx: " + sx + " ty: " + sy + " tz: " + sz); - // To avoid NPE at logging in - if (worldObj == null) - { - WarpDrive.debugPrint("WorldObj is null"); - return; - } + System.out.println("source: " + source); + System.out.println("target: " + target); + System.out.println("r: " + r); + System.out.println("g: " + g); + System.out.println("b " + b); + System.out.println("age: " + age); + System.out.println("energy: " + energy);*/ + + // To avoid NPE at logging in + if (worldObj == null) + { + System.out.println("WorldObj is null"); + return; + } WarpDrive.proxy.renderBeam(worldObj, source.clone(), target.clone(), r, g, b, age, energy); } diff --git a/src/cr0s/WarpDrive/SoundHandler.java b/src/cr0s/WarpDrive/SoundHandler.java index b0993218..c76e5814 100644 --- a/src/cr0s/WarpDrive/SoundHandler.java +++ b/src/cr0s/WarpDrive/SoundHandler.java @@ -5,21 +5,22 @@ import cpw.mods.fml.relauncher.SideOnly; import net.minecraftforge.client.event.sound.SoundLoadEvent; import net.minecraftforge.event.ForgeSubscribe; -public class SoundHandler { +public class SoundHandler +{ @SideOnly(Side.CLIENT) @ForgeSubscribe - public void onSoundLoad(SoundLoadEvent event) { - try { + public void onSoundLoad(SoundLoadEvent event) + { + try + { System.out.println("[WarpDrive] Registering sound files..."); - event.manager.addSound("warpdrive:warp_4s.ogg"); - event.manager.addSound("warpdrive:warp_10s.ogg"); - event.manager.addSound("warpdrive:warp_30s.ogg"); + event.manager.addSound("warpdrive:warp.ogg"); event.manager.addSound("warpdrive:hilaser.ogg"); event.manager.addSound("warpdrive:midlaser.ogg"); event.manager.addSound("warpdrive:lowlaser.ogg"); - event.manager.addSound("warpdrive:cloak.ogg"); - event.manager.addSound("warpdrive:decloak.ogg"); - } catch (Exception e) { + } + catch (Exception e) + { System.err.println("Failed to register sound: " + e.getLocalizedMessage()); e.printStackTrace(); } diff --git a/src/cr0s/WarpDrive/SpaceEventHandler.java b/src/cr0s/WarpDrive/SpaceEventHandler.java index d47bb72a..3de997a0 100644 --- a/src/cr0s/WarpDrive/SpaceEventHandler.java +++ b/src/cr0s/WarpDrive/SpaceEventHandler.java @@ -1,58 +1,48 @@ package cr0s.WarpDrive; -import ic2.api.item.Items; - import java.util.HashMap; import java.util.List; -import cr0s.WarpDrive.CloakedArea; -import cr0s.WarpDrive.api.IBreathingHelmet; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; -import net.minecraft.world.EnumGameType; -import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.event.ForgeSubscribe; -import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; /** - * + * Обработчик событий в мире Space * @author Cr0s */ -public class SpaceEventHandler { - private HashMap entity_airBlock; - private HashMap player_airTank; - private HashMap player_cloakTicks; +public class SpaceEventHandler +{ + private HashMap vacuumPlayers; + private HashMap cloakPlayersTimers; + private long lastTimer = 0; - private final int CLOAK_CHECK_TIMEOUT_TICKS = 100; - private final int AIR_BLOCK_TICKS = 20; - private final int AIR_TANK_TICKS = 300; - private final int AIR_DROWN_TICKS = 20; + private final int CLOAK_CHECK_TIMEOUT_SEC = 5; - public SpaceEventHandler() { - entity_airBlock = new HashMap(); - player_airTank = new HashMap(); - player_cloakTicks = new HashMap(); + public SpaceEventHandler() + { + vacuumPlayers = new HashMap(); + cloakPlayersTimers = new HashMap(); + this.lastTimer = 0; } @ForgeSubscribe - public void livingUpdate(LivingUpdateEvent event) { + public void livingUpdate(LivingUpdateEvent event) + { EntityLivingBase entity = event.entityLiving; - int x = MathHelper.floor_double(entity.posX); - int y = MathHelper.floor_double(entity.posY); - int z = MathHelper.floor_double(entity.posZ); - - // Instant kill if entity exceeds world's limit - if (x > WarpDrive.WORLD_LIMIT_BLOCKS || z > WarpDrive.WORLD_LIMIT_BLOCKS) { - if (entity instanceof EntityPlayerMP) { - if (((EntityPlayerMP)entity).capabilities.isCreativeMode) { + + if (Math.abs(MathHelper.floor_double(entity.posX)) > WarpDrive.WORLD_LIMIT_BLOCKS || Math.abs(MathHelper.floor_double(entity.posZ)) > WarpDrive.WORLD_LIMIT_BLOCKS) + { + if (entity instanceof EntityPlayerMP) + { + if (((EntityPlayerMP)entity).capabilities.isCreativeMode) + { return; } } @@ -60,193 +50,153 @@ public class SpaceEventHandler { entity.attackEntityFrom(DamageSource.outOfWorld, 9000); return; } - if (entity instanceof EntityPlayerMP) { + if (entity instanceof EntityPlayerMP) updatePlayerCloakState(entity); - - // skip players in creative - if (((EntityPlayerMP)entity).theItemInWorldManager.getGameType() == EnumGameType.CREATIVE) { - return; - } - } - - // skip dead or invulnerable entities - if (entity.isDead || entity.isEntityInvulnerable()) { - return; - } - - // If entity is in vacuum, check and start consuming air cells - if (entity.worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID || entity.worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) { - int id1 = entity.worldObj.getBlockId(x, y, z); - int id2 = entity.worldObj.getBlockId(x, y - 1, z); - boolean inVacuum = (id1 != WarpDriveConfig.airID && id2 != WarpDriveConfig.airID); - Integer air; - if (!inVacuum) {// In space with air blocks - air = entity_airBlock.get(entity.entityId); - if (air == null) { - entity_airBlock.put(entity.entityId, AIR_BLOCK_TICKS); - } else if (air <= 1) {// time elapsed => consume air block - entity_airBlock.put(entity.entityId, AIR_BLOCK_TICKS); - - int metadata; - if (id1 == WarpDriveConfig.airID) { - metadata = entity.worldObj.getBlockMetadata(x, y, z); - if (metadata > 0 && metadata < 15) { - entity.worldObj.setBlockMetadataWithNotify(x, y, z, metadata - 1, 2); - } - } else { - metadata = entity.worldObj.getBlockMetadata(x, y - 1, z); - if (metadata > 0 && metadata < 15) { - entity.worldObj.setBlockMetadataWithNotify(x, y - 1, z, metadata - 1, 2); - } - } - } else { - entity_airBlock.put(entity.entityId, air - 1); - } - } else {// In space without air blocks - // Damage entity if in vacuum without protection - if (entity instanceof EntityPlayerMP) { - EntityPlayerMP player = (EntityPlayerMP)entity; - air = player_airTank.get(player.username); - boolean hasHelmet = false; - ItemStack helmetStack = player.getCurrentArmor(3); - if (helmetStack != null) { - Item helmet = helmetStack.getItem(); - if (helmet instanceof IBreathingHelmet) { - IBreathingHelmet breathHelmet = (IBreathingHelmet)helmet; - if (breathHelmet.canBreath(player)) { - hasHelmet = true; - if (air == null) {// new player in space => grace period - player_airTank.put(player.username, AIR_TANK_TICKS); - } else if (air <= 1) { - if (breathHelmet.removeAir(player)) { - player_airTank.put(player.username, AIR_TANK_TICKS); - } else { - player_airTank.put(player.username, AIR_DROWN_TICKS); - player.attackEntityFrom(DamageSource.drown, 2.0F); - } - } else { - player_airTank.put(player.username, air - 1); - } + // If player in vaccum, check and start consuming air cells + if (entity.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID || entity.worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) + { + boolean inVacuum = isEntityInVacuum(entity); + + // Damage entity if in vacuum without protection + if (inVacuum) + { + if (entity instanceof EntityPlayerMP) + { + + if (((EntityPlayerMP)entity).getCurrentArmor(3) != null && WarpDriveConfig.i.SpaceHelmets.contains(((EntityPlayerMP)entity).getCurrentArmor(3).itemID)) + { + Integer airValue = vacuumPlayers.get(((EntityPlayerMP)entity).username); + + if (airValue == null) + { + vacuumPlayers.put(((EntityPlayerMP)entity).username, 300); + airValue = 300; + } + + if (airValue <= 0) + { + if (consumeO2(((EntityPlayerMP)entity).inventory.mainInventory)) + { + setPlayerAirValue(entity, 300); + ((EntityPlayerMP)entity).inventory.addItemStackToInventory(new ItemStack(WarpDriveConfig.i.IC2_Air[0],1,0)); } - } else if (WarpDriveConfig.SpaceHelmets.contains(helmetStack.itemID)) { - hasHelmet = true; - if (air == null) {// new player in space => grace period - player_airTank.put(player.username, AIR_TANK_TICKS); - } else if (air <= 1) { - if (consumeO2(player.inventory.mainInventory, player)) { - player_airTank.put(player.username, AIR_TANK_TICKS); - } else { - player_airTank.put(player.username, AIR_DROWN_TICKS); - entity.attackEntityFrom(DamageSource.drown, 2.0F); - } - } else { - player_airTank.put(player.username, air - 1); + else + { + setPlayerAirValue(entity, 0); + entity.attackEntityFrom(DamageSource.drown, 1); } } + else + { + setPlayerAirValue(entity, airValue - 1); + } } - - if (!hasHelmet) { - if (air == null) {// new player in space => grace period - player_airTank.put(player.username, AIR_TANK_TICKS); - } else if (air <= 1) { - player_airTank.put(player.username, AIR_DROWN_TICKS); - entity.attackEntityFrom(DamageSource.drown, 2.0F); - } else { - player_airTank.put(player.username, air - 1); - } + else + { + entity.attackEntityFrom(DamageSource.drown, 1); } // If player falling down, teleport on earth - if (entity.posY < -10.0D) { - player.mcServer.getConfigurationManager().transferPlayerToDimension(player, 0, new SpaceTeleporter(DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID), 0, x, 250, z)); - player.setFire(30); - player.setPositionAndUpdate(entity.posX, 250.0D, entity.posZ); + if (entity.posY < -10.0D) + { + ((EntityPlayerMP)entity).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) entity), 0, new SpaceTeleporter(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), 0, MathHelper.floor_double(entity.posX), 250, MathHelper.floor_double(entity.posZ))); + ((EntityPlayerMP)entity).setFire(30); + ((EntityPlayerMP)entity).setPositionAndUpdate(entity.posX, 250D, entity.posZ); } - } else { - entity_airBlock.put(entity.entityId, 0); - entity.attackEntityFrom(DamageSource.drown, 2.0F); + } + else + { + entity.attackEntityFrom(DamageSource.drown, 1); } } } } - private void updatePlayerCloakState(EntityLivingBase entity) { + private void updatePlayerCloakState(EntityLivingBase entity) + { + // Make sure for elapsed time is second after last update + if (System.currentTimeMillis() - this.lastTimer > 1000) + lastTimer = System.currentTimeMillis(); + else + return; + try { - EntityPlayerMP player = (EntityPlayerMP)entity; - Integer cloakTicks = player_cloakTicks.get(player.username); + EntityPlayerMP p = (EntityPlayerMP)entity; + Integer cloakTicks = this.cloakPlayersTimers.get(p.username); - if (cloakTicks == null) { - player_cloakTicks.put(player.username, 0); + if (cloakTicks == null) + { + this.cloakPlayersTimers.remove(p.username); + this.cloakPlayersTimers.put(p.username, 0); + return; } - if (cloakTicks >= CLOAK_CHECK_TIMEOUT_TICKS) { - player_cloakTicks.put(player.username, 0); + if (cloakTicks >= CLOAK_CHECK_TIMEOUT_SEC) + { + this.cloakPlayersTimers.remove(p.username); + this.cloakPlayersTimers.put(p.username, 0); - List cloaks = WarpDrive.instance.cloaks.getCloaksForPoint(player.worldObj.provider.dimensionId, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ), false); - if (cloaks.size() != 0) { - //WarpDrive.debugPrint("[Cloak] Player inside " + cloaks.size() + " cloaked areas"); - for (CloakedArea area : cloaks) { - //WarpDrive.debugPrint("[Cloak] Frequency: " + area.frequency + ". In: " + area.isPlayerInArea(p) + ", W: " + area.isPlayerWithinArea(p)); - if (!area.isPlayerInArea(player.username) && area.isEntityWithinArea(player)) { - area.playerEnteringCloakedArea(player); + List cloaks = WarpDrive.instance.cloaks.getCloaksForPoint(p.worldObj.provider.dimensionId, MathHelper.floor_double(p.posX), MathHelper.floor_double(p.posY), MathHelper.floor_double(p.posZ), false); + if (cloaks.size() != 0) + { + //System.out.println("[Cloak] Player inside " + cloaks.size() + " cloaked areas"); + for (CloakedArea area : cloaks) + { + //System.out.println("[Cloak] Frequency: " + area.frequency + ". In: " + area.isPlayerInArea(p) + ", W: " + area.isPlayerWithinArea(p)); + if (!area.isPlayerInArea(p) && area.isPlayerWithinArea(p)) + { + WarpDrive.instance.cloaks.playerEnteringCloakedArea(area, p); } } - } else { - //WarpDrive.debugPrint("[Cloak] Player is not inside any cloak fields. Check, which field player may left..."); - WarpDrive.instance.cloaks.checkPlayerLeftArea(player); + } else + { + //System.out.println("[Cloak] Player is not inside any cloak fields. Check, which field player may left..."); + WarpDrive.instance.cloaks.checkPlayerLeavedArea(p); } - } else { - player_cloakTicks.put(player.username, cloakTicks + 1); } - } catch (Exception e) { - e.printStackTrace(); - } + else + { + this.cloakPlayersTimers.remove(p.username); + this.cloakPlayersTimers.put(p.username, cloakTicks + 1); + } + } catch (Exception e) { e.printStackTrace(); } } - private static boolean consumeO2(ItemStack[] inventory, EntityPlayerMP entityPlayer) { - for (int j = 0; j < inventory.length; ++j) { - if (inventory[j] != null && inventory[j].itemID == WarpDriveConfig.IC2_Air[0] && inventory[j].getItemDamage() == WarpDriveConfig.IC2_Air[1]) { - inventory[j].stackSize--; - if (inventory[j].stackSize <= 0) { - inventory[j] = null; - } + private void setPlayerAirValue(EntityLivingBase entity, Integer air) + { + vacuumPlayers.remove(((EntityPlayerMP)entity).username); + vacuumPlayers.put(((EntityPlayerMP)entity).username, air); + } - if (WarpDriveConfig.IC2_Empty.length != 0) { -// WarpDrive.debugPrint("giveEmptyCell"); - ItemStack emptyCell = new ItemStack(WarpDriveConfig.IC2_Empty[0], 1, WarpDriveConfig.IC2_Empty[1]); - if (!entityPlayer.inventory.addItemStackToInventory(emptyCell)) { - World world = entityPlayer.worldObj; - EntityItem itemEnt = new EntityItem(world, entityPlayer.posX, entityPlayer.posY, entityPlayer.posZ, emptyCell); - entityPlayer.worldObj.spawnEntityInWorld(itemEnt); - } - } + /** + * Проверка, находится ли Entity в открытом космосе + * @param e + * @return + */ + private boolean isEntityInVacuum(Entity e) + { + int x = MathHelper.floor_double(e.posX); + int y = MathHelper.floor_double(e.posY); + int z = MathHelper.floor_double(e.posZ); + int id1 = e.worldObj.getBlockId(x, y, z); + int id2 = e.worldObj.getBlockId(x, y + 1, z); + + if (id1 == WarpDriveConfig.i.airID || id2 == WarpDriveConfig.i.airID) + return false; + return true; + } + + private boolean consumeO2(ItemStack[] i) + { + for (int j = 0; j < i.length; ++j) + if (i[j] != null && i[j].itemID == WarpDriveConfig.i.IC2_Air[0] && i[j].getItemDamage() == WarpDriveConfig.i.IC2_Air[1]) + { + if (--i[j].stackSize <= 0) + i[j] = null; return true; } - } return false; } - - @ForgeSubscribe - public void livingFall(LivingFallEvent event) - { - EntityLivingBase entity = event.entityLiving; - float distance = event.distance; - - if (entity instanceof EntityPlayer) - { - EntityPlayer player = (EntityPlayer) entity; - int check = MathHelper.ceiling_float_int(distance - 3.0F); - - if (check > 0) - { - if ((player.getCurrentArmor(0) != null && player.getCurrentArmor(0).itemID == Items.getItem("quantumBoots").itemID) || - (player.getCurrentArmor(2) != null && WarpDriveConfig.Jetpacks.contains(player.getCurrentArmor(2).itemID))) - { - event.setCanceled(true); // Don't damage player - } - } - } - } } diff --git a/src/cr0s/WarpDrive/SpaceGenerator.java b/src/cr0s/WarpDrive/SpaceGenerator.java index 374dd39f..784e0cd5 100644 --- a/src/cr0s/WarpDrive/SpaceGenerator.java +++ b/src/cr0s/WarpDrive/SpaceGenerator.java @@ -35,7 +35,7 @@ public class SpaceGenerator extends ChunkProviderGenerate implements IChunkProvi @Override public Chunk provideChunk(int par1, int par2) { - this.rand.setSeed(par1 * 341873128712L + par2 * 132897987541L); + this.rand.setSeed((long) par1 * 341873128712L + (long) par2 * 132897987541L); byte[] var3 = new byte[32768]; generateTerrain(par1, par2, var3); //this.caveGenerator.generate(this, this.worldObj, par1, par2, var3); @@ -156,7 +156,8 @@ public class SpaceGenerator extends ChunkProviderGenerate implements IChunkProvi } @Override - public List getPossibleCreatures(EnumCreatureType var1, int var2, int var3, int var4) + public List getPossibleCreatures(EnumCreatureType var1, int var2, int var3, + int var4) { // TODO Auto-generated method stub return null; diff --git a/src/cr0s/WarpDrive/SpaceProvider.java b/src/cr0s/WarpDrive/SpaceProvider.java index 3b991da4..88ea3e0c 100644 --- a/src/cr0s/WarpDrive/SpaceProvider.java +++ b/src/cr0s/WarpDrive/SpaceProvider.java @@ -2,6 +2,7 @@ package cr0s.WarpDrive; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChunkCoordinates; @@ -109,7 +110,7 @@ public class SpaceProvider extends WorldProvider for (int var2 = 0; var2 <= 15; ++var2) { - float var3 = 1.0F - var2 / 15.0F; + float var3 = 1.0F - (float)var2 / 15.0F; this.lightBrightnessTable[var2] = (1.0F - var3) / (var3 * 3.0F + 1.0F) * (1.0F - var1) + var1; } } @@ -132,14 +133,14 @@ public class SpaceProvider extends WorldProvider { setCloudRenderer(new CloudRenderBlank()); //setSkyRenderer(new SpaceSkyRenderer()); - return this.worldObj.getWorldVec3Pool().getVecFromPool(0.0D, 0.0D, 0.0D); + return this.worldObj.getWorldVec3Pool().getVecFromPool((double) 0, (double) 0, (double) 0); } @SideOnly(Side.CLIENT) @Override public Vec3 getFogColor(float par1, float par2) { - return this.worldObj.getWorldVec3Pool().getVecFromPool(0.0D, 0.0D, 0.0D); + return this.worldObj.getWorldVec3Pool().getVecFromPool((double) 0, (double) 0, (double) 0); } @SideOnly(Side.CLIENT) diff --git a/src/cr0s/WarpDrive/SpaceSkyRenderer.java b/src/cr0s/WarpDrive/SpaceSkyRenderer.java index df9c791f..70e4077b 100644 --- a/src/cr0s/WarpDrive/SpaceSkyRenderer.java +++ b/src/cr0s/WarpDrive/SpaceSkyRenderer.java @@ -264,12 +264,12 @@ public class SpaceSkyRenderer extends IRenderHandler var2.draw(); } - private static Vec3 getCustomSkyColor() + private Vec3 getCustomSkyColor() { return Vec3.fakePool.getVecFromPool(0.26796875D, 0.1796875D, 0.0D); } - public static float getSkyBrightness(float par1) + public float getSkyBrightness(float par1) { final float var2 = FMLClientHandler.instance().getClient().theWorld.getCelestialAngle(par1); float var3 = 1.0F - (MathHelper.sin(var2 * (float) Math.PI * 2.0F) * 2.0F + 0.25F); diff --git a/src/cr0s/WarpDrive/SpaceTpCommand.java b/src/cr0s/WarpDrive/SpaceTpCommand.java index 51df1238..c9c1e276 100644 --- a/src/cr0s/WarpDrive/SpaceTpCommand.java +++ b/src/cr0s/WarpDrive/SpaceTpCommand.java @@ -7,49 +7,53 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.MathHelper; import net.minecraft.world.WorldServer; -public class SpaceTpCommand extends CommandBase { +public class SpaceTpCommand extends CommandBase +{ @Override - public int getRequiredPermissionLevel() { + public int getRequiredPermissionLevel() + { return 2; } @Override - public String getCommandName() { + public String getCommandName() + { return "space"; } @Override - public void processCommand(ICommandSender icommandsender, String[] astring) { - EntityPlayerMP player = null; + public void processCommand(ICommandSender icommandsender, String[] astring) + { + EntityPlayerMP player = (EntityPlayerMP)icommandsender; MinecraftServer server = MinecraftServer.getServer(); - int targetDim = WarpDriveConfig.G_SPACE_DIMENSION_ID; + int targetDim = WarpDrive.instance.spaceDimID; - if (icommandsender != null && icommandsender instanceof EntityPlayerMP) { - player = (EntityPlayerMP)icommandsender; - } - if (astring.length >= 1) { - if ("hyper".equals(astring[0])) { - targetDim = WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID; - } else if ("overworld".equals(astring[0])) { - targetDim = 0; - } else { + if (astring.length >= 1) + { + if ("hyper".equals(astring[0])) + { + targetDim = WarpDrive.instance.hyperSpaceDimID; + } + else + { + notifyAdmins(icommandsender, "/space: teleporting player " + astring[0] + " to space", new Object[0]); player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(astring[0]); } } - if (player == null) { - notifyAdmins(icommandsender, "/space: undefined player"); - return; + if (player == null) + { + return; } - WorldServer targetWorld = server.worldServerForDimension(targetDim); - notifyAdmins(icommandsender, "/space: teleporting player " + player.getDisplayName() + " to " + targetDim + ":" + targetWorld.getWorldInfo().getWorldName(), new Object[0]); - SpaceTeleporter teleporter = new SpaceTeleporter(targetWorld, 0, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)); + WorldServer to = server.worldServerForDimension(targetDim); + SpaceTeleporter teleporter = new SpaceTeleporter(to, 0, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)); server.getConfigurationManager().transferPlayerToDimension(player, targetDim, teleporter); } @Override - public String getCommandUsage(ICommandSender icommandsender) { - return "/space [hyper|overworld|]"; + public String getCommandUsage(ICommandSender icommandsender) + { + return "/space [hyper|]"; } } diff --git a/src/cr0s/WarpDrive/SpaceWorldGenerator.java b/src/cr0s/WarpDrive/SpaceWorldGenerator.java index 30582863..8b129202 100644 --- a/src/cr0s/WarpDrive/SpaceWorldGenerator.java +++ b/src/cr0s/WarpDrive/SpaceWorldGenerator.java @@ -1,9 +1,10 @@ package cr0s.WarpDrive; +import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.IWorldGenerator; - import java.util.Random; - +import java.util.List; +import java.util.ArrayList; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; @@ -39,7 +40,7 @@ public class SpaceWorldGenerator implements IWorldGenerator @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { - if (world.provider.dimensionId != WarpDriveConfig.G_SPACE_DIMENSION_ID) + if (world.provider.dimensionId != WarpDrive.instance.spaceDimID) return; int x = (chunkX * 16) + (5 - random.nextInt(10)); int z = (chunkZ * 16) + (5 - random.nextInt(10)); @@ -47,294 +48,233 @@ public class SpaceWorldGenerator implements IWorldGenerator return; int y = Y_LIMIT_DOWN + random.nextInt(Y_LIMIT - Y_LIMIT_DOWN); // Moon setup - if (random.nextInt(700) == 1) + if (random.nextInt(8000) == 1) generateMoon(world, x, y, z); // Simple asteroids - else if (random.nextInt(150) == 1) { - generateAsteroidOfBlock(world, x, y, z, 6, 11, -1, 0); + else if (random.nextInt(500) == 1) + generateAsteroid(world, x, y, z, 6, 11); // Random asteroid of block - } else if (random.nextInt(400) == 1) { + else if (random.nextInt(1000) == 1) + { generateRandomAsteroid(world, x, y, z, 6, 11); - if (random.nextBoolean()) { + if (random.nextBoolean()) generateGasCloudOfColor(world, x, y, z, 6, 11, random.nextInt(12)); - } - } else if (random.nextInt(200) == 1) {// Ice asteroid + } + // Ice asteroid + else if (random.nextInt(2000) == 1) generateAsteroidOfBlock(world, x, y, z, 6, 11, Block.ice.blockID, 0); - } else if (random.nextInt(500) == 1) {// Asteroid field + // Asteroid field + else if (random.nextInt(3500) == 1) generateAsteroidField(world, x, y, z); - } else if (random.nextInt(1400) == 1) {// Diamond asteroid - generateAsteroidOfBlock(world, x, y, z, 3, 2, Block.oreDiamond.blockID, 0); + // Diamond asteroid + else if (random.nextInt(10000) == 1) + { + generateAsteroidOfBlock(world, x, y, z, 4, 6, Block.oreDiamond.blockID, 0); // Diamond block core world.setBlock(x, y, z, Block.blockDiamond.blockID, 0, 2); - if (random.nextBoolean()) { + if (random.nextBoolean()) + generateGasCloudOfColor(world, x, y, z, 6, 11, random.nextInt(12)); + } + // Quartz asteroid + else if (WarpDriveConfig.i.isAELoaded && random.nextInt(20000) == 1) + { + generateAsteroidOfBlock(world, x, y, z, 4, 6, WarpDriveConfig.i.getAEBlock("blkQuartzOre").itemID, WarpDriveConfig.i.getAEBlock("blkQuartzOre").getItemDamage()); + if (random.nextBoolean()) generateGasCloudOfColor(world, x, y, z, 6, 11, random.nextInt(12)); - } - } else if (WarpDriveConfig.isAppliedEnergisticsLoaded && random.nextInt(1600) == 1) {// Quartz asteroid - generateAsteroidOfBlock(world, x, y, z, 3, 2, WarpDriveConfig.getAEBlock("blkQuartzOre").itemID, WarpDriveConfig.getAEBlock("blkQuartzOre").getItemDamage()); - if (random.nextBoolean()) { - generateGasCloudOfColor(world, x, y, z, 4, 7, random.nextInt(12)); - } } } - public static void generateMoon(World world, int x, int y, int z) { - int coreRadius = 5 + world.rand.nextInt(12); - int moonRadius = coreRadius + 5 + world.rand.nextInt(26); - int y2 = Math.max(moonRadius + 6, Math.min(y, 255 - moonRadius - 6)); - System.out.println("Generating moon at " + x + " " + y2 + " " + z); - - int[] block = WarpDriveConfig.getDefaultSurfaceBlock(world.rand, world.rand.nextInt(10) > 8, true); - + public void generateMoon(World world, int x, int y, int z) + { + System.out.println("Generating moon at " + x + " " + y + " " + z); + int t = generateSphereEntity(world, x, y, z, MOON_RADIUS, false, 0, 0); // Generate moon's core - if (block[0] == Block.netherrack.blockID) { - generateSphereDirect(world, x, y2, z, coreRadius, false, Block.lavaStill.blockID, 0, false); // Lava core - world.setBlock(x, y2, z, Block.bedrock.blockID, 0, 0); - } else if (block[0] != Block.whiteStone.blockID) { - if (world.rand.nextInt(100) >= 10) { - generateSphereDirect(world, x, y2, z, coreRadius, false, Block.lavaStill.blockID, 0, false); // Lava core - world.setBlock(x, y2, z, Block.bedrock.blockID, 0, 0); - generateSphereDirect(world, x, y2, z, coreRadius + 1, false, Block.obsidian.blockID, 0, true); // Obsidian shell - } else { - coreRadius = Math.max(coreRadius, 7); - generateSphereDirect(world, x, y2, z, coreRadius, false, Block.leaves.blockID, 0, false); - world.setBlock(x, y2, z, Block.bedrock.blockID, 0, 0); - generateSmallShip(world, x, y2, z, coreRadius - 6); + if (t == Block.netherrack.blockID) + generateSphere2(world, x, y, z, MOON_CORE_RADIUS, false, Block.lavaStill.blockID, 0, false); // Lava core + else if (t != Block.whiteStone.blockID) + { + if (world.rand.nextInt(10) > 2) + { + generateSphere2(world, x, y, z, MOON_CORE_RADIUS, false, Block.lavaStill.blockID, 0, false); // Lava core + generateSphere2(world, x, y, z, MOON_CORE_RADIUS + 1, false, Block.obsidian.blockID, 0, true); // Obsidian shell + } + else + { + generateSphere2(world, x, y, z, MOON_CORE_RADIUS, false, 0, 0, false); + generateSmallShip(world, x, y, z); } } - - // Place bedrock blocks - world.setBlock(x + coreRadius , y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x - coreRadius , y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z + coreRadius , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z - coreRadius , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 + coreRadius , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 - coreRadius , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x + moonRadius / 2 , y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x - moonRadius / 2 , y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z + moonRadius / 2 , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z - moonRadius / 2 , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 + moonRadius / 2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 - moonRadius / 2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x + moonRadius - 10, y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x - moonRadius + 10, y2 , z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z + moonRadius - 10, Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 , z - moonRadius + 10, Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 + moonRadius - 10, z , Block.bedrock.blockID, 0, 0); - world.setBlock(x , y2 - moonRadius + 10, z , Block.bedrock.blockID, 0, 0); - // Generate moon's blocks - generateSphereEntity(world, x, y2, z, moonRadius, false, block[0], block[1], true); // Generate moon's atmosphere - if (world.rand.nextBoolean()) { - generateGasSphereEntity(world, x, y2, z, moonRadius + 2 + world.rand.nextInt(5), true, world.rand.nextInt(12)); - } + if (world.rand.nextBoolean()) + generateGasSphereEntity(world, x, y, z, MOON_RADIUS + 5, true, 1 + world.rand.nextInt(11)); + // Place bedrock blocks + world.setBlock(x, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x + MOON_CORE_RADIUS, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x - MOON_CORE_RADIUS, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z + MOON_CORE_RADIUS, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z - MOON_CORE_RADIUS, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y + MOON_CORE_RADIUS, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y - MOON_CORE_RADIUS, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x + MOON_RADIUS / 2, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x - MOON_RADIUS / 2, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z + MOON_RADIUS / 2, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z - MOON_RADIUS / 2, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y + MOON_RADIUS / 2, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y - MOON_RADIUS / 2, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x + MOON_RADIUS - 10, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x - MOON_RADIUS + 10, y, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z + MOON_RADIUS - 10, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y, z - MOON_RADIUS + 10, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y + MOON_RADIUS - 10, z, Block.bedrock.blockID, 0, 0); + world.setBlock(x, y - MOON_RADIUS + 10, z, Block.bedrock.blockID, 0, 0); } - private static void placeStarCore(World world, int x, int y, int z, int radius) { + private void placeStarCore(World world, int x, int y, int z, int radius) + { EntityStarCore core = new EntityStarCore(world, x, y, z, radius); core.xCoord = x; core.yCoord = y; core.zCoord = z; - core.setPosition(x, y, z); + core.setPosition((double)x, (double)y, (double)z); world.spawnEntityInWorld(core); } - - public void generateStar(World world, int x, int y, int z, Integer type) { - Integer starClass = type == -1 ? world.rand.nextInt(3) : type; - Integer y2 = y; + public void generateStar(World world, int x, int y, int z) + { + int starClass = world.rand.nextInt(3); System.out.println("Generating star (class " + starClass + ") at " + x + " " + y + " " + z); - switch (starClass) { + switch (starClass) + { case 0: // red dwarf - y2 = Math.max(RED_DWARF_RADIUS + 6, Math.min(y, 255 - RED_DWARF_RADIUS - 6)); - generateSphereEntity(world, x, y2, z, RED_DWARF_RADIUS, false, Block.blockRedstone.blockID, 0, false); + generateSphereEntity(world, x, y, z, RED_DWARF_RADIUS, false, Block.blockRedstone.blockID, 0); // Heliosphere of red gas - generateGasSphereEntity(world, x, y2, z, RED_DWARF_RADIUS + 6, true, 1); - placeStarCore(world, x, y2, z, RED_DWARF_RADIUS + 6); + generateGasSphereEntity(world, x, y, z, RED_DWARF_RADIUS + 6, true, 1); + placeStarCore(world, x, y, z, RED_DWARF_RADIUS + 6); break; - case 1: - y2 = Math.max(YELLOW_GIANT_RADIUS + 6, Math.min(y, 255 - YELLOW_GIANT_RADIUS - 6)); - generateSphereEntity(world, x, y2, z, YELLOW_GIANT_RADIUS, false, Block.glowStone.blockID, 0, false); + case 1: // yellow giant + generateSphereEntity(world, x, y, z, YELLOW_GIANT_RADIUS, false, Block.glowStone.blockID, 0); // Heliosphere of yellow gas - generateGasSphereEntity(world, x, y2, z, YELLOW_GIANT_RADIUS + 6, true, 3); - placeStarCore(world, x, y2, z, YELLOW_GIANT_RADIUS + 6); + generateGasSphereEntity(world, x, y, z, YELLOW_GIANT_RADIUS + 6, true, 3); + placeStarCore(world, x, y, z, YELLOW_GIANT_RADIUS + 6); break; case 2: - y2 = Math.max(YELLOW_SUPERGIANT_RADIUS + 6, Math.min(y, 255 - YELLOW_SUPERGIANT_RADIUS - 6)); - generateSphereEntity(world, x, y2, z, YELLOW_SUPERGIANT_RADIUS, false, Block.glowStone.blockID, 0, false); + generateSphereEntity(world, x, y, z, YELLOW_SUPERGIANT_RADIUS, false, Block.glowStone.blockID, 0); // Heliosphere of yellow gas - generateGasSphereEntity(world, x, y2, z, YELLOW_SUPERGIANT_RADIUS + 6, true, 3); - placeStarCore(world, x, y2, z, YELLOW_SUPERGIANT_RADIUS + 6); + generateGasSphereEntity(world, x, y, z, YELLOW_SUPERGIANT_RADIUS + 6, true, 3); + placeStarCore(world, x, y, z, YELLOW_SUPERGIANT_RADIUS + 6); break; } } - private static void generateSphereEntity(World world, int x, int y, int z, int radius, boolean hollow, int blockID, int blockMeta, boolean generateOres) { - EntitySphereGen esg = new EntitySphereGen(world, x, y, z, radius, blockID, blockMeta, hollow, true, generateOres); + private int generateSphereEntity(World world, int x, int y, int z, int radius, boolean hollow, int blockID, int blockMeta) + { + EntitySphereGen esg = new EntitySphereGen(world, x, y, z, radius, blockID, blockMeta, hollow, false); + esg.xCoord = x; + esg.yCoord = y; + esg.zCoord = z; + world.spawnEntityInWorld(esg); + return esg.defaultBlock[0]; + } + + private void generateGasSphereEntity(World world, int x, int y, int z, int radius, boolean hollow, int color) + { + EntitySphereGen esg = new EntitySphereGen(world, x, y, z, radius, WarpDriveConfig.i.gasID, color, hollow, true); + esg.xCoord = x; + esg.yCoord = y; + esg.zCoord = z; world.spawnEntityInWorld(esg); } - private static void generateGasSphereEntity(World world, int x, int y, int z, int radius, boolean hollow, int color) { - EntitySphereGen esg = new EntitySphereGen(world, x, y, z, radius, WarpDriveConfig.gasID, color, hollow, true, false); - world.spawnEntityInWorld(esg); + private void generateSmallShip(World world, int x, int y, int z) + { + x = x + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(10)); + y = y + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(10)); + z = z + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(10)); + System.out.println("Generating small ship at " + x + " " + y + " " + z); + new WorldGenSmallShip(world.rand.nextBoolean()).generate(world, world.rand, x, y, z); } - private static void generateSmallShip(World world, int x, int y, int z, int jitter) { - int x2 = x + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(jitter)); - int y2 = y + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(jitter)); - int z2 = z + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(jitter)); - System.out.println("Generating small ship at " + x2 + "," + y2 + "," + z2); - new WorldGenSmallShip(world.rand.nextBoolean()).generate(world, world.rand, x2, y2, z2); - } - - public static void generateRandomAsteroid(World world, int x, int y, int z, int asteroidSizeMax, int centerRadiusMax) { - if (world.rand.nextInt(30) == 1) { + private void generateRandomAsteroid(World world, int x, int y, int z, int asteroidSizeMax, int centerRadiusMax) + { + if (world.rand.nextInt(30) == 1) + { int[] t = new int[] {0, 0}; - if (world.rand.nextInt(25) == 1) { - while(t[0] == 0) { - t = WarpDriveConfig.getRandomNetherBlock(world.rand, 0, 0); - } - } else if (world.rand.nextInt(35) == 1) { - while(t[0] == 0) { - t = WarpDriveConfig.getRandomEndBlock(world.rand, 0, 0); - } - } else { - while(t[0] == 0) { - t = WarpDriveConfig.getRandomOverworldBlock(world.rand, 0, 0); - } - } - generateAsteroidOfBlock(world, x, y, z, Math.min(3, asteroidSizeMax), Math.min(2, centerRadiusMax), t[0], t[1]); - } else { - generateAsteroidOfBlock(world, x, y, z, asteroidSizeMax, centerRadiusMax, -1, 0); + if (world.rand.nextInt(25) == 1) + while(t[0] == 0) + t = WarpDriveConfig.i.getRandomNetherBlock(world.rand, 0, 0); + else if (world.rand.nextInt(50) == 1) + while(t[0] == 0) + t = WarpDriveConfig.i.getRandomEndBlock(world.rand, 0, 0); + else + while(t[0] == 0) + t = WarpDriveConfig.i.getRandomOverworldBlock(world.rand, 0, 0); + generateAsteroidOfBlock(world, x, y, z, asteroidSizeMax, centerRadiusMax, t[0], t[1]); } + else + generateAsteroid(world, x, y, z, asteroidSizeMax, centerRadiusMax); } - private static float binomialRandom(World world) { - float linear = world.rand.nextFloat(); - // ideal sphere repartition = x ^ 0.5 (sqrt) - // Dilution but slow to compute = 0.5 * ( x ^ 0.3 + 1 + (x - 1) ^ 3 ) - // Optimized 'pushed out' form = 1.25 - 0.625 / (0.5 + 2 * x) - // Natural sphere with ring = (1 - x ^ 2.5) * x ^ 0.5 + x ^ 4 - - // rectangular approach: return 0.5F * linear + 0.5F * linear * linear; - return 1.25F - 0.625F / (0.5F + 2.0F * linear); - } - public static void generateAsteroidField(World world, int x, int y1, int z) { - LocalProfiler.start("SpaceWorldGenerator.generateAsteroidField"); - // 6.0.1 au = 120 radius with 60 to 140 big + 60 to 140 small + 5 to 13 gaz - // 45238 blocks surface with 120 to 280 asteroids => 161 to 376 blocks per asteroid (big & small) - - // 6.0.2 av big = 80 to 180 radius with 40 to 90 big + 80 to 200 small + 5 to 13 gaz - // 20106 to 101787 surface with 120 to 290 asteroids => 69 to 848 blocks per asteroid - - // 6.0.2 av small = 30 to 80 radius with 2 to 22 big + 15 to 75 small + 0 to 3 gaz - // 2827 to 20106 surface with 17 to 97 asteroids => 29 to 1182 blocks per asteroid - - // random distanced one = 89727 surface 256 asteroids => 350 blocks per asteroid - - /* - boolean isBig = world.rand.nextInt(3) == 1; - int numOfBigAsteroids, numOfSmallAsteroids, numOfClouds, maxDistance, maxHeight; - if (isBig) { - numOfBigAsteroids = 40 + world.rand.nextInt(50); - numOfSmallAsteroids = 80 + world.rand.nextInt(120); - numOfClouds = 5 + world.rand.nextInt(8); - maxDistance = 80 + world.rand.nextInt(100); - maxHeight = 40 + world.rand.nextInt(40); - } else { - numOfBigAsteroids = 2 + world.rand.nextInt(20); - numOfSmallAsteroids = 15 + world.rand.nextInt(60); - numOfClouds = 0 + world.rand.nextInt(3); - maxDistance = 30 + world.rand.nextInt(50); - maxHeight = 30 + world.rand.nextInt(30); - }/**/ - - float surfacePerAsteroid = 80.0F + world.rand.nextFloat() * 300; - int maxDistance = 30 + world.rand.nextInt(170); - int maxDistanceBig = Math.round(maxDistance * (0.6F + 0.2F * world.rand.nextFloat())); - int maxDistanceSmall = Math.round(maxDistance * 1.1F); - float bigRatio = 0.3F + world.rand.nextFloat() * 0.3F; - float surfaceBig = (float) (Math.PI * Math.pow(maxDistanceBig, 2)); - float surfaceSmall = (float) (Math.PI * Math.pow(maxDistanceSmall, 2)); - int numOfBigAsteroids = Math.round(bigRatio * surfaceBig / surfacePerAsteroid); - int numOfSmallAsteroids = Math.round((1.0F - bigRatio) * surfaceSmall / surfacePerAsteroid); - int numOfClouds = Math.round(numOfBigAsteroids * 1.0F / (10.0F + world.rand.nextInt(10))); - int maxHeight = 70 + world.rand.nextInt(50); - int y2 = Math.min(240 - maxHeight, Math.max(y1, maxHeight)); - System.out.println("Generating asteroid field at " + x + "," + y2 + "," + z - + " qty " + numOfBigAsteroids + ", " + numOfSmallAsteroids + ", " + numOfClouds - + " over " + maxDistance + ", " + maxHeight + " surfacePerAsteroid " + String.format("%.1f", surfacePerAsteroid)); - + /** + * Asteroid field generator + * @param world мир + * @param x координата центра поля + * @param y координата центра поля + * @param z координата центра поля + */ + public void generateAsteroidField(World world, int x, int y, int z) + { + int numOfAsteroids = 15 + world.rand.nextInt(30); + int numOfClouds = 5 + world.rand.nextInt(10); + // Minimal distance between asteroids in field + final int FIELD_ASTEROID_MIN_DISTANCE = 5; + // Maximum distance + final int FIELD_ASTEROID_MAX_DISTANCE = 100; // Setting up of big asteroids - for (int i = 1; i <= numOfBigAsteroids; i++) { - float binomial = binomialRandom(world); - double bearing = world.rand.nextFloat() * 2.0D * Math.PI; - double yawn = world.rand.nextFloat() * Math.PI; - float horizontalRange = Math.max(6.0F, binomial * maxDistanceBig); - float verticalRange = Math.max(3.0F, binomial * maxHeight); - - int aX = (int) (x + Math.round(horizontalRange * Math.cos(bearing))); - int aY = (int) (y2 + Math.round(verticalRange * Math.cos(yawn))); - int aZ = (int) (z + Math.round(horizontalRange * Math.sin(bearing))); - /*System.out.println(String.format("Big asteroid: %.3f %.3f r %.3f r makes %3d, %3d, %3d", new Object[] { - Double.valueOf(binomial),Double.valueOf(bearing), Double.valueOf(yawn), - Integer.valueOf(aX), Integer.valueOf(aY), Integer.valueOf(aZ)}));/**/ + for (int i = 1; i <= numOfAsteroids; i++) + { + int aX = x + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aY = y + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aZ = z + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); // Place an asteroid generateRandomAsteroid(world, aX, aY, aZ, 4, 6); } - // Setting up small asteroids - for (int i = 1; i <= numOfSmallAsteroids; i++) { - float binomial = binomialRandom(world); - double bearing = world.rand.nextFloat() * 2.0D * Math.PI; - double yawn = world.rand.nextFloat() * Math.PI; - float horizontalRange = Math.max(6.0F, binomial * maxDistanceSmall); - float verticalRange = Math.max(3.0F, binomial * maxHeight); - - int aX = (int) (x + Math.round(horizontalRange * Math.cos(bearing))); - int aY = (int) (y2 + Math.round(verticalRange * Math.cos(yawn))); - int aZ = (int) (z + Math.round(horizontalRange * Math.sin(bearing))); - + for (int i = 1; i <= numOfAsteroids; i++) + { + int aX = x + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aY = y + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aZ = z + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); // Placing - if (world.rand.nextInt(400) != 1) { - generateRandomAsteroid(world, aX, aY, aZ, 3, 3); - } else { - generateSmallShip(world, aX, aY, aZ, 8); - } + if (world.rand.nextInt(100) != 0) + generateRandomAsteroid(world, aX, aY, aZ, 2, 2); + else + generateSmallShip(world, aX, aY, aZ); } - // Setting up gas clouds - for (int i = 1; i <= numOfClouds; i++) { - float binomial = binomialRandom(world); - double bearing = world.rand.nextFloat() * 2.0D * Math.PI; - double yawn = world.rand.nextFloat() * Math.PI; - float horizontalRange = Math.max(6.0F, binomial * maxDistanceBig); - float verticalRange = Math.max(3.0F, binomial * maxHeight); - - int aX = (int) (x + Math.round(horizontalRange * Math.cos(bearing))); - int aY = (int) (y2 + Math.round(verticalRange * Math.cos(yawn))); - int aZ = (int) (z + Math.round(horizontalRange * Math.sin(bearing))); - + for (int i = 1; i <= numOfClouds; i++) + { + int aX = x + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aY = y + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); + int aZ = z + (((world.rand.nextBoolean()) ? -1 : 1) * (FIELD_ASTEROID_MIN_DISTANCE + world.rand.nextInt(FIELD_ASTEROID_MAX_DISTANCE))); // Placing - if (world.rand.nextBoolean()) { + if (world.rand.nextInt(10) != 0) generateGasCloudOfColor(world, aX, aY, aZ, 12, 15, world.rand.nextInt(12)); - } } - - LocalProfiler.stop(); } /** * Gas cloud generator * - * @param x coordinate of center - * @param y coordinate of center - * @param z coordinate of center + * @param x x-coord of center + * @param y center + * @param z center * @param cloudSizeMax maximum gas cloud size (by number of balls it consists) * @param centerRadiusMax maximum radius of central ball */ - public static void generateGasCloudOfColor(World world, int x, int y, int z, int cloudSizeMax, int centerRadiusMax, int color) { + public void generateGasCloudOfColor(World world, int x, int y, int z, int cloudSizeMax, int centerRadiusMax, int color) + { int cloudSize = 1 + world.rand.nextInt(20); if (cloudSizeMax != 0) cloudSize = Math.min(cloudSizeMax, cloudSize); @@ -345,7 +285,8 @@ public class SpaceWorldGenerator implements IWorldGenerator // Asteroid's center generateGasSphereEntity(world, x, y, z, centerRadius, false, color); // Asteroids knolls - for (int i = 1; i <= cloudSize; i++) { + for (int i = 1; i <= cloudSize; i++) + { int radius = 2 + world.rand.nextInt(centerRadius); int newX = x + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); int newY = y + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); @@ -357,36 +298,65 @@ public class SpaceWorldGenerator implements IWorldGenerator /** * Asteroid of block generator * - * @param x coordinate of center - * @param y coordinate of center - * @param z coordinate of center + * @param x x-coord of center + * @param y center + * @param z center * @param asteroidSizeMax maximum asteroid size (by number of balls it consists) * @param centerRadiusMax maximum radius of central ball */ - private static void generateAsteroidOfBlock(World world, int x, int y, int z, int asteroidSizeMax, int centerRadiusMax, int blockID, int meta) { - // FIXME: get a proper range of random instead of capping it + private void generateAsteroidOfBlock(World world, int x, int y, int z, int asteroidSizeMax, int centerRadiusMax, int blockID, int meta) + { int asteroidSize = 1 + world.rand.nextInt(6); - if (asteroidSizeMax != 0) { + if (asteroidSizeMax != 0) asteroidSize = Math.min(asteroidSizeMax, asteroidSize); - } int centerRadius = 1 + world.rand.nextInt(6); - if (centerRadiusMax != 0) { + if (centerRadiusMax != 0) centerRadius = Math.min(centerRadiusMax, centerRadius); - } final int CENTER_SHIFT = 2; // Offset from center of central ball // Asteroid's center - int[] t = WarpDriveConfig.getDefaultSurfaceBlock(world.rand, true, false); - generateSphereDirect(world, x, y, z, centerRadius, true, blockID, meta, false, t); + int[] t = WarpDriveConfig.i.getDefaultSurfaceBlock(world.rand, true, false); + generateSphere2(world, x, y, z, centerRadius, true, blockID, meta, false, t); // Asteroids knolls - for (int i = 1; i <= asteroidSize; i++) { - int radius = 1 + world.rand.nextInt(centerRadius); + for (int i = 1; i <= asteroidSize; i++) + { + int radius = 2 + world.rand.nextInt(centerRadius); int newX = x + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); int newY = y + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); int newZ = z + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); - generateSphereDirect(world, newX, newY, newZ, radius, true, blockID, meta, false, t); + generateSphere2(world, newX, newY, newZ, radius, true, blockID, meta, false, t); } } - + + /** + * Asteroid generator + * + * @param x x-coord of center + * @param y center + * @param z center + * @param asteroidSizeMax maximum asteroid size (by number of balls it consists) + * @param centerRadiusMax maximum radius of central ball + */ + public void generateAsteroid(World world, int x, int y, int z, int asteroidSizeMax, int centerRadiusMax) + { + int asteroidSize = 1 + world.rand.nextInt(6); + if (asteroidSizeMax != 0) + asteroidSize = Math.min(asteroidSizeMax, asteroidSize); + int centerRadius = 1 + world.rand.nextInt(6); + if (centerRadiusMax != 0) + centerRadius = Math.min(centerRadiusMax, centerRadius); + final int CENTER_SHIFT = 2; + int[] t = WarpDriveConfig.i.getDefaultSurfaceBlock(world.rand, true, false); + generateSphere2(world, x, y, z, centerRadius, true, -1, 0, false, t); + for (int i = 1; i <= asteroidSize; i++) + { + int radius = 2 + world.rand.nextInt(centerRadius); + int newX = x + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); + int newY = y + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); + int newZ = z + (((world.rand.nextBoolean()) ? -1 : 1) * world.rand.nextInt(CENTER_SHIFT + centerRadius / 2)); + generateSphere2(world, newX, newY, newZ, radius, true, -1, 0, false, t); + } + } + /** * Sphere generator * @param world target world @@ -398,69 +368,73 @@ public class SpaceWorldGenerator implements IWorldGenerator * @param forcedID sphere of specified blocks or random blocks if not specified * @return */ - public static void generateSphereDirect(World world, int xCoord, int yCoord, int zCoord, double radius, boolean corrupted, int forcedID, int meta, boolean hollow) { - if (forcedID == -1) { - generateSphereDirect(world, xCoord, yCoord, zCoord, radius, corrupted, forcedID, meta, hollow, WarpDriveConfig.getDefaultSurfaceBlock(world.rand, corrupted, false)); - } else { - generateSphereDirect(world, xCoord, yCoord, zCoord, radius, corrupted, forcedID, meta, hollow, new int[] {forcedID, meta}); - } + public void generateSphere2(World world, int xCoord, int yCoord, int zCoord, double radius, boolean corrupted, int forcedID, int meta, boolean hollow) + { + if (forcedID == -1) + generateSphere2(world, xCoord, yCoord, zCoord, radius, corrupted, forcedID, meta, hollow, WarpDriveConfig.i.getDefaultSurfaceBlock(world.rand, corrupted, false)); + else + generateSphere2(world, xCoord, yCoord, zCoord, radius, corrupted, forcedID, meta, hollow, new int[] {forcedID, meta}); } - public static void generateSphereDirect(World world, int xCoord, int yCoord, int zCoord, double radius, boolean corrupted, int forcedID, int meta, boolean hollow, int[] defaultBlock) { - double radiusC = radius + 0.5D; // Radius from center of block - double radiusSq = radiusC * radiusC; // Optimization to avoid sqrts... - double radius1Sq = (radiusC - 1.0D) * (radiusC - 1.0D); // for hollow sphere - int ceilRadius = (int) Math.ceil(radiusC); + public void generateSphere2(World world, int xCoord, int yCoord, int zCoord, double radius, boolean corrupted, int forcedID, int meta, boolean hollow, int[] defaultBlock) + { + radius += 0.5D; // Radius from center of block + double radiusSq = radius * radius; // Optimization to avoid sqrts... + double radius1Sq = (radius - 1.0D) * (radius - 1.0D); // for hollow sphere + int ceilRadius = (int) Math.ceil(radius); - int[] blockID = new int[] {0, 0}; - if (forcedID != -1) { + int[] blockID; + if (forcedID == 0) + blockID = new int[] {0, 0}; + else if (forcedID == -1) + blockID = new int[] {forcedID, meta};//SRANYA JABA might not have been initialized + else blockID = new int[] {forcedID, meta}; - } // Pass the cube and check points for sphere equation x^2 + y^2 + z^2 = r^2 - for (int x = 0; x <= ceilRadius; x++) { - double x2 = (x + 0.5D) * (x + 0.5D); - for (int y = 0; y <= ceilRadius; y++) { - double y2 = (y + 0.5D) * (y + 0.5D); - for (int z = 0; z <= ceilRadius; z++) { - double z2 = (z + 0.5D) * (z + 0.5D); - double dSq = x2 + y2 + z2; // Distance from current position to center + for (int x = 0; x <= ceilRadius; x++) + for (int y = 0; y <= ceilRadius; y++) + for (int z = 0; z <= ceilRadius; z++) + { + double dSq = lengthSq(x, y, z); // Distance from current position to center // Skip too far blocks if (dSq > radiusSq) continue; // Hollow sphere condition - if ((hollow) && ((dSq < radius1Sq) || ((lengthSq(x + 1.5D, y + 0.5D, z + 0.5D) <= radiusSq) && (lengthSq(x + 0.5D, y + 1.5D, z + 0.5D) <= radiusSq) && (lengthSq(x + 0.5D, y + 0.5D, z + 1.5D) <= radiusSq)))) + if ((hollow) && ((dSq < radius1Sq) || ((lengthSq(x + 1, y, z) <= radiusSq) && (lengthSq(x, y + 1, z) <= radiusSq) && (lengthSq(x, y, z + 1) <= radiusSq)))) continue; // Place blocks - if (!corrupted || world.rand.nextInt(5) != 1) { + if (!corrupted || world.rand.nextInt(10) != 1) + { if (forcedID == -1) - blockID = WarpDriveConfig.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); + blockID = WarpDriveConfig.i.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); world.setBlock(xCoord + x, yCoord + y, zCoord + z, blockID[0], blockID[1], 2); world.setBlock(xCoord - x, yCoord + y, zCoord + z, blockID[0], blockID[1], 2); } - if (!corrupted || world.rand.nextInt(5) != 1) { + if (!corrupted || world.rand.nextInt(10) != 1) + { if (forcedID == -1) - blockID = WarpDriveConfig.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); + blockID = WarpDriveConfig.i.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); world.setBlock(xCoord + x, yCoord - y, zCoord + z, blockID[0], blockID[1], 2); world.setBlock(xCoord + x, yCoord + y, zCoord - z, blockID[0], blockID[1], 2); } - if (!corrupted || world.rand.nextInt(5) != 1) { + if (!corrupted || world.rand.nextInt(10) != 1) + { if (forcedID == -1) - blockID = WarpDriveConfig.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); + blockID = WarpDriveConfig.i.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); world.setBlock(xCoord - x, yCoord - y, zCoord + z, blockID[0], blockID[1], 2); world.setBlock(xCoord + x, yCoord - y, zCoord - z, blockID[0], blockID[1], 2); } - if (!corrupted || world.rand.nextInt(5) != 1) { + if (!corrupted || world.rand.nextInt(10) != 1) + { if (forcedID == -1) - blockID = WarpDriveConfig.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); + blockID = WarpDriveConfig.i.getRandomSurfaceBlock(world.rand, defaultBlock[0], defaultBlock[1], false); world.setBlock(xCoord - x, yCoord + y, zCoord - z, blockID[0], blockID[1], 2); world.setBlock(xCoord - x, yCoord - y, zCoord - z, blockID[0], blockID[1], 2); } } - } - } } private static double lengthSq(double x, double y, double z) diff --git a/src/cr0s/WarpDrive/TileEntityAirGenerator.java b/src/cr0s/WarpDrive/TileEntityAirGenerator.java new file mode 100644 index 00000000..a821a975 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityAirGenerator.java @@ -0,0 +1,180 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityAirGenerator extends TileEntity implements IEnergySink +{ + public boolean addedToEnergyNet = false; + + private final int EU_PER_AIRBLOCK = 10; + private final int MAX_ENERGY_VALUE = 36 * EU_PER_AIRBLOCK; + private int currentEnergyValue = 0; + + private int cooldownTicks = 0; + private final float AIR_POLLUTION_INTERVAL = 4; // seconds + + private final int START_CONCENTRATION_VALUE = 15; + + @Override + public void updateEntity() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + if (!addedToEnergyNet && !this.tileEntityInvalid) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + // Air generator works only in spaces + if (worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID && worldObj.provider.dimensionId != WarpDrive.instance.hyperSpaceDimID) + { + return; + } + + if (addedToEnergyNet && currentEnergyValue > EU_PER_AIRBLOCK) + { + if (cooldownTicks++ > AIR_POLLUTION_INTERVAL * 20) + { + cooldownTicks = 0; + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); // set enabled texture + releaseAir(); + } + } + else + { + if (cooldownTicks++ > 20) + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); // set disabled texture + cooldownTicks = 0; + } + } + } + + private void releaseAir() + { + if (worldObj.isAirBlock(xCoord + 1, yCoord, zCoord) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord + 1, yCoord, zCoord, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + + if (worldObj.isAirBlock(xCoord - 1, yCoord, zCoord) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord - 1, yCoord, zCoord, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + + if (worldObj.isAirBlock(xCoord, yCoord + 1, zCoord) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord, yCoord + 1, zCoord, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + + if (worldObj.isAirBlock(xCoord, yCoord - 1, zCoord) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord, yCoord - 1, zCoord, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + + if (worldObj.isAirBlock(xCoord, yCoord, zCoord + 1) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord, yCoord, zCoord + 1, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + + if (worldObj.isAirBlock(xCoord, yCoord, zCoord - 1) && (currentEnergyValue - EU_PER_AIRBLOCK >= 0)) + { + worldObj.setBlock(xCoord, yCoord, zCoord - 1, WarpDriveConfig.i.airID, START_CONCENTRATION_VALUE, 2); + currentEnergyValue -= EU_PER_AIRBLOCK; + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); + } + + // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() + { + return (MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) + { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > MAX_ENERGY_VALUE) + { + leftover = (getCurrentEnergyValue() - MAX_ENERGY_VALUE); + currentEnergyValue = MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() + { + return currentEnergyValue; + } + + @Override + public void onChunkUnload() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } +} diff --git a/src/cr0s/WarpDrive/TileEntityCamera.java b/src/cr0s/WarpDrive/TileEntityCamera.java new file mode 100644 index 00000000..905e5319 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityCamera.java @@ -0,0 +1,167 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.network.packet.Packet62LevelSound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityCamera extends TileEntity implements IPeripheral +{ + private int dx, dz, dy; + private float yaw, pitch; // laser direction + + private int frequency = -1; // beam frequency + private float r, g, b; // beam color (corresponds to frequency) + + private boolean isEmitting = false; + + private String[] methodsArray = + { + "freq" + }; + + private final int REGISTRY_UPDATE_INTERVAL_SEC = 10; + private int ticks = 0; + + private int packetSendTicks = 20; + + @Override + public void updateEntity() + { + // Update frequency on clients + if (FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + if (packetSendTicks-- == 0) + { + packetSendTicks = 20 * 5; + sendFreqPacket(); + } + + return; + } + + if (++ticks > 20 * REGISTRY_UPDATE_INTERVAL_SEC) + { + ticks = 0; + WarpDrive.instance.cams.updateInRegistry(new CamRegistryItem(this.frequency, new ChunkPosition(xCoord, yCoord, zCoord), worldObj).setType(0)); + } + } + + public int getFrequency() + { + return frequency; + } + + public void setFrequency(int freq) + { + frequency = freq; + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + frequency = tag.getInteger("frequency"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("frequency", frequency); + } + + public void sendFreqPacket() + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try + { + // Write source vector + outputStream.writeInt(xCoord); + outputStream.writeInt(yCoord); + outputStream.writeInt(zCoord); + outputStream.writeInt(this.frequency); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveFreq"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(xCoord, yCoord, zCoord, 100, worldObj.provider.dimensionId, packet); + } + } + + // IPeripheral methods implementation + @Override + public String getType() + { + return "camera"; + } + + @Override + public String[] getMethodNames() + { + return methodsArray; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { + if (arguments.length == 1) + frequency = ((Double)arguments[0]).intValue(); + return new Integer[] { frequency }; + } + + @Override + public boolean canAttachToSide(int side) + { + return true; + } + + @Override + public void attach(IComputerAccess computer) + { + } + + @Override + public void detach(IComputerAccess computer) + { + } +} diff --git a/src/cr0s/WarpDrive/TileEntityCloakingDeviceCore.java b/src/cr0s/WarpDrive/TileEntityCloakingDeviceCore.java new file mode 100644 index 00000000..cc4d8396 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityCloakingDeviceCore.java @@ -0,0 +1,480 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; +import ic2.api.energy.tile.IEnergyTile; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.server.MinecraftServer; +import net.minecraft.src.ModLoader; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraft.world.chunk.storage.ExtendedBlockStorage; +import net.minecraftforge.common.MinecraftForge; +import net.minecraft.entity.player.EntityPlayerMP; + +public class TileEntityCloakingDeviceCore extends TileEntity implements IEnergySink, + IPeripheral { + public boolean addedToEnergyNet = false; + + private final int MAX_ENERGY_VALUE = 500000000; // 500kk eU + private int currentEnergyValue = 0; + + private String[] methodsArray = { "setFieldTier", // 0 setFieldTier(1 or 2) + "isAssemblyValid", // 1 - returns true or false + "getEnergyLevel", // 2 + "enableCloakingField", // 3 enables field if assembled right + "disableCloakingField", // 4 disables cloaking field + "setFieldFrequency" // 5 setFieldFrequency(int) + }; + + public boolean isEnabled = false; + public byte tier = 1; // cloaking field tier, 1 or 2 + public int frequency = 0; + + // Spatial cloaking field parameters + public int front, back, up, down, left, right; + public int minX = 0, minY = 0, minZ = 0, maxX = 0, maxY = 0, maxZ = 0; + + private int updateTicks = 0; + private int laserDrawingTicks = 0; + + @Override + public void updateEntity() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + return; + } + + if (!addedToEnergyNet && !this.tileEntityInvalid) { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + if (--this.updateTicks <= 0) { + this.updateTicks = ((this.tier == 1) ? 20 : (tier == 2) ? 10 : 20) * WarpDriveConfig.i.CD_FIELD_REFRESH_INTERVAL_SECONDS; // resetting timer + + if (validateAssembly() && isEnabled) { + // Consume power for sustaining cloaking field + countBlocksAndConsumeEnergy(); + + if (currentEnergyValue >= 0) { + if (!WarpDrive.instance.cloaks.isAreaExists(this.frequency)) { + WarpDrive.instance.cloaks.addCloakedAreaWorld(worldObj, minX, minY, minZ, maxX, maxY, maxZ, frequency, tier); + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); + worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, "warpdrive:cloak", 4F, 1F); + + // Enable coils + setCoilsState(true); + } else { + // Refresh the field + CloakedArea area = WarpDrive.instance.cloaks.getCloakedArea(frequency); + if (area != null) + area.sendCloakPacketToPlayersEx(false); // recloak field + } + } else { + currentEnergyValue = 0; + setCoilsState(false); + disableCloakingField(); + } + } else if (!validateAssembly() && isEnabled) { + currentEnergyValue = 0; + setCoilsState(false); + disableCloakingField(); + } + } + + if (laserDrawingTicks++ > 100) { + laserDrawingTicks = 0; + + if (isEnabled) + drawLasers(); + } + } + + public void setCoilsState(boolean enabled) { + final int START_LENGTH = 2; // Step length from core block to main coils + + // Directions to check (all six directions: left, right, up, down, front, back) + byte[] dx = { 1, -1, 0, 0, 0, 0 }; + byte[] dy = { 0, 0, -1, 1, 0, 0 }; + byte[] dz = { 0, 0, 0, 0, -1, 1 }; + + for (int i = 0; i < 6; i++) + searchCoilInDirectionAndSetState(dx[i], dy[i], dz[i], enabled); + } + + public void searchCoilInDirectionAndSetState(byte dx, byte dy, byte dz, boolean state) { + for (int i = 0; i < WarpDriveConfig.i.CD_MAX_CLOAKING_FIELD_SIDE; i++) { + if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.i.cloakCoilID) + worldObj.setBlockMetadataWithNotify(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz, (state) ? 1 : 0, 2); + } + } + + public void searchCoilInDirectionAndDrawLaser(byte dx, byte dy, byte dz) { + final int START_LENGTH = 2; + float r = 0.0f, g = 1.0f, b = 0; + if (this.tier == 1) { + r = 0.0f; g = 1.0f; + } else if (this.tier == 2) { + r = 1.0f; g = 0.0f; + } + + for (int i = START_LENGTH + 1; i < WarpDriveConfig.i.CD_MAX_CLOAKING_FIELD_SIDE; i++) { + if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.i.cloakCoilID) + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz).add(0.5), r, g, b, 110, 0, 100); + } + } + + public void drawLasers() { + final int START_LENGTH = 2; + float r = 0.0f, g = 1.0f, b = 0; + if (this.tier == 1) { + r = 0.0f; g = 1.0f; + } else if (this.tier == 2) { + r = 1.0f; g = 0.0f; + } + + // Directions to check (all six directions: left, right, up, down, front, back) + byte[] dx = { 1, -1, 0, 0, 0, 0 }; + byte[] dy = { 0, 0, -1, 1, 0, 0 }; + byte[] dz = { 0, 0, 0, 0, -1, 1 }; + + for (int k = 0; k < 6; k++) + searchCoilInDirectionAndDrawLaser(dx[k], dy[k], dz[k]); + + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 6; j++) { + switch (worldObj.rand.nextInt(6)) { + case 0: + r = 1.0f; + g = b = 0; + break; + case 1: + r = b = 0; + g = 1.0f; + break; + case 2: + r = g = 0; + b = 1.0f; + break; + case 3: + r = b = 0.5f; + g = 0; + break; + case 4: + r = g = 1.0f; + b = 0; + break; + case 5: + r = 1.0f; + b = 0.5f; + g = 0f; + } + + sendLaserPacket(new Vector3(xCoord + START_LENGTH * dx[i], yCoord + START_LENGTH * dy[i], zCoord + START_LENGTH * dz[i]).add(0.5), new Vector3(xCoord + START_LENGTH * dx[j], yCoord + START_LENGTH * dy[j], zCoord + START_LENGTH * dz[j]).add(0.5), r, g, b, 110, 0, 100); + } + } + } + + public void disableCloakingField() { + this.isEnabled = false; + + if (WarpDrive.instance.cloaks.isAreaExists(this.frequency)) + WarpDrive.instance.cloaks.removeCloakedArea(this.frequency); + + worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, "warpdrive:decloak", 4F, 1F); + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); + } + public void countBlocksAndConsumeEnergy() { + int blocksCount = 0; + for (int y = minY; y <= maxY; y++) + for (int x = minX; x <= maxX; x++) + for(int z = minZ; z <= maxZ; z++) + if (worldObj.getBlockId(x, y, z) != 0) + blocksCount++; + int energyToConsume = blocksCount * ((this.tier == 1) ? WarpDriveConfig.i.CD_ENERGY_PER_BLOCK_TIER1 : WarpDriveConfig.i.CD_ENERGY_PER_BLOCK_TIER2); + + this.currentEnergyValue -= energyToConsume; + } + + public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try { + // Write source vector + outputStream.writeDouble(source.x); + outputStream.writeDouble(source.y); + outputStream.writeDouble(source.z); + // Write target vector + outputStream.writeDouble(dest.x); + outputStream.writeDouble(dest.y); + outputStream.writeDouble(dest.z); + // Write r, g, b of laser + outputStream.writeFloat(r); + outputStream.writeFloat(g); + outputStream.writeFloat(b); + // Write age + outputStream.writeByte(age); + // Write energy value + outputStream.writeInt(energy); + } catch (Exception ex) { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + + // Send packet to all players within cloaked area + List list = worldObj.getEntitiesWithinAABB(EntityPlayerMP.class, AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + for (Entity e : list) { + if (e != null && e instanceof EntityPlayer) { + ((EntityPlayerMP)e).playerNetServerHandler.sendPacketToPlayer(packet); + } + } + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); + this.tier = tag.getByte("tier"); + this.frequency = tag.getInteger("frequency"); + this.isEnabled = tag.getBoolean("enabled"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); + tag.setByte("tier", this.tier); + tag.setInteger("frequency", this.frequency); + tag.setBoolean("enabled", this.isEnabled); + } + + public int searchCoilInDirection(byte dx, byte dy, byte dz) { + for (int i = 3; i < WarpDriveConfig.i.CD_MAX_CLOAKING_FIELD_SIDE; i++) { + if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.i.cloakCoilID) + return i; + } + + return 0; + } + public boolean validateAssembly() { + final int START_LENGTH = 2; // Step length from core block to main coils + + // Directions to check (all six directions: left, right, up, down, front, back) + byte[] dx = { 1, -1, 0, 0, 0, 0 }; + byte[] dy = { 0, 0, -1, 1, 0, 0 }; + byte[] dz = { 0, 0, 0, 0, -1, 1 }; + + for (int i = 0; i < 6; i++) + if (worldObj.getBlockId(xCoord + START_LENGTH * dx[i], yCoord + START_LENGTH * dy[i], zCoord + START_LENGTH * dz[i]) != WarpDriveConfig.i.cloakCoilID) + return false; + + // Check cloaking field parameters defining coils + this.left = searchCoilInDirection((byte)1, (byte)0, (byte)0) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.left == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + this.right = searchCoilInDirection((byte)-1, (byte)0, (byte)0) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.right == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + + this.up = searchCoilInDirection((byte)0, (byte)1, (byte)0) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.up == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + this.down = searchCoilInDirection((byte)0, (byte)-1, (byte)0) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.down == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + + this.front = searchCoilInDirection((byte)0, (byte)0, (byte)1) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.front == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + this.back = searchCoilInDirection((byte)0, (byte)0, (byte)-1) + WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS; + if (this.back == WarpDriveConfig.i.CD_COIL_CAPTURE_BLOCKS) return false; + + int x1 = 0, x2 = 0, z1 = 0, z2 = 0; + + + z1 = zCoord - this.back; + z2 = zCoord + this.front; + x1 = xCoord - this.right; + x2 = xCoord + this.left; + + if (x1 < x2) { + this.minX = x1;this. maxX = x2; + } + else { + this.minX = x2; this.maxX = x1; + } + + if (z1 < z2) { + this.minZ = z1; this.maxZ = z2; + } + else { + this.minZ = z2; this.maxZ = z1; + } + + this.minY = yCoord - this.down; + this.maxY = yCoord + this.up; + + return true; + } + + // CC + // IPeripheral methods implementation + @Override + public String getType() { + return "cloakingdevicecore"; + } + + @Override + public String[] getMethodNames() { + return methodsArray; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, + int method, Object[] arguments) throws Exception { + switch (method) { + case 0: // setFieldTier(1 or 2) + if (arguments.length == 1) { + this.tier = ((Double)arguments[0]).byteValue(); + } + + break; + case 1: // isAssemblyValid() + return new Object[] { (boolean)validateAssembly() }; + + case 2: // getEnergyLevel() + return new Object[] { currentEnergyValue }; + + case 3: // enableCloakingField() + this.isEnabled = true; + break; + + case 4: // disableCloakingField() + disableCloakingField(); + setCoilsState(false); + break; + + case 5: // setFieldFrequency(int) + if (arguments.length == 1) { + if (isEnabled) + disableCloakingField(); + + if (WarpDrive.instance.cloaks.isAreaExists(((Double)arguments[0]).intValue())) + return new Object[] { (Boolean)false }; + + this.frequency = ((Double)arguments[0]).intValue(); + return new Object[] { (Boolean)true }; + } + break; + } + + return null; + } + + @Override + public boolean canAttachToSide(int side) { + return true; + } + + @Override + public void attach(IComputerAccess computer) { + } + + @Override + public void detach(IComputerAccess computer) { + } + + // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() { + return (MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > MAX_ENERGY_VALUE) { + leftover = (getCurrentEnergyValue() - MAX_ENERGY_VALUE); + currentEnergyValue = MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, + ForgeDirection direction) { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() { + return currentEnergyValue; + } + + public int collectAllEnergy() { + int energy = currentEnergyValue; + currentEnergyValue = 0; + return energy; + } + + @Override + public void onChunkUnload() { + if (addedToEnergyNet) { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() { + if (addedToEnergyNet) { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } + } diff --git a/src/cr0s/WarpDrive/machines/TileEntityLaser.java b/src/cr0s/WarpDrive/TileEntityLaser.java similarity index 50% rename from src/cr0s/WarpDrive/machines/TileEntityLaser.java rename to src/cr0s/WarpDrive/TileEntityLaser.java index 3459622b..c0234152 100644 --- a/src/cr0s/WarpDrive/machines/TileEntityLaser.java +++ b/src/cr0s/WarpDrive/TileEntityLaser.java @@ -1,20 +1,25 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; +import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.network.packet.Packet62LevelSound; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; @@ -23,18 +28,21 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.ChunkPosition; -import cr0s.WarpDrive.*; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.MinecraftForge; -public class TileEntityLaser extends WarpTE implements IPeripheral { +public class TileEntityLaser extends TileEntity implements IPeripheral +{ //magic constants - private final int SCANNING_BEAM_LENGTH = 400; //FIXME merge re-adding a non-used definition? + private final int SCANNING_BEAM_LENGTH = 400; private final int SCANNING_BEAM_FREQ = 1420; private int dx, dz, dy; public float yaw, pitch; // laser direction - private int beamFrequency = -1; // beam frequency - private int cameraFrequency = -1; // camera frequency + private int frequency = -1; // beam frequency + public int camFreq = -1; // camera frequency private float r, g, b; // beam color (corresponds to frequency) public boolean isEmitting = false; @@ -51,65 +59,80 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { public int delayTicks = 0; private int energyFromOtherBeams = 0; - + private MovingObjectPosition firstHit = null; + private int hitX = 0; + private int hitY = 0; + private int hitZ = 0; + private int hitBlockId = 0; + private int hitBlockMeta = 0; + private float hitBlockResistance = 0; private int camUpdateTicks = 20; private int registryUpdateTicks = 20 * 10; @Override - public void updateEntity() { - if (isWithCamera()) { - registryUpdateTicks--; - if (registryUpdateTicks == 0 && FMLCommonHandler.instance().getEffectiveSide().isClient()) { + public void updateEntity() + { + // Frequency is not set + if (frequency <= 0 || frequency > 65000) + { + return; + } + + if (isWithCamera()) + { + if (registryUpdateTicks-- == 0 && FMLCommonHandler.instance().getEffectiveSide().isClient()) + { registryUpdateTicks = 20 * 10; - WarpDrive.instance.cams.updateInRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord), cameraFrequency, 1); + WarpDrive.instance.cams.updateInRegistry(new CamRegistryItem(this.camFreq, new ChunkPosition(xCoord, yCoord, zCoord), worldObj).setType(1)); } - camUpdateTicks--; - if (camUpdateTicks == 0) { + if (camUpdateTicks-- == 0) + { camUpdateTicks = 20 * 5; // 5 seconds sendFreqPacket(); // send own cam frequency to clients } } - // Frequency is not set - if (beamFrequency <= 0 || beamFrequency > 65000) { - return; - } - - delayTicks++; - if (isEmitting && ((beamFrequency != 1420 && delayTicks > WarpDriveConfig.LE_EMIT_DELAY_TICKS) || ((beamFrequency == 1420) && delayTicks > WarpDriveConfig.LE_EMIT_SCAN_DELAY_TICKS))) { + if (isEmitting && ((frequency != SCANNING_BEAM_FREQ && ++delayTicks > WarpDriveConfig.i.LE_EMIT_DELAY_TICKS) || ((frequency == SCANNING_BEAM_FREQ) && ++delayTicks > WarpDriveConfig.i.LE_EMIT_SCAN_DELAY_TICKS))) + { delayTicks = 0; isEmitting = false; - emitBeam(Math.min(this.consumeEnergyFromBoosters() + MathHelper.floor_double(energyFromOtherBeams * WarpDriveConfig.LE_COLLECT_ENERGY_MULTIPLIER), WarpDriveConfig.LE_MAX_LASER_ENERGY)); + emitBeam(Math.min(this.collectEnergyFromBoosters() + MathHelper.floor_double(energyFromOtherBeams * WarpDriveConfig.i.LE_COLLECT_ENERGY_MULTIPLIER), WarpDriveConfig.i.LE_MAX_LASER_ENERGY)); energyFromOtherBeams = 0; } } - public void addBeamEnergy(int amount) { - if (isEmitting) { + public void addBeamEnergy(int amount) + { + if (isEmitting) energyFromOtherBeams += amount; - WarpDrive.debugPrint("[LE] Added energy: " + amount); - } else { - WarpDrive.debugPrint("[LE] Ignored energy: " + amount); - } } - private int consumeEnergyFromBoosters() { + private int collectEnergyFromBoosters() + { int energyCollected = 0; - if (findFirstBooster() != null) { - int newX, newY, newZ; - TileEntity te; - for (int shift = 1; shift <= WarpDriveConfig.LE_MAX_BOOSTERS_NUMBER; shift++) { - newX = xCoord + (dx * shift); - newY = yCoord + (dy * shift); - newZ = zCoord + (dz * shift); - te = worldObj.getBlockTileEntity(newX, newY, newZ); - if (te != null && te instanceof TileEntityParticleBooster) { - energyCollected += ((TileEntityParticleBooster)te).consumeAllEnergy(); - } else { + if (findFirstBooster() != null) + { + int maxShift = WarpDriveConfig.i.LE_MAX_BOOSTERS_NUMBER; + if (frequency == SCANNING_BEAM_FREQ) + maxShift = 1; + + for (int shift = 1; shift <= maxShift; shift++) + { + int newX = xCoord + (dx * shift); + int newY = yCoord + (dy * shift); + int newZ = zCoord + (dz * shift); + TileEntity te = worldObj.getBlockTileEntity(newX, newY, newZ); + + if (te != null && te instanceof TileEntityParticleBooster) + { + energyCollected += ((TileEntityParticleBooster)te).collectAllEnergy(); + } + else + { break; } } @@ -119,67 +142,81 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { } // TODO refactor me - private void emitBeam(int parEnergy) { - int energy = parEnergy; // FIXME + private void emitBeam(int energy) + { // Beam power calculations - int beamLengthBlocks = energy / WarpDriveConfig.LE_BEAM_LENGTH_PER_ENERGY_DIVIDER; + int beamLengthBlocks = energy / WarpDriveConfig.i.LE_BEAM_LENGTH_PER_ENERGY_DIVIDER; + + if (frequency == SCANNING_BEAM_FREQ) + beamLengthBlocks = SCANNING_BEAM_LENGTH; - if (energy == 0 || beamLengthBlocks < 1 || beamFrequency > 65000 || beamFrequency <= 0) { + if (energy == 0 || beamLengthBlocks < 1 || frequency > 65000 || frequency <= 0) + { return; } - Vector3 beamVector = new Vector3(this).translate(0.5D); - WarpDrive.debugPrint("" + this + " Energy " + energy + " over " + beamLengthBlocks + " blocks, Initial beam " + beamVector); + Vector3 beamVector = new Vector3(this).add(0.5); float yawz = MathHelper.cos(-yaw * 0.017453292F - (float) Math.PI); float yawx = MathHelper.sin(-yaw * 0.017453292F - (float) Math.PI); float pitchhorizontal = -MathHelper.cos(-pitch * 0.017453292F); float pitchvertical = MathHelper.sin(-pitch * 0.017453292F); float directionx = yawx * pitchhorizontal; float directionz = yawz * pitchhorizontal; - Vector3 lookVector = new Vector3(directionx, pitchvertical, directionz); + Vector3 lookVector = new Vector3((double) directionx, (double) pitchvertical, (double) directionz); Vector3.translate(beamVector, lookVector); Vector3 reachPoint = beamVector.clone().translate(beamVector.clone(), beamVector.clone().scale(lookVector.clone(), beamLengthBlocks)); - WarpDrive.debugPrint("" + this + " Beam " + beamVector + " Look " + lookVector + " Reach " + reachPoint + " TranslatedBeam " + beamVector); Vector3 endPoint = reachPoint.clone(); playSoundCorrespondsEnergy(energy); + int distanceTravelled = 0; //distance travelled from beam emitter to previous hit if there were any - + // This is scanning beam, do not deal damage to blocks - if (beamFrequency == SCANNING_BEAM_FREQ) { + if (frequency == SCANNING_BEAM_FREQ) + { firstHit = worldObj.rayTraceBlocks_do_do(beamVector.toVec3(), reachPoint.toVec3(), false, false); - if (firstHit != null) { - WarpDrive.sendLaserPacket(worldObj, beamVector, new Vector3(firstHit.hitVec), r, g, b, 50, energy, 200); + if (firstHit != null) + { + hitBlockId = worldObj.getBlockId(firstHit.blockX, firstHit.blockY, firstHit.blockZ); + hitBlockMeta = worldObj.getBlockMetadata(firstHit.blockX, firstHit.blockY, firstHit.blockZ); + hitBlockResistance = Block.blocksList[hitBlockId].blockResistance; + hitX = firstHit.blockX; + hitY = firstHit.blockY; + hitZ = firstHit.blockZ; + sendLaserPacket(beamVector, new Vector3(firstHit.hitVec), r, g, b, 50, energy, 200); } else { - WarpDrive.sendLaserPacket(worldObj, beamVector, reachPoint, r, g, b, 50, energy, 200); - } - + sendLaserPacket(beamVector, reachPoint, r, g, b, 50, energy, 200); + } + return; } - for (int passedBlocks = 0; passedBlocks < beamLengthBlocks; passedBlocks++) { + for (int passedBlocks = 0; passedBlocks < beamLengthBlocks; ++passedBlocks) + { // Get next block hit MovingObjectPosition hit = worldObj.rayTraceBlocks_do_do(beamVector.toVec3(), reachPoint.toVec3(), true, false); // FIXME entity ray-tracing MovingObjectPosition entityHit = raytraceEntities(beamVector.clone(), lookVector.clone(), true, beamLengthBlocks); - WarpDrive.debugPrint("Entity hit is " + entityHit); - - if (entityHit != null && entityHit.entityHit instanceof EntityLivingBase) { + if (entityHit != null && entityHit.entityHit instanceof EntityLivingBase) + { EntityLivingBase e = (EntityLivingBase)entityHit.entityHit; double distanceToEntity = entityHit.hitVec.distanceTo(beamVector.clone().toVec3()); - if (hit == null || (hit != null && hit.hitVec.distanceTo(beamVector.clone().toVec3()) > distanceToEntity)) { - if (distanceToEntity <= beamLengthBlocks) { - e.setFire(WarpDriveConfig.LE_ENTITY_HIT_SET_ON_FIRE_TIME); - e.attackEntityFrom(DamageSource.inFire, energy / WarpDriveConfig.LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER); + if (hit == null || (hit != null && hit.hitVec.distanceTo(beamVector.clone().toVec3()) > distanceToEntity)) + { + if (distanceToEntity <= beamLengthBlocks) + { + ((EntityLivingBase)e).setFire(WarpDriveConfig.i.LE_ENTITY_HIT_SET_ON_FIRE_TIME); + ((EntityLivingBase)e).attackEntityFrom(DamageSource.inFire, energy / WarpDriveConfig.i.LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER); - if (energy > WarpDriveConfig.LE_ENTITY_HIT_EXPLOSION_LASER_ENERGY) { + if (energy > WarpDriveConfig.i.LE_ENTITY_HIT_EXPLOSION_LASER_ENERGY) + { worldObj.newExplosion(null, e.posX, e.posY, e.posZ, 4F, true, true); } // consume energy - energy -= WarpDriveConfig.LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER + (10 * distanceToEntity); + energy -= WarpDriveConfig.i.LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER + (10 * distanceToEntity); endPoint = new Vector3(entityHit.hitVec); break; } @@ -187,66 +224,79 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { } // Laser is missed - if (hit == null && entityHit == null) { + if (hit == null && entityHit == null) + { endPoint = reachPoint; break; - } else if (hit != null) { + } + else if (hit != null) + { // We got a hit block int distance = (int) new Vector3(hit.hitVec).distanceTo(beamVector); // Laser gone too far - if (distance >= beamLengthBlocks) { + if (distance >= beamLengthBlocks) + { endPoint = reachPoint; break; } int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ); - // int blockMeta = worldObj.getBlockMetadata(hit.blockX, hit.blockY, hit.blockZ); + int blockMeta = worldObj.getBlockMetadata(hit.blockX, hit.blockY, hit.blockZ); float resistance = Block.blocksList[blockID].blockResistance; - if (blockID == Block.bedrock.blockID) { + if (blockID == Block.bedrock.blockID) + { endPoint = new Vector3(hit.hitVec); break; } // Hit is a laser head - if (blockID == WarpDriveConfig.laserID || blockID == WarpDriveConfig.laserCamID) { + if (blockID == WarpDriveConfig.i.laserID || blockID == WarpDriveConfig.i.laserCamID) + { // Compare frequencies TileEntityLaser tel = (TileEntityLaser)worldObj.getBlockTileEntity(hit.blockX, hit.blockY, hit.blockZ); - if (tel != null && tel.getBeamFrequency() == beamFrequency) { + if (tel != null && tel.getFrequency() == frequency) + { tel.addBeamEnergy(energy); endPoint = new Vector3(hit.hitVec); break; } } - if (Block.blocksList[blockID].blockMaterial == Material.glass) { + if (Block.blocksList[blockID].blockMaterial == Material.glass) + { worldObj.destroyBlock(hit.blockX, hit.blockY, hit.blockZ, (worldObj.rand.nextInt(20) == 0)); endPoint = new Vector3(hit.hitVec); } - energy -= WarpDriveConfig.LE_BLOCK_HIT_CONSUME_ENERGY + (resistance * WarpDriveConfig.LE_BLOCK_HIT_CONSUME_ENERGY_PER_BLOCK_RESISTANCE) + ( (distance - distanceTravelled) * WarpDriveConfig.LE_BLOCK_HIT_CONSUME_ENERGY_PER_DISTANCE); + energy -= WarpDriveConfig.i.LE_BLOCK_HIT_CONSUME_ENERGY + (resistance * WarpDriveConfig.i.LE_BLOCK_HIT_CONSUME_ENERGY_PER_BLOCK_RESISTANCE) + ( (distance - distanceTravelled) * WarpDriveConfig.i.LE_BLOCK_HIT_CONSUME_ENERGY_PER_DISTANCE); distanceTravelled = distance; endPoint = new Vector3(hit.hitVec); - if (energy <= 0) { + if (energy <= 0) + { break; } - if (resistance >= Block.obsidian.blockResistance) { + if (resistance >= Block.obsidian.blockResistance) + { worldObj.newExplosion(null, hit.blockX, hit.blockY, hit.blockZ, 4F * (2 + (energy / 500000)), true, true); worldObj.setBlock(hit.blockX, hit.blockY, hit.blockZ, (worldObj.rand.nextBoolean()) ? Block.fire.blockID : 0); - } else { + } + else + { worldObj.destroyBlock(hit.blockX, hit.blockY, hit.blockZ, (worldObj.rand.nextInt(20) == 0)); } } } - WarpDrive.instance.sendLaserPacket(worldObj, beamVector, endPoint, r, g, b, 50, energy, beamLengthBlocks); + sendLaserPacket(beamVector, endPoint, r, g, b, 50, energy, beamLengthBlocks); } - public MovingObjectPosition raytraceEntities(Vector3 beamVec, Vector3 lookVec, boolean collisionFlag, double reachDistance) { + public MovingObjectPosition raytraceEntities(Vector3 beamVec, Vector3 lookVec, boolean collisionFlag, double reachDistance) + { MovingObjectPosition pickedEntity = null; Vec3 playerPosition = beamVec.toVec3(); Vec3 playerLook = lookVec.toVec3(); @@ -257,30 +307,40 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { List entitiesHit = worldObj.getEntitiesWithinAABBExcludingEntity(null, boxToScan); double closestEntity = reachDistance; - if (entitiesHit == null || entitiesHit.isEmpty()) { + if (entitiesHit == null || entitiesHit.isEmpty()) + { return null; } - for (Entity entityHit : (Iterable) entitiesHit) { - if (entityHit != null && entityHit.canBeCollidedWith() && entityHit.boundingBox != null) { - double border = entityHit.getCollisionBorderSize(); - AxisAlignedBB aabb = entityHit.boundingBox.expand(border, border, border); + for (Entity entityHit : (Iterable) entitiesHit) + { + if (entityHit != null && entityHit.canBeCollidedWith() && entityHit.boundingBox != null) + { + float border = entityHit.getCollisionBorderSize(); + AxisAlignedBB aabb = entityHit.boundingBox.expand((double) border, (double) border, (double) border); MovingObjectPosition hitMOP = aabb.calculateIntercept(playerPosition, playerViewOffset); - if (hitMOP != null) { - if (aabb.isVecInside(playerPosition)) { - if (0.0D < closestEntity || closestEntity == 0.0D) { + if (hitMOP != null) + { + if (aabb.isVecInside(playerPosition)) + { + if (0.0D < closestEntity || closestEntity == 0.0D) + { pickedEntity = new MovingObjectPosition(entityHit); - if (pickedEntity != null) { + if (pickedEntity != null) + { pickedEntity.hitVec = hitMOP.hitVec; closestEntity = 0.0D; } } - } else { + } + else + { double distance = playerPosition.distanceTo(hitMOP.hitVec); - if (distance < closestEntity || closestEntity == 0.0D) { + if (distance < closestEntity || closestEntity == 0.0D) + { pickedEntity = new MovingObjectPosition(entityHit); pickedEntity.hitVec = hitMOP.hitVec; closestEntity = distance; @@ -293,180 +353,272 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { return pickedEntity; } - public boolean isWithCamera() { - return (getBlockType().blockID == WarpDriveConfig.laserCamID); + public boolean isWithCamera() + { + return (worldObj.getBlockId(xCoord, yCoord, zCoord) == WarpDriveConfig.i.laserCamID); } - public int getBeamFrequency() { - return beamFrequency; - } - - public void setBeamFrequency(int parBeamFrequency) { - if (beamFrequency != parBeamFrequency) { - WarpDrive.debugPrint("" + this + " Beam frequency set from " + beamFrequency + " to " + parBeamFrequency); - beamFrequency = parBeamFrequency; - } - updateColor(); + public int getFrequency() + { + return frequency; } - public int getCameraFrequency() { - return cameraFrequency; - } - - public void setCameraFrequency(int parCameraFrequency) { - if (cameraFrequency != parCameraFrequency) { - WarpDrive.debugPrint("" + this + " Camera frequency set from " + cameraFrequency + " to " + parCameraFrequency); - cameraFrequency = parCameraFrequency; - } - if (worldObj != null) { - WarpDrive.instance.cams.updateInRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord), cameraFrequency, 1); - } - } - - private TileEntityParticleBooster findFirstBooster() { + private TileEntityParticleBooster findFirstBooster() + { TileEntity result; result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = 1; - dy = 0; dz = 0; + dy = 0; return (TileEntityParticleBooster) result; } result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = -1; - dy = 0; dz = 0; + dy = 0; return (TileEntityParticleBooster) result; } result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = 0; - dy = 0; dz = 1; + dy = 0; return (TileEntityParticleBooster) result; } result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = 0; - dy = 0; dz = -1; + dy = 0; return (TileEntityParticleBooster) result; } result = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = 0; - dy = 1; dz = 0; + dy = 1; return (TileEntityParticleBooster) result; } result = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord); - if (result != null && result instanceof TileEntityParticleBooster) { + + if (result != null && result instanceof TileEntityParticleBooster) + { dx = 0; - dy = -1; dz = 0; + dy = -1; return (TileEntityParticleBooster) result; } return null; } - private void playSoundCorrespondsEnergy(int energy) { - if (energy <= 500000) { + public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try + { + // Write source vector + outputStream.writeDouble(source.x); + outputStream.writeDouble(source.y); + outputStream.writeDouble(source.z); + // Write target vector + outputStream.writeDouble(dest.x); + outputStream.writeDouble(dest.y); + outputStream.writeDouble(dest.z); + // Write r, g, b of laser + outputStream.writeFloat(r); + outputStream.writeFloat(g); + outputStream.writeFloat(b); + // Write age + outputStream.writeByte(age); + // Write energy value + outputStream.writeInt(energy); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(source.intX(), source.intY(), source.intZ(), radius, worldObj.provider.dimensionId, packet); + ByteArrayOutputStream bos2 = new ByteArrayOutputStream(8); + DataOutputStream outputStream2 = new DataOutputStream(bos2); + + try + { + // Write source vector + outputStream2.writeDouble(source.x); + outputStream2.writeDouble(source.y); + outputStream2.writeDouble(source.z); + // Write target vector + outputStream2.writeDouble(dest.x); + outputStream2.writeDouble(dest.y); + outputStream2.writeDouble(dest.z); + // Write r, g, b of laser + outputStream2.writeFloat(r); + outputStream2.writeFloat(g); + outputStream2.writeFloat(b); + // Write age + outputStream2.writeByte(age); + // Write energy value + outputStream2.writeInt(energy); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet2 = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(dest.intX(), dest.intY(), dest.intZ(), radius, worldObj.provider.dimensionId, packet); + } + } + + private void playSoundCorrespondsEnergy(int energy) + { + if (energy <= 500000) + { worldObj.playSoundEffect(xCoord + 0.5f, yCoord - 0.5f, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F); - } else if (energy > 500000 && energy <= 1000000) { + } + else if (energy > 500000 && energy <= 1000000) + { worldObj.playSoundEffect(xCoord + 0.5f, yCoord - 0.5f, zCoord + 0.5f, "warpdrive:midlaser", 4F, 1F); - } else if (energy > 1000000) { + } + else if (energy > 1000000) + { worldObj.playSoundEffect(xCoord + 0.5f, yCoord - 0.5f, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); } } - private void updateColor() { - if (beamFrequency > 65000 || beamFrequency <= 0) { // Invalid frequency + private boolean parseFrequency(int freq) + { + if (freq > 65000 || freq <= 0) // Invalid frequency + { + r = 1; + g = 0; + b = 0; + return false; + } + + if (freq > 0 && freq <= 10000) // red + { r = 1; g = 0; b = 0; } - - if (beamFrequency > 0 && beamFrequency <= 10000) { // red - r = 1; - g = 0; - b = 0; - } else if (beamFrequency > 10000 && beamFrequency <= 20000) { // orange + else if (freq > 10000 && freq <= 20000) // orange + { r = 1; g = 0; b = 0.5f; - } else if (beamFrequency > 20000 && beamFrequency <= 30000) { // yellow + } + else if (freq > 20000 && freq <= 30000) // yellow + { r = 1; g = 1; b = 0; - } else if (beamFrequency > 30000 && beamFrequency <= 40000) { // green + } + else if (freq > 30000 && freq <= 40000) // green + { r = 0; g = 1; b = 0; - } else if (beamFrequency > 50000 && beamFrequency <= 60000) { // blue + } + else if (freq > 50000 && freq <= 60000) // blue + { r = 0; g = 0; b = 1; - } else if (beamFrequency > 60000 && beamFrequency <= 65000) { // violet + } + else if (freq > 60000 && freq <= 65000) // violet + { r = 0.5f; g = 0; b = 0.5f; - } else { // impossible frequency + } + else // impossible frequency + { r = 1; g = 0; b = 0; } + + return true; } @Override - public void readFromNBT(NBTTagCompound tag) { + public void readFromNBT(NBTTagCompound tag) + { super.readFromNBT(tag); - setBeamFrequency(tag.getInteger("beamFrequency")); - setCameraFrequency(tag.getInteger("cameraFrequency")); + frequency = tag.getInteger("frequency"); + camFreq = tag.getInteger("camfreq"); } @Override - public void writeToNBT(NBTTagCompound tag) { + public void writeToNBT(NBTTagCompound tag) + { super.writeToNBT(tag); - tag.setInteger("beamFrequency", beamFrequency); - tag.setInteger("cameraFrequency", cameraFrequency); + tag.setInteger("frequency", frequency); + tag.setInteger("camFreq", camFreq); } - @Override - public void onChunkUnload() { - WarpDrive.instance.cams.removeFromRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord)); - super.onChunkUnload(); - } - // IPeripheral methods implementation @Override - public String getType() { + public String getType() + { return "laser"; } @Override - public String[] getMethodNames() { + public String[] getMethodNames() + { return methodsArray; } @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { switch (method) { case 0: // emitBeam(yaw, pitch) // emitBeam(dx, dy, dz) - if (arguments.length == 2) { + if (arguments.length == 2) + { yaw = ((Double)arguments[0]).floatValue(); pitch = ((Double)arguments[1]).floatValue(); isEmitting = true; delayTicks = 0; - } else if (arguments.length == 3) { + } + else if (arguments.length == 3) + { double dx = (Double)arguments[0]; double dy = (Double)arguments[1]; double dz = -(Double)arguments[2]; //FIXME kostyl @@ -483,58 +635,65 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { delayTicks = 0; } break; - case 1: // getX return new Integer[] { xCoord, yCoord, zCoord }; - case 2: // Freq - if (arguments.length == 1) { - int parFrequency = ((Double)arguments[0]).intValue(); - if ((parFrequency <= 65000) && (parFrequency > 0)) { - setBeamFrequency(parFrequency); - } + if (arguments.length == 1) + { + if (parseFrequency(((Double)arguments[0]).intValue())) + frequency = ((Double)arguments[0]).intValue(); + else + return new Integer[] { -1 }; } - return new Integer[] { beamFrequency }; - + return new Integer[] { frequency }; case 3: // getFirstHit() - if (firstHit != null) { + if (firstHit != null) + { int blockID = worldObj.getBlockId(firstHit.blockX, firstHit.blockY, firstHit.blockZ); int blockMeta = worldObj.getBlockMetadata(firstHit.blockX, firstHit.blockY, firstHit.blockZ); float blockResistance = Block.blocksList[blockID].blockResistance; - Object[] info = { firstHit.blockX, firstHit.blockY, firstHit.blockZ, blockID, blockMeta, blockResistance }; + Object[] info = { hitX, hitY, hitZ, hitBlockId, hitBlockMeta, (Float)hitBlockResistance }; return info; - } else { - return new Integer[] { 0, 0, 0, 0, 0, -1 }; } - + else + return new Integer[] { 0, 0, 0, 0, 0, -1 }; case 4: // getBoosterDXDZ findFirstBooster(); return new Integer[] { dx, dz }; case 5: // CamFreq (only for lasers with cam) - if (isWithCamera()) { - if (arguments.length == 1) { - setCameraFrequency(((Double)arguments[0]).intValue()); - } + if (isWithCamera()) + { + if (arguments.length == 1) + camFreq = ((Double)arguments[0]).intValue(); + return new Integer[] { camFreq }; } - return new Integer[] { cameraFrequency }; + break; } return null; } // Camera frequency refresh to clients packet - public void sendFreqPacket() { - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { + public void sendFreqPacket() + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { ByteArrayOutputStream bos = new ByteArrayOutputStream(8); DataOutputStream outputStream = new DataOutputStream(bos); - try { + try + { + // Write source vector outputStream.writeInt(xCoord); outputStream.writeInt(yCoord); outputStream.writeInt(zCoord); - outputStream.writeInt(cameraFrequency); - } catch (Exception e) { - e.printStackTrace(); + outputStream.writeInt(this.camFreq); + } + catch (Exception ex) + { + ex.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); @@ -542,20 +701,22 @@ public class TileEntityLaser extends WarpTE implements IPeripheral { packet.data = bos.toByteArray(); packet.length = bos.size(); MinecraftServer.getServer().getConfigurationManager().sendToAllNear(xCoord, yCoord, zCoord, 100, worldObj.provider.dimensionId, packet); -// WarpDrive.debugPrint("" + this + " Packet '" + packet.channel + "' sent (" + xCoord + ", " + yCoord + ", " + zCoord + ") '" + cameraFrequency + "'"); } } @Override - public void attach(IComputerAccess computer) { + public boolean canAttachToSide(int side) + { + return true; } @Override - public void detach(IComputerAccess computer) { + public void attach(IComputerAccess computer) + { } @Override - public boolean equals(IPeripheral other) { - return other == this; + public void detach(IComputerAccess computer) + { } } diff --git a/src/cr0s/WarpDrive/TileEntityLift.java b/src/cr0s/WarpDrive/TileEntityLift.java new file mode 100644 index 00000000..e99f5aa4 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityLift.java @@ -0,0 +1,343 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityLift extends TileEntity implements IEnergySink +{ + public boolean addedToEnergyNet = false; + + private final int MAX_ENERGY_VALUE = 2048; // eU + private int currentEnergyValue = 0; + + private int mode = 0; // 0 - inactive, 1 - up, 2 - down + private int firstUncoveredY; + + private boolean isEnabled = false; + + int ticks = 0; + + @Override + public void updateEntity() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + if (!addedToEnergyNet && !this.tileEntityInvalid) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + if (++ticks > 40) + { + ticks = 0; + + // Switching mode + if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) + { + mode = 2; // down + } + else + { + mode = 1; // up + } + + isEnabled = (worldObj.isAirBlock(xCoord, yCoord + 1, zCoord) && worldObj.isAirBlock(xCoord, yCoord + 2, zCoord)); + + if (currentEnergyValue != MAX_ENERGY_VALUE || !isEnabled) + { + mode = 0; + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); // disabled + return; + } + + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, mode, 2); // current mode + + // Launch a beam + if (isEnabled) + { + // Search non-air blocks under lift + for (int ny = yCoord - 1; ny > 0; ny--) + { + if (!worldObj.isAirBlock(xCoord, ny, zCoord)) + { + firstUncoveredY = ny; + break; + } + } + + if (yCoord - firstUncoveredY > 0) + if (mode == 1) + { + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord, firstUncoveredY, zCoord).add(0.5), 0f, 1f, 0f, 40, 0, 100); + } + else if (mode == 2) + { + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord, firstUncoveredY, zCoord).add(0.5), 0f, 0f, 1f, 40, 0, 100); + } + + liftEntity(); + } + } + } + + public void liftEntity() + { + int xmax, zmax, x1, x2, z1, z2; + int xmin, zmin; + final int CUBE_SIDE = 2; + x1 = xCoord + CUBE_SIDE / 2; + x2 = xCoord - CUBE_SIDE / 2; + + if (x1 < x2) + { + xmin = x1; + xmax = x2; + } + else + { + xmin = x2; + xmax = x1; + } + + z1 = zCoord + CUBE_SIDE / 2; + z2 = zCoord - CUBE_SIDE / 2; + + if (z1 < z2) + { + zmin = z1; + zmax = z2; + } + else + { + zmin = z2; + zmax = z1; + } + + // Lift up + if (mode == 1) + { + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(xmin + 0.3, firstUncoveredY, zmin + 0.3, xmax - 0.3, yCoord, zmax - 0.3); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, aabb); + + if (list != null) // up + { + for (Object o : list) + { + if (o != null && o instanceof EntityLivingBase) + { + ((EntityLivingBase)o).setPositionAndUpdate(xCoord + 0.5f, yCoord + 1, zCoord + 0.5f); + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord, firstUncoveredY, zCoord).add(0.5), 1, 1, 0, 40, 0, 100); + worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); + currentEnergyValue = 0; + return; + } + } + } + } + else if (mode == 2) // down + { + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(xmin + 0.3, yCoord, zmin + 0.3, xmax - 0.3, yCoord + 2, zmax - 0.3); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, aabb); + + if (list != null) + { + for (Object o : list) + { + if (o != null && o instanceof EntityLivingBase) + { + ((EntityLivingBase)o).setPositionAndUpdate(xCoord + 0.5f, firstUncoveredY + 1, zCoord + 0.5f); + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord, firstUncoveredY + 1, zCoord).add(0.5), 1, 1, 0, 40, 0, 100); + worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); + currentEnergyValue = 0; + return; + } + } + } + } + } + + public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try + { + // Write source vector + outputStream.writeDouble(source.x); + outputStream.writeDouble(source.y); + outputStream.writeDouble(source.z); + // Write target vector + outputStream.writeDouble(dest.x); + outputStream.writeDouble(dest.y); + outputStream.writeDouble(dest.z); + // Write r, g, b of laser + outputStream.writeFloat(r); + outputStream.writeFloat(g); + outputStream.writeFloat(b); + // Write age + outputStream.writeByte(age); + // Write energy value + outputStream.writeInt(energy); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(source.intX(), source.intY(), source.intZ(), radius, worldObj.provider.dimensionId, packet); + ByteArrayOutputStream bos2 = new ByteArrayOutputStream(8); + DataOutputStream outputStream2 = new DataOutputStream(bos2); + + try + { + // Write source vector + outputStream2.writeDouble(source.x); + outputStream2.writeDouble(source.y); + outputStream2.writeDouble(source.z); + // Write target vector + outputStream2.writeDouble(dest.x); + outputStream2.writeDouble(dest.y); + outputStream2.writeDouble(dest.z); + // Write r, g, b of laser + outputStream2.writeFloat(r); + outputStream2.writeFloat(g); + outputStream2.writeFloat(b); + // Write age + outputStream2.writeByte(age); + // Write energy value + outputStream2.writeInt(energy); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet2 = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(dest.intX(), dest.intY(), dest.intZ(), radius, worldObj.provider.dimensionId, packet); + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); + } + + // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() + { + return (MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) + { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > MAX_ENERGY_VALUE) + { + leftover = (getCurrentEnergyValue() - MAX_ENERGY_VALUE); + currentEnergyValue = MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() + { + return currentEnergyValue; + } + + public int collectAllEnergy() + { + int energy = currentEnergyValue; + currentEnergyValue = 0; + return energy; + } + + @Override + public void onChunkUnload() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } +} diff --git a/src/cr0s/WarpDrive/TileEntityMiningLaser.java b/src/cr0s/WarpDrive/TileEntityMiningLaser.java new file mode 100644 index 00000000..e62b2dfb --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityMiningLaser.java @@ -0,0 +1,700 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.network.packet.Packet62LevelSound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.inventory.IInventory; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.fluids.FluidRegistry; +import appeng.api.WorldCoord; +import appeng.api.IAEItemStack; +import appeng.api.Util; +import appeng.api.events.GridTileLoadEvent; +import appeng.api.events.GridTileUnloadEvent; +import appeng.api.me.tiles.IGridMachine; +import appeng.api.me.tiles.ITileCable; +import appeng.api.me.util.IGridInterface; +import appeng.api.me.util.IMEInventoryHandler; + + +public class TileEntityMiningLaser extends TileEntity implements IPeripheral, IGridMachine, ITileCable +{ + Boolean powerStatus = false; + private IGridInterface grid; + + private int dx, dz, dy; + private boolean isMining = false; + private boolean isQuarry = false; + private boolean useDeiterium = false; + private boolean AENetworkReady = false; + + private String[] methodsArray = + { + "mine", //0 + "stop", //1 + "isMining", //2 + "quarry", //3 + "state", //4 + "offset" //5 + }; + + private int delayTicksScan = 0; + private int delayTicksMine = 0; + private int currentMode = 0; // 0 - scan next layer, 1 - collect valuables + + private int currentLayer; + + private ArrayList valuablesInLayer = new ArrayList(); + private int valuableIndex = 0; + + private int layerOffset = 1; + + private Vector3 minerVector; + //private long uid = 0; + + TileEntityParticleBooster booster = null; + + private boolean isOnEarth = false; + //int t = 20; + @Override + public void updateEntity() + { + if (isMining) + { + isOnEarth = (worldObj.provider.dimensionId == 0); + if (minerVector != null) + { + minerVector.x = xCoord; + minerVector.y = yCoord - 1; + minerVector.z = zCoord; + minerVector = minerVector.add(0.5); + } + + if (currentMode == 0) + { + if (++delayTicksScan > WarpDriveConfig.i.ML_SCAN_DELAY) + { + delayTicksScan = 0; + valuablesInLayer.clear(); + valuableIndex = 0; + if (!collectEnergyPacketFromBooster(isOnEarth ? WarpDriveConfig.i.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.i.ML_EU_PER_LAYER_SPACE, true)) + return; + while (currentLayer > 0) + { + scanLayer(); + if (valuablesInLayer.size() > 0) + { + if (!collectEnergyPacketFromBooster(isOnEarth ? WarpDriveConfig.i.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.i.ML_EU_PER_LAYER_SPACE, false)) + return; + sendLaserPacket(minerVector, new Vector3(xCoord, currentLayer, zCoord).add(0.5), 0, 0, 1, 20, 0, 50); + worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); + int blockID = worldObj.getBlockId(xCoord, currentLayer, zCoord); + if (blockID != 0) + if (canDig(blockID)) + harvestBlock(new Vector3(xCoord, currentLayer, zCoord)); + currentMode = 1; + return; + } + else + --currentLayer; + } + if (currentLayer <= 0) + isMining = false; + } + } + else + { + if (++delayTicksMine > WarpDriveConfig.i.ML_MINE_DELAY && isMining) + { + delayTicksMine = 0; + while(valuableIndex < valuablesInLayer.size() && isMining) + { + Vector3 valuable = valuablesInLayer.get(valuableIndex++); + int blockID = worldObj.getBlockId(valuable.intX(), valuable.intY(), valuable.intZ()); + if (blockID == 0 || !canDig(blockID)) + continue; + sendLaserPacket(minerVector, new Vector3(valuable.intX(), valuable.intY(), valuable.intZ()).add(0.5), 1, 1, 0, 2 * WarpDriveConfig.i.ML_MINE_DELAY, 0, 50); + worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F); + harvestBlock(valuable); + return;//top lel, yes yes + } + delayTicksMine = 0; + currentMode = 0; + --currentLayer; + } + } + } + } + + + private boolean canDig(int blockID) + { + if (blockID == 0) + return false; + if (Block.blocksList[blockID] != null) + return ( (WarpDriveConfig.i.MinerOres.contains(blockID) || + Block.blocksList[blockID].blockHardness <= Block.obsidian.blockHardness) && + blockID !=WarpDriveConfig.i.MFFS_Field && + blockID != Block.bedrock.blockID ); + else + return (blockID != WarpDriveConfig.i.MFFS_Field && blockID != Block.bedrock.blockID); + } + + private void harvestBlock(Vector3 valuable) + { + int blockID = worldObj.getBlockId(valuable.intX(), valuable.intY(), valuable.intZ()); + int blockMeta = worldObj.getBlockMetadata(valuable.intX(), valuable.intY(), valuable.intZ()); + if (blockID != Block.waterMoving.blockID && blockID != Block.waterStill.blockID && blockID != Block.lavaMoving.blockID && blockID != Block.lavaStill.blockID) + { + List stacks = getItemStackFromBlock(valuable.intX(), valuable.intY(), valuable.intZ(), blockID, blockMeta); + if (stacks != null) + for (ItemStack stack : stacks) + { + if (grid != null && AENetworkReady) + putInGrid(stack); + else + putInChest(findChest(), stack); + } + worldObj.playAuxSFXAtEntity(null, 2001, valuable.intX(), valuable.intY(), valuable.intZ(), blockID + (blockMeta << 12)); + } + else if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID) + // Evaporate water + worldObj.playSoundEffect((double)((float)valuable.intX() + 0.5F), (double)((float)valuable.intY() + 0.5F), (double)((float)valuable.intZ() + 0.5F), "random.fizz", 0.5F, 2.6F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.8F); + worldObj.setBlockToAir(valuable.intX(), valuable.intY(), valuable.intZ()); + } + + private IInventory findChest() + { + TileEntity result = null; + result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); + + if (result != null && result instanceof IInventory) + { + return (IInventory) result; + } + + result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); + + if (result != null && result instanceof IInventory) + { + return (IInventory) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); + + if (result != null && result instanceof IInventory) + { + return (IInventory) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); + + if (result != null && result instanceof IInventory) + { + return (IInventory) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); + + if (result != null && result instanceof IInventory) + { + return (IInventory) result; + } + + return null; + } + + public List getItemStackFromBlock(int i, int j, int k, int blockID, int blockMeta) + { + Block block = Block.blocksList[blockID]; + if (block == null) + return null; + if (useDeiterium && grid != null && AENetworkReady) + { + IMEInventoryHandler cellArray = grid.getCellArray(); + if (cellArray != null) + { + int consume = isQuarry?15:1000; + IAEItemStack entryToAEIS = Util.createItemStack(new ItemStack(WarpDriveConfig.i.AEExtraFDI, consume, FluidRegistry.getFluidID("deuterium"))); + long contained = cellArray.countOfItemType(entryToAEIS); + if (block.canSilkHarvest(worldObj, null, i, j, k, blockMeta) && contained >= consume) + { + cellArray.extractItems(entryToAEIS); + ArrayList t = new ArrayList(); + t.add(new ItemStack(blockID, 1, blockMeta)); + return t; + } + } + } + return block.getBlockDropped(worldObj, i, j, k, blockMeta, 0); + } + + public int putInGrid(ItemStack itemStackSource) + { + int transferred = itemStackSource.stackSize; + IMEInventoryHandler cellArray = grid.getCellArray(); + if (cellArray != null) + { + IAEItemStack ret = cellArray.addItems(Util.createItemStack(itemStackSource)); + if (ret != null) + transferred -= ret.getStackSize(); + } + return transferred; + } + + public int putInChest(IInventory inventory, ItemStack itemStackSource) + { + if (inventory == null || itemStackSource == null) + { + isMining = false; //stopping operation + return 0; + } + + int transferred = 0; + + for (int i = 0; i < inventory.getSizeInventory(); i++) + { + if (!inventory.isItemValidForSlot(i, itemStackSource)) + { + continue; + } + + ItemStack itemStack = inventory.getStackInSlot(i); + + if (itemStack == null || !itemStack.isItemEqual(itemStackSource)) + { + continue; + } + + int transfer = Math.min(itemStackSource.stackSize - transferred, itemStack.getMaxStackSize() - itemStack.stackSize); + itemStack.stackSize += transfer; + transferred += transfer; + + if (transferred == itemStackSource.stackSize) + { + return transferred; + } + } + + for (int i = 0; i < inventory.getSizeInventory(); i++) + { + if (!inventory.isItemValidForSlot(i, itemStackSource)) + { + continue; + } + + ItemStack itemStack = inventory.getStackInSlot(i); + + if (itemStack != null) + { + continue; + } + + int transfer = Math.min(itemStackSource.stackSize - transferred, itemStackSource.getMaxStackSize()); + ItemStack dest = copyWithSize(itemStackSource, transfer); + inventory.setInventorySlotContents(i, dest); + transferred += transfer; + + if (transferred == itemStackSource.stackSize) + { + return transferred; + } + } + + return transferred; + } + + public ItemStack copyWithSize(ItemStack itemStack, int newSize) + { + ItemStack ret = itemStack.copy(); + ret.stackSize = newSize; + return ret; + } + + private void scanLayer() + { + valuablesInLayer.clear(); + int xmax, zmax, x1, x2, z1, z2; + int xmin, zmin; + final int CUBE_SIDE = 8; + x1 = xCoord + CUBE_SIDE / 2; + x2 = xCoord - CUBE_SIDE / 2; + + if (x1 < x2) + { + xmin = x1; + xmax = x2; + } + else + { + xmin = x2; + xmax = x1; + } + + z1 = zCoord + CUBE_SIDE / 2; + z2 = zCoord - CUBE_SIDE / 2; + + if (z1 < z2) + { + zmin = z1; + zmax = z2; + } + else + { + zmin = z2; + zmax = z1; + } + + // Search for valuable blocks + for (int x = xmin; x <= xmax; x++) + for (int z = zmin; z <= zmax; z++) + { + int blockID = worldObj.getBlockId(x, currentLayer, z); + if (canDig(blockID)) + if (isQuarry) // Quarry collects all blocks + { + if (!worldObj.isAirBlock(x, currentLayer, z) && blockID != Block.lavaMoving.blockID && blockID != Block.lavaStill.blockID) + valuablesInLayer.add(new Vector3(x, currentLayer, z)); + } + else // Not-quarry collect only valuables blocks + if (WarpDriveConfig.i.MinerOres.contains(worldObj.getBlockId(x, currentLayer, z))) + valuablesInLayer.add(new Vector3(x, currentLayer, z)); + } + + valuableIndex = 0; + } + + private boolean collectEnergyPacketFromBooster(int packet, boolean test) + { + if (booster == null) + booster = findFirstBooster(); + if (booster != null) + if (test) + return packet <= booster.getCurrentEnergyValue(); + else + return booster.consumeEnergy(packet); + return false; + } + + private TileEntityParticleBooster findFirstBooster() + { + TileEntity result; + result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); + + if (result != null && result instanceof TileEntityParticleBooster) + { + dx = 1; + dz = 0; + dy = 0; + return (TileEntityParticleBooster) result; + } + + result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); + + if (result != null && result instanceof TileEntityParticleBooster) + { + dx = -1; + dz = 0; + dy = 0; + return (TileEntityParticleBooster) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); + + if (result != null && result instanceof TileEntityParticleBooster) + { + dx = 0; + dz = 1; + dy = 0; + return (TileEntityParticleBooster) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); + + if (result != null && result instanceof TileEntityParticleBooster) + { + dx = 0; + dz = -1; + dy = 0; + return (TileEntityParticleBooster) result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); + + if (result != null && result instanceof TileEntityParticleBooster) + { + dx = 0; + dz = 0; + dy = 1; + return (TileEntityParticleBooster) result; + } + + return null; + } + + public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { + if (source == null || dest == null || worldObj == null) + { + return; + } + + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try + { + // Write source vector + outputStream.writeDouble(source.x); + outputStream.writeDouble(source.y); + outputStream.writeDouble(source.z); + // Write target vector + outputStream.writeDouble(dest.x); + outputStream.writeDouble(dest.y); + outputStream.writeDouble(dest.z); + // Write r, g, b of laser + outputStream.writeFloat(r); + outputStream.writeFloat(g); + outputStream.writeFloat(b); + // Write age + outputStream.writeByte(age); + // Write energy value + outputStream.writeInt(0); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(source.intX(), source.intY(), source.intZ(), radius, worldObj.provider.dimensionId, packet); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(dest.intX(), dest.intY(), dest.intZ(), radius, worldObj.provider.dimensionId, packet); + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + isMining = tag.getBoolean("isMining"); + isQuarry = tag.getBoolean("isQuarry"); + currentLayer = tag.getInteger("currentLayer"); + useDeiterium = tag.getBoolean("useDeiterium"); + minerVector = new Vector3(xCoord, yCoord - 1, zCoord).add(0.5); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setBoolean("isMining", isMining); + tag.setBoolean("isQuarry", isQuarry); + tag.setInteger("currentLayer", currentLayer); + tag.setBoolean("useDeiterium", useDeiterium); + } +//CC + // IPeripheral methods implementation + @Override + public String getType() + { + return "mininglaser"; + } + + @Override + public String[] getMethodNames() + { + return methodsArray; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { + switch (method) + { + case 0: // Mine() + if (isMining) + return new Boolean[] { false }; + isQuarry = false; + delayTicksScan = 0; + currentMode = 0; + minerVector = new Vector3(xCoord, yCoord - 1, zCoord).add(0.5); + currentLayer = yCoord - layerOffset; + isMining = true; + useDeiterium = (arguments.length == 1 && FluidRegistry.isFluidRegistered("deuterium")); + return new Boolean[] { true }; + + case 1: // stop() + isMining = false; + break; + + case 2: // isMining() + return new Boolean[] { isMining }; + case 3: // Quarry() + if (isMining) + return new Boolean[] { false }; + + isQuarry = true; + delayTicksScan = 0; + currentMode = 0; + minerVector = new Vector3(xCoord, yCoord - 1, zCoord).add(0.5); + currentLayer = yCoord - layerOffset; + isMining = true; + useDeiterium = (arguments.length == 1 && FluidRegistry.isFluidRegistered("deuterium")); + return new Boolean[] { true }; + + case 4: // State is: state, energy, currentLayer, valuablesMined, valuablesInLayer = getMinerState() + int energy = 0; + if (booster != null) + energy = booster.getCurrentEnergyValue(); + String state = "not mining"; + Integer valuablesInLayer, valuablesMined; + if (isMining) + { + valuablesInLayer = this.valuablesInLayer.size(); + valuablesMined = this.valuableIndex; + state = "mining" + ((isQuarry) ? " (quarry mode)" : ""); + if (energy < 0) + state = "out of energy"; + return new Object[] {state, energy, currentLayer, valuablesMined, valuablesInLayer}; + } + return new Object[] {state, energy, currentLayer, 0, 0}; + + case 5: // Offset + if (arguments.length == 1) + { + int t = ((Double)arguments[0]).intValue(); + if (t < 0) + t = 0; + layerOffset = t + 1; + } + return new Integer[] { layerOffset-1 }; + } + return null; + } + + @Override + public boolean canAttachToSide(int side) + { + return true; + } + + @Override + public void attach(IComputerAccess computer) + { + } + + @Override + public void detach(IComputerAccess computer) + { + } +//AE + @Override + public float getPowerDrainPerTick() + { + return 1; + } + + @Override + public void validate() + { + super.validate(); + MinecraftForge.EVENT_BUS.post(new GridTileLoadEvent(this, worldObj, getLocation())); + } + + @Override + public void invalidate() + { + super.invalidate(); + MinecraftForge.EVENT_BUS.post(new GridTileUnloadEvent(this, worldObj, getLocation())); + } + + @Override + public WorldCoord getLocation() + { + return new WorldCoord(xCoord, yCoord, zCoord); + } + + @Override + public boolean isValid() + { + return true; + } + + @Override + public void setPowerStatus(boolean hasPower) + { + powerStatus = hasPower; + } + + @Override + public boolean isPowered() + { + return powerStatus; + } + + @Override + public IGridInterface getGrid() + { + return grid; + } + + @Override + public void setGrid(IGridInterface gi) + { + grid = gi; + } + + @Override + public World getWorld() + { + return worldObj; + } + + @Override + public boolean coveredConnections() + { + return true; + } + + public void setNetworkReady( boolean isReady ) + { + AENetworkReady = isReady; + } + + public boolean isMachineActive() + { + return true; + } +} diff --git a/src/cr0s/WarpDrive/TileEntityMonitor.java b/src/cr0s/WarpDrive/TileEntityMonitor.java new file mode 100644 index 00000000..c5819990 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityMonitor.java @@ -0,0 +1,151 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.network.packet.Packet62LevelSound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.ChunkPosition; +import net.minecraft.world.World; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityMonitor extends TileEntity implements IPeripheral +{ + private int frequency; + + private String[] methodsArray = + { + "freq" + }; + + private int packetSendTicks = 20; + + @Override + public void updateEntity() + { + if (FMLCommonHandler.instance().getEffectiveSide().isServer()) + { + if (packetSendTicks-- == 0) + { + packetSendTicks = 20 * 5; + sendFreqPacket(); + } + + return; + } + } + + public int getFrequency() + { + return frequency; + } + + public void setFrequency(int freq) + { + frequency = freq; + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + frequency = tag.getInteger("frequency"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("frequency", frequency); + } + + // IPeripheral methods implementation + @Override + public String getType() + { + return "monitor"; + } + + @Override + public String[] getMethodNames() + { + return methodsArray; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { + if (arguments.length == 1) + frequency = ((Double)arguments[0]).intValue(); + return new Integer[] { frequency }; + } + + public void sendFreqPacket() + { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try + { + // Write source vector + outputStream.writeInt(xCoord); + outputStream.writeInt(yCoord); + outputStream.writeInt(zCoord); + outputStream.writeInt(this.frequency); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveFreq"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer.getServer().getConfigurationManager().sendToAllNear(xCoord, yCoord, zCoord, 100, worldObj.provider.dimensionId, packet); + } + } + + @Override + public boolean canAttachToSide(int side) + { + return true; + } + + @Override + public void attach(IComputerAccess computer) + { + } + + @Override + public void detach(IComputerAccess computer) + { + } +} diff --git a/src/cr0s/WarpDrive/TileEntityParticleBooster.java b/src/cr0s/WarpDrive/TileEntityParticleBooster.java new file mode 100644 index 00000000..74cc7f32 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityParticleBooster.java @@ -0,0 +1,150 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityParticleBooster extends TileEntity implements IEnergySink +{ + public boolean addedToEnergyNet = false; + + private int currentEnergyValue = 0; + + int ticks = 0; + + @Override + public void updateEntity() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + if (!addedToEnergyNet && !this.tileEntityInvalid) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + if (++ticks > 40) + { + ticks = 0; + currentEnergyValue = Math.min(currentEnergyValue, WarpDriveConfig.i.PB_MAX_ENERGY_VALUE); + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, currentEnergyValue / 10000, 2); + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); + } + + // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() + { + return (WarpDriveConfig.i.PB_MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) + { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > WarpDriveConfig.i.PB_MAX_ENERGY_VALUE) + { + leftover = (getCurrentEnergyValue() - WarpDriveConfig.i.PB_MAX_ENERGY_VALUE); + currentEnergyValue = WarpDriveConfig.i.PB_MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() + { + return currentEnergyValue; + } + + public boolean consumeEnergy(int amount) + { + if (currentEnergyValue - amount < 0) + { + return false; + } + + currentEnergyValue -= amount; + return true; + } + + public int collectAllEnergy() + { + int energy = currentEnergyValue; + currentEnergyValue = 0; + return energy; + } + + @Override + public void onChunkUnload() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } +} diff --git a/src/cr0s/WarpDrive/TileEntityProtocol.java b/src/cr0s/WarpDrive/TileEntityProtocol.java new file mode 100644 index 00000000..cb4cf021 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityProtocol.java @@ -0,0 +1,683 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.DamageSource; + +/** + * Protocol block tile entity + * @author Cr0s + */ +public class TileEntityProtocol extends TileEntity implements IPeripheral +{ + // Variables + private int distance = 0; + private int direction = 0; + private int mode = 0; + + private boolean jumpFlag = false; + private boolean summonFlag = false; + private String toSummon = ""; + + private String targetJumpgateName = ""; + + // Gabarits + private int front, right, up; + private int back, left, down; + + // Player attaching + public ArrayList players = new ArrayList(); + public String playersString = ""; + + private String beaconFrequency = ""; + + boolean ready = false; // Ready to operate (valid assembly) + + public String[] methodsArray = + { + "dim_getp", "dim_setp", // 0, 1 + "dim_getn", "dim_setn", // 2, 3 + "set_mode", "set_distance", "set_direction", // 4, 5, 6 + "get_attached_players", "summon", "summon_all", // 7, 8, 9 + "get_x", "get_y", "get_z", // 10, 11, 12 + "get_energy_level", "do_jump", "get_ship_size", // 13, 14, 15 + "set_beacon_frequency", "get_dx", "get_dz", // 16, 17, 18 + "set_core_frequency", "is_in_space", "is_in_hyperspace", // 19, 20, 21 + "set_target_jumpgate", // 22 + }; + + private int ticks = 0; + private final int BLOCK_UPDATE_INTERVAL = 20 * 3; // 3 seconds + + private TileEntity core; + + @Override + public void updateEntity() + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + if (++ticks >= BLOCK_UPDATE_INTERVAL) + { + findCoreBlock(); + + if (core != null) + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, this.mode, 1 + 2); // Activated + } + else + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); // Inactive + } + + ticks = 0; + } + } + + private void setJumpDistance(int distance) + { + this.distance = distance; + } + + private void setMode(int mode) + { + this.mode = mode; + } + + private void setDirection(int dir) + { + if (dir == 1) + { + dir = -1; + } + else if (dir == 2) + { + dir = -2; + } + else if (dir == 255) + { + dir = 270; + } + + this.direction = dir; + } + + private void doJump() + { + if (core != null && core instanceof TileEntityReactor) + { + ((TileEntityReactor)core).randomCooldownAddition = worldObj.rand.nextInt(60); // Adding random ticks to cooldown + } + + setJumpFlag(true); + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + setMode(tag.getInteger("mode")); + setFront(tag.getInteger("front")); + setRight(tag.getInteger("right")); + setUp(tag.getInteger("up")); + setBack(tag.getInteger("back")); + setLeft(tag.getInteger("left")); + setDown(tag.getInteger("down")); + setDistance(tag.getInteger("distance")); + playersString = tag.getString("players"); + updatePlayersList(); + setBeaconFrequency(tag.getString("bfreq")); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + updatePlayersString(); + tag.setString("players", playersString); + tag.setInteger("mode", this.mode); + tag.setInteger("front", this.front); + tag.setInteger("right", this.right); + tag.setInteger("up", this.up); + tag.setInteger("back", this.back); + tag.setInteger("left", this.left); + tag.setInteger("down", this.down); + tag.setInteger("distance", this.distance); + tag.setString("bfreq", getBeaconFrequency()); + } + + public void attachPlayer(EntityPlayer ep) + { + for (int i = 0; i < players.size(); i++) + { + String nick = players.get(i); + + if (ep.username.equals(nick)) + { + ep.addChatMessage("[WarpCtrlr] Detached."); + players.remove(i); + return; + } + } + + ep.attackEntityFrom(DamageSource.generic, 1); + ep.addChatMessage("[WarpCtrlr] Successfully attached."); + players.add(ep.username); + updatePlayersString(); + } + + public void updatePlayersString() + { + String nick; + this.playersString = ""; + + for (int i = 0; i < players.size(); i++) + { + nick = players.get(i); + this.playersString += nick + "|"; + } + } + + public void updatePlayersList() + { + String[] playersArray = playersString.split("\\|"); + + for (int i = 0; i < playersArray.length; i++) + { + String nick = playersArray[i]; + + if (!nick.isEmpty()) + { + players.add(nick); + } + } + } + + public String getAttachedPlayersList() + { + String list = ""; + + for (int i = 0; i < this.players.size(); i++) + { + String nick = this.players.get(i); + list += nick + ((i == this.players.size() - 1) ? "" : ", "); + } + + if (players.isEmpty()) + { + list = ""; + } + + return list; + } + + /** + * @return the jumpFlag + */ + public boolean isJumpFlag() + { + return jumpFlag; + } + + /** + * @param jumpFlag the jumpFlag to set + */ + public void setJumpFlag(boolean jumpFlag) + { + this.jumpFlag = jumpFlag; + } + + /** + * @return the front + */ + public int getFront() + { + return front; + } + + /** + * @param front the front to set + */ + public void setFront(int front) + { + this.front = front; + } + + /** + * @return the right + */ + public int getRight() + { + return right; + } + + /** + * @param right the right to set + */ + public void setRight(int right) + { + this.right = right; + } + + /** + * @return the up + */ + public int getUp() + { + return up; + } + + /** + * @param up the up to set + */ + public void setUp(int up) + { + this.up = up; + } + + /** + * @return the back + */ + public int getBack() + { + return back; + } + + /** + * @param back the back to set + */ + public void setBack(int back) + { + this.back = back; + } + + /** + * @return the left + */ + public int getLeft() + { + return left; + } + + /** + * @param left the left to set + */ + public void setLeft(int left) + { + this.left = left; + } + + /** + * @return the down + */ + public int getDown() + { + return down; + } + + /** + * @param down the down to set + */ + public void setDown(int down) + { + this.down = down; + } + + public void setDistance(int distance) + { + this.distance = distance; + } + + public int getDistance() + { + return this.distance; + } + + /** + * @return the mode + */ + public int getMode() + { + return mode; + } + + /** + * @return the direction + */ + public int getDirection() + { + return direction; + } + + /** + * @return the summonFlag + */ + public boolean isSummonAllFlag() + { + return summonFlag; + } + + /** + * @param summonFlag the summonFlag to set + */ + public void setSummonAllFlag(boolean summonFlag) + { + this.summonFlag = summonFlag; + } + + @Override + public String getType() + { + return "warpcore"; + } + + @Override + public String[] getMethodNames() + { + return (methodsArray); + } + + @Override + public boolean canAttachToSide(int side) + { + return true; + } + + @Override + public void attach(IComputerAccess computer) + { + } + + @Override + public void detach(IComputerAccess computer) + { + } + + /** + * @return the toSummon + */ + public String getToSummon() + { + return toSummon; + } + + /** + * @param toSummon the toSummon to set + */ + public void setToSummon(String toSummon) + { + this.toSummon = toSummon; + } + + /** + * @return the beaconFrequency + */ + public String getBeaconFrequency() + { + return beaconFrequency; + } + + /** + * @param beaconFrequency the beaconFrequency to set + */ + public void setBeaconFrequency(String beaconFrequency) + { + this.beaconFrequency = beaconFrequency; + } + + public TileEntity findCoreBlock() + { + this.core = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); + + if (this.core != null && this.core instanceof TileEntityReactor) + { + return this.core; + } + + this.core = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); + + if (this.core != null && this.core instanceof TileEntityReactor) + { + return this.core; + } + + this.core = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); + + if (this.core != null && this.core instanceof TileEntityReactor) + { + return this.core; + } + + this.core = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); + + if (this.core != null && this.core instanceof TileEntityReactor) + { + return this.core; + } + + return null; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { + switch (method) + { + case 0: // dim_getp () + return new Integer[] { getFront(), getRight(), getUp() }; + case 1: // dim_setp (front, right, up) + if ( arguments.length != 3 || + ( ( (Double)arguments[0] ).intValue() < 0 || + ( (Double)arguments[1] ).intValue() < 0 || + ( (Double)arguments[2] ).intValue() < 0 || + ( (Double)arguments[0] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || + ( (Double)arguments[1] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || + ( (Double)arguments[2] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE ) ) + { + return new Integer[] { -1 }; + } + + setFront(((Double)arguments[0]).intValue()); + setRight(((Double)arguments[1]).intValue()); + setUp(((Double)arguments[2]).intValue()); + WarpDrive.instance.registry.removeDeadCores(); + break; + + case 2: // dim_getn () + return new Integer[] { getBack(), getLeft(), getDown() }; + case 3: // dim_setn (back, left, down) + if ( arguments.length != 3 || + ( ( (Double)arguments[0] ).intValue() < 0 || + ( (Double)arguments[1] ).intValue() < 0 || + ( (Double)arguments[2] ).intValue() < 0 || + ( (Double)arguments[0] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || + ( (Double)arguments[1] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || + ( (Double)arguments[2] ).intValue() > WarpDriveConfig.i.WC_MAX_SHIP_SIDE ) ) + { + return new Integer[] { -1 }; + } + + setBack(((Double)arguments[0]).intValue()); + setLeft(((Double)arguments[1]).intValue()); + setDown(((Double)arguments[2]).intValue()); + WarpDrive.instance.registry.removeDeadCores(); + break; + + case 4: // set_mode (mode) + if (arguments.length != 1) + { + return new Integer[] { -1 }; + } + + setMode(((Double)arguments[0]).intValue()); + break; + + case 5: // set_distance (distance) + if (arguments.length != 1) + { + return new Integer[] { -1 }; + } + + setJumpDistance(((Double)arguments[0]).intValue()); + break; + + case 6: // set_direction (dir) + if (arguments.length != 1) + { + return new Integer[] { -1 }; + } + + setDirection(((Double)arguments[0]).intValue()); + break; + + case 7: // get_attached_players + String list = ""; + + for (int i = 0; i < this.players.size(); i++) + { + String nick = this.players.get(i); + list += nick + ((i == this.players.size() - 1) ? "" : ","); + } + + if (players.isEmpty()) + { + list = ""; + } + + return new Object[] { (String)list }; + + case 8: // summon + if (arguments.length != 1) + { + return new Integer[] { -1 }; + } + + int playerID = ((Double)arguments[0]).intValue(); + + if (playerID >= 0 && playerID < players.size()) + { + setToSummon(players.get(playerID)); + } + + break; + + case 9: // summon_all + this.setSummonAllFlag(true); + + case 10: // get_x + if (core == null) + { + return null; + } + + return new Object[] { (Integer)core.xCoord }; + + case 11: // get_y + if (core == null) + { + return null; + } + + return new Object[] { (Integer)core.yCoord }; + + case 12: // get_z + if (core == null) + { + return null; + } + + return new Object[] { (Integer)core.zCoord }; + + case 13: // get_energy_value + if (core != null) + { + return new Object[] { (Integer)((TileEntityReactor)core).currentEnergyValue }; + } + + return null; + + case 14: // do_jump + doJump(); + break; + + case 15: // get_ship_size + if (core != null) + { + ((TileEntityReactor)core).calculateSpatialShipParameters(); + return new Object[] { (Integer)((TileEntityReactor)core).getRealShipVolume() }; + } + + break; + + case 16: // set_beacon_frequency + if (arguments.length == 1) + { + setBeaconFrequency((String)arguments[0]); + } + + break; + + case 17: // get_dx + if (core != null && core instanceof TileEntityReactor) + { + return new Object[] { (Integer)(((TileEntityReactor)core).dx) }; + } + + break; + + case 18: // get_dz + if (core != null && core instanceof TileEntityReactor) + { + return new Object[] { (Integer)(((TileEntityReactor)core).dz) }; + } + + break; + + case 19: // set_core_frequency + if (arguments.length == 1 && (core != null && core instanceof TileEntityReactor)) + { + ((TileEntityReactor)core).coreFrequency = ((String)arguments[0]).replace("/", "").replace(".", "").replace("\\", "."); + } + + break; + + case 20: // is_in_space + return new Boolean[] { worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID }; + case 21: // is_in_hyperspace + return new Boolean[] { worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID }; + case 22: // set_target_jumpgate + if (arguments.length == 1) + { + setTargetJumpgateName((String)arguments[0]); + } + + break; + } + + return new Integer[] { 0 }; + } + + /** + * @return the targetJumpgateName + */ + public String getTargetJumpgateName() + { + return targetJumpgateName; + } + + /** + * @param targetJumpgateName the targetJumpgateName to set + */ + public void setTargetJumpgateName(String targetJumpgateName) + { + this.targetJumpgateName = targetJumpgateName; + } +} diff --git a/src/cr0s/WarpDrive/TileEntityRadar.java b/src/cr0s/WarpDrive/TileEntityRadar.java new file mode 100644 index 00000000..2a6d6630 --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityRadar.java @@ -0,0 +1,256 @@ +package cr0s.WarpDrive; + +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityRadar extends TileEntity implements IPeripheral, IEnergySink +{ + public boolean addedToEnergyNet = false; + + private int currentEnergyValue = 0; + + private String[] methodsArray = + { + "scanRay", // 0 + "scanRadius", // 1 + "getResultsCount", // 2 + "getResult", // 3 + "getEnergyLevel", // 4 + "pos" // 5 + }; + + private ArrayList results; + + private int scanRadius = 0; + private int cooldownTime = 0; + + private boolean isEnergyEnoughForScanRadiusW(int radius) + { + int needEnergy = (radius * radius); + return ((getCurrentEnergyValue() - needEnergy) > 0); + } + + @Override + public void updateEntity() + { + if (!addedToEnergyNet && !this.tileEntityInvalid) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + try + { + if (worldObj.getBlockMetadata(xCoord, yCoord, zCoord) == 2) + { + if (cooldownTime++ > (20 * ((scanRadius / 1000) + 1))) + { + WarpDrive.instance.registry.removeDeadCores(); + results = WarpDrive.instance.registry.searchWarpCoresInRadius(xCoord, yCoord, zCoord, scanRadius); + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); + cooldownTime = 0; + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); + } + + // IPeripheral methods implementation + @Override + public String getType() + { + return "radar"; + } + + @Override + public String[] getMethodNames() + { + return methodsArray; + } + + @Override + public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception + { + switch (method) + { + case 0: // scanRay (toX, toY, toZ) + return new Object[] { -1 }; + case 1: // scanRadius (radius) + if (arguments.length == 1) + { + int radius = ((Double)arguments[0]).intValue(); + if (radius <= 0 || radius > 10000) + { + scanRadius = 0; + return new Boolean[] { false }; + } + if (radius != 0 && isEnergyEnoughForScanRadiusW(radius)) + { + // Consume energy + this.currentEnergyValue -= radius * radius; + // Begin searching + scanRadius = radius; + cooldownTime = 0; + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 2, 1 + 2); + } + else + { + results = null; + return new Boolean[] { false }; + } + } + else + return new Boolean[] { false }; + return new Boolean[] { true }; + + case 2: // getResultsCount + if (results != null) + return new Integer[] { results.size() }; + return new Integer[] { 0 }; + case 3: // getResult + if (arguments.length == 1 && (results != null)) + { + int index = ((Double)arguments[0]).intValue(); + if (index > -1 && index < results.size()) + { + TileEntityReactor res = results.get(index); + if (res != null) + { + int yAddition = (res.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) ? 256 : (res.worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) ? 512 : 0; + return new Object[] { (String)res.coreFrequency, (Integer)res.xCoord, (Integer)res.yCoord + yAddition, (Integer)res.zCoord }; + } + } + } + return new Object[] { (String)"FAIL", 0, 0, 0 }; + case 4: // getEnergyLevel + return new Integer[] { getCurrentEnergyValue() }; + case 5: // Pos + return new Integer[] { xCoord, yCoord, zCoord }; + } + + return null; + } + + @Override + public boolean canAttachToSide(int side) + { + return true; + } + + @Override + public void attach(IComputerAccess computer) + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); + } + + @Override + public void detach(IComputerAccess computer) + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); + } + + // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() + { + return (WarpDriveConfig.i.WR_MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) + { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > WarpDriveConfig.i.WR_MAX_ENERGY_VALUE) + { + leftover = (getCurrentEnergyValue() - WarpDriveConfig.i.WR_MAX_ENERGY_VALUE); + currentEnergyValue = WarpDriveConfig.i.WR_MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() + { + return currentEnergyValue; + } + + @Override + public void onChunkUnload() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } +} diff --git a/src/cr0s/WarpDrive/TileEntityReactor.java b/src/cr0s/WarpDrive/TileEntityReactor.java new file mode 100644 index 00000000..6c206f5e --- /dev/null +++ b/src/cr0s/WarpDrive/TileEntityReactor.java @@ -0,0 +1,1163 @@ +package cr0s.WarpDrive; + +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; + +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.potion.Potion; +import net.minecraft.potion.PotionEffect; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.tileentity.TileEntityChest; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.MathHelper; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.ForgeDirection; +import net.minecraftforge.common.MinecraftForge; +import cpw.mods.fml.common.FMLCommonHandler; + +/** + * @author Cr0s + */ +public class TileEntityReactor extends TileEntity implements IEnergySink +{ + public boolean addedToEnergyNet = false; + + public Boolean ready; + + public Boolean invalidAssembly = false; + + public Boolean launchState = false; + + int ticks; + + public final int JUMP_UP = -1; + public final int JUMP_DOWN = -2; + int dx, dz; + int direction; + int distance; + + public int maxX, maxY, maxZ; + public int minX, minY, minZ; + + public int shipFront, shipBack; + public int shipLeft, shipRight; + public int shipUp, shipDown; + public int shipHeight, shipWidth, shipLength; + int shipSize = 0; //ship length in the direction of a jump + int shipVolume = 0; //number of all blocks the ship consists of + int currentMode = 0; + + int currentEnergyValue = 0; + + private final byte MODE_BASIC_JUMP = 1; // 0-128 + private final byte MODE_LONG_JUMP = 2; // 0-12800 + private final byte MODE_BEACON_JUMP = 4; // Jump ship by beacon + private final byte MODE_HYPERSPACE = 5; // Jump to Hyperspace + private final byte MODE_TELEPORT = -1; + private final byte MODE_GATE_JUMP = 6; // Jump via jumpgate + + int cooldownTime = 0; + public int randomCooldownAddition = 0; + + private int registryUpdateTicks = 0; + public String coreFrequency = "default"; + + public int isolationBlocksCount = 0; + public int isolationUpdateTicks = 0; + + public String coreState = ""; + public TileEntityProtocol controller; + + private boolean soundPlayed = false; + + @Override + public void updateEntity() + { + if (!FMLCommonHandler.instance().getEffectiveSide().isClient() && !addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + + // Update warp core in cores registry + if (++registryUpdateTicks > WarpDriveConfig.i.WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS * 20) + { + registryUpdateTicks = 0; + WarpDrive.instance.registry.updateInRegistry(this); + } + + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + if (++isolationUpdateTicks > WarpDriveConfig.i.WC_ISOLATION_UPDATE_INTARVAL_SECONDS * 20) + { + isolationUpdateTicks = 0; + updateIsolationState(); + } + + TileEntity c = findControllerBlock(); + + if (c != null) + { + this.controller = (TileEntityProtocol)c; + this.currentMode = controller.getMode(); + shipFront = controller.getFront(); + shipRight = controller.getRight(); + shipUp = controller.getUp(); + shipBack = controller.getBack(); + shipLeft = controller.getLeft(); + shipDown = controller.getDown(); + + if (this.controller.isSummonAllFlag()) + { + summonPlayers(); + controller.setSummonAllFlag(false); + } + else if (!this.controller.getToSummon().isEmpty()) + { + summonSinglePlayer(this.controller.getToSummon()); + this.controller.setToSummon(""); + } + } + else + { + invalidAssembly = true; + return; + } + + switch (currentMode) + { + case MODE_TELEPORT: + if (isChestSummonMode()) + { + if (ticks++ < 20) + { + return; + } + + if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) + { + summonPlayersByChestCode(); + ticks = 0; + } + } + else + { + teleportPlayersToSpace(); + } + + break; + + case MODE_BASIC_JUMP: + case MODE_LONG_JUMP: + case MODE_BEACON_JUMP: + case MODE_HYPERSPACE: + case MODE_GATE_JUMP: + if (controller == null) + { + return; + } + + coreState = "Energy level: " + currentEnergyValue + " Eu"; + + if (controller.isJumpFlag()) + { + // Set up activated animation + if (worldObj.getBlockMetadata(xCoord, yCoord, zCoord) == 0) + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); // Set block state to "active" + makePlayersOnShipDrunk(); + } + + if (!soundPlayed) + { + worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, "warpdrive:warp", 4F, 1F); + this.soundPlayed = true; + } + + // Awaiting cooldown time + if (/*currentMode != MODE_BASIC_JUMP && */cooldownTime++ < ((WarpDriveConfig.i.WC_COOLDOWN_INTERVAL_SECONDS) * 20) + randomCooldownAddition) + { + //System.out.println("[WC] Awaiting cooldown: " + cooldownTime + " < " + ( ((WarpDriveConfig.i.WC_COOLDOWN_INTERVAL_SECONDS) * 20) + randomCooldownAddition)); + return; + } + + cooldownTime = 0; + soundPlayed = false; + + if (!prepareToJump()) + { + return; + } + + if (WarpDrive.instance.registry.isWarpCoreIntersectsWithOthers(this)) + { + this.controller.setJumpFlag(false); + messageToAllPlayersOnShip("Warp field intersects with other ship's field. Cannot jump."); + return; + } + + if (WarpDrive.instance.cloaks.isInCloak(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, false)) + { + this.controller.setJumpFlag(false); + messageToAllPlayersOnShip("Wap-Core is inside cloaking field. Can't jump. Disable cloaking field to jump!"); + return; + } + + doJump(); + controller.setJumpFlag(false); + } + else + { + worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); // Deactivate block animation + } + + break; + } + } + + public void messageToAllPlayersOnShip(String msg) + { + AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); + + for (Object o : list) + { + if (o == null || !(o instanceof EntityPlayer)) + { + continue; + } + + ((EntityPlayer)o).addChatMessage("[WarpCore] " + msg); + } + } + + public void updateIsolationState() + { + // Search block in cube around core with side 10 + int xmax, ymax, zmax, x1, x2, z1, z2; + int xmin, ymin, zmin; + final int ISOLATION_CUBE_SIDE = 6; + x1 = xCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); + x2 = xCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); + + if (x1 < x2) + { + xmin = x1; + xmax = x2; + } + else + { + xmin = x2; + xmax = x1; + } + + z1 = zCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); + z2 = zCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); + + if (z1 < z2) + { + zmin = z1; + zmax = z2; + } + else + { + zmin = z2; + zmax = z1; + } + + ymax = yCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); + ymin = yCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); + this.isolationBlocksCount = 0; + + // Search for warp isolation blocks + for (int y = ymin; y <= ymax; y++) + { + for (int x = xmin; x <= xmax; x++) + { + for (int z = zmin; z <= zmax; z++) + { + if (worldObj.getBlockId(x, y, z) == WarpDriveConfig.i.isolationID) + { + this.isolationBlocksCount++; + } + } + } + } + } + + public void makePlayersOnShipDrunk() + { + if (!prepareToJump()) + { + return; + } + + AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); + + for (Object o : list) + { + if (o == null || !(o instanceof EntityPlayer)) + { + continue; + } + + // Set "drunk" effect + ((EntityPlayer)o).addPotionEffect(new PotionEffect(Potion.confusion.id, 180, 0, true)); + } + } + + public void summonPlayers() + { + calculateSpatialShipParameters(); + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); + + for (int i = 0; i < controller.players.size(); i++) + { + String nick = controller.players.get(i); + EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(nick); + + if (player != null && !testBB(aabb, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))) + { + summonPlayer(player, xCoord + dx, yCoord, zCoord + dz); + } + } + } + + public void summonSinglePlayer(String nickname) + { + calculateSpatialShipParameters(); + AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); + + for (int i = 0; i < controller.players.size(); i++) + { + String nick = controller.players.get(i); + EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(nick); + + if (player != null && nick.equals(nickname) && !testBB(aabb, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))) + { + summonPlayer(player, xCoord + dx, yCoord, zCoord + dz); + return; + } + } + } + + public void summonPlayer(EntityPlayerMP player, int x, int y, int z) + { + if (this.currentEnergyValue - WarpDriveConfig.i.WC_ENERGY_PER_ENTITY_TO_SPACE >= 0) + { + player.setPositionAndUpdate(x, y, z); + + if (player.dimension != worldObj.provider.dimensionId) + { + player.mcServer.getConfigurationManager().transferPlayerToDimension(player, this.worldObj.provider.dimensionId, new SpaceTeleporter(DimensionManager.getWorld(this.worldObj.provider.dimensionId), 0, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))); + } + + this.currentEnergyValue -= WarpDriveConfig.i.WC_ENERGY_PER_ENTITY_TO_SPACE; + } + } + + public boolean prepareToJump() + { + if (controller == null) + return false; + + this.direction = controller.getDirection(); + this.shipFront = controller.getFront(); + this.shipRight = controller.getRight(); + this.shipUp = controller.getUp(); + this.shipBack = controller.getBack(); + this.shipLeft = controller.getLeft(); + this.shipDown = controller.getDown(); + this.distance = Math.min(WarpDriveConfig.i.WC_MAX_JUMP_DISTANCE, controller.getDistance()); + return calculateSpatialShipParameters(); + } + + public boolean calculateSpatialShipParameters() + { + int x1 = 0, x2 = 0, z1 = 0, z2 = 0; + + if (Math.abs(dx) > 0) + { + if (dx == 1) + { + x1 = xCoord - shipBack; + x2 = xCoord + shipFront; + z1 = zCoord - shipLeft; + z2 = zCoord + shipRight; + } + else + { + x1 = xCoord - shipFront; + x2 = xCoord + shipBack; + z1 = zCoord - shipRight; + z2 = zCoord + shipLeft; + } + } + else if (Math.abs(dz) > 0) + { + if (dz == 1) + { + z1 = zCoord - shipBack; + z2 = zCoord + shipFront; + x1 = xCoord - shipRight; + x2 = xCoord + shipLeft; + } + else + { + z1 = zCoord - shipFront; + z2 = zCoord + shipBack; + x1 = xCoord - shipLeft; + x2 = xCoord + shipRight; + } + } + + if (x1 < x2) + { + minX = x1; + maxX = x2; + } + else + { + minX = x2; + maxX = x1; + } + + if (z1 < z2) + { + minZ = z1; + maxZ = z2; + } + else + { + minZ = z2; + maxZ = z1; + } + + minY = yCoord - shipDown; + maxY = yCoord + shipUp; + this.shipSize = 0; + + int sizeFrontBack = shipFront + shipBack; + int sizeRightLeft = shipRight + shipLeft; + int sizeUpDown = shipUp + shipDown; + + switch (this.direction) + { + case 0: + case 180: + this.shipSize = sizeFrontBack; + break; + + case 90: + case 270: + this.shipSize = sizeRightLeft; + break; + + case -1: + case -2: + this.shipSize = sizeUpDown; + break; + } + // Ship size is too big + if (sizeFrontBack > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || sizeRightLeft > WarpDriveConfig.i.WC_MAX_SHIP_SIDE || sizeUpDown > WarpDriveConfig.i.WC_MAX_SHIP_SIDE) + { + messageToAllPlayersOnShip("Ship is too long. Cannot jump."); + this.controller.setJumpFlag(false); + return false; + } + + this.shipVolume = getRealShipVolume(); + + if (shipVolume > WarpDriveConfig.i.WC_MAX_SHIP_VOLUME_ON_SURFACE && worldObj.provider.dimensionId == 0) + { + this.controller.setJumpFlag(false); + return false; + } + + return true; + } + + private void doBeaconJump() + { + if (currentEnergyValue - calculateRequiredEnergy(shipVolume, distance) < 0) + { + this.controller.setJumpFlag(false); + return; + } + + // Search beacon coordinates + String freq = controller.getBeaconFrequency(); + int beaconX = 0, beaconZ = 0; + boolean isBeaconFound = false; + EntityPlayerMP player; + + for (int i = 0; i < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); i++) + { + player = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(i); + + // Skip players from other dimensions + if (player.dimension != worldObj.provider.dimensionId) + { + continue; + } + + TileEntity te = worldObj.getBlockTileEntity(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY) - 1, MathHelper.floor_double(player.posZ)); + + if (te != null && (te instanceof TileEntityProtocol)) + { + if (((TileEntityProtocol)te).getBeaconFrequency().equals(freq)) + { + beaconX = te.xCoord; + beaconZ = te.zCoord; + isBeaconFound = true; + break; + } + } + } + + // Now make jump to a beacon + if (isBeaconFound) + { + // Consume all energy + currentEnergyValue -= calculateRequiredEnergy(shipVolume, distance); + EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, 1, 0, dx, dz, this); + jump.maxX = maxX; + jump.minX = minX; + jump.maxZ = maxZ; + jump.minZ = minZ; + jump.maxY = maxY; + jump.minY = minY; + jump.shipFront = shipFront; + jump.shipBack = shipBack; + jump.shipLeft = shipLeft; + jump.shipRight = shipRight; + jump.shipUp = shipUp; + jump.shipDown = shipDown; + jump.shipLength = this.shipSize; + jump.xCoord = xCoord; + jump.yCoord = yCoord; + jump.zCoord = zCoord; + jump.isCoordJump = true; // is jump to a beacon + jump.destX = beaconX; + jump.destY = yCoord; + jump.destZ = beaconZ; + jump.on = true; + worldObj.spawnEntityInWorld(jump); + coreState = ""; + } + } + + private boolean isShipInJumpgate(JumpGate jg) + { + AxisAlignedBB aabb = jg.getGateAABB(); + int numBlocks = 0; + + if (aabb.isVecInside(worldObj.getWorldVec3Pool().getVecFromPool(maxX - minX, maxY - minY, maxZ - minZ))) + { + return true; + } + + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + for (int y = minY; y <= maxY; y++) + { + if (!worldObj.isAirBlock(x, y, z)) + { + if (aabb.minX <= x && aabb.maxX >= x && aabb.minY <= y && aabb.maxY >= y && aabb.minZ <= z && aabb.maxZ >= z) + { + numBlocks++; + } + } + } + } + } + + if (numBlocks == 0) + { + return false; + } + + // At least 80% of ship must be inside jumpgate + if (shipVolume / numBlocks > 0.8F) + { + return true; + } + + return false; + } + + private boolean isFreePlaceForShip(int destX, int destY, int destZ) + { + int newX, newY, newZ; + + if (destY + shipUp > 255 || destY - shipDown < 5) + { + return false; + } + + int moveX = destX - xCoord; + int moveY = destY - yCoord; + int moveZ = destZ - zCoord; + + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + for (int y = minY; y <= maxY; y++) + { + if (!worldObj.isAirBlock(x, y, z)) + { + newX = moveX + x; + newY = moveY + y; + newZ = moveZ + z; + + if (!worldObj.isAirBlock(newX, newY, newZ)) + { + return false; + } + } + } + } + } + + return true; + } + + private void doGateJump() + { + if (currentEnergyValue - calculateRequiredEnergy(shipVolume, distance) < 0) + { + this.controller.setJumpFlag(false); + return; + } + + // Search beacon coordinates + String gateName = controller.getTargetJumpgateName(); + JumpGate jg = WarpDrive.instance.jumpGates.findGateByName(gateName); + int gateX, gateY, gateZ; + int destX = 0, destY = 0, destZ = 0; + boolean isGateFound = (jg != null); + + // Now make jump to a beacon + if (isGateFound) + { + gateX = jg.xCoord; + gateY = jg.yCoord; + gateZ = jg.zCoord; + destX = gateX; + destY = gateY; + destZ = gateZ; + JumpGate nearestGate = WarpDrive.instance.jumpGates.findNearestGate(xCoord, yCoord, zCoord); + + if (!isShipInJumpgate(nearestGate)) + { + messageToAllPlayersOnShip("[GATE] Ship is not inside the jumpgate. Jump rejected. Nearest jumpgate: " + nearestGate.toNiceString()); + this.controller.setJumpFlag(false); + return; + } + + // If gate is blocked by obstacle + if (!isFreePlaceForShip(gateX, gateY, gateZ)) + { + // Randomize destination coordinates and check for collision with obstacles around jumpgate + // Try to find good place for ship + int numTries = 10; // num tries to check for collision + boolean placeFound = false; + + for (; numTries > 0; numTries--) + { + // randomize dest. coordinates around jumpgate + destX = gateX + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(100)); + destZ = gateZ + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(100)); + destY = gateY + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(50)); + + // check for collision + if (isFreePlaceForShip(destX, destY, destZ)) + { + placeFound = true; + break; + } + } + + if (!placeFound) + { + messageToAllPlayersOnShip("[GATE] Destination gate is blocked by obstacles. Cannot jump."); + this.controller.setJumpFlag(false); + return; + } + + } + + // Consume energy + currentEnergyValue -= calculateRequiredEnergy(shipVolume, distance); + EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, 1, 0, dx, dz, this); + jump.maxX = maxX; + jump.minX = minX; + jump.maxZ = maxZ; + jump.minZ = minZ; + jump.maxY = maxY; + jump.minY = minY; + jump.shipFront = shipFront; + jump.shipBack = shipBack; + jump.shipLeft = shipLeft; + jump.shipRight = shipRight; + jump.shipUp = shipUp; + jump.shipDown = shipDown; + jump.shipLength = this.shipSize; + jump.xCoord = xCoord; + jump.yCoord = yCoord; + jump.zCoord = zCoord; + jump.isCoordJump = true; + jump.destX = destX; + jump.destY = destY; + jump.destZ = destZ; + jump.on = true; + worldObj.spawnEntityInWorld(jump); + coreState = ""; + } + else + { + messageToAllPlayersOnShip("[GATE] Destination jumpgate is not found. Check jumpgate name."); + this.controller.setJumpFlag(false); + } + } + + public void doJump() + { + if (currentMode == this.MODE_GATE_JUMP) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + doGateJump(); + return; + } + + if (currentMode == this.MODE_BEACON_JUMP) + { + doBeaconJump(); + return; + } + + // Check ship size for hyperspace jump + if (currentMode == this.MODE_HYPERSPACE) + { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { + return; + } + + JumpGate t = WarpDrive.instance.jumpGates.findNearestGate(xCoord, yCoord, zCoord); + + if (t != null && !isShipInJumpgate(t)) + { + if (shipVolume < WarpDriveConfig.i.WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE) + { + this.messageToAllPlayersOnShip("Ship is too small (" + shipVolume + "/" + WarpDriveConfig.i.WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE + "). Insufficient ship mass to open hyperspace portal."); + this.controller.setJumpFlag(false); + return; + } + } + } + + if (currentMode == this.MODE_BASIC_JUMP || currentMode == this.MODE_LONG_JUMP || currentMode == MODE_HYPERSPACE) + { + if (this.currentEnergyValue - calculateRequiredEnergy(shipVolume, distance) < 0) + { + messageToAllPlayersOnShip("Insufficient energy to jump!"); + this.controller.setJumpFlag(false); + return; + } + + this.currentEnergyValue -= calculateRequiredEnergy(shipVolume, distance); + if (this.currentMode == this.MODE_BASIC_JUMP) + { + distance += shipSize; + } + + if (currentMode == this.MODE_LONG_JUMP && (direction != -1 && direction != -2)) + { + if (worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID) + { + distance *= 100; + } + } + + EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, distance, direction, dx, dz, this); + jump.maxX = maxX; + jump.minX = minX; + jump.maxZ = maxZ; + jump.minZ = minZ; + jump.maxY = maxY; + jump.minY = minY; + jump.shipFront = shipFront; + jump.shipBack = shipBack; + jump.shipLeft = shipLeft; + jump.shipRight = shipRight; + jump.shipUp = shipUp; + jump.shipDown = shipDown; + jump.shipLength = this.shipSize; + jump.isCoordJump = false; + + if (currentMode == MODE_HYPERSPACE) + { + jump.toHyperSpace = (worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID); + jump.fromHyperSpace = (worldObj.provider.dimensionId == WarpDrive.instance.hyperSpaceDimID); + } + + jump.xCoord = xCoord; + jump.yCoord = yCoord; + jump.zCoord = zCoord; + jump.mode = currentMode; + jump.on = true; + worldObj.spawnEntityInWorld(jump); + coreState = ""; + } + } + + public void teleportPlayersToSpace() + { + if (currentMode == MODE_TELEPORT && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) + { + if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) + { + AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(xCoord - 5, yCoord - 5, zCoord - 5, xCoord + 5, yCoord + 5, zCoord + 5); + List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); + + for (Object o : list) + { + if (currentEnergyValue - WarpDriveConfig.i.WC_ENERGY_PER_ENTITY_TO_SPACE < 0) + { + return; + } + + currentEnergyValue -= WarpDriveConfig.i.WC_ENERGY_PER_ENTITY_TO_SPACE; + Entity entity = (Entity) o; + int x = MathHelper.floor_double(entity.posX); + int z = MathHelper.floor_double(entity.posZ); + //int y = MathHelper.floor_double(entity.posY); + final int WOOL_BLOCK_ID = 35; + int newY; + + for (newY = 254; newY > 0; newY--) + { + if (DimensionManager.getWorld(WarpDrive.instance.spaceDimID).getBlockId(x, newY, z) == WOOL_BLOCK_ID) + { + break; + } + } + + if (newY <= 0) + { + newY = 254; + } + + if (entity instanceof EntityPlayerMP) + { + ((EntityPlayerMP) entity).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) entity), WarpDrive.instance.spaceDimID, new SpaceTeleporter(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), 0, x, 256, z)); + WorldServer space = DimensionManager.getWorld(WarpDrive.instance.spaceDimID); + + if (space.isAirBlock(x, newY, z)) + { + space.setBlock(x, newY, z, Block.stone.blockID, 0, 2); + space.setBlock(x + 1, newY, z, Block.stone.blockID, 0, 2); + space.setBlock(x - 1, newY, z, Block.stone.blockID, 0, 2); + space.setBlock(x, newY, z + 1, Block.stone.blockID, 0, 2); + space.setBlock(x, newY, z - 1, Block.stone.blockID, 0, 2); + space.setBlock(x + 1, newY, z + 1, Block.stone.blockID, 0, 2); + space.setBlock(x - 1, newY, z - 1, Block.stone.blockID, 0, 2); + space.setBlock(x + 1, newY, z - 1, Block.stone.blockID, 0, 2); + space.setBlock(x - 1, newY, z + 1, Block.stone.blockID, 0, 2); + } + + ((EntityPlayerMP) entity).setPositionAndUpdate(x, newY + 2, z); + } + } + } + } + } + + public void summonPlayersByChestCode() + { + if (worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord) == null) + { + return; + } + + TileEntityChest chest = (TileEntityChest)worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); + EntityPlayerMP player; + + for (int i = 0; i < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); i++) + { + player = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(i); + + if (checkPlayerInventory(chest, player)) + { + summonPlayer(player, xCoord, yCoord + 2, zCoord); + } + } + } + + public boolean checkPlayerInventory(TileEntityChest chest, EntityPlayerMP player) + { + Boolean result = false; + final int MIN_KEY_LENGTH = 5; + int keyLength = 0; + + for (int index = 0; index < chest.getSizeInventory(); index++) + { + ItemStack chestItem = chest.getStackInSlot(index); + ItemStack playerItem = player.inventory.getStackInSlot(9 + index); + + if (chestItem == null || playerItem == null) + { + continue; + } + + if (chestItem.itemID != playerItem.itemID || chestItem.getItemDamage() != playerItem.getItemDamage() || chestItem.stackSize != playerItem.stackSize) + { + return false; + } + else + { + result = true; + } + + keyLength++; + } + + if (keyLength < MIN_KEY_LENGTH) + { + return false; + } + + return result; + } + + public Boolean isChestSummonMode() + { + TileEntity te = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); + + if (te != null) + { + return (te instanceof TileEntityChest); + } + + return false; + } + + public boolean testBB(AxisAlignedBB axisalignedbb, int x, int y, int z) + { + return axisalignedbb.minX <= (double) x && axisalignedbb.maxX >= (double) x && axisalignedbb.minY <= (double) y && axisalignedbb.maxY >= (double) y && axisalignedbb.minZ <= (double) z && axisalignedbb.maxZ >= (double) z; + } + + public String getCoreState() + { + return "[WarpCore] " + this.coreState; + } + + public int calculateRequiredEnergy(int shipVolume, int jumpDistance) + { + int energyValue = 0; + + switch (currentMode) + { + case MODE_BASIC_JUMP: + energyValue = (WarpDriveConfig.i.WC_ENERGY_PER_BLOCK_MODE1 * shipVolume) + (WarpDriveConfig.i.WC_ENERGY_PER_DISTANCE_MODE1 * jumpDistance); + break; + + case MODE_LONG_JUMP: + energyValue = (WarpDriveConfig.i.WC_ENERGY_PER_BLOCK_MODE2 * shipVolume) + (WarpDriveConfig.i.WC_ENERGY_PER_DISTANCE_MODE2 * jumpDistance); + break; + + case MODE_HYPERSPACE: + energyValue = WarpDriveConfig.i.WC_MAX_ENERGY_VALUE / 10; // 10% of maximum + break; + + case MODE_BEACON_JUMP: + energyValue = WarpDriveConfig.i.WC_MAX_ENERGY_VALUE / 2; // half of maximum + break; + + case MODE_GATE_JUMP: + energyValue = 2 * shipVolume; + } + + return energyValue; + } + + public int getRealShipVolume() + { + int shipVol = 0; + + for (int x = minX; x <= maxX; x++) + { + for (int z = minZ; z <= maxZ; z++) + { + for (int y = minY; y <= maxY; y++) + { + int blockID = worldObj.getBlockId(x, y, z); + + if (blockID != 0) + { + shipVol++; + } + } + } + } + + return shipVol; + } + + public TileEntity findControllerBlock() + { + TileEntity result; + result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); + + if (result != null && result instanceof TileEntityProtocol) + { + dx = 1; + dz = 0; + return result; + } + + result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); + + if (result != null && result instanceof TileEntityProtocol) + { + dx = -1; + dz = 0; + return result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); + + if (result != null && result instanceof TileEntityProtocol) + { + dx = 0; + dz = 1; + return result; + } + + result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); + + if (result != null && result instanceof TileEntityProtocol) + { + dx = 0; + dz = -1; + return result; + } + + return null; + } + + @Override + public double demandedEnergyUnits() + { + if (this.controller != null && controller.getMode() == 0) + { + return 0; + } + + return (WarpDriveConfig.i.WC_MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) + { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (currentEnergyValue > WarpDriveConfig.i.WC_MAX_ENERGY_VALUE) + { + leftover = (currentEnergyValue - WarpDriveConfig.i.WC_MAX_ENERGY_VALUE); + currentEnergyValue = WarpDriveConfig.i.WC_MAX_ENERGY_VALUE; + } + + return leftover; + } + + @Override + public int getMaxSafeInput() + { + return Integer.MAX_VALUE; + } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) + { + return true; + } + + @Override + public void readFromNBT(NBTTagCompound tag) + { + super.readFromNBT(tag); + currentEnergyValue = tag.getInteger("energy"); + coreFrequency = tag.getString("corefrequency"); + isolationBlocksCount = tag.getInteger("isolation"); + WarpDrive.instance.registry.updateInRegistry(this); + } + + @Override + public void writeToNBT(NBTTagCompound tag) + { + super.writeToNBT(tag); + tag.setInteger("energy", currentEnergyValue); + tag.setString("corefrequency", coreFrequency); + tag.setInteger("isolation", this.isolationBlocksCount); + } + + @Override + public void onChunkUnload() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + WarpDrive.instance.registry.removeFromRegistry(this); + } + + @Override + public void validate() + { + super.validate(); + WarpDrive.instance.registry.updateInRegistry(this); + if (!addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } + } + + @Override + public void invalidate() + { + if (addedToEnergyNet) + { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } +} diff --git a/src/cr0s/WarpDrive/machines/TileEntityShipScanner.java b/src/cr0s/WarpDrive/TileEntityShipScanner.java similarity index 71% rename from src/cr0s/WarpDrive/machines/TileEntityShipScanner.java rename to src/cr0s/WarpDrive/TileEntityShipScanner.java index 1ae6f273..0884c61f 100644 --- a/src/cr0s/WarpDrive/machines/TileEntityShipScanner.java +++ b/src/cr0s/WarpDrive/TileEntityShipScanner.java @@ -1,29 +1,50 @@ -package cr0s.WarpDrive.machines; +package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.*; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import dan200.computer.api.IComputerAccess; +import dan200.computer.api.ILuaContext; +import dan200.computer.api.IPeripheral; +import net.minecraftforge.common.ForgeDirection; +import ic2.api.energy.event.EnergyTileLoadEvent; +import ic2.api.energy.event.EnergyTileUnloadEvent; +import ic2.api.energy.tile.IEnergySink; import ic2.api.energy.tile.IEnergyTile; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.packet.Packet250CustomPayload; +import net.minecraft.server.MinecraftServer; +import net.minecraft.src.ModLoader; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; +import net.minecraftforge.common.MinecraftForge; + +public class TileEntityShipScanner extends TileEntity implements IEnergySink, + IPeripheral { + public boolean addedToEnergyNet = false; -public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { private final int MAX_ENERGY_VALUE = 500000000; // 500kk eU + private int currentEnergyValue = 0; private int state = 0; // 0 - inactive, 1 - active private int firstUncoveredY; @@ -38,17 +59,16 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { int warpCoreSearchTicks = 0; // Config //TODO add to WarpDriveConfig - private final String SCHEMATICS_DIR = "warpDrive_schematics"; + private final String SCHEMATICS_DIR = "schematics"; private final int EU_PER_BLOCK_SCAN = 100; // eU per block of ship volume (including air) private final int EU_PER_BLOCK_DEPLOY = 5000; - private final int BLOCK_TO_DEPLOY_PER_TICK = 3000; + private final int BLOCK_TO_DEPLOY_PER_TICK = 1000; private final int ALLOWED_DEPLOY_RADIUS = 50; // blocks - private String[] methodsArray = { - "scan", // 0 - "fileName", // 1 - "energy", // 2 - "deploy" // 3 deployShipFromSchematic(file, offsetX, offsetY, offsetZ) + private String[] methodsArray = { "scan", // 0 + "fileName", // 1 + "energy", // 2 + "deploy" // 3 deploy(file, offsetX, offsetY, offsetZ) }; private String schematicFileName; @@ -66,7 +86,10 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; - super.updateEntity(); + if (!addedToEnergyNet && !this.tileEntityInvalid) { + MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); + addedToEnergyNet = true; + } if (++warpCoreSearchTicks > 20) { core = searchWarpCore(); @@ -81,9 +104,9 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { if (state == 0) { // inactive if (++laserTicks > 20) { - WarpDrive.sendLaserPacket(worldObj, - new Vector3(this).translate(0.5D), new Vector3(core.xCoord, core.yCoord, core.zCoord).translate(0.5D), - 0f, 1f, 0f, 40, 0, 100); + sendLaserPacket(new Vector3(this).add(0.5), new Vector3( + core.xCoord, core.yCoord, core.zCoord).add(0.5), 0f, + 1f, 0f, 40, 0, 100); laserTicks = 0; } } else if (state == 1 && !isDeploying) { // active: scanning @@ -129,7 +152,7 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { g = 0f; } - WarpDrive.sendLaserPacket(worldObj, new Vector3(this).translate(0.5D), new Vector3(x, core.maxY, randomZ).translate(0.5D), r, g, b, 15, 0, 100); + sendLaserPacket(new Vector3(this).add(0.5), new Vector3(x, core.maxY, randomZ).add(0.5), r, g, b, 15, 0, 100); } } @@ -165,17 +188,17 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { if (block != null && block.blockID != Block.bedrock.blockID && - !WarpDriveConfig.scannerIgnoreBlocks.contains(block.blockID) && - worldObj.isAirBlock(newX + block.x, newY + block.y, newZ + block.z)) { + !WarpDriveConfig.i.scannerIgnoreBlocks.contains(block.blockID) && + worldObj.isAirBlock(newX + block.x, newY + block.y, newZ + block.z)) + { moveBlockSimple(block); if (worldObj.rand.nextInt(100) <= 10) { worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F); - WarpDrive.sendLaserPacket(worldObj, - new Vector3(this).translate(0.5D), - new Vector3(newX + block.x, newY + block.y, newZ + block.z).translate(0.5D), - 0f, 1f, 0f, 15, 0, 100); + sendLaserPacket(new Vector3(this).add(0.5), new Vector3( + newX + block.x, newY + block.y, newZ + block.z).add(0.5), 0f, + 1f, 0f, 15, 0, 100); } } @@ -190,17 +213,20 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { } private TileEntityReactor searchWarpCore() { - StringBuilder reason = new StringBuilder(); TileEntityReactor result = null; // Search for warp cores above for (int newY = yCoord + 1; newY <= 255; newY++) { - if (worldObj.getBlockId(xCoord, newY, zCoord) == WarpDriveConfig.coreID) { // found warp core above + if (worldObj.getBlockId(xCoord, newY, zCoord) == WarpDriveConfig.i.coreID) { // found + // warp + // core + // above result = (TileEntityReactor) worldObj.getBlockTileEntity( xCoord, newY, zCoord); if (result != null) { - if (!result.validateShipSpatialParameters(reason)) { // If we can't refresh ship's spatial parameters + if (!result.prepareToJump()) { // If we can't refresh ship's + // spatial parameters result = null; } } @@ -212,6 +238,89 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { return result; } + public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, + float b, int age, int energy, int radius) { + Side side = FMLCommonHandler.instance().getEffectiveSide(); + + if (side == Side.SERVER) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(8); + DataOutputStream outputStream = new DataOutputStream(bos); + + try { + // Write source vector + outputStream.writeDouble(source.x); + outputStream.writeDouble(source.y); + outputStream.writeDouble(source.z); + // Write target vector + outputStream.writeDouble(dest.x); + outputStream.writeDouble(dest.y); + outputStream.writeDouble(dest.z); + // Write r, g, b of laser + outputStream.writeFloat(r); + outputStream.writeFloat(g); + outputStream.writeFloat(b); + // Write age + outputStream.writeByte(age); + // Write energy value + outputStream.writeInt(energy); + } catch (Exception ex) { + ex.printStackTrace(); + } + + Packet250CustomPayload packet = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer + .getServer() + .getConfigurationManager() + .sendToAllNear(source.intX(), source.intY(), source.intZ(), + radius, worldObj.provider.dimensionId, packet); + ByteArrayOutputStream bos2 = new ByteArrayOutputStream(8); + DataOutputStream outputStream2 = new DataOutputStream(bos2); + + try { + // Write source vector + outputStream2.writeDouble(source.x); + outputStream2.writeDouble(source.y); + outputStream2.writeDouble(source.z); + // Write target vector + outputStream2.writeDouble(dest.x); + outputStream2.writeDouble(dest.y); + outputStream2.writeDouble(dest.z); + // Write r, g, b of laser + outputStream2.writeFloat(r); + outputStream2.writeFloat(g); + outputStream2.writeFloat(b); + // Write age + outputStream2.writeByte(age); + // Write energy value + outputStream2.writeInt(energy); + } catch (Exception ex) { + ex.printStackTrace(); + } + + Packet250CustomPayload packet2 = new Packet250CustomPayload(); + packet.channel = "WarpDriveBeam"; + packet.data = bos.toByteArray(); + packet.length = bos.size(); + MinecraftServer + .getServer() + .getConfigurationManager() + .sendToAllNear(dest.intX(), dest.intY(), dest.intZ(), + radius, worldObj.provider.dimensionId, packet); + } + } + + // Checks energy level + private boolean isEnoughEnergyForScan() { + if (core != null) { + return core.shipVolume * EU_PER_BLOCK_SCAN <= currentEnergyValue; + } + + return false; + } + private void saveShipToSchematic(String fileName) { NBTTagCompound schematic = new NBTTagCompound("Schematic"); @@ -231,7 +340,7 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { int size = width * length * height; // Consume energy - consumeEnergy(size * EU_PER_BLOCK_SCAN, false); + currentEnergyValue = Math.abs(currentEnergyValue - size * EU_PER_BLOCK_SCAN); byte localBlocks[] = new byte[size]; @@ -247,10 +356,9 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { for (int z = 0; z < length; z++) { int blockID = worldObj.getBlockId(core.minX + x, core.minY + y, core.minZ + z); - // Do not scan air, bedrock and specified forbidden blocks (like ore or Warp-Cores) - if (worldObj.isAirBlock(core.minX + x, core.minY + y, core.minZ + z) || blockID == Block.bedrock.blockID /*|| WarpDriveConfig.scannerIgnoreBlocks.contains(blockID)/**/) { + // Do not scan air and bedrock + if ( worldObj.isAirBlock(core.minX + x, core.minY + y, core.minZ + z) || blockID == Block.bedrock.blockID ) blockID = 0; - } int blockMetadata = (byte) worldObj.getBlockMetadata(core.minX + x, core.minY + y, core.minZ + z); localBlocks[x + (y * length + z) * width] = (byte) blockID; @@ -307,8 +415,7 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { writeNBTToFile(fileName, schematic); } - private static void writeNBTToFile(String fileName, NBTTagCompound nbttagcompound) { - System.out.println("[ShipScanner] Filename: " + fileName); + private void writeNBTToFile(String fileName, NBTTagCompound nbttagcompound) { try { File file = new File(fileName); @@ -318,7 +425,8 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { FileOutputStream fileoutputstream = new FileOutputStream(file); - CompressedStreamTools.writeCompressed(nbttagcompound, fileoutputstream); + CompressedStreamTools.writeCompressed(nbttagcompound, + fileoutputstream); fileoutputstream.close(); } catch (Exception exception) { @@ -340,11 +448,10 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { .append(System.currentTimeMillis()).append(".schematic")) .toString(); } while (new File(SCHEMATICS_DIR + "/" + schematicFileName).exists()); - saveShipToSchematic(SCHEMATICS_DIR + "/" + schematicFileName); } - private static NBTTagCompound readNBTFromFile(String fileName) { + private NBTTagCompound readNBTFromFile(String fileName) { try { File file = new File(fileName); if (!file.exists()) { @@ -352,7 +459,8 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { } FileInputStream fileinputstream = new FileInputStream(file); - NBTTagCompound nbttagcompound = CompressedStreamTools.readCompressed(fileinputstream); + NBTTagCompound nbttagcompound = CompressedStreamTools + .readCompressed(fileinputstream); fileinputstream.close(); @@ -364,6 +472,10 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { return null; } + private boolean isEnoughEnergyForDeploy(int size) { + return MAX_ENERGY_VALUE <= currentEnergyValue; + } + // Returns result array for CC interface: [ code, "message" ] private Object[] deployShip(String fileName, int offsetX, int offsetY, int offsetZ) { NBTTagCompound schematic = readNBTFromFile(SCHEMATICS_DIR + "/" + fileName); @@ -392,10 +504,8 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { // Check energy level - if (!consumeEnergy(size * EU_PER_BLOCK_DEPLOY, false)) { - String msg = "[ShipScanner] Not enough energy! Need at least " + (size * EU_PER_BLOCK_DEPLOY) + " EU"; - WarpDrive.debugPrint(msg); - return new Object[] { 1, msg }; + if (!isEnoughEnergyForDeploy(size)) { + return new Object[] { 1, "Not enough energy! Need at least " + MAX_ENERGY_VALUE + " Eu" }; } // Check specified area for occupation by blocks @@ -414,6 +524,9 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { return new Object[] { 2, "Deploying area occupied with " + occupiedBlockCount + " blocks. Can't deploy ship." }; } + // Consume energy + currentEnergyValue = 0; + // Set deployment vars this.blocksToDeploy = new JumpBlock[size]; this.isDeploying = true; @@ -469,27 +582,11 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { jb.blockMeta = (localMetadata[x + (y * length + z) * width]) & 0xFF; jb.blockNBT = tileEntities[x + (y * length + z) * width]; - - - + jb.x = x; jb.y = y; jb.z = z; - - if (jb.blockID != 0 && Block.blocksList[jb.blockID] != null) { - System.out.print("[ShipScanner] Saving block: " + Block.blocksList[jb.blockID].getUnlocalizedName() + ", TE: "); - if (tileEntities[x + (y * length + z) * width] == null) { - System.out.println("null!"); - } else { - System.out.println(tileEntities[x + (y * length + z) * width].getString("id")); - } - - blocksToDeploy[x + (y * length + z) * width] = jb; - } else { - jb = null; - - blocksToDeploy[x + (y * length + z) * width] = jb; - } + blocksToDeploy[x + (y * length + z) * width] = jb; } } } @@ -501,11 +598,13 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); + this.currentEnergyValue = tag.getInteger("energy"); } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); + tag.setInteger("energy", this.getCurrentEnergyValue()); } // CC @@ -529,15 +628,15 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { if (this.state == 1) return new Object[] { false, 0, "Already scanning" }; - if (core == null) { - return new Object[] { false, 1, "Warp-Core not found" }; - } else if (consumeEnergy(core.shipVolume * EU_PER_BLOCK_SCAN, true)) { + if (core != null && isEnoughEnergyForScan()) { scanShip(); + } else if (core == null) { + return new Object[] { false, 1, "Warp-Core not found" }; } else { return new Object[] { false, 2, "Not enough energy!" }; } - break; + break; case 1: // getSchematicFileName() if (state != 0 && !schematicFileName.isEmpty()) return new Object[] { "Scanning in process. Please wait." }; @@ -545,7 +644,7 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { return new Object[] { schematicFileName }; case 2: // getEnergyLevel() - return new Object[] { getEnergyStored() }; + return new Object[] { currentEnergyValue }; case 3: // deployShipFromSchematic(schematicFileName, offsetX, offsetY, offsetZ) if (arguments.length == 4) { @@ -554,20 +653,24 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { int y = ((Double)arguments[2]).intValue(); int z = ((Double)arguments[3]).intValue(); - if (!new File(SCHEMATICS_DIR + "/" + fileName).exists()) { + if (!new File(SCHEMATICS_DIR + "/" + fileName).exists()) return new Object[] { 0, "Specified .schematic file not found!" }; - } else + else { return deployShip(fileName, x, y, z); } - } else { + } else return new Object[] { 4, ".schematic file name not specified or invalid arguments count!" }; - } } return null; } + @Override + public boolean canAttachToSide(int side) { + return true; + } + @Override public void attach(IComputerAccess computer) { } @@ -577,10 +680,65 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { } // IEnergySink methods implementation + @Override + public double demandedEnergyUnits() { + return (MAX_ENERGY_VALUE - currentEnergyValue); + } + + @Override + public double injectEnergyUnits(ForgeDirection directionFrom, double amount) { + double leftover = 0; + currentEnergyValue += Math.round(amount); + + if (getCurrentEnergyValue() > MAX_ENERGY_VALUE) { + leftover = (getCurrentEnergyValue() - MAX_ENERGY_VALUE); + currentEnergyValue = MAX_ENERGY_VALUE; + } + + return leftover; + } + @Override public int getMaxSafeInput() { return Integer.MAX_VALUE; } + + @Override + public boolean acceptsEnergyFrom(TileEntity emitter, + ForgeDirection direction) { + return true; + } + + /** + * @return the currentEnergyValue + */ + public int getCurrentEnergyValue() { + return currentEnergyValue; + } + + public int collectAllEnergy() { + int energy = currentEnergyValue; + currentEnergyValue = 0; + return energy; + } + + @Override + public void onChunkUnload() { + if (addedToEnergyNet) { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + } + + @Override + public void invalidate() { + if (addedToEnergyNet) { + MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); + addedToEnergyNet = false; + } + + super.invalidate(); + } public boolean moveBlockSimple(JumpBlock shipBlock) { @@ -751,10 +909,5 @@ public class TileEntityShipScanner extends WarpEnergyTE implements IPeripheral { return true; } } - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; } } diff --git a/src/cr0s/WarpDrive/TransitionPlane.java b/src/cr0s/WarpDrive/TransitionPlane.java deleted file mode 100644 index d0cd97ad..00000000 --- a/src/cr0s/WarpDrive/TransitionPlane.java +++ /dev/null @@ -1,104 +0,0 @@ -package cr0s.WarpDrive; - - -import cr0s.WarpDrive.Vector3; -import net.minecraft.nbt.NBTTagCompound; - -/** - * TransitionPlane Class is used for defining transition planes between dimensions. - * - * @author LemADEC - */ - -public class TransitionPlane implements Cloneable -{ - public int dimensionId; - public int dimensionCenterX, dimensionCenterZ; - public int borderSizeX, borderSizeZ; - public int spaceCenterX, spaceCenterZ; - - public TransitionPlane() { - this(0, 0, 0, 5000, 5000, 0, 0); - } - - public TransitionPlane(int parDimensionId, int parDimensionCenterX, int parDimensionCenterZ, int parBorderSizeX, int parBorderSizeZ, int parSpaceCenterX, int parSpaceCenterZ) { - this.dimensionId = parDimensionId; - this.spaceCenterX = parSpaceCenterX; - this.spaceCenterZ = parSpaceCenterZ; - this.dimensionCenterX = parDimensionCenterX; - this.dimensionCenterZ = parDimensionCenterZ; - this.borderSizeX = parBorderSizeX; - this.borderSizeZ = parBorderSizeZ; - } - - public TransitionPlane(NBTTagCompound nbt) { - readFromNBT(nbt); - } - - /** - * Makes a new copy of this Vector. Prevents variable referencing problems. - */ - @Override - public TransitionPlane clone() { - return new TransitionPlane(dimensionId, dimensionCenterX, dimensionCenterZ, borderSizeX, borderSizeZ, spaceCenterX, spaceCenterZ); - } - - /** - * Compute transition. - * - * @param world - * @return - */ - - public boolean isValidToSpace(Vector3 currentPosition) { - return ( (Math.abs(currentPosition.x - dimensionCenterX) <= borderSizeX) && (Math.abs(currentPosition.z - dimensionCenterZ) <= borderSizeZ) ); - } - - public boolean isValidFromSpace(Vector3 currentPosition) { - return ( (Math.abs(currentPosition.x - spaceCenterX) <= borderSizeX) && (Math.abs(currentPosition.z - spaceCenterX) <= borderSizeZ) ); - } - - public void readFromNBT(NBTTagCompound tag) { - this.dimensionId = tag.getInteger("dimensionId"); - this.dimensionCenterX = tag.getInteger("dimensionCenterX"); - this.dimensionCenterZ = tag.getInteger("dimensionCenterZ"); - this.borderSizeX = tag.getInteger("borderSizeX"); - this.borderSizeZ = tag.getInteger("borderSizeZ"); - this.spaceCenterX = tag.getInteger("spaceCenterX"); - this.spaceCenterZ = tag.getInteger("spaceCenterZ"); - } - - public void writeToNBT(NBTTagCompound tag) { - tag.setInteger("dimensionId", dimensionId); - tag.setInteger("dimensionCenterX", dimensionCenterX); - tag.setInteger("dimensionCenterZ", dimensionCenterZ); - tag.setInteger("borderSizeX", borderSizeX); - tag.setInteger("borderSizeZ", borderSizeZ); - tag.setInteger("spaceCenterX", spaceCenterX); - tag.setInteger("spaceCenterZ", spaceCenterZ); - } - - - @Override - public int hashCode() { - return ("dim:" + dimensionId + "(" + dimensionCenterX + "," + dimensionCenterZ + ")_Border(" + borderSizeX + "," + borderSizeZ + ")_Space(" + spaceCenterX + "," + spaceCenterZ).hashCode(); - } - - @Override - public boolean equals(Object o) { - if (o instanceof TransitionPlane) { - TransitionPlane transitionPlane = (TransitionPlane) o; - return this.dimensionId == transitionPlane.dimensionId - && this.dimensionCenterX == transitionPlane.dimensionCenterX && this.dimensionCenterZ == transitionPlane.dimensionCenterZ - && this.borderSizeX == transitionPlane.borderSizeX && this.borderSizeZ == transitionPlane.borderSizeZ - && this.spaceCenterX == transitionPlane.spaceCenterX && this.spaceCenterZ == transitionPlane.spaceCenterZ; - } - - return false; - } - - @Override - public String toString() { - return "TransitionPlane [dim:" + dimensionId + "(" + dimensionCenterX + ", " + dimensionCenterZ + ") Border(" + borderSizeX + ", " + borderSizeZ + ") Space(" + spaceCenterX + ", " + spaceCenterZ + ")]"; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/Vector3.java b/src/cr0s/WarpDrive/Vector3.java index 51bbaed5..20ba8d48 100644 --- a/src/cr0s/WarpDrive/Vector3.java +++ b/src/cr0s/WarpDrive/Vector3.java @@ -203,14 +203,6 @@ public class Vector3 implements Cloneable return Math.sqrt(var2 * var2 + var4 * var4 + var6 * var6); } - public double distanceTo_square(Vector3 vector3) - { - double var2 = vector3.x - this.x; - double var4 = vector3.y - this.y; - double var6 = vector3.z - this.z; - return var2 * var2 + var4 * var4 + var6 * var6; - } - /** * Multiplies the vector by negative one. */ @@ -493,26 +485,26 @@ public class Vector3 implements Cloneable return translateMatrix(getRotationMatrix(angle, axis), this.clone()); } - public double[] getRotationMatrix(float angle_deg) + public double[] getRotationMatrix(float angle) { double[] matrix = new double[16]; Vector3 axis = this.clone().normalize(); - double xn = axis.x; - double yn = axis.y; - double zn = axis.z; - float angle_rad = angle_deg * 0.0174532925F; - float cos = (float) Math.cos(angle_rad); + double x = axis.x; + double y = axis.y; + double z = axis.z; + angle *= 0.0174532925D; + float cos = (float) Math.cos(angle); float ocos = 1.0F - cos; - float sin = (float) Math.sin(angle_rad); - matrix[0] = (xn * xn * ocos + cos); - matrix[1] = (yn * xn * ocos + zn * sin); - matrix[2] = (xn * zn * ocos - yn * sin); - matrix[4] = (xn * yn * ocos - zn * sin); - matrix[5] = (yn * yn * ocos + cos); - matrix[6] = (yn * zn * ocos + xn * sin); - matrix[8] = (xn * zn * ocos + yn * sin); - matrix[9] = (yn * zn * ocos - xn * sin); - matrix[10] = (zn * zn * ocos + cos); + float sin = (float) Math.sin(angle); + matrix[0] = (x * x * ocos + cos); + matrix[1] = (y * x * ocos + z * sin); + matrix[2] = (x * z * ocos - y * sin); + matrix[4] = (x * y * ocos - z * sin); + matrix[5] = (y * y * ocos + cos); + matrix[6] = (y * z * ocos + x * sin); + matrix[8] = (x * z * ocos + y * sin); + matrix[9] = (y * z * ocos - x * sin); + matrix[10] = (z * z * ocos + cos); matrix[15] = 1.0F; return matrix; } @@ -541,12 +533,12 @@ public class Vector3 implements Cloneable double yawRadians = Math.toRadians(yaw); double pitchRadians = Math.toRadians(pitch); double rollRadians = Math.toRadians(roll); - double oldX = this.x; - double oldY = this.y; - double oldZ = this.z; - this.x = oldX * Math.cos(yawRadians) * Math.cos(pitchRadians) + oldZ * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) - Math.sin(yawRadians) * Math.cos(rollRadians)) + oldY * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) + Math.sin(yawRadians) * Math.sin(rollRadians)); - this.z = oldX * Math.sin(yawRadians) * Math.cos(pitchRadians) + oldZ * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) + Math.cos(yawRadians) * Math.cos(rollRadians)) + oldY * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) - Math.cos(yawRadians) * Math.sin(rollRadians)); - this.y = -oldX * Math.sin(pitchRadians) + oldZ * Math.cos(pitchRadians) * Math.sin(rollRadians) + oldY * Math.cos(pitchRadians) * Math.cos(rollRadians); + double x = this.x; + double y = this.y; + double z = this.z; + this.x = x * Math.cos(yawRadians) * Math.cos(pitchRadians) + z * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) - Math.sin(yawRadians) * Math.cos(rollRadians)) + y * (Math.cos(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) + Math.sin(yawRadians) * Math.sin(rollRadians)); + this.z = x * Math.sin(yawRadians) * Math.cos(pitchRadians) + z * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.sin(rollRadians) + Math.cos(yawRadians) * Math.cos(rollRadians)) + y * (Math.sin(yawRadians) * Math.sin(pitchRadians) * Math.cos(rollRadians) - Math.cos(yawRadians) * Math.sin(rollRadians)); + this.y = -x * Math.sin(pitchRadians) + z * Math.cos(pitchRadians) * Math.sin(rollRadians) + y * Math.cos(pitchRadians) * Math.cos(rollRadians); } /** @@ -560,13 +552,13 @@ public class Vector3 implements Cloneable public void rotate(double yaw) { double yawRadians = Math.toRadians(yaw); - double oldX = this.x; - double oldZ = this.z; + double x = this.x; + double z = this.z; if (yaw != 0) { - this.x = oldX * Math.cos(yawRadians) - oldZ * Math.sin(yawRadians); - this.z = oldX * Math.sin(yawRadians) + oldZ * Math.cos(yawRadians); + this.x = x * Math.cos(yawRadians) - z * Math.sin(yawRadians); + this.z = x * Math.sin(yawRadians) + z * Math.cos(yawRadians); } } @@ -577,11 +569,11 @@ public class Vector3 implements Cloneable * @param rotationYaw * @param rotationPitch */ - public static Vector3 getDeltaPositionFromRotation(float rotationYaw1, float rotationPitch1) + public static Vector3 getDeltaPositionFromRotation(float rotationYaw, float rotationPitch) { - float rotationYaw2 = rotationYaw1 + 90; - float rotationPitch2 = -rotationPitch1; - return new Vector3(Math.cos(Math.toRadians(rotationYaw2)), Math.sin(Math.toRadians(rotationPitch2)), Math.sin(Math.toRadians(rotationYaw2))); + rotationYaw = rotationYaw + 90; + rotationPitch = -rotationPitch; + return new Vector3(Math.cos(Math.toRadians(rotationYaw)), Math.sin(Math.toRadians(rotationPitch)), Math.sin(Math.toRadians(rotationYaw))); } /** diff --git a/src/cr0s/WarpDrive/WarpCoresRegistry.java b/src/cr0s/WarpDrive/WarpCoresRegistry.java index 966f1860..f4649451 100644 --- a/src/cr0s/WarpDrive/WarpCoresRegistry.java +++ b/src/cr0s/WarpDrive/WarpCoresRegistry.java @@ -1,29 +1,33 @@ package cr0s.WarpDrive; import java.util.ArrayList; -import java.util.LinkedList; -import cr0s.WarpDrive.machines.TileEntityReactor; +import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; /** Registry of active Warp Cores in world * @author Cr0s */ -public class WarpCoresRegistry { - private LinkedList registry; +public class WarpCoresRegistry +{ + private ArrayList registry; - public WarpCoresRegistry() { - registry = new LinkedList(); + public WarpCoresRegistry() + { + registry = new ArrayList(); } - public int searchCoreInRegistry(TileEntityReactor core) { + public int searchCoreInRegistry(TileEntityReactor core) + { int res = -1; - for (int i = 0; i < registry.size(); i++) { + for (int i = 0; i < registry.size(); i++) + { TileEntityReactor c = registry.get(i); - if (c.xCoord == core.xCoord && c.yCoord == core.yCoord && c.zCoord == core.zCoord) { + if (c.xCoord == core.xCoord && c.yCoord == core.yCoord && c.zCoord == core.zCoord) + { return i; } } @@ -31,41 +35,49 @@ public class WarpCoresRegistry { return res; } - public boolean isCoreInRegistry(TileEntityReactor core) { + public boolean isCoreInRegistry(TileEntityReactor core) + { return (searchCoreInRegistry(core) != -1); } - public void updateInRegistry(TileEntityReactor core) { + public void updateInRegistry(TileEntityReactor core) + { int idx = searchCoreInRegistry(core); // update - if (idx != -1) { + if (idx != -1) + { registry.set(idx, core); - } else { + } + else + { registry.add(core); } } - public void removeFromRegistry(TileEntityReactor core) { - int idx = searchCoreInRegistry(core); + public void removeFromRegistry(TileEntityReactor core) + { + int idx; - if (idx != -1) { + if ((idx = searchCoreInRegistry(core)) != -1) + { registry.remove(idx); } } - public ArrayList searchWarpCoresInRadius(int x, int y, int z, int radius) { - ArrayList res = new ArrayList(registry.size()); + public ArrayList searchWarpCoresInRadius(int x, int y, int z, int radius) + { + ArrayList res = new ArrayList(); - printRegistry(); - for (TileEntityReactor c : registry) { + for (TileEntityReactor c : registry) + { double d3 = c.xCoord - x; double d4 = c.yCoord - y; double d5 = c.zCoord - z; double distance = MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5); -// if (distance <= radius && !(c.controller == null || c.controller.getMode() == 0) && !isCoreHidden(c)) { - if (distance <= radius && !isCoreHidden(c)) { + if (distance <= radius && !(c.controller == null || c.controller.getMode() == 0) && !isCoreHidden(c)) + { res.add(c); } } @@ -73,22 +85,26 @@ public class WarpCoresRegistry { return res; } - public void printRegistry() { + public void printRegistry() + { System.out.println("WarpCores registry:"); removeDeadCores(); - for (TileEntityReactor c : registry) { - System.out.println("- " + c.coreFrequency + " (" + c.xCoord + ", " + c.yCoord + ", " + c.zCoord + ")"); + for (TileEntityReactor c : registry) + { + System.out.println(c.coreFrequency + " (" + c.xCoord + "; " + c.yCoord + "; " + c.zCoord + ")"); } } final int LOWER_HIDE_POINT = 18; - private boolean isCoreHidden(TileEntityReactor core) { - if (core.isolationBlocksCount > 5) { + private boolean isCoreHidden(TileEntityReactor core) + { + if (core.isolationBlocksCount > 5) + { int randomNumber = core.worldObj.rand.nextInt(150); - if (randomNumber < LOWER_HIDE_POINT + core.isolationBlocksCount) { - WarpDrive.debugPrint("" + this + " Core '" + core.coreFrequency + "' is hidden"); + if (randomNumber < LOWER_HIDE_POINT + core.isolationBlocksCount) + { return true; } } @@ -96,27 +112,28 @@ public class WarpCoresRegistry { return false; } - public boolean isWarpCoreIntersectsWithOthers(TileEntityReactor core) { - StringBuilder reason = new StringBuilder(); + public boolean isWarpCoreIntersectsWithOthers(TileEntityReactor core) + { AxisAlignedBB aabb1, aabb2; removeDeadCores(); - - core.validateShipSpatialParameters(reason); - aabb1 = AxisAlignedBB.getBoundingBox(core.minX, core.minY, core.minZ, core.maxX, core.maxY, core.maxZ); - for (TileEntityReactor c : registry) { + for (TileEntityReactor c : registry) + { // Skip cores in other worlds - if (c.worldObj != core.worldObj) { + if (c.worldObj != core.worldObj) + { continue; } // Skip self - if (c.xCoord == core.xCoord && c.yCoord == core.yCoord && c.zCoord == core.zCoord) { + if (c.xCoord == core.xCoord && c.yCoord == core.yCoord && c.zCoord == core.zCoord) + { continue; } // Skip offline warp cores - if (c.controller == null || c.controller.getMode() == 0 || !c.validateShipSpatialParameters(reason)) { + if (c.controller == null || c.controller.getMode() == 0 || !c.prepareToJump()) + { continue; } @@ -124,12 +141,19 @@ public class WarpCoresRegistry { double d3 = c.xCoord - core.xCoord; double d4 = c.yCoord - core.yCoord; double d5 = c.zCoord - core.zCoord; - double distance2 = d3 * d3 + d4 * d4 + d5 * d5; + double distance = MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5); - if (distance2 <= ((2 * WarpDriveConfig.WC_MAX_SHIP_SIDE) - 1) * ((2 * WarpDriveConfig.WC_MAX_SHIP_SIDE) - 1)) { + if (distance <= (2 * WarpDriveConfig.i.WC_MAX_SHIP_SIDE) - 1) + { + // Check for warpfields intersections + core.prepareToJump(); // calculate spatial parameters + c.prepareToJump(); // Compare warp-fields for intersection + aabb1 = AxisAlignedBB.getBoundingBox(core.minX, core.minY, core.minZ, core.maxX, core.maxY, core.maxZ); aabb2 = AxisAlignedBB.getBoundingBox(c.minX, c.minY, c.minZ, c.maxX, c.maxY, c.maxZ); - if (aabb1.intersectsWith(aabb2)) { + + if (aabb1.intersectsWith(aabb2)) + { return true; } } @@ -138,18 +162,17 @@ public class WarpCoresRegistry { return false; } - public void removeDeadCores() { - LocalProfiler.start("WarpCoresRegistry Removing dead cores"); + public void removeDeadCores() + { + LocalProfiler.start("WCR.removeDeadCores()"); + ArrayList oldRegistry = (ArrayList) registry.clone(); - TileEntityReactor c; - for (int i = registry.size() - 1; i >= 0; i--) { - c = registry.get(i); - if (c == null || c.worldObj == null || c.worldObj.getBlockId(c.xCoord, c.yCoord, c.zCoord) != WarpDriveConfig.coreID || c.worldObj.getBlockTileEntity(c.xCoord, c.yCoord, c.zCoord) != c || c.worldObj.getBlockTileEntity(c.xCoord, c.yCoord, c.zCoord).isInvalid()) { - WarpDrive.debugPrint("Removing 'dead' core at " + ((c != null)? c.xCoord : "?") + ", " + ((c != null)? c.yCoord : "?") + ", " + ((c != null)? c.zCoord : "?")); - registry.remove(i); - } - } + for (TileEntityReactor c : registry) + if (c == null || c.worldObj == null || c.worldObj.getBlockId(c.xCoord, c.yCoord, c.zCoord) != WarpDriveConfig.i.coreID || c.worldObj.getBlockTileEntity(c.xCoord, c.yCoord, c.zCoord) != c || c.worldObj.getBlockTileEntity(c.xCoord, c.yCoord, c.zCoord).isInvalid()) + oldRegistry.remove(c); + // Update old registry to new witout dead cores + this.registry = (ArrayList) oldRegistry.clone(); LocalProfiler.stop(); } diff --git a/src/cr0s/WarpDrive/WarpDrive.java b/src/cr0s/WarpDrive/WarpDrive.java index c3592c94..2628c648 100644 --- a/src/cr0s/WarpDrive/WarpDrive.java +++ b/src/cr0s/WarpDrive/WarpDrive.java @@ -3,7 +3,11 @@ package cr0s.WarpDrive; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; +import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; +import cpw.mods.fml.common.Mod.PostInit; +import cpw.mods.fml.common.Mod.PreInit; +import cpw.mods.fml.common.Mod.ServerStarting; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; @@ -11,16 +15,8 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.item.*; -import cr0s.WarpDrive.machines.*; -import dan200.computercraft.api.ComputerCraftAPI; +import cpw.mods.fml.common.registry.LanguageRegistry; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import net.minecraft.block.Block; @@ -29,8 +25,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.network.packet.Packet250CustomPayload; -import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.Configuration; @@ -38,22 +32,19 @@ import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.LoadingCallback; import net.minecraftforge.common.ForgeChunkManager.Ticket; -import net.minecraftforge.common.ForgeChunkManager.Type; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.oredict.ShapedOreRecipe; -import net.minecraftforge.oredict.ShapelessOreRecipe; -@Mod(modid = "WarpDrive", name = "WarpDrive", version = "1.2.5.0", - dependencies = "required-after:IC2; required-after:ComputerCraft; after:CCTurtle; after:gregtech_addon; required-after:AppliedEnergistics; after:AdvancedSolarPanel; after:AtomicScience; after:ICBM|Explosion; after:MFFS; after:GraviSuite; after:UndergroundBiomes; after:NetherOres") +@Mod(modid = "WarpDrive", name = "WarpDrive", version = "1.2.0_ZLO", dependencies="required-after:IC2; after:required-AppliedEnergistics; after:extracells; required-after:ComputerCraft; after:CCTurtle; after:gregtech_addon; after:AdvancedSolarPanel; after:AtomicScience; after:ICBM|Explosion; after:MFFS; after:GraviSuite") @NetworkMod(clientSideRequired = true, serverSideRequired = true, channels = { - "WarpDriveBeam", - "WarpDriveFreq", + "WarpDriveBeam", + "WarpDriveFreq", "WarpDriveLaserT", "WarpDriveCloaks" }, packetHandler = PacketHandler.class) /** * @author Cr0s */ -public class WarpDrive implements LoadingCallback { +public class WarpDrive implements LoadingCallback +{ // World limits public final static int WORLD_LIMIT_BLOCKS = 100000; @@ -68,43 +59,33 @@ public class WarpDrive implements LoadingCallback { public static Block monitorBlock; public static Block boosterBlock; public static Block miningLaserBlock; - public static Block laserTreeFarmBlock; public static Block liftBlock; public static Block scannerBlock; public static Block cloakBlock; public static Block cloakCoilBlock; - public static Block transporterBlock; - public static Block reactorMonitorBlock; - public static Block powerReactorBlock; - public static Block powerLaserBlock; - + public static Block airBlock; public static Block gasBlock; public static Block iridiumBlock; - public static Block transportBeaconBlock; - - public static Item reactorLaserFocusItem; - public static ItemWarpComponent componentItem; - + public static BiomeGenBase spaceBiome; public World space; + private int spaceProviderID; + public int spaceDimID; public SpaceWorldGenerator spaceWorldGenerator; public HyperSpaceWorldGenerator hyperSpaceWorldGenerator; - public World hyperSpace; - - // Client settings - public static float normalFOV = 70.0F; - public static float normalSensitivity = 1.0F; - public static CreativeTabs warpdriveTab = new WarpDriveCreativeTab("Warpdrive","Warpdrive").setBackgroundImageName("warpdrive:creativeTab"); - + public World hyperSpace; + private int hyperSpaceProviderID; + public int hyperSpaceDimID; + @Instance("WarpDrive") public static WarpDrive instance; - @SidedProxy(clientSide = "cr0s.WarpDrive.client.ClientProxy", serverSide = "cr0s.WarpDrive.CommonProxy") + @SidedProxy(clientSide = "cr0s.WarpDrive.ClientProxy", serverSide = "cr0s.WarpDrive.CommonProxy") public static CommonProxy proxy; - public WarpCoresRegistry warpCores; + public WarpCoresRegistry registry; public JumpGatesRegistry jumpGates; public CloakManager cloaks; @@ -112,708 +93,249 @@ public class WarpDrive implements LoadingCallback { public CamRegistry cams; public boolean isOverlayEnabled = false; public int overlayType = 0; - public String debugMessage = ""; - - public static WarpDrivePeripheralHandler peripheralHandler = new WarpDrivePeripheralHandler(); - - public static String defHelpStr = "help(\"functionName\"): returns help for the function specified"; - public static String defEnergyStr = "energy(): returns currently contained energy, max contained energy"; - - private LinkedList warpTickets = new LinkedList(); @EventHandler - public void preInit(FMLPreInitializationEvent event) { - WarpDriveConfig.preInit(new Configuration(event.getSuggestedConfigurationFile())); + //@PreInit + public void preInit(FMLPreInitializationEvent event) + { + WarpDriveConfig.Init(new Configuration(event.getSuggestedConfigurationFile())); - if (FMLCommonHandler.instance().getSide().isClient()) { - Minecraft mc = Minecraft.getMinecraft(); - - // System.out.println("[WarpDrive] Registering sounds event handler..."); + if (FMLCommonHandler.instance().getSide().isClient()) + { + System.out.println("[WarpDrive] Registering sounds event handler..."); MinecraftForge.EVENT_BUS.register(new SoundHandler()); - - normalFOV = mc.gameSettings.fovSetting; - normalSensitivity = mc.gameSettings.mouseSensitivity; - System.out.println("[WarpDrive] FOV is " + normalFOV + " Sensitivity is " + normalSensitivity); - } - } - - @SideOnly(Side.CLIENT) - @EventHandler - public void init(FMLInitializationEvent event) { -// FIXME FMLInterModComms.sendMessage("Waila", "register", "cr0s.WarpDrive.client.WailaHandler.callbackRegister"); - } - - public static void debugPrint(String out) { - if (WarpDriveConfig.debugMode == false) { - return; - } - if (WarpDriveConfig.debugMode) { - System.out.println(out); } } - @EventHandler - public void load(FMLInitializationEvent event) { - WarpDriveConfig.load(); - + @Init + public void load(FMLInitializationEvent event) + { + WarpDriveConfig.i.Init2(); + // WARP CORE + this.warpCore = new BlockReactor(WarpDriveConfig.i.coreID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Warp Core"); + LanguageRegistry.addName(warpCore, "Warp Core"); + GameRegistry.registerBlock(warpCore, "warpCore"); + GameRegistry.registerTileEntity(TileEntityReactor.class, "warpCore"); // CORE CONTROLLER - protocolBlock = new BlockProtocol(WarpDriveConfig.controllerID,0, Material.rock); - + this.protocolBlock = new BlockProtocol(WarpDriveConfig.i.controllerID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Warp Controller"); + LanguageRegistry.addName(protocolBlock, "Warp Controller"); GameRegistry.registerBlock(protocolBlock, "protocolBlock"); GameRegistry.registerTileEntity(TileEntityProtocol.class, "protocolBlock"); - - // WARP CORE - warpCore = new BlockReactor(WarpDriveConfig.coreID, 0, Material.rock); - - GameRegistry.registerBlock(warpCore, "warpCore"); - GameRegistry.registerTileEntity(TileEntityReactor.class, "warpCore"); - // WARP RADAR - radarBlock = new BlockRadar(WarpDriveConfig.radarID, 0, Material.rock); - + this.radarBlock = new BlockRadar(WarpDriveConfig.i.radarID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("W-Radar"); + LanguageRegistry.addName(radarBlock, "W-Radar"); GameRegistry.registerBlock(radarBlock, "radarBlock"); GameRegistry.registerTileEntity(TileEntityRadar.class, "radarBlock"); - // WARP ISOLATION - isolationBlock = new BlockWarpIsolation( WarpDriveConfig.isolationID, 0, Material.rock); - + this.isolationBlock = new BlockWarpIsolation(WarpDriveConfig.i.isolationID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Warp-Field Isolation Block"); + LanguageRegistry.addName(isolationBlock, "Warp-Field Isolation Block"); GameRegistry.registerBlock(isolationBlock, "isolationBlock"); - // AIR GENERATOR - airgenBlock = new BlockAirGenerator(WarpDriveConfig.airgenID, 0,Material.rock); - + this.airgenBlock = new BlockAirGenerator(WarpDriveConfig.i.airgenID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Air Generator"); + LanguageRegistry.addName(airgenBlock, "Air Generator"); GameRegistry.registerBlock(airgenBlock, "airgenBlock"); GameRegistry.registerTileEntity(TileEntityAirGenerator.class, "airgenBlock"); - - // AIR BLOCK - airBlock = (new BlockAir(WarpDriveConfig.airID)); - + this.airBlock = (new BlockAir(WarpDriveConfig.i.airID)).setHardness(0.0F).setUnlocalizedName("Air block"); + LanguageRegistry.addName(airBlock, "Air block"); GameRegistry.registerBlock(airBlock, "airBlock"); - // GAS BLOCK - gasBlock = (new BlockGas(WarpDriveConfig.gasID)); - + this.gasBlock = (new BlockGas(WarpDriveConfig.i.gasID)).setHardness(0.0F).setUnlocalizedName("Gas block"); + LanguageRegistry.addName(gasBlock, "Gas block"); GameRegistry.registerBlock(gasBlock, "gasBlock"); - // LASER EMITTER - laserBlock = new BlockLaser(WarpDriveConfig.laserID, 0,Material.rock); - + this.laserBlock = new BlockLaser(WarpDriveConfig.i.laserID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Laser Emitter"); + LanguageRegistry.addName(laserBlock, "Laser Emitter"); GameRegistry.registerBlock(laserBlock, "laserBlock"); GameRegistry.registerTileEntity(TileEntityLaser.class, "laserBlock"); - // LASER EMITTER WITH CAMERA - laserCamBlock = new BlockLaserCam(WarpDriveConfig.laserCamID, 0, Material.rock); - + this.laserCamBlock = new BlockLaserCam(WarpDriveConfig.i.laserCamID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Laser Emitter + Camera"); + LanguageRegistry.addName(laserCamBlock, "Laser Emitter + Camera"); GameRegistry.registerBlock(laserCamBlock, "laserCamBlock"); - // CAMERA - cameraBlock = new BlockCamera(WarpDriveConfig.camID, 0,Material.rock); - + this.cameraBlock = new BlockCamera(WarpDriveConfig.i.camID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Camera block"); + LanguageRegistry.addName(cameraBlock, "Camera"); GameRegistry.registerBlock(cameraBlock, "cameraBlock"); GameRegistry.registerTileEntity(TileEntityCamera.class, "cameraBlock"); - // MONITOR - monitorBlock = new BlockMonitor(WarpDriveConfig.monitorID); - + this.monitorBlock = new BlockMonitor(WarpDriveConfig.i.monitorID) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Monitor"); + LanguageRegistry.addName(monitorBlock, "Monitor"); GameRegistry.registerBlock(monitorBlock, "monitorBlock"); GameRegistry.registerTileEntity(TileEntityMonitor.class, "monitorBlock"); - - // MINING LASER - miningLaserBlock = new BlockMiningLaser(WarpDriveConfig.miningLaserID, 0, Material.rock); - + this.miningLaserBlock = new BlockMiningLaser(WarpDriveConfig.i.miningLaserID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Mining Laser"); + LanguageRegistry.addName(miningLaserBlock, "Mining Laser"); GameRegistry.registerBlock(miningLaserBlock, "miningLaserBlock"); GameRegistry.registerTileEntity(TileEntityMiningLaser.class, "miningLaserBlock"); - - // LASER TREE FARM - laserTreeFarmBlock = new BlockLaserTreeFarm(WarpDriveConfig.laserTreeFarmID, 0, Material.rock); - - GameRegistry.registerBlock(laserTreeFarmBlock, "laserTreeFarmBlock"); - GameRegistry.registerTileEntity(TileEntityLaserTreeFarm.class,"laserTreeFarmBlock"); - // PARTICLE BOOSTER - boosterBlock = new BlockParticleBooster(WarpDriveConfig.particleBoosterID, 0, Material.rock); - + this.boosterBlock = new BlockParticleBooster(WarpDriveConfig.i.particleBoosterID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Particle Booster"); + LanguageRegistry.addName(boosterBlock, "Particle Booster"); GameRegistry.registerBlock(boosterBlock, "boosterBlock"); GameRegistry.registerTileEntity(TileEntityParticleBooster.class, "boosterBlock"); - // LASER LIFT - liftBlock = new BlockLift(WarpDriveConfig.liftID, 0, Material.rock); - + this.liftBlock = new BlockLift(WarpDriveConfig.i.liftID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Laser lift"); + LanguageRegistry.addName(liftBlock, "Laser lift"); GameRegistry.registerBlock(liftBlock, "liftBlock"); GameRegistry.registerTileEntity(TileEntityLift.class, "liftBlock"); - // IRIDIUM BLOCK - iridiumBlock = new BlockIridium(WarpDriveConfig.iridiumBlockID); - + this.iridiumBlock = new BlockIridium(WarpDriveConfig.i.iridiumID) + .setHardness(0.8F).setResistance(150 * 4).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Block of Iridium"); + LanguageRegistry.addName(iridiumBlock, "Block of Iridium"); GameRegistry.registerBlock(iridiumBlock, "iridiumBlock"); - - // SHIP SCANNER - scannerBlock = new BlockShipScanner(WarpDriveConfig.shipScannerID, 0, Material.rock); - - GameRegistry.registerBlock(scannerBlock, "scannerBlock"); - GameRegistry.registerTileEntity(TileEntityShipScanner.class, "scannerBlock"); - // CLOAKING DEVICE CORE - cloakBlock = new BlockCloakingDeviceCore(WarpDriveConfig.cloakCoreID, 0, Material.rock); - - GameRegistry.registerBlock(cloakBlock, "cloakBlock"); - GameRegistry.registerTileEntity(TileEntityCloakingDeviceCore.class, "cloakBlock"); - - // CLOAKING DEVICE COIL - cloakCoilBlock = new BlockCloakingCoil(WarpDriveConfig.cloakCoilID, 0, Material.rock); - - GameRegistry.registerBlock(cloakCoilBlock, "cloakCoilBlock"); - - // TRANSPORTER - transporterBlock = new BlockTransporter(WarpDriveConfig.transporterID,Material.rock); - - GameRegistry.registerBlock(transporterBlock, "transporter"); - GameRegistry.registerTileEntity(TileEntityTransporter.class,"transporter"); - - reactorMonitorBlock = new BlockLaserReactorMonitor(WarpDriveConfig.reactorMonitorID, Material.rock); - - GameRegistry.registerBlock(reactorMonitorBlock, "reactorMonitor"); - GameRegistry.registerTileEntity(TileEntityLaserReactorMonitor.class,"reactorMonitor"); - - // TRANSPORT BEACON - /*transportBeaconBlock = new BlockTransportBeacon(WarpDriveConfig.transportBeaconID) - .setHardness(0.5F) - .setStepSound(Block.soundMetalFootstep) - .setCreativeTab(CreativeTabs.tabRedstone) - .setUnlocalizedName("warpdrive.blocks.TransporterBeacon"); - - GameRegistry.registerBlock(transportBeaconBlock, "transportBeacon");*/ - - // POWER STUFF - powerReactorBlock = new BlockPowerReactor(WarpDriveConfig.powerReactorID); - GameRegistry.registerBlock(powerReactorBlock,"powerReactor"); - GameRegistry.registerTileEntity(TileEntityPowerReactor.class, "powerReactor"); - powerLaserBlock = new BlockPowerLaser(WarpDriveConfig.powerLaserID); - GameRegistry.registerBlock(powerLaserBlock, "powerLaser"); - GameRegistry.registerTileEntity(TileEntityPowerLaser.class, "powerLaser"); - - // REACTOR LASER FOCUS - reactorLaserFocusItem = new ItemReactorLaserFocus(WarpDriveConfig.reactorLaserFocusID); - GameRegistry.registerItem(reactorLaserFocusItem, "reactorLaserFocus"); - - // COMPONENT ITEMS - componentItem = new ItemWarpComponent(WarpDriveConfig.componentID); - GameRegistry.registerItem(componentItem, "component"); - - + // SHIP SCANNER + this.scannerBlock = new BlockShipScanner(WarpDriveConfig.i.shipScannerID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Ship Scanner"); + + LanguageRegistry.addName(scannerBlock, "Ship Scanner"); + GameRegistry.registerBlock(scannerBlock, "scannerBlock"); + GameRegistry.registerTileEntity(TileEntityShipScanner.class, "scannerBlock"); + + // CLOAKING DEVICE CORE + this.cloakBlock = new BlockCloakingDeviceCore(WarpDriveConfig.i.cloakCoreID, 0, Material.rock) + .setHardness(0.5F).setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone).setUnlocalizedName("Cloaking Device Core"); + + LanguageRegistry.addName(cloakBlock, "Cloaking Device Core"); + GameRegistry.registerBlock(cloakBlock, "cloakBlock"); + GameRegistry.registerTileEntity(TileEntityCloakingDeviceCore.class, "cloakBlock"); + + // CLOAKING DEVICE COIL + this.cloakCoilBlock = new BlockCloakingCoil(WarpDriveConfig.i.cloakCoilID, 0, Material.rock) + .setHardness(0.5F) + .setStepSound(Block.soundMetalFootstep) + .setCreativeTab(CreativeTabs.tabRedstone) + .setUnlocalizedName("Cloaking Device Coil"); + + LanguageRegistry.addName(cloakCoilBlock, "Cloaking Device Coil"); + GameRegistry.registerBlock(cloakCoilBlock, "cloakCoilBlock"); + proxy.registerEntities(); ForgeChunkManager.setForcedChunkLoadingCallback(instance, instance); - spaceWorldGenerator = new SpaceWorldGenerator(); GameRegistry.registerWorldGenerator(spaceWorldGenerator); hyperSpaceWorldGenerator = new HyperSpaceWorldGenerator(); GameRegistry.registerWorldGenerator(hyperSpaceWorldGenerator); - registerSpaceDimension(); registerHyperSpaceDimension(); - MinecraftForge.EVENT_BUS.register(new SpaceEventHandler()); - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - warpdriveTab.setBackgroundImageName("items.png"); + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) + { MinecraftForge.EVENT_BUS.register(new CameraOverlay(Minecraft.getMinecraft())); } - - ComputerCraftAPI.registerPeripheralProvider(peripheralHandler); } - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - space = DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID); - hyperSpace = DimensionManager.getWorld(WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID); - - if (WarpDriveConfig.isICLoaded && WarpDriveConfig.recipesIC2) { - initIC2Recipes(); - } - if (WarpDriveConfig.isAppliedEnergisticsLoaded && WarpDriveConfig.isThermalExpansionLoaded) { - initAETERecipes(); - } - if (!WarpDriveConfig.recipesIC2) { - initVanillaRecipes(); - } - - warpCores = new WarpCoresRegistry(); - jumpGates = new JumpGatesRegistry(); - cams = new CamRegistry(); - } - - private static void initVanillaRecipes() { - componentItem.registerRecipes(); - //WarpCore - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(warpCore), false, "ipi", "ici", "idi", - 'i', Item.ingotIron, - 'p', componentItem.getIS(6), - 'c', componentItem.getIS(2), - 'd', Item.diamond)); - - //Controller - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(protocolBlock), false, "ici", "idi", "iii", - 'i', Item.ingotIron, - 'c', componentItem.getIS(5), - 'd', Item.diamond)); - - //Radar - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(radarBlock), false, "ggg", "pdc", "iii", - 'i', Item.ingotIron, - 'c', componentItem.getIS(5), - 'p', componentItem.getIS(6), - 'g', Block.glass, - 'd', Item.diamond)); - - //Isolation Block - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(isolationBlock), false, "igi", "geg", "igi", - 'i', Item.ingotIron, - 'g', Block.glass, - 'e', Item.enderPearl)); - - //Air generator - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(airgenBlock), false, "ibi", "i i", "ipi", - 'i', Item.ingotIron, - 'b', Block.fenceIron, - 'p', componentItem.getIS(6))); - - //Laser - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserBlock), false, "ili", "iri", "ici", - 'i', Item.ingotIron, - 'r', Item.redstone, - 'c', componentItem.getIS(5), - 'l', componentItem.getIS(3), - 'p', componentItem.getIS(6))); - - //Mining laser - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(miningLaserBlock), false, "ici", "iti", "ili", - 'i', Item.ingotIron, - 'r', Item.redstone, - 't', componentItem.getIS(1), - 'c', componentItem.getIS(5), - 'l', componentItem.getIS(3))); - - //Tree farm laser - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserTreeFarmBlock), false, "ili", "sts", "ici", - 'i', Item.ingotIron, - 's', "treeSapling", - 't', componentItem.getIS(1), - 'c', componentItem.getIS(5), - 'l', componentItem.getIS(3))); - - //Laser Lift - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(liftBlock), false, "ipi", "rtr", "ili", - 'i', Item.ingotIron, - 'r', Item.redstone, - 't', componentItem.getIS(1), - 'l', componentItem.getIS(3), - 'p', componentItem.getIS(6))); - - //Transporter - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(transporterBlock), false, "iii", "ptc", "iii", - 'i', Item.ingotIron, - 't', componentItem.getIS(1), - 'c', componentItem.getIS(5), - 'p', componentItem.getIS(6))); - - //Particle Booster - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(boosterBlock), false, "ipi", "rgr", "iii", - 'i', Item.ingotIron, - 'r', Item.redstone, - 'g', Block.glass, - 'p', componentItem.getIS(6))); - - //Camera - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cameraBlock), false, "ngn", "i i", "ici", - 'i', Item.ingotIron, - 'n', Item.goldNugget, - 'g', Block.glass, - 'c', componentItem.getIS(5))); - - //LaserCamera - GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(laserCamBlock), cameraBlock, laserBlock)); - - //Monitor - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(monitorBlock), false, "ggg", "iti", "ici", - 'i', Item.ingotIron, - 't', Block.torchWood, - 'g', Block.glass, - 'c', componentItem.getIS(5))); - - //Cloaking device - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cloakBlock), false, "ipi", "lrl", "ici", - 'i', Item.ingotIron, - 'r', Item.redstone, - 'l', componentItem.getIS(3), - 'c', componentItem.getIS(5), - 'p', componentItem.getIS(6))); - - //Cloaking coil - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(cloakCoilBlock), false, "ini", "rdr", "ini", - 'i', Item.ingotIron, - 'd', Item.diamond, - 'r', Item.redstone, - 'n', Item.goldNugget)); - - //Power Laser - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(powerLaserBlock), false, "iii","ilg","ici", - 'i', Item.ingotIron, - 'g', Block.glass, - 'c', componentItem.getIS(5), - 'l', componentItem.getIS(3))); - - //Power Reactor - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(powerReactorBlock), false, "ipi","gog","ici", - 'i', Item.ingotIron, - 'g', Block.glass, - 'o', componentItem.getIS(4), - 'c', componentItem.getIS(5), - 'p', componentItem.getIS(6))); - } - - private static void initAETERecipes() { - ItemStack redstoneEnergycell = GameRegistry.findItemStack("ThermalExpansion", "cellReinforced", 1); - ItemStack bucketEnder = GameRegistry.findItemStack("ThermalExpansion", "bucketEnder", 1); - ItemStack fluixCrystal = WarpDriveConfig.getAEMaterial("matFluxCrystal"); - ItemStack quantumEntangledSingularity = WarpDriveConfig.getAEMaterial("matQuantumEntangledSingularity"); - ItemStack vibrantQuartzGlass = WarpDriveConfig.getAEBlock("blkQuartzLamp"); - vibrantQuartzGlass.setItemDamage(4); - ItemStack antimatter = GameRegistry.findItemStack("ResonantInduction|Atomic", "antimatter", 1); - antimatter.setItemDamage(1); - ItemStack floppy = GameRegistry.findItemStack("ComputerCraft", "disk", 1); - ItemStack ultimateLappack = new ItemStack(WarpDriveConfig.GS_ultimateLappack, 1, 0); - - // top = advancedCircuit, redstoneEnergycell, advancedCircuit - // middle = fluix crystal, advancedMachine, fluix crystal - // bottom = advancedCircuit, bucket Resonant ender, advancedCircuit - GameRegistry.addRecipe(new ItemStack(warpCore), "crc", "fmf", "cec", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'r', redstoneEnergycell, - 'e', bucketEnder, - 'f', fluixCrystal); - - // top = advancedCircuit, floppy, advancedCircuit - // middle = advancedCircuit, advancedMachine, advancedCircuit - // bottom = advancedCircuit, flux crystal, advancedCircuit - GameRegistry.addRecipe(new ItemStack(protocolBlock), "coc", "cmc", "cfc", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'o', floppy, - 'f', fluixCrystal); - - // top = Iridium plate, Ultimate lappack, Iridium plate - // middle = Singularity, 1 gram antimatter, Singularity - // bottom = Iridium plate, Ultimate lappack, Iridium plate - GameRegistry.addRecipe(new ItemStack(powerReactorBlock), "ili", "sas", "ili", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 's', quantumEntangledSingularity, - 'a', antimatter, - 'l', ultimateLappack); - - // top = Advanced circuit, Advanced alloy, Advanced alloy - // middle = Advanced circuit, Warp drive laser, Vibrant quartz glass - // bottom = Advanced circuit, Certus quartz tank, Advanced alloy - ItemStack isMiningLaserBlock = new ItemStack(miningLaserBlock.blockID, 1, 0); - ItemStack isCertusQuartzTank = new ItemStack(WarpDriveConfig.AEExtra_certusQuartzTank.blockID, 1, 0); - - GameRegistry.addRecipe(new ItemStack(powerLaserBlock), "caa", "czg", "cta", - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 'z', isMiningLaserBlock, - 't', isCertusQuartzTank, - 'g', vibrantQuartzGlass); - } - - private static void initIC2Recipes() { + @PostInit + public void postInit(FMLPostInitializationEvent event) + { + space = DimensionManager.getWorld(spaceDimID); + hyperSpace = DimensionManager.getWorld(hyperSpaceDimID); GameRegistry.addRecipe(new ItemStack(warpCore), "ici", "cmc", "ici", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit")); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit")); GameRegistry.addRecipe(new ItemStack(protocolBlock), "iic", "imi", "cii", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit")); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit")); GameRegistry.addRecipe(new ItemStack(radarBlock), "ifi", "imi", "imi", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'f', WarpDriveConfig.getIC2Item("frequencyTransmitter")); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'f', WarpDriveConfig.i.getIC2Item("frequencyTransmitter")); GameRegistry.addRecipe(new ItemStack(isolationBlock), "iii", "idi", "iii", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'd', Block.blockDiamond); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'd', Block.blockDiamond); GameRegistry.addRecipe(new ItemStack(airgenBlock), "lcl", "lml", "lll", - 'l', Block.leaves, - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit")); - + 'l', Block.leaves, 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit")); GameRegistry.addRecipe(new ItemStack(laserBlock), "sss", "ama", "aaa", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 's', WarpDriveConfig.getIC2Item("advancedCircuit")); - + 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy"), 's', WarpDriveConfig.i.getIC2Item("advancedCircuit")); GameRegistry.addRecipe(new ItemStack(miningLaserBlock), "aaa", "ama", "ccc", - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 'm', WarpDriveConfig.getIC2Item("miner")); - + 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy"), 'm', WarpDriveConfig.i.getIC2Item("miner")); GameRegistry.addRecipe(new ItemStack(boosterBlock), "afc", "ama", "cfa", - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 'f', WarpDriveConfig.getIC2Item("glassFiberCableItem"), - 'm', WarpDriveConfig.getIC2Item("mfeUnit")); - + 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy"), 'f', WarpDriveConfig.i.getIC2Item("glassFiberCableItem"), 'm', WarpDriveConfig.i.getIC2Item("mfeUnit")); GameRegistry.addRecipe(new ItemStack(liftBlock), "aca", "ama", "a#a", - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 'm', WarpDriveConfig.getIC2Item("magnetizer")); - + 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy"), 'm', WarpDriveConfig.i.getIC2Item("magnetizer")); GameRegistry.addRecipe(new ItemStack(iridiumBlock), "iii", "iii", "iii", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate")); - - GameRegistry.addShapelessRecipe( - new ItemStack(WarpDriveConfig.getIC2Item("iridiumPlate").getItem(), 9), - new ItemStack(iridiumBlock)); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate")); + GameRegistry.addShapelessRecipe(new ItemStack(WarpDriveConfig.i.getIC2Item("iridiumPlate").getItem(), 9), new ItemStack(iridiumBlock)); + GameRegistry.addRecipe(new ItemStack(laserCamBlock), "imi", "cec", "#k#", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'e', laserBlock, - 'k', cameraBlock); - + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'e', laserBlock, 'k', cameraBlock); GameRegistry.addRecipe(new ItemStack(cameraBlock), "cgc", "gmg", "cgc", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'g', Block.glass); - - GameRegistry.addRecipe(new ItemStack(monitorBlock), "gcg", "gmg", "ggg", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'g', Block.glass); - + 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'g', Block.glass); + GameRegistry.addRecipe(new ItemStack(monitorBlock), "gcg", "gmg", "ggg", + 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'g', Block.glass); GameRegistry.addRecipe(new ItemStack(scannerBlock), "sgs", "mma", "amm", - 'm', WarpDriveConfig.getIC2Item("advancedMachine"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy"), - 's', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'g', Block.glass); - - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(laserTreeFarmBlock),false,new Object[] { - "cwc", "wmw", "cwc", - 'c', WarpDriveConfig.getIC2Item("electronicCircuit"), - 'w', "logWood", - 'm', miningLaserBlock })); - - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(transporterBlock), false, new Object[] { - "ece", "imi", "iei", - 'e', Item.enderPearl, - 'c', WarpDriveConfig.getIC2Item("electronicCircuit"), - 'i', WarpDriveConfig.getIC2Item("plateiron"), - 'm', WarpDriveConfig.getIC2Item("machine") })); - - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(reactorLaserFocusItem),false,new Object[] { - " p ", "pdp", " p ", - 'p', WarpDriveConfig.getIC2Item("plateiron"), - 'd', "gemDiamond"})); - - GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(reactorMonitorBlock), false, new Object[] { - "pdp", "dmd", "pdp", - 'p', WarpDriveConfig.getIC2Item("plateiron"), - 'd', "gemDiamond", - 'm', WarpDriveConfig.getIC2Item("mfeUnit")})); - + 'm', WarpDriveConfig.i.getIC2Item("advancedMachine"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy"), 's', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'g', Block.glass); GameRegistry.addRecipe(new ItemStack(cloakBlock), "imi", "mcm", "imi", - 'i', iridiumBlock, - 'c', cloakCoilBlock, - 'm', WarpDriveConfig.getIC2Item("advancedMachine")); - + 'i', iridiumBlock, 'c', cloakCoilBlock, 'm', WarpDriveConfig.i.getIC2Item("advancedMachine")); GameRegistry.addRecipe(new ItemStack(cloakCoilBlock), "iai", "aca", "iai", - 'i', WarpDriveConfig.getIC2Item("iridiumPlate"), - 'c', WarpDriveConfig.getIC2Item("advancedCircuit"), - 'a', WarpDriveConfig.getIC2Item("advancedAlloy")); - } + 'i', WarpDriveConfig.i.getIC2Item("iridiumPlate"), 'c', WarpDriveConfig.i.getIC2Item("advancedCircuit"), 'a', WarpDriveConfig.i.getIC2Item("advancedAlloy")); + registry = new WarpCoresRegistry(); - private static void registerSpaceDimension() { - spaceBiome = (new BiomeSpace(24)) - .setColor(0) - .setDisableRain() - .setBiomeName("Space"); - DimensionManager.registerProviderType(WarpDriveConfig.G_SPACE_PROVIDER_ID, SpaceProvider.class, true); - DimensionManager.registerDimension(WarpDriveConfig.G_SPACE_DIMENSION_ID, WarpDriveConfig.G_SPACE_PROVIDER_ID); - } - - private static void registerHyperSpaceDimension() { - DimensionManager.registerProviderType(WarpDriveConfig.G_HYPERSPACE_PROVIDER_ID, HyperSpaceProvider.class, true); - DimensionManager.registerDimension(WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID, WarpDriveConfig.G_HYPERSPACE_PROVIDER_ID); - } - - @EventHandler - public void serverLoad(FMLServerStartingEvent event) { - cloaks = new CloakManager(); - MinecraftForge.EVENT_BUS.register(new CloakChunkWatcher()); - - event.registerServerCommand(new GenerateCommand()); - event.registerServerCommand(new SpaceTpCommand()); - event.registerServerCommand(new InvisibleCommand()); - event.registerServerCommand(new JumpgateCommand()); - event.registerServerCommand(new DebugCommand()); - } - - private ArrayList worldTickets(World worldObj) { - ArrayList worldTicks = new ArrayList(warpTickets.size()); - for(Ticket t: warpTickets) { - if (t.world.equals(worldObj)) { - worldTicks.add(t); - } - } - return worldTicks; - } - - public Ticket registerChunkLoadTE(WarpChunkTE te, boolean refreshLoading) { - World worldObj = te.worldObj; - ArrayList worldTicks = worldTickets(worldObj); - boolean isWorldTicketed = worldTicks.size() != 0; - if(isWorldTicketed) + if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - if(ForgeChunkManager.ticketCountAvailableFor(this, worldObj) > 0) - { - Ticket t = ForgeChunkManager.requestTicket(this, worldObj, Type.NORMAL); - if(t != null) - { - te.giveTicket(t); - if(refreshLoading) - te.refreshLoading(); - return t; - } - else { - WarpDrive.debugPrint("Ticket not granted"); - } - } - else { - WarpDrive.debugPrint("No tickets left!"); - } + jumpGates = new JumpGatesRegistry(); } else { - Ticket t = ForgeChunkManager.requestTicket(this, worldObj, Type.NORMAL); - if(t != null) - { - te.giveTicket(t); - if(refreshLoading) - te.refreshLoading(); - return t; - } - else - { - WarpDrive.debugPrint("Ticket not granted"); - } + cams = new CamRegistry(); } - return null; } - - public Ticket registerChunkLoadTE(WarpChunkTE te) + + private void registerSpaceDimension() { - return registerChunkLoadTE(te,true); + spaceBiome = (new BiomeSpace(23)).setColor(0).setDisableRain().setBiomeName("Space"); + this.spaceProviderID = 14; + DimensionManager.registerProviderType(this.spaceProviderID, SpaceProvider.class, true); + this.spaceDimID = DimensionManager.getNextFreeDimId(); + DimensionManager.registerDimension(this.spaceDimID, this.spaceProviderID); } - - public Ticket getTicket(WarpChunkTE te) + + private void registerHyperSpaceDimension() { - return registerChunkLoadTE(te,false); + this.hyperSpaceProviderID = 15; + DimensionManager.registerProviderType(this.hyperSpaceProviderID, HyperSpaceProvider.class, true); + this.hyperSpaceDimID = DimensionManager.getNextFreeDimId(); + DimensionManager.registerDimension(this.hyperSpaceDimID, this.hyperSpaceProviderID); } - - public void removeTicket(Ticket t) + + @ServerStarting + public void serverLoad(FMLServerStartingEvent event) { - for(Ticket ticket:warpTickets) - if(t.equals(ticket)) - warpTickets.remove(ticket); + cloaks = new CloakManager(); + MinecraftForge.EVENT_BUS.register(new CloakChunkWatcher()); + event.registerServerCommand(new GenerateCommand()); + event.registerServerCommand(new SpaceTpCommand()); + event.registerServerCommand(new InvisibleCommand()); } @Override public void ticketsLoaded(List tickets, World world) { for (Ticket ticket : tickets) + { ForgeChunkManager.releaseTicket(ticket); + } } - - - public static void sendLaserPacket(World worldObj, Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) { - Side side = FMLCommonHandler.instance().getEffectiveSide(); - if (side == Side.SERVER) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(8); - DataOutputStream outputStream = new DataOutputStream(bos); - - try { - // Write source vector - outputStream.writeDouble(source.x); - outputStream.writeDouble(source.y); - outputStream.writeDouble(source.z); - // Write target vector - outputStream.writeDouble(dest.x); - outputStream.writeDouble(dest.y); - outputStream.writeDouble(dest.z); - // Write r, g, b of laser - outputStream.writeFloat(r); - outputStream.writeFloat(g); - outputStream.writeFloat(b); - // Write age - outputStream.writeByte(age); - // Write energy value - outputStream.writeInt(energy); - } catch (Exception ex) { - ex.printStackTrace(); - } - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = "WarpDriveBeam"; - packet.data = bos.toByteArray(); - packet.length = bos.size(); - if (source.distanceTo_square(dest) < 3600 /* 60 * 60 */) { - MinecraftServer.getServer().getConfigurationManager().sendToAllNear( - (source.intX() + dest.intX()) / 2, (source.intY() + dest.intY()) / 2, (source.intZ() + dest.intZ()) / 2, - radius, worldObj.provider.dimensionId, packet); - return; - } - MinecraftServer.getServer().getConfigurationManager().sendToAllNear( - source.intX(), source.intY(), source.intZ(), - radius, worldObj.provider.dimensionId, packet); - - ByteArrayOutputStream bos2 = new ByteArrayOutputStream(8); - DataOutputStream outputStream2 = new DataOutputStream(bos2); - - try { - // Write source vector - outputStream2.writeDouble(source.x); - outputStream2.writeDouble(source.y); - outputStream2.writeDouble(source.z); - // Write target vector - outputStream2.writeDouble(dest.x); - outputStream2.writeDouble(dest.y); - outputStream2.writeDouble(dest.z); - // Write r, g, b of laser - outputStream2.writeFloat(r); - outputStream2.writeFloat(g); - outputStream2.writeFloat(b); - // Write age - outputStream2.writeByte(age); - // Write energy value - outputStream2.writeInt(energy); - } catch (Exception ex) { - ex.printStackTrace(); - } - - Packet250CustomPayload packet2 = new Packet250CustomPayload(); - packet2.channel = "WarpDriveBeam"; - packet2.data = bos.toByteArray(); - packet2.length = bos.size(); - MinecraftServer.getServer().getConfigurationManager().sendToAllNear( - dest.intX(), dest.intY(), dest.intZ(), - radius, worldObj.provider.dimensionId, packet2); - } - } } \ No newline at end of file diff --git a/src/cr0s/WarpDrive/WarpDriveConfig.java b/src/cr0s/WarpDrive/WarpDriveConfig.java index 12bf13b1..50f7d2fd 100644 --- a/src/cr0s/WarpDrive/WarpDriveConfig.java +++ b/src/cr0s/WarpDrive/WarpDriveConfig.java @@ -1,241 +1,175 @@ package cr0s.WarpDrive; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.HashSet; import java.util.Set; import java.util.Random; - +import java.lang.reflect.*; import cpw.mods.fml.common.Loader; import net.minecraftforge.common.Configuration; -import net.minecraftforge.oredict.OreDictionary; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.world.World; import ic2.api.item.Items; public class WarpDriveConfig { - private static Configuration config; - public static int coreID, controllerID, radarID, isolationID, airID, airgenID, gasID, laserID, miningLaserID, particleBoosterID, liftID, laserCamID, camID, monitorID, iridiumBlockID, shipScannerID, cloakCoreID, cloakCoilID; - public static int laserTreeFarmID, transporterID, transportBeaconID, reactorLaserFocusID, reactorMonitorID, powerReactorID, powerLaserID, componentID; + public static WarpDriveConfig i; + private Configuration config; + public int coreID, controllerID, radarID, isolationID, airID, airgenID, gasID, laserID, miningLaserID, particleBoosterID, liftID, laserCamID, camID, monitorID, iridiumID, shipScannerID, cloakCoreID, cloakCoilID; // - /* - * The variables which store whether or not individual mods are loaded - */ - public static boolean isGregLoaded = false; - public static boolean isAppliedEnergisticsLoaded = false; - public static boolean isAdvSolPanelLoaded = false; - public static boolean isAtomicScienceLoaded = false; - public static boolean isAEExtraLoaded = false; - public static boolean isICBMLoaded = false; - public static boolean isMFFSLoaded = false; - public static boolean isGraviSuiteLoaded = false; - public static boolean isICLoaded = false; - public static boolean isCCLoaded = false; - public static boolean isUndergroundBiomesLoaded = false; - public static boolean isNetherOresLoaded = false; - public static boolean isThermalExpansionLoaded = false; - public static boolean isMetallurgyLoaded = false; - public static boolean isAdvancedRepulsionSystemsLoaded = false; - - /* - * The variables that control which recipes should be loaded - */ - public static boolean recipesIC2 = true; + public boolean isGregLoaded = false, isAELoaded = false, isAEExtraLoaded = false, isAdvSolPanelLoaded = false, isASLoaded = false, isICBMLoaded = false, isMFFSLoaded = false, isGraviSuiteLoaded = false; // - public static int[] IC2_Air; - public static int[] IC2_Empty; - public static int IC2_RubberWood; - public static ItemStack IC2_Resin; - public static Item IC2_fluidCell; - public static int CC_Computer = 0, CC_peripheral = 0, CC_Floppy = 0, CCT_Turtle = 0, CCT_Upgraded = 0, CCT_Advanced = 0; - public static int GT_Ores = 0, GT_Granite = 0, GT_Machine = 0; - public static int ASP = 0; - public static int AS_Turbine = 0, AS_deuteriumCell = 0; - public static int ICBM_Machine = 0, ICBM_Missile = 0, ICBM_Explosive = 0; - public static int GS_ultimateLappack = 0; - public static int UB_igneousStone = 0, UB_igneousCobblestone = 0, UB_metamorphicStone = 0, UB_metamorphicCobblestone = 0, UB_sedimentaryStone = 0; - public static int NetherOres_count; - public static int[] NetherOres_block; - public static int[][] Metallurgy_overworldOresBlock; - public static int[][] Metallurgy_netherOresBlock; - public static int[][] Metallurgy_endOresBlock; - public static ArrayList forceFieldBlocks; - - public static Set SpaceHelmets, Jetpacks, MinerOres, MinerLogs, MinerLeaves, scannerIgnoreBlocks; - private static Class AEBlocks; - private static Class AEMaterials; - private static Class AEItems; - public static ArrayList CommonWorldGenOres; - public static Item AEExtra_fluidDrive; - public static Block AEExtra_certusQuartzTank; - - public static boolean debugMode = false; + public int[] IC2_Air; + public int CC_Computer = 0, CC_peripheral = 0, CCT_Turtle = 0, CCT_Upgraded = 0, CCT_Advanced = 0, GT_Ores = 0, GT_Granite = 0, GT_Machine = 0, ASP = 0, AS_Turbine = 0, ICBM_Machine = 0, ICBM_Missile = 0, ICBM_Explosive = 0, MFFS_Field = 0; + public Set SpaceHelmets, Jetpacks, MinerOres, scannerIgnoreBlocks; + private Class AEBlocks; + private Class AEMaterials; + private Class AEItems; + public Item AEExtraFDI; + public ArrayList CommonWorldGenOres; // Mod config - // General - public static int G_SPACE_PROVIDER_ID = 14; - public static int G_SPACE_DIMENSION_ID = 2; - public static int G_HYPERSPACE_PROVIDER_ID = 15; - public static int G_HYPERSPACE_DIMENSION_ID = 3; - // Warp Core - public static int WC_MAX_ENERGY_VALUE = 100000000; - public static int WC_ENERGY_PER_BLOCK_MODE1 = 10; // eU - public static int WC_ENERGY_PER_DISTANCE_MODE1 = 100; // eU - public static int WC_ENERGY_PER_BLOCK_MODE2 = 1000; // eU - public static int WC_ENERGY_PER_DISTANCE_MODE2 = 1000; // eU - public static int WC_ENERGY_PER_ENTITY_TO_SPACE = 1000000; // eU - public static int WC_MAX_JUMP_DISTANCE = 128; // Maximum jump length value - public static int WC_MAX_SHIP_VOLUME_ON_SURFACE = 3000; // Maximum ship mass to jump on earth - public static int WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE = 1200; // Minimum ship volume value for hyperspace travel - public static int WC_MAX_SHIP_SIDE = 127; - public static int WC_COOLDOWN_INTERVAL_SECONDS = 4; // FIXME update me - public static int WC_COLLISION_TOLERANCE_BLOCKS = 3; - public static int WC_WARMUP_SHORTJUMP_SECONDS = 10; - public static int WC_WARMUP_LONGJUMP_SECONDS = 30; - public static int WC_WARMUP_RANDOM_TICKS = 60; - public static int WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS = 10; - public static int WC_ISOLATION_UPDATE_INTERVAL_SECONDS = 10; - - // Warp Radar - public static int WR_MAX_ENERGY_VALUE = 100000000; // 100kk eU - - // Particle Booster - public static int PB_MAX_ENERGY_VALUE = 100000; - - // Mining Laser - public static int ML_MAX_BOOSTERS_NUMBER = 1; - public static int ML_WARMUP_DELAY_TICKS = 20; - public static int ML_SCAN_DELAY_TICKS = 10; - public static int ML_MINE_DELAY_TICKS = 3; - public static int ML_EU_PER_LAYER_SPACE = 2000; - public static int ML_EU_PER_LAYER_EARTH = 10000; - public static int ML_EU_PER_BLOCK_SPACE = 500; - public static int ML_EU_PER_BLOCK_EARTH = 2500; - public static double ML_EU_MUL_ORESONLY = 4.0; - public static double ML_EU_MUL_SILKTOUCH = 2.5; - public static double ML_EU_MUL_FORTUNE = 2.5; -// public static double ML_MAX_SPEED = 10; -// public static double ML_MIN_SPEED = 0.1; - public static int ML_MAX_RADIUS = 6; + public int WC_MAX_ENERGY_VALUE = 100000000; + public int WC_ENERGY_PER_BLOCK_MODE1 = 10; // eU + public int WC_ENERGY_PER_DISTANCE_MODE1 = 100; // eU + public int WC_ENERGY_PER_BLOCK_MODE2 = 1000; // eU + public int WC_ENERGY_PER_DISTANCE_MODE2 = 1000; // eU + public int WC_ENERGY_PER_ENTITY_TO_SPACE = 1000000; // eU + public int WC_MAX_JUMP_DISTANCE = 128; // Maximum jump length value + public int WC_MAX_SHIP_VOLUME_ON_SURFACE = 15000; // Maximum ship volume to jump on earth + public int WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE = 500; // Minimum ship volume value for hyperspace travel + public int WC_MAX_SHIP_SIDE = 199; //miaximum ship length - 1 + public int WC_COOLDOWN_INTERVAL_SECONDS = 4; + public int WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS = 10; + public int WC_ISOLATION_UPDATE_INTARVAL_SECONDS = 10; - //Tree farm - public static int TF_MAX_SIZE=32; + // Warp Radar + public int WR_MAX_ENERGY_VALUE = 100000000; // 100kk eU - //Transporter - public static int TR_MAX_ENERGY=10000000; - public static boolean TR_RELATIVE_COORDS=false; - public static double TR_EU_PER_METRE=100; - public static double TR_MAX_SCAN_RANGE=4; - public static double TR_MAX_BOOST_MUL=4; + // Particle Booster + public int PB_MAX_ENERGY_VALUE = 100000; + + // Mining Laser + public int ML_MAX_BOOSTERS_NUMBER = 1; + public int ML_SCAN_DELAY = 20 * 5; + public int ML_MINE_DELAY = 10; + public int ML_EU_PER_LAYER_SPACE = 500; + public int ML_EU_PER_LAYER_EARTH = 5000; // Laser Emitter - public static int LE_MAX_BOOSTERS_NUMBER = 10; - public static int LE_MAX_LASER_ENERGY = 4000000; - public static int LE_EMIT_DELAY_TICKS = 20 * 3; - public static int LE_EMIT_SCAN_DELAY_TICKS = 10; - public static double LE_COLLECT_ENERGY_MULTIPLIER = 0.60D; - public static int LE_BEAM_LENGTH_PER_ENERGY_DIVIDER = 5000; - public static int LE_ENTITY_HIT_SET_ON_FIRE_TIME = 100; - public static int LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER = 10000; - public static int LE_ENTITY_HIT_EXPLOSION_LASER_ENERGY = 1000000; - public static int LE_BLOCK_HIT_CONSUME_ENERGY = 70000; - public static int LE_BLOCK_HIT_CONSUME_ENERGY_PER_BLOCK_RESISTANCE = 1000; - public static int LE_BLOCK_HIT_CONSUME_ENERGY_PER_DISTANCE = 10; - - // POWER REACTOR - public static int PR_MAX_ENERGY = 10000000; - public static int PR_TICK_TIME = 20; - public static int PR_MAX_LASERS = 3; - - // REACTOR MONITOR - public static int RM_MAX_ENERGY = 1000000; - public static double RM_EU_PER_HEAT = 2; - - public static String schemaLocation = "/home/cros/mc_site/schematics/"; + public int LE_MAX_BOOSTERS_NUMBER = 10; + public int LE_MAX_LASER_ENERGY = 4000000; + public int LE_EMIT_DELAY_TICKS = 20 * 3; + public int LE_EMIT_SCAN_DELAY_TICKS = 10; + public double LE_COLLECT_ENERGY_MULTIPLIER = 0.60D; + public int LE_BEAM_LENGTH_PER_ENERGY_DIVIDER = 5000; + public int LE_ENTITY_HIT_SET_ON_FIRE_TIME = 100; + public int LE_ENTITY_HIT_DAMAGE_PER_ENERGY_DIVIDER = 10000; + public int LE_ENTITY_HIT_EXPLOSION_LASER_ENERGY = 1000000; + public int LE_BLOCK_HIT_CONSUME_ENERGY = 70000; + public int LE_BLOCK_HIT_CONSUME_ENERGY_PER_BLOCK_RESISTANCE = 1000; + public int LE_BLOCK_HIT_CONSUME_ENERGY_PER_DISTANCE = 10; // Cloaking device core - public static int CD_MAX_CLOAKING_FIELD_SIDE = 100; - public static int CD_ENERGY_PER_BLOCK_TIER1 = 1000; - public static int CD_ENERGY_PER_BLOCK_TIER2 = 5000; - public static int CD_FIELD_REFRESH_INTERVAL_SECONDS = 10; - public static int CD_COIL_CAPTURE_BLOCKS = 5; + public int CD_MAX_CLOAKING_FIELD_SIDE = 100; + public int CD_ENERGY_PER_BLOCK_TIER1 = 1000; + public int CD_ENERGY_PER_BLOCK_TIER2 = 5000; + public int CD_FIELD_REFRESH_INTERVAL_SECONDS = 10; + public int CD_COIL_CAPTURE_BLOCKS = 5; - public static ItemStack getIC2Item(String id) { + private WarpDriveConfig() {} + + public ItemStack getIC2Item(String id) + { return Items.getItem(id); } - public static ItemStack getAEBlock(String id) { - try { + public ItemStack getAEBlock(String id) + { + try + { Object ret = AEBlocks.getField(id).get(null); if (ret instanceof ItemStack) return (ItemStack)ret; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Call getAEBlock failed for " + id); + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Call getAEBlock failed for " + id); } return null; } - public static ItemStack getAEMaterial(String id) { - try { + public ItemStack getAEMaterial(String id) + { + try + { Object ret = AEMaterials.getField(id).get(null); if (ret instanceof ItemStack) return (ItemStack)ret; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Call getAEMaterial failed for " + id); + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Call getAEMaterial failed for " + id); } return null; } - public static ItemStack getAEItem(String id) { - try { + public ItemStack getAEItem(String id) + { + try + { Object ret = AEItems.getField(id).get(null); if (ret instanceof ItemStack) return (ItemStack)ret; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Call getAEItem failed for " + id); + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Call getAEItem failed for " + id); } return null; } - public static void preInit(Configuration configIn) { - config = configIn; + public static void Init(Configuration config) + { + if (i == null) + i = new WarpDriveConfig(); + i.config = config; } - public static void loadWarpDriveConfig() { - // General - G_SPACE_PROVIDER_ID = config.get("General", "space_provider_id", 14).getInt(); - G_SPACE_DIMENSION_ID = config.get("General", "space_dimension_id", -2).getInt(); - G_HYPERSPACE_PROVIDER_ID = config.get("General", "hyperspace_provider_id", 15).getInt(); - G_HYPERSPACE_DIMENSION_ID = config.get("General", "hyperspace_dimension_id", -3).getInt(); - + public void loadWarpDriveConfig() + { // Warp Core WC_MAX_ENERGY_VALUE = config.get("WarpCore", "max_energy_value", 100000000).getInt(); WC_ENERGY_PER_BLOCK_MODE1 = config.get("WarpCore", "energy_per_block_mode1", 10).getInt(); WC_ENERGY_PER_DISTANCE_MODE1 = config.get("WarpCore", "energy_per_distance_mode1", 100).getInt(); - WC_ENERGY_PER_DISTANCE_MODE2 = config.get("WarpCore", "energy_per_distance_mode2", 1000).getInt(); - WC_ENERGY_PER_BLOCK_MODE2 = config.get("WarpCore", "energy_per_block_mode2", 1000).getInt(); - WC_ENERGY_PER_ENTITY_TO_SPACE = config.get("WarpCore", "energy_per_entity_to_space", 1000000).getInt(); - WC_MAX_JUMP_DISTANCE = config.get("WarpCore", "max_jump_distance", 128).getInt(); - WC_MAX_SHIP_VOLUME_ON_SURFACE = config.get("WarpCore", "max_ship_volume_on_surface", 15000).getInt(); // Maximum ship mass to jump on earth (15k blocks) - WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE = config.get("WarpCore", "min_ship_volume_for_hyperspace", 500).getInt(); // Minimum ship volume value for hyper space - WC_MAX_SHIP_SIDE = config.get("WarpCore", "max_ship_side", 100).getInt(); - WC_COLLISION_TOLERANCE_BLOCKS = config.get("WarpCore", "collision_tolerance_blocks", 5).getInt(); - - WC_COOLDOWN_INTERVAL_SECONDS = config.get("WarpCore", "cooldown_interval_seconds", 4).getInt(); - WC_WARMUP_SHORTJUMP_SECONDS = config.get("WarpCore", "warmup_shortjump_seconds", 10).getInt(); - WC_WARMUP_LONGJUMP_SECONDS = config.get("WarpCore", "warmup_longjump_seconds", 30).getInt(); - - WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS = config.get("WarpCore", "cores_registry_update_interval", 10).getInt(); - WC_ISOLATION_UPDATE_INTERVAL_SECONDS = config.get("WarpCore", "isolation_update_interval", 10).getInt(); - - // Warp Radar - WR_MAX_ENERGY_VALUE = config.get("WarpRadar", "max_energy_value", 100000000).getInt(); - - // Particle Booster - PB_MAX_ENERGY_VALUE = config.get("ParticleBooster", "max_energy_value", 100000).getInt(); + WC_ENERGY_PER_DISTANCE_MODE2 = config.get("WarpCore", "energy_per_distance_mode2", 1000).getInt(); + WC_ENERGY_PER_BLOCK_MODE2 = config.get("WarpCore", "energy_per_block_mode2", 1000).getInt(); + WC_ENERGY_PER_ENTITY_TO_SPACE = config.get("WarpCore", "energy_ped_entity_to_space", 1000000).getInt(); + WC_MAX_JUMP_DISTANCE = config.get("WarpCore", "max_jump_distance", 128).getInt(); + WC_MAX_SHIP_VOLUME_ON_SURFACE = config.get("WarpCore", "max_ship_volume_on_surface", 15000).getInt(); // Maximum ship mass to jump on earth (15k blocks) + WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE = config.get("WarpCore", "min_ship_volume_for_hyperspace", 500).getInt(); ; // Minimum ship volume value for hyper space + WC_MAX_SHIP_SIDE = config.get("WarpCore", "max_ship_side", 100).getInt(); + + WC_COOLDOWN_INTERVAL_SECONDS = config.get("WarpCore", "cooldown_interval_seconds", 4).getInt(); + WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS = config.get("WarpCore", "cores_registry_update_interval", 10).getInt(); + WC_ISOLATION_UPDATE_INTARVAL_SECONDS = config.get("WarpCore", "isolation_update_interval", 10).getInt(); + + // Warp Radar + WR_MAX_ENERGY_VALUE = config.get("WarpRadar", "max_energy_value", 100000000).getInt(); + + // Particle Booster + PB_MAX_ENERGY_VALUE = config.get("ParticleBooster", "max_energy_value", 100000).getInt(); + + // Mining Laser + ML_MAX_BOOSTERS_NUMBER = config.get("MiningLaser", "max_boosters_number", 1).getInt(); + ML_SCAN_DELAY = 20 * config.get("MiningLaser", "scan_delay_seconds", 5).getInt(); + ML_MINE_DELAY = config.get("MiningLaser", "mine_delay_ticks", 10).getInt(); + ML_EU_PER_LAYER_SPACE = config.get("MiningLaser", "eu_per_layer_space", 500).getInt(); + ML_EU_PER_LAYER_EARTH = config.get("MiningLaser", "eu_per_layer_earth", 5000).getInt(); // Laser Emitter LE_MAX_BOOSTERS_NUMBER = config.get("LaserEmitter", "max_boosters_number", 10).getInt(); @@ -259,51 +193,11 @@ public class WarpDriveConfig CD_ENERGY_PER_BLOCK_TIER2 = config.get("CloakingDevice", "energy_per_block_tier2", 500).getInt(); CD_FIELD_REFRESH_INTERVAL_SECONDS = config.get("CloakingDevice", "field_refresh_interval_seconds", 3).getInt(); CD_COIL_CAPTURE_BLOCKS = config.get("CloakingDevice", "coil_capture_blocks", 5).getInt(); - - // Dark's modifications - debugMode = config.get("Dark's stuff", "debug_mode", false).getBoolean(false); - schemaLocation = config.get("Dark's stuff", "schematic_location", schemaLocation).getString(); - - // Mining Laser - ML_MAX_BOOSTERS_NUMBER = config.get("MiningLaser", "max_boosters_number", 1).getInt(); - ML_WARMUP_DELAY_TICKS = config.get("MiningLaser", "warmup_delay_ticks", 20).getInt(); - ML_SCAN_DELAY_TICKS = config.get("MiningLaser", "scan_delay_ticks", 10).getInt(); - ML_MINE_DELAY_TICKS = config.get("MiningLaser", "mine_delay_ticks", 3).getInt(); - ML_EU_PER_LAYER_SPACE = config.get("MiningLaser", "eu_per_layer_space", 2000).getInt(); - ML_EU_PER_LAYER_EARTH = config.get("MiningLaser", "eu_per_layer_earth", 10000).getInt(); - ML_EU_PER_BLOCK_SPACE = config.get("MiningLaser", "eu_per_block_space", 500).getInt(); - ML_EU_PER_BLOCK_EARTH = config.get("MiningLaser", "eu_per_block_earth", 2500).getInt(); - ML_MAX_RADIUS = config.get("MiningLaser", "max_radius", 5).getInt(); - ML_EU_MUL_ORESONLY = config.get("MiningLaser", "oresonly_power_mul", 4.0).getDouble(4.0); - ML_EU_MUL_SILKTOUCH = config.get("MiningLaser", "silktouch_power_mul", 2.5).getDouble(2.5); - ML_EU_MUL_FORTUNE = config.get("MiningLaser", "fortune_power_base", 2.5).getDouble(2.5); -// ML_MAX_SPEED = config.get("MiningLaser", "max_speed_mul", 10).getDouble(10); -// ML_MIN_SPEED = config.get("MiningLaser", "min_speed_mul", 0.1).getDouble(0.1); - - // Tree Farm - TF_MAX_SIZE = config.get("TreeFarm", "max_treefarm_size", 16).getInt(); - - // Transporter - TR_MAX_ENERGY = config.get("Transporter", "max_energy", 1000000).getInt(); - TR_RELATIVE_COORDS = config.get("Transporter", "relative_coords", true).getBoolean(true); - TR_EU_PER_METRE = config.get("Transporter", "eu_per_ent_per_metre", 100).getDouble(100); - TR_MAX_BOOST_MUL = config.get("Transporter", "max_boost", 4).getInt(); - - // Reactor - PR_MAX_ENERGY = config.get("Reactor", "max_energy", 100000000).getInt(); - PR_TICK_TIME = config.get("Reactor", "ticks_per_update",20).getInt(); - PR_MAX_LASERS = config.get("Reactor", "max_lasers", 4).getInt(); - - // Reactor monitor - RM_MAX_ENERGY = config.get("Reactor Monitor", "max_rm_energy", 1000000).getInt(); - RM_EU_PER_HEAT = config.get("Reactor Monitor", "eu_per_heat", 2).getDouble(2); - - // Recipes config - recipesIC2 = config.get("Recipes", "ic2_recipes",true).getBoolean(true); } - public static void load() { - CommonWorldGenOres = new ArrayList(30); + public void Init2() + { + CommonWorldGenOres = new ArrayList(); CommonWorldGenOres.add(new int[] {Block.oreIron.blockID, 0}); CommonWorldGenOres.add(new int[] {Block.oreGold.blockID, 0}); CommonWorldGenOres.add(new int[] {Block.oreCoal.blockID, 0}); @@ -311,14 +205,10 @@ public class WarpDriveConfig CommonWorldGenOres.add(new int[] {Block.oreLapis.blockID, 0}); CommonWorldGenOres.add(new int[] {Block.oreRedstoneGlowing.blockID, 0}); CommonWorldGenOres.add(new int[] {Block.oreRedstone.blockID, 0}); - - forceFieldBlocks = new ArrayList(); - +// SpaceHelmets = new HashSet(); Jetpacks = new HashSet(); MinerOres = new HashSet(); - MinerLogs = new HashSet(); - MinerLeaves = new HashSet(); scannerIgnoreBlocks = new HashSet(); config.load(); coreID = config.getBlock("core", 500).getInt(); @@ -335,147 +225,70 @@ public class WarpDriveConfig laserCamID = config.getBlock("lasercam", 512).getInt(); camID = config.getBlock("camera", 513).getInt(); monitorID = config.getBlock("monitor", 514).getInt(); - iridiumBlockID = config.getBlock("iridium", 515).getInt(); + iridiumID = config.getBlock("iridium", 515).getInt(); shipScannerID = config.getBlock("shipscanner", 516).getInt(); cloakCoreID = config.getBlock("cloakcore", 517).getInt(); cloakCoilID = config.getBlock("cloakcoil", 518).getInt(); - laserTreeFarmID = config.getBlock("lasertreefarm", 519).getInt(); - transporterID = config.getBlock("transporter", 520).getInt(); - transportBeaconID = config.getBlock("transportBeacon", 521).getInt(); - reactorMonitorID = config.getBlock("reactorMonitor",522).getInt(); - powerLaserID = config.getBlock("powerLaser", 523).getInt(); - powerReactorID = config.getBlock("powerReactor",524).getInt(); - - reactorLaserFocusID = config.getItem("reactorLaserFocus", 8700).getInt(); - componentID = config.getItem("component", 8701).getInt(); - - isICLoaded = Loader.isModLoaded("IC2"); - if (isICLoaded) - loadIC2(); - - isCCLoaded = Loader.isModLoaded("ComputerCraft"); - if (isCCLoaded) - loadCC(); - + LoadIC2(); + LoadCC(); isGregLoaded = Loader.isModLoaded("gregtech_addon"); if (isGregLoaded) - loadGT(); - - isAppliedEnergisticsLoaded = Loader.isModLoaded("AppliedEnergistics"); - if (isAppliedEnergisticsLoaded) - loadAppliedEnergistics(); - + LoadGT(); + isAELoaded = Loader.isModLoaded("AppliedEnergistics"); + if (isAELoaded) + LoadAE(); isAEExtraLoaded = Loader.isModLoaded("extracells"); if (isAEExtraLoaded) - loadAEExtra(); - + LoadAEExtra(); isAdvSolPanelLoaded = Loader.isModLoaded("AdvancedSolarPanel"); if (isAdvSolPanelLoaded) - loadASP(); - - isAtomicScienceLoaded = Loader.isModLoaded("ResonantInduction|Atomic"); - if (isAtomicScienceLoaded) - loadAtomicScience(); - + LoadASP(); + isASLoaded = Loader.isModLoaded("AtomicScience"); + if (isASLoaded) + LoadAS(); isICBMLoaded = Loader.isModLoaded("ICBM|Explosion"); if (isICBMLoaded) - loadICBM(); - + LoadICBM(); isMFFSLoaded = Loader.isModLoaded("MFFS"); if (isMFFSLoaded) - loadMFFS(); - + LoadMFFS(); isGraviSuiteLoaded = Loader.isModLoaded("GraviSuite"); if (isGraviSuiteLoaded) - loadGraviSuite(); - - isUndergroundBiomesLoaded = Loader.isModLoaded("UndergroundBiomes"); - if (isUndergroundBiomesLoaded) - loadUndergroundBiomes(); - - isNetherOresLoaded = Loader.isModLoaded("NetherOres"); - if (isNetherOresLoaded) - loadNetherOres(); - - isThermalExpansionLoaded = Loader.isModLoaded("ThermalExpansion"); - if (isThermalExpansionLoaded) - loadThermalExpansion(); - - isMetallurgyLoaded = Loader.isModLoaded("Metallurgy3Core"); - if (isMetallurgyLoaded) { - loadMetallurgy(); - } - - isAdvancedRepulsionSystemsLoaded = Loader.isModLoaded("AdvancedRepulsionSystems"); - if (isAdvancedRepulsionSystemsLoaded) { - loadAdvancedRepulsionSystems(); - } + LoadGS(); // + MinerOres.add(iridiumID); MinerOres.add(Block.oreNetherQuartz.blockID); + for (int[] t : CommonWorldGenOres) + MinerOres.add(t[0]); + MinerOres.add(Block.wood.blockID); + MinerOres.add(Block.planks.blockID); + MinerOres.add(Block.rail.blockID); + MinerOres.add(Block.oreDiamond.blockID); MinerOres.add(Block.obsidian.blockID); MinerOres.add(Block.web.blockID); MinerOres.add(Block.fence.blockID); MinerOres.add(Block.torchWood.blockID); MinerOres.add(Block.glowStone.blockID); - LoadOreDict(); + // Ignore WarpDrive blocks (which potentially will be duplicated by cheaters using ship scan/deploy) scannerIgnoreBlocks.add(coreID); scannerIgnoreBlocks.add(controllerID); - scannerIgnoreBlocks.add(iridiumBlockID); + scannerIgnoreBlocks.add(iridiumID); - if (isICLoaded) { - scannerIgnoreBlocks.add(Items.getItem("mfsUnit").itemID); - scannerIgnoreBlocks.add(Items.getItem("mfeUnit").itemID); - scannerIgnoreBlocks.add(Items.getItem("cesuUnit").itemID); - scannerIgnoreBlocks.add(Items.getItem("batBox").itemID); - } - if (isICBMLoaded) { - scannerIgnoreBlocks.add(ICBM_Explosive); - } - if (isCCLoaded) { - scannerIgnoreBlocks.add(CC_Computer); - scannerIgnoreBlocks.add(CCT_Turtle); - scannerIgnoreBlocks.add(CCT_Upgraded); - scannerIgnoreBlocks.add(CCT_Advanced); - } + scannerIgnoreBlocks.add(Items.getItem("mfsUnit").itemID); + scannerIgnoreBlocks.add(Items.getItem("mfeUnit").itemID); + scannerIgnoreBlocks.add(Items.getItem("cesuUnit").itemID); + scannerIgnoreBlocks.add(Items.getItem("batBox").itemID); + // Do not deploy ores and valuables - for (int[] t : CommonWorldGenOres) {// each element of this set is pair [id, meta] + for (int[] t : CommonWorldGenOres) // each element of this set is pair [id, meta] scannerIgnoreBlocks.add(t[0]); // we adding ID only - } loadWarpDriveConfig(); config.save(); } - - private static void LoadOreDict() { - String[] oreNames = OreDictionary.getOreNames(); - for(String oreName: oreNames) { - String lowerOreName = oreName.toLowerCase(); - if (oreName.substring(0,3).equals("ore")) { - ArrayList item = OreDictionary.getOres(oreName); - for(ItemStack i: item) { - MinerOres.add(i.itemID); - WarpDrive.debugPrint("WD: Added ore ID: "+i.itemID); - } - } - if (lowerOreName.contains("log")) { - ArrayList item = OreDictionary.getOres(oreName); - for(ItemStack i: item) { - MinerLogs.add(i.itemID); - WarpDrive.debugPrint("WD: Added log ID: "+i.itemID); - } - } - if (lowerOreName.contains("leave") || lowerOreName.contains("leaf")) { - ArrayList item = OreDictionary.getOres(oreName); - for(ItemStack i: item) { - MinerLeaves.add(i.itemID); - WarpDrive.debugPrint("WD: Added leaf ID: "+i.itemID); - } - } - } - } - private static void loadIC2() + private void LoadIC2() { ASP = Items.getItem("solarPanel").itemID; SpaceHelmets.add(Items.getItem("hazmatHelmet").itemID); @@ -483,65 +296,57 @@ public class WarpDriveConfig Jetpacks.add(Items.getItem("jetpack").itemID); Jetpacks.add(Items.getItem("electricJetpack").itemID); IC2_Air = new int[] {Items.getItem("airCell").itemID, Items.getItem("airCell").getItemDamage()}; - IC2_Empty = new int[] {Items.getItem("cell").itemID, Items.getItem("cell").getItemDamage()}; - ItemStack rubberWood = Items.getItem("rubberWood"); - IC2_Resin = Items.getItem("resin"); - if(rubberWood != null) { - IC2_RubberWood = rubberWood.itemID; - } - ItemStack ore = Items.getItem("uraniumOre"); - if (ore != null) CommonWorldGenOres.add(new int[] {ore.itemID, ore.getItemDamage()}); - ore = Items.getItem("copperOre"); - if (ore != null) CommonWorldGenOres.add(new int[] {ore.itemID, ore.getItemDamage()}); - ore = Items.getItem("tinOre"); - if (ore != null) CommonWorldGenOres.add(new int[] {ore.itemID, ore.getItemDamage()}); - ore = Items.getItem("leadOre"); - if (ore != null) CommonWorldGenOres.add(new int[] {ore.itemID, ore.getItemDamage()}); - + CommonWorldGenOres.add(new int[] {Items.getItem("uraniumOre").itemID, Items.getItem("uraniumOre").getItemDamage()}); + CommonWorldGenOres.add(new int[] {Items.getItem("copperOre").itemID, Items.getItem("copperOre").getItemDamage()}); + CommonWorldGenOres.add(new int[] {Items.getItem("tinOre").itemID, Items.getItem("tinOre").getItemDamage()}); + CommonWorldGenOres.add(new int[] {Items.getItem("leadOre").itemID, Items.getItem("leadOre").getItemDamage()}); MinerOres.add(Items.getItem("rubberWood").itemID); - IC2_fluidCell = Items.getItem("FluidCell").getItem(); + AEExtraFDI = Items.getItem("FluidCell").getItem(); } - private static void loadCC() + private void LoadCC() { try { - Class z = Class.forName("dan200.computercraft.ComputerCraft"); + Class z = Class.forName("dan200.ComputerCraft"); CC_Computer = z.getField("computerBlockID").getInt(null); CC_peripheral = z.getField("peripheralBlockID").getInt(null); - CC_Floppy = z.getField("diskItemID").getInt(null); + z = Class.forName("dan200.CCTurtle"); CCT_Turtle = z.getField("turtleBlockID").getInt(null); CCT_Upgraded = z.getField("turtleUpgradedBlockID").getInt(null); CCT_Advanced = z.getField("turtleAdvancedBlockID").getInt(null); + scannerIgnoreBlocks.add(CC_Computer); + scannerIgnoreBlocks.add(CCT_Turtle); + scannerIgnoreBlocks.add(CCT_Upgraded); + scannerIgnoreBlocks.add(CCT_Advanced); } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading ComputerCraft classes"); + System.out.println("WarpDriveConfig Error loading CC classes AWWW SHEEEEET NIGGA"); e.printStackTrace(); } } - private static void loadGT() + private void LoadGT() { try { - Class z = Class.forName("gregtechmod.GT_Mod"); - int[] t = (int[])z.getField("sBlockIDs").get(null); + int[] t = (int[])Class.forName("gregtechmod.GT_Mod").getField("sBlockIDs").get(null); GT_Machine = t[1]; GT_Ores = t[2]; // meta 1-15 = ores GT_Granite = t[5]; // 0 - black, 1 - black cobble, 8 - red, 9 - red cobble MinerOres.add(GT_Ores); - //MinerOres.add(GT_Granite); + MinerOres.add(GT_Granite); } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading GT classes"); + System.out.println("WarpDriveConfig Error loading GT classes"); e.printStackTrace(); isGregLoaded = false; } } - private static void loadAppliedEnergistics() + private void LoadAE() { try { @@ -552,32 +357,29 @@ public class WarpDriveConfig } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading AppliedEnergistics classes"); + System.out.println("WarpDriveConfig Error loading AE classes"); e.printStackTrace(); - isAppliedEnergisticsLoaded = false; + isAELoaded = false; } } - private static void loadAEExtra() + private void LoadAEExtra() { try { Class z = Class.forName("extracells.ItemEnum"); Object z1 = z.getEnumConstants()[6]; - AEExtra_fluidDrive = (Item)z1.getClass().getDeclaredMethod("getItemInstance").invoke(z1); - z = Class.forName("extracells.BlockEnum"); - z1 = z.getEnumConstants()[9]; - AEExtra_certusQuartzTank = (Block)z1.getClass().getDeclaredMethod("getBlockInstance").invoke(z1); + AEExtraFDI = (Item)z1.getClass().getDeclaredMethod("getItemInstance").invoke(z1); } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading AEExtra classes"); + System.out.println("WarpDriveConfig Error loading AEExtra classes"); e.printStackTrace(); isAEExtraLoaded = false; } - } - - private static void loadASP() + } + + private void LoadASP() { try { @@ -589,199 +391,124 @@ public class WarpDriveConfig } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading ASP classes"); + System.out.println("WarpDriveConfig Error loading ASP classes"); e.printStackTrace(); isAdvSolPanelLoaded = false; } } - private static void loadAtomicScience() { - try { - Class z = Class.forName("resonantinduction.atomic.Atomic"); + private void LoadAS() + { + try + { +/* + Class z = Class.forName("atomicscience.AtomicScience"); CommonWorldGenOres.add(new int[] {((Block)z.getField("blockUraniumOre").get(null)).blockID, 0}); AS_Turbine = ((Block)z.getField("blockElectricTurbine").get(null)).blockID; - AS_deuteriumCell = ((Item)z.getField("itemDeuteriumCell").get(null)).itemID; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading AS classes"); - isAtomicScienceLoaded = false; +*/ + Class z = Class.forName("atomicscience.ZhuYaoAS"); + CommonWorldGenOres.add(new int[] {((Block)z.getField("bHeOre").get(null)).blockID, 0}); + AS_Turbine = ((Block)z.getField("bWoLun").get(null)).blockID; + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Error loading AS classes"); + e.printStackTrace(); + isASLoaded = false; } } - private static void loadICBM() { - try { + private void LoadICBM() + { + try + { Class z = Class.forName("icbm.core.ICBMCore"); CommonWorldGenOres.add(new int[] {((Block)z.getField("blockSulfurOre").get(null)).blockID, 0}); z = Class.forName("icbm.explosion.ICBMExplosion"); ICBM_Machine = ((Block)z.getField("blockMachine").get(null)).blockID; ICBM_Missile = ((Item)z.getField("itemMissile").get(null)).itemID; ICBM_Explosive = ((Block)z.getField("blockExplosive").get(null)).blockID; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading ICBM classes"); + scannerIgnoreBlocks.add(ICBM_Explosive); + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Error loading ICBM classes"); e.printStackTrace(); isICBMLoaded = false; } } - private static void loadMFFS() { - try { + private void LoadMFFS() + { + try + { Class z = Class.forName("mffs.ModularForceFieldSystem"); - int blockId = ((Block)z.getField("blockForceField").get(null)).blockID; - forceFieldBlocks.add(blockId); - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading MFFS classes"); + MFFS_Field = ((Block)z.getField("blockForceField").get(null)).blockID; + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Error loading MFFS classes"); e.printStackTrace(); isICBMLoaded = false; } } - private static void loadGraviSuite() { - try { + private void LoadGS() + { + try + { Class z = Class.forName("gravisuite.GraviSuite"); if (z.getField("ultimateSolarHelmet").get(null) != null) SpaceHelmets.add(((Item)z.getField("ultimateSolarHelmet").get(null)).itemID); Jetpacks.add(z.getField("advJetpackID").getInt(null) + 256); Jetpacks.add(z.getField("graviChestPlateID").getInt(null) + 256); - GS_ultimateLappack = z.getField("ultimateLappackID").getInt(null) + 256; - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading GS classes"); + } + catch (Exception e) + { + System.out.println("WarpDriveConfig Error loading GS classes"); e.printStackTrace(); isGraviSuiteLoaded = false; } } - private static void loadUndergroundBiomes() { - try { - Class z = Class.forName("exterminatorJeff.undergroundBiomes.common.UndergroundBiomes"); - UB_igneousStone = ((Block)z.getField("igneousStone").get(null)).blockID; - UB_igneousCobblestone = ((Block)z.getField("igneousCobblestone").get(null)).blockID; - UB_metamorphicStone = ((Block)z.getField("metamorphicStone").get(null)).blockID; - UB_metamorphicCobblestone = ((Block)z.getField("metamorphicCobblestone").get(null)).blockID; - UB_sedimentaryStone = ((Block)z.getField("sedimentaryStone").get(null)).blockID; - WarpDrive.debugPrint("WarpDriveConfig found UndergroundBiomes blocks " + UB_igneousStone + ", " + UB_igneousCobblestone + ", " + UB_metamorphicStone + ", " + UB_metamorphicCobblestone + ", " + UB_sedimentaryStone); - } catch (Exception e) { - WarpDrive.debugPrint("WarpDriveConfig Error loading UndergroundBiomes classes"); - e.printStackTrace(); - isUndergroundBiomesLoaded = false; - } - } - - private static void loadNetherOres() { - try { - NetherOres_count = 21; // FIXME: extract it properly -/* Class z = Class.forName("powercrystals.netherores.ores.Ores"); - NO_netherOresCount = z.getField("values").get(null).length; - WarpDrive.debugPrint("WarpDriveConfig found NetherOres count " + NO_netherOresCount); - - z = Class.forName("powercrystals.netherores.NetherOresCore"); - for (int i = 0; i < (NO_netherOresCount + 15) / 16; i++) - { - NO_netherOresBlock[i] = ((Block[])z.getDeclaredField("blockNetherOres").get(null))[i].blockID; - WarpDrive.debugPrint("WarpDriveConfig found NetherOres blockId " + NO_netherOresBlock[i]); - }*/ - NetherOres_block = new int[(NetherOres_count + 15) / 16]; - NetherOres_block[0] = 1440; - NetherOres_block[1] = 1442; - System.out.println("WarpDriveConfig found " + NetherOres_count + " NetherOres"); - } - catch (Exception e) + public int[] getDefaultSurfaceBlock(Random random, boolean corrupted, boolean isMoon) + { + if (isMoon) { - System.out.println("WarpDriveConfig Error loading NetherOres classes"); - e.printStackTrace(); - isNetherOresLoaded = false; - } - } - - private static void loadThermalExpansion() { - try { -// TEEnergyCell = Class.forName("thermalexpansion.block.energycell.BlockEnergyCell"); -// TEFluids = Class.forName("thermalexpansion.fluid.TEFluids"); - } catch (Exception e) { - System.out.println("WarpDriveConfig Error loading ThermalExpansion classes"); - e.printStackTrace(); - isThermalExpansionLoaded = false; - } - } - - private static void loadMetallurgy() { - try { - Metallurgy_overworldOresBlock = new int[][] { { 905, 7}, { 905, 8}, { 905, 9}, { 905, 10}, { 905, 11}, { 905, 12}, { 906, 0}, { 906, 1}, { 906, 2}, { 906, 4}, { 906, 5}, { 906, 6}, { 906, 7}, { 906, 8}, { 906, 11}, { 906, 13}, { 906, 14} }; - Metallurgy_netherOresBlock = new int[][] { { 903, 0}, { 903, 1}, { 903, 2}, { 903, 3}, { 903, 4}, { 903, 5}, { 903, 6}, { 903, 7}, { 903, 8}, { 903, 9} }; - Metallurgy_endOresBlock = new int[][] { { 900, 5}, { 900, 6} }; - } catch (Exception e) { - System.out.println("WarpDriveConfig Error loading Metallurgy classes"); - e.printStackTrace(); - isMetallurgyLoaded = false; - } - } - - private static void loadAdvancedRepulsionSystems() { - try { - Class z = Class.forName("mods.immibis.ars.ARSMod"); - int fieldBlockId = ((Block)z.getField("MFFSFieldblock").get(null)).blockID; - forceFieldBlocks.add(fieldBlockId); - } catch (Exception e) { - System.out.println("WarpDriveConfig Error loading AdvancedRepulsionSystems classes"); - e.printStackTrace(); - isAdvancedRepulsionSystemsLoaded = false; - } - } - - public static int[] getDefaultSurfaceBlock(Random random, boolean corrupted, boolean isMoon) { - if (isMoon) { - if (isGregLoaded && (random.nextInt(100) == 1)) { - if (random.nextBoolean()) { + if (random.nextInt(100) == 1) + if (random.nextBoolean()) return new int[] {GT_Granite, (corrupted && random.nextBoolean())?1:0}; - } else { + else return new int[] {GT_Granite, (corrupted && random.nextBoolean())?9:8}; - } - } else if (random.nextInt(5) == 1) { + else if (random.nextInt(666) == 1) return new int[] {Block.netherrack.blockID, 0}; - } else if (random.nextInt(15) == 1) { + else if (random.nextInt(1000) == 1) return new int[] {Block.whiteStone.blockID, 0}; - } - } else { - if (isGregLoaded && (random.nextInt(25) == 1)) { - if (random.nextBoolean()) { - return new int[] {GT_Granite, (corrupted && random.nextBoolean())?1:0}; - } else { - return new int[] {GT_Granite, (corrupted && random.nextBoolean())?9:8}; - } - } else if (random.nextInt(6) == 1) { - return new int[] {Block.netherrack.blockID, 0}; - } else if (random.nextInt(50) == 1) { - return new int[] {Block.whiteStone.blockID, 0}; - } } - if (corrupted && random.nextBoolean()) { - if (isUndergroundBiomesLoaded) { - int rnd = random.nextInt(8 + 8 + 2); - if (rnd < 8) { - return new int[] {UB_igneousCobblestone, rnd}; - } else if (rnd < (8 + 8)) { - return new int[] {UB_metamorphicCobblestone, rnd - 8}; - } - } + else + { + if (random.nextInt(25) == 1) + if (random.nextBoolean()) + return new int[] {GT_Granite, (corrupted && random.nextBoolean())?1:0}; + else + return new int[] {GT_Granite, (corrupted && random.nextBoolean())?9:8}; + else if (random.nextInt(50) == 1) + return new int[] {Block.netherrack.blockID, 0}; + else if (random.nextInt(150) == 1) + return new int[] {Block.whiteStone.blockID, 0}; + } + if (corrupted && random.nextBoolean()) return new int[] {Block.cobblestone.blockID, 0}; - } - if (isUndergroundBiomesLoaded) { - int rnd = random.nextInt(8 + 8 + 8 + 3); - if (rnd < 8) { - return new int[] {UB_igneousStone, rnd}; - } else if (rnd < (8 + 8)) { - return new int[] {UB_metamorphicStone, rnd - 8}; - } - else if (rnd < (8 + 8 + 8)) { - return new int[] {UB_sedimentaryStone, rnd - 8 - 8}; - } - } return new int[] {Block.stone.blockID, 0}; } - public static int[] getRandomSurfaceBlock(Random random, int blockID, int blockMeta, boolean bedrock) { - if (bedrock && (random.nextInt(1000) == 1)) { + public int[] getRandomSurfaceBlock(Random random, int blockID, int blockMeta, boolean bedrock) + { + if (bedrock && random.nextInt(1000) == 1) return new int[] {Block.bedrock.blockID, 0}; - } else if (blockID == GT_Granite) { - if ((blockMeta == 0) || (blockMeta == 1)) { + if (blockID == GT_Granite) + if (blockMeta == 0 || blockMeta == 1) + { int[] t; t = getRandomOverworldBlock(random, blockID, blockMeta); if (t[0] == blockID) @@ -789,7 +516,9 @@ public class WarpDriveConfig if (t[0] == blockID) t = getRandomEndBlock(random, blockID, blockMeta); return t; - } else if ((blockMeta == 8) || (blockMeta == 9)) { + } + else if (blockMeta == 8 || blockMeta == 9) + { int[] t; t = getRandomOverworldBlock(random, blockID, blockMeta); if (t[0] == blockID) @@ -798,27 +527,25 @@ public class WarpDriveConfig t = getRandomOverworldBlock(random, blockID, blockMeta); return t; } - } else if (blockID == Block.whiteStone.blockID) { + else if (blockID == Block.whiteStone.blockID) return getRandomEndBlock(random, blockID, blockMeta); - } else if (blockID == Block.netherrack.blockID) { + else if (blockID == Block.netherrack.blockID) return getRandomNetherBlock(random, blockID, blockMeta); - } return getRandomOverworldBlock(random, blockID, blockMeta); } - public static int[] getRandomOverworldBlock(Random random, int blockID, int blockMeta) + public int[] getRandomOverworldBlock(Random random, int blockID, int blockMeta) { - if (random.nextInt(25) == 5) { + if (random.nextInt(25) == 5) return CommonWorldGenOres.get(random.nextInt(CommonWorldGenOres.size())); - } else if (isMetallurgyLoaded && (random.nextInt(25) == 1)) { - return Metallurgy_overworldOresBlock[random.nextInt(Metallurgy_overworldOresBlock.length)]; - } else if (isAppliedEnergisticsLoaded && random.nextInt(750) == 1) { + else if (isAELoaded && random.nextInt(750) == 1) return new int[] {getAEBlock("blkQuartzOre").itemID, getAEBlock("blkQuartzOre").getItemDamage()}; - } else if (random.nextInt(250) == 1) { + else if (random.nextInt(250) == 1) return new int[] {Block.oreDiamond.blockID, 0}; - } else if (!isNetherOresLoaded && (random.nextInt(10000) == 42)) { - return new int[] {iridiumBlockID, 0}; - } else if (isGregLoaded) { + else if (random.nextInt(10000) == 42) + return new int[] {iridiumID, 0}; + if (isGregLoaded) + { if (random.nextInt(50) == 1) return new int[] {GT_Ores, 5}; //Bauxite S /* Stone/Iron/Diamod pick | +S = Silktouch recommended */ else if (random.nextInt(50) == 1) @@ -841,33 +568,32 @@ public class WarpDriveConfig return new int[] {blockID, blockMeta}; } - public static int[] getRandomNetherBlock(Random random, int blockID, int blockMeta) { - if (isICLoaded && (!isNetherOresLoaded) && (random.nextInt(10000) == 42)) { - return new int[] {iridiumBlockID, 0}; - } else if (isNetherOresLoaded && (random.nextInt(25) == 1)) { - int rnd = random.nextInt(NetherOres_count); - return new int[] {NetherOres_block[rnd / 16], rnd % 16}; - } else if (isMetallurgyLoaded && (random.nextInt(25) == 1)) { - return Metallurgy_netherOresBlock[random.nextInt(Metallurgy_netherOresBlock.length)]; - } else if (random.nextInt(25) == 1) { + public int[] getRandomNetherBlock(Random random, int blockID, int blockMeta) + { + if (random.nextInt(10000) == 42) + return new int[] {iridiumID, 0}; + else if (random.nextInt(25) == 1) return new int[] {Block.oreNetherQuartz.blockID, 0}; - } else if (isGregLoaded) { + else if (isGregLoaded) + { if (random.nextInt(100) == 1) return new int[] {GT_Ores, 6}; //Pyrite S+S else if (random.nextInt(100) == 1) return new int[] {GT_Ores, 8}; //Sphalerite S+S else if (random.nextInt(500) == 1) return new int[] {GT_Ores, 7}; //Cinnabar I+S - } else if ((!isNetherOresLoaded) && (random.nextInt(100) == 13)) + } + else if (random.nextInt(100) == 13) return CommonWorldGenOres.get(random.nextInt(CommonWorldGenOres.size())); return new int[] {blockID, blockMeta}; } - public static int[] getRandomEndBlock(Random random, int blockID, int blockMeta) + public int[] getRandomEndBlock(Random random, int blockID, int blockMeta) { - if (isICLoaded && random.nextInt(10000) == 42) { - return new int[] { iridiumBlockID, 0 }; - } else if (isGregLoaded) { + if (random.nextInt(10000) == 42) + return new int[] {iridiumID, 0}; + else if (isGregLoaded) + { if (random.nextInt(250) == 1) return new int[] {GT_Ores, 9}; //Tungstate I else if (random.nextInt(500) == 1) @@ -876,15 +602,9 @@ public class WarpDriveConfig return new int[] {GT_Ores, 10}; //Cooperite=Sheldonite D else if (random.nextInt(1000) == 1) return new int[] {GT_Ores, 11}; //Olivine D+S - } else if (isMetallurgyLoaded && (random.nextInt(25) == 1)) { - return Metallurgy_endOresBlock[random.nextInt(Metallurgy_endOresBlock.length)]; - } else if (random.nextInt(200) == 13) { - return CommonWorldGenOres.get(random.nextInt(CommonWorldGenOres.size())); } + else if (random.nextInt(200) == 13) + return CommonWorldGenOres.get(random.nextInt(CommonWorldGenOres.size())); return new int[] {blockID, blockMeta}; } - - public static boolean isAirBlock(World worldObj, int id, int x, int y, int z) { - return id == 0 || Block.blocksList[id] == null || Block.blocksList[id].isAirBlock(worldObj, x, y, z); - } } diff --git a/src/cr0s/WarpDrive/WarpDriveCreativeTab.java b/src/cr0s/WarpDrive/WarpDriveCreativeTab.java deleted file mode 100644 index eaba5a3c..00000000 --- a/src/cr0s/WarpDrive/WarpDriveCreativeTab.java +++ /dev/null @@ -1,31 +0,0 @@ -package cr0s.WarpDrive; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; - -public class WarpDriveCreativeTab extends CreativeTabs { - String topLabel; - - public WarpDriveCreativeTab(int par1, String par2Str) { - super(par1, par2Str); - } - - public WarpDriveCreativeTab(String par1Str,String topLabelIn) { - super(par1Str); - topLabel = topLabelIn; - } - - @Override - @SideOnly(Side.CLIENT) - public Item getTabIconItem() { - return WarpDrive.componentItem; - // return WarpDrive.reactorLaserFocusItem; - } - - @Override - public String getTranslatedTabLabel() { - return topLabel; - } -} diff --git a/src/cr0s/WarpDrive/WarpDrivePeripheralHandler.java b/src/cr0s/WarpDrive/WarpDrivePeripheralHandler.java deleted file mode 100644 index 6c92d8ca..00000000 --- a/src/cr0s/WarpDrive/WarpDrivePeripheralHandler.java +++ /dev/null @@ -1,18 +0,0 @@ -package cr0s.WarpDrive; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import dan200.computercraft.api.peripheral.IPeripheral; -import dan200.computercraft.api.peripheral.IPeripheralProvider; - -public class WarpDrivePeripheralHandler implements IPeripheralProvider { - @Override - public IPeripheral getPeripheral(World world, int x, int y, int z, int side) { -// WarpDrive.debugPrint("Checking Peripheral at " + x + ", " + y + ", " + z); - TileEntity te = world.getBlockTileEntity(x, y, z); - if(te instanceof IPeripheral) { - return (IPeripheral)te; - } - return null; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/WorldGenSmallShip.java b/src/cr0s/WarpDrive/WorldGenSmallShip.java index 0ce04b4a..43592fcc 100644 --- a/src/cr0s/WarpDrive/WorldGenSmallShip.java +++ b/src/cr0s/WarpDrive/WorldGenSmallShip.java @@ -1,5 +1,6 @@ package cr0s.WarpDrive; +import cpw.mods.fml.common.Loader; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.monster.EntityZombie; @@ -15,39 +16,39 @@ public class WorldGenSmallShip extends WorldGenerator private boolean corrupted; private int solarType; - public WorldGenSmallShip(boolean corrupted) { + public WorldGenSmallShip(boolean corrupted) + { this.corrupted = corrupted; - solarType = WarpDriveConfig.getIC2Item("solarPanel").getItemDamage(); + solarType = WarpDriveConfig.i.getIC2Item("solarPanel").getItemDamage(); } @Override - public boolean generate(World world, Random rand, int centerX, int centerY, int centerZ) + public boolean generate(World world, Random rand, int i, int j, int k) { - if (WarpDriveConfig.isAdvSolPanelLoaded) + if (WarpDriveConfig.i.isAdvSolPanelLoaded) solarType = rand.nextInt(2); - ItemStack cableType = WarpDriveConfig.getIC2Item("copperCableBlock").copy(); + ItemStack cableType = WarpDriveConfig.i.getIC2Item("copperCableBlock").copy(); switch (rand.nextInt(4)) { case 0: - cableType = WarpDriveConfig.getIC2Item("glassFiberCableBlock").copy(); + cableType = WarpDriveConfig.i.getIC2Item("glassFiberCableBlock").copy(); break; case 1: - cableType = WarpDriveConfig.getIC2Item("glassFiberCableBlock").copy(); + cableType = WarpDriveConfig.i.getIC2Item("glassFiberCableBlock").copy(); break; case 2: - cableType = WarpDriveConfig.getIC2Item("insulatedGoldCableBlock").copy(); + cableType = WarpDriveConfig.i.getIC2Item("insulatedGoldCableBlock").copy(); break; case 3: - cableType = WarpDriveConfig.getIC2Item("doubleInsulatedIronCableBlock").copy(); + cableType = WarpDriveConfig.i.getIC2Item("doubleInsulatedIronCableBlock").copy(); break; } - int i = centerX - 5, j = centerY - 4, k = centerZ - 6; world.setBlock(i + 0, j + 1, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 0, j + 1, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 1, j + 1, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -217,7 +218,7 @@ public class WorldGenSmallShip extends WorldGenerator world.setBlock(i + 7, j + 6, k + 3, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 7, j + 6, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 7, j + 6, k + 6, cableType.itemID, cableType.getItemDamage(), 0); - world.setBlock(i + 7, j + 6, k + 7, WarpDriveConfig.ASP, solarType, 0); + world.setBlock(i + 7, j + 6, k + 7, WarpDriveConfig.i.ASP, solarType, 0); world.setBlock(i + 7, j + 6, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 7, j + 6, k + 11, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 7, j + 7, k + 5, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -250,7 +251,7 @@ public class WorldGenSmallShip extends WorldGenerator world.setBlock(i + 8, j + 6, k + 3, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 8, j + 6, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 8, j + 6, k + 6, cableType.itemID, cableType.getItemDamage(), 0); - world.setBlock(i + 8, j + 6, k + 7, WarpDriveConfig.ASP, solarType, 0); + world.setBlock(i + 8, j + 6, k + 7, WarpDriveConfig.i.ASP, solarType, 0); world.setBlock(i + 8, j + 6, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 8, j + 6, k + 11, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 8, j + 7, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -285,9 +286,9 @@ public class WorldGenSmallShip extends WorldGenerator world.setBlock(i + 9, j + 6, k + 3, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 9, j + 6, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 9, j + 6, k + 6, cableType.itemID, cableType.getItemDamage(), 0); - world.setBlock(i + 9, j + 6, k + 7, WarpDriveConfig.ASP, solarType, 0); + world.setBlock(i + 9, j + 6, k + 7, WarpDriveConfig.i.ASP, solarType, 0); // Placing air generator - world.setBlock(i + 9, j + 5, k + 7, WarpDriveConfig.airgenID, 0, 0); + world.setBlock(i + 9, j + 5, k + 7, WarpDriveConfig.i.airgenID, 0, 0); world.setBlock(i + 9, j + 6, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 9, j + 6, k + 11, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 9, j + 7, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -325,9 +326,9 @@ public class WorldGenSmallShip extends WorldGenerator world.setBlock(i + 10, j + 6, k + 3, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 10, j + 6, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 10, j + 6, k + 6, cableType.itemID, cableType.getItemDamage(), 0); - world.setBlock(i + 10, j + 6, k + 7, WarpDriveConfig.ASP, solarType, 0); + world.setBlock(i + 10, j + 6, k + 7, WarpDriveConfig.i.ASP, solarType, 0); // Placing air generator - world.setBlock(i + 10, j + 5, k + 7, WarpDriveConfig.airgenID, 0, 0); + world.setBlock(i + 10, j + 5, k + 7, WarpDriveConfig.i.airgenID, 0, 0); world.setBlock(i + 10, j + 6, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 10, j + 6, k + 11, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 10, j + 7, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -361,7 +362,7 @@ public class WorldGenSmallShip extends WorldGenerator // Place warp-controller if (rand.nextBoolean()) { - world.setBlock(i + 11, j + 3, k + 7, WarpDriveConfig.controllerID); + world.setBlock(i + 11, j + 3, k + 7, WarpDriveConfig.i.controllerID); } world.setBlock(i + 11, j + 3, k + 8, WorldGenStructure.getGlassBlock(corrupted, rand)); @@ -372,7 +373,7 @@ public class WorldGenSmallShip extends WorldGenerator // Place computer if (rand.nextBoolean()) { - world.setBlock(i + 11, j + 4, k + 7, WarpDriveConfig.CC_Computer, 12, 3); + world.setBlock(i + 11, j + 4, k + 7, 1225, 16384, 0); } world.setBlock(i + 11, j + 4, k + 8, WorldGenStructure.getGlassBlock(corrupted, rand)); @@ -383,7 +384,7 @@ public class WorldGenSmallShip extends WorldGenerator world.setBlock(i + 11, j + 6, k + 3, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 11, j + 6, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 11, j + 6, k + 6, cableType.itemID, cableType.getItemDamage(), 0); - world.setBlock(i + 11, j + 6, k + 7, WarpDriveConfig.ASP, solarType, 0); + world.setBlock(i + 11, j + 6, k + 7, WarpDriveConfig.i.ASP, solarType, 0); world.setBlock(i + 11, j + 6, k + 10, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 11, j + 6, k + 11, WorldGenStructure.getStoneBlock(corrupted, rand)); world.setBlock(i + 11, j + 7, k + 4, WorldGenStructure.getStoneBlock(corrupted, rand)); @@ -417,7 +418,7 @@ public class WorldGenSmallShip extends WorldGenerator // Place warp-core if (rand.nextBoolean()) { - world.setBlock(i + 12, j + 3, k + 7, WarpDriveConfig.coreID); + world.setBlock(i + 12, j + 3, k + 7, WarpDriveConfig.i.coreID); } world.setBlock(i + 12, j + 3, k + 8, WorldGenStructure.getGlassBlock(corrupted, rand)); @@ -554,7 +555,7 @@ public class WorldGenSmallShip extends WorldGenerator return true; } - public static void spawnNPC(World world, int i, int j, int k) + public void spawnNPC(World world, int i, int j, int k) { int numMobs = 2 + world.rand.nextInt(10); @@ -563,7 +564,7 @@ public class WorldGenSmallShip extends WorldGenerator for (int idx = 0; idx < numMobs; idx++) { EntityVillager entityvillager = new EntityVillager(world, 0); - entityvillager.setLocationAndAngles(i + 0.5D, j, k + 0.5D, 0.0F, 0.0F); + entityvillager.setLocationAndAngles((double)i + 0.5D, (double)j, (double)k + 0.5D, 0.0F, 0.0F); world.spawnEntityInWorld(entityvillager); } } @@ -572,7 +573,7 @@ public class WorldGenSmallShip extends WorldGenerator for (int idx = 0; idx < numMobs; idx++) { EntityZombie entityzombie = new EntityZombie(world); - entityzombie.setLocationAndAngles(i + 0.5D, j, k + 0.5D, 0.0F, 0.0F); + entityzombie.setLocationAndAngles((double)i + 0.5D, (double)j, (double)k + 0.5D, 0.0F, 0.0F); world.spawnEntityInWorld(entityzombie); } } @@ -585,12 +586,11 @@ public class WorldGenSmallShip extends WorldGenerator if (te != null) { TileEntityChest chest = (TileEntityChest)te; - int size = chest.getSizeInventory(); - int numBonuses = rand.nextInt(size) / 2; + int numBonuses = rand.nextInt(28); - for (int i = 0; i < size; i++) + for (int i = 0; i < chest.getSizeInventory(); i++) { - if (rand.nextInt(size) <= numBonuses) + if (rand.nextInt(15) == 0) { numBonuses--; chest.setInventorySlotContents(i, getRandomBonus(rand)); @@ -609,14 +609,14 @@ public class WorldGenSmallShip extends WorldGenerator switch (rand.nextInt(14)) { case 0: - res = WarpDriveConfig.getIC2Item("massFabricator").copy(); - res.stackSize = 1; // + rand.nextInt(2); + res = WarpDriveConfig.i.getIC2Item("massFabricator").copy(); + res.stackSize = 1 + rand.nextInt(2); isDone = true; break; case 1: - res = WarpDriveConfig.getIC2Item("nuke").copy(); - res.stackSize = 1 + rand.nextInt(2); + res = WarpDriveConfig.i.getIC2Item("nuke").copy(); + res.stackSize = 1 + rand.nextInt(64); isDone = true; break; @@ -628,14 +628,14 @@ public class WorldGenSmallShip extends WorldGenerator break;// skipped case 6: - res = WarpDriveConfig.getIC2Item("glassFiberCableItem").copy(); - res.stackSize = 2 + rand.nextInt(12); + res = WarpDriveConfig.i.getIC2Item("glassFiberCableItem").copy(); + res.stackSize = 2 + rand.nextInt(63); isDone = true; break; case 7: - res = WarpDriveConfig.getIC2Item("matter").copy(); - res.stackSize = 2 + rand.nextInt(14); + res = WarpDriveConfig.i.getIC2Item("matter").copy(); + res.stackSize = 2 + rand.nextInt(63); isDone = true; break; @@ -645,10 +645,10 @@ public class WorldGenSmallShip extends WorldGenerator // AE Quarz case 9: - if (WarpDriveConfig.isAppliedEnergisticsLoaded) + if (WarpDriveConfig.i.isAELoaded) { - res = WarpDriveConfig.getAEMaterial("matQuartz").copy(); - res.stackSize = 2 + rand.nextInt(22); + res = WarpDriveConfig.i.getAEMaterial("matQuartz").copy(); + res.stackSize = 2 + rand.nextInt(63); isDone = true; } @@ -656,37 +656,37 @@ public class WorldGenSmallShip extends WorldGenerator // AE improved processor case 10: - if (WarpDriveConfig.isAppliedEnergisticsLoaded) + if (WarpDriveConfig.i.isAELoaded) { - res = WarpDriveConfig.getAEMaterial("matProcessorAdvanced").copy(); - res.stackSize = 1 + rand.nextInt(3); + res = WarpDriveConfig.i.getAEMaterial("matProcessorAdvanced").copy(); + res.stackSize = 2 + rand.nextInt(63); isDone = true; } break; // Rocket launcher platform Tier3 case 11: - if (WarpDriveConfig.isICBMLoaded) + if (WarpDriveConfig.i.isICBMLoaded) { - res = new ItemStack(WarpDriveConfig.ICBM_Machine, 1 + rand.nextInt(1), 2).copy(); + res = new ItemStack(WarpDriveConfig.i.ICBM_Machine, 2 + rand.nextInt(1), 2).copy(); isDone = true; } break; // Missles from conventional to hypersonic case 12: - if (WarpDriveConfig.isICBMLoaded) + if (WarpDriveConfig.i.isICBMLoaded) { - res = new ItemStack(WarpDriveConfig.ICBM_Missile, 2 + rand.nextInt(1), rand.nextInt(10)).copy(); + res = new ItemStack(WarpDriveConfig.i.ICBM_Missile, 2 + rand.nextInt(1), rand.nextInt(21)).copy(); isDone = true; } break; // Advanced solar panels case 13: - if (WarpDriveConfig.isAdvSolPanelLoaded) + if (WarpDriveConfig.i.isAdvSolPanelLoaded) { - res = new ItemStack(WarpDriveConfig.ASP, rand.nextInt(3), solarType).copy(); + res = new ItemStack(WarpDriveConfig.i.ASP, rand.nextInt(3), solarType).copy(); isDone = true; } break; diff --git a/src/cr0s/WarpDrive/WorldGenStation.java b/src/cr0s/WarpDrive/WorldGenStation.java index c2fced01..e91b1bf6 100644 --- a/src/cr0s/WarpDrive/WorldGenStation.java +++ b/src/cr0s/WarpDrive/WorldGenStation.java @@ -16,7 +16,8 @@ public class WorldGenStation { public WorldGenStation() { } - public static boolean generate(World world, Random rand, int i, int j, int k) { + public boolean generate(World world, Random rand, int i, int j, int k) + { world.setBlock(i + 1, j + 0, k + 3, Block.stone.blockID); world.setBlock(i + 1, j + 0, k + 12, Block.stone.blockID); world.setBlock(i + 1, j + 1, k + 3, Block.stone.blockID); diff --git a/src/cr0s/WarpDrive/WorldGenStructure.java b/src/cr0s/WarpDrive/WorldGenStructure.java index 90bd262a..263be895 100644 --- a/src/cr0s/WarpDrive/WorldGenStructure.java +++ b/src/cr0s/WarpDrive/WorldGenStructure.java @@ -2,31 +2,19 @@ package cr0s.WarpDrive; import java.util.Random; -import net.minecraft.block.Block; - public class WorldGenStructure { public static int getStoneBlock(boolean corrupted, Random rand) { if (corrupted && (rand.nextInt(15) == 1)) return 0; - - if (WarpDriveConfig.isICLoaded) { - return WarpDriveConfig.getIC2Item("reinforcedStone").itemID; - } else { - return Block.stone.blockID; - } + return WarpDriveConfig.i.getIC2Item("reinforcedStone").itemID; } public static int getGlassBlock(boolean corrupted, Random rand) { if (corrupted && (rand.nextInt(30) == 1)) return 0; - - if (WarpDriveConfig.isICLoaded) { - return WarpDriveConfig.getIC2Item("reinforcedGlass").itemID; - } else { - return Block.glass.blockID; - } + return WarpDriveConfig.i.getIC2Item("reinforcedGlass").itemID; } } diff --git a/src/cr0s/WarpDrive/api/IBreathingHelmet.java b/src/cr0s/WarpDrive/api/IBreathingHelmet.java deleted file mode 100644 index f8af02ff..00000000 --- a/src/cr0s/WarpDrive/api/IBreathingHelmet.java +++ /dev/null @@ -1,8 +0,0 @@ -package cr0s.WarpDrive.api; - -import net.minecraft.entity.Entity; - -public interface IBreathingHelmet { - public boolean canBreath(Entity player); - public boolean removeAir(Entity player); -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/client/WailaHandler.java-notcompiling b/src/cr0s/WarpDrive/client/WailaHandler.java-notcompiling deleted file mode 100644 index 15e9a887..00000000 --- a/src/cr0s/WarpDrive/client/WailaHandler.java-notcompiling +++ /dev/null @@ -1,48 +0,0 @@ -package cr0s.WarpDrive.client; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; -import mcp.mobius.waila.api.IWailaRegistrar; - -import java.util.List; - -import cr0s.WarpDrive.machines.TileEntityReactor; -import cr0s.WarpDrive.machines.WarpEnergyTE; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - -public class WailaHandler implements IWailaDataProvider { - @Override - public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) { - return null; - } - - @Override - public List getWailaHead(ItemStack itemStack, List toolTip, IWailaDataAccessor accessor, IWailaConfigHandler config) { - return toolTip; - } - - @Override - public List getWailaBody(ItemStack itemStack, List toolTip, IWailaDataAccessor accessor, IWailaConfigHandler config) { - if (accessor.getTileEntity() instanceof WarpEnergyTE) { - WarpEnergyTE energyTE = (WarpEnergyTE) accessor.getTileEntity(); - toolTip.add(String.format("Energy level %.0f %% (%d/%d EU)", (energyTE.getEnergyStored() * 100.0F / energyTE.getMaxEnergyStored()), energyTE.getEnergyStored(), + energyTE.getMaxEnergyStored())); - if (energyTE instanceof TileEntityReactor) { - TileEntityReactor reactorTE = (TileEntityReactor) energyTE; - toolTip.add(String.format("Cooldown remaining: %d s", Math.ceil(reactorTE.getCooldown() / 20))); - } - } - return toolTip; - } - - @Override - public List getWailaTail(ItemStack itemStack, List toolTip, IWailaDataAccessor accessor, IWailaConfigHandler config) { - return toolTip; - } - - public static void callbackRegister(IWailaRegistrar registrar) { - WailaHandler instance = new WailaHandler(); - registrar.registerBodyProvider(instance, WarpEnergyTE.class); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/item/ItemReactorLaserFocus.java b/src/cr0s/WarpDrive/item/ItemReactorLaserFocus.java deleted file mode 100644 index ec1ac5fe..00000000 --- a/src/cr0s/WarpDrive/item/ItemReactorLaserFocus.java +++ /dev/null @@ -1,134 +0,0 @@ -package cr0s.WarpDrive.item; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import ic2.api.reactor.IReactor; -import ic2.api.reactor.IReactorComponent; - -public class ItemReactorLaserFocus extends Item implements IReactorComponent -{ - private final static int maxHeat = 3000; - - public ItemReactorLaserFocus(int id) - { - super(id); - setMaxDamage(maxHeat); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.items.ReactorLaserFocus"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) - { - this.itemIcon = par1IconRegister.registerIcon("warpdrive:reactorFocus"); - } - - private static void damageComponent(ItemStack self,int damage) - { - //WarpDrive.debugPrint("ReactorCompDamage:" + damage); - int currDamage = self.getItemDamage(); - int nextDamage = Math.min(maxHeat,Math.max(0, currDamage + damage)); - self.setItemDamage(nextDamage); - } - - private static void balanceComponent(ItemStack self, ItemStack other) - { - final int selfBalance = 4; - int otherDamage = other.getItemDamage(); - int myDamage = self.getItemDamage(); - int newOne = (otherDamage + (selfBalance-1)*myDamage) / selfBalance; - int newTwo = otherDamage - (newOne - myDamage); - self.setItemDamage(newTwo); - other.setItemDamage(newOne); - } - - private static void coolComponent(ItemStack self, IReactorComponent comp, IReactor reactor, ItemStack stack, int x, int y) - { - int maxTransfer = maxHeat - self.getItemDamage(); - int compHeat = comp.getCurrentHeat(reactor, stack, x, y); - int transferHeat = - Math.min(compHeat,maxTransfer); - int retained = comp.alterHeat(reactor, stack, x, y, transferHeat); - damageComponent(self,retained - transferHeat); - } - - private static void coolReactor(IReactor reactor,ItemStack stack) - { - int reactorHeat = reactor.getHeat(); - int myHeat = stack.getItemDamage(); - int transfer = Math.min(maxHeat - myHeat,reactorHeat); - reactor.addHeat(-transfer); - damageComponent(stack,transfer); - } - - @Override - public void processChamber(IReactor reactor, ItemStack yourStack, int x, int y, boolean heatrun) - { - if(heatrun) - { - int[] xDif = {-1,0,0,1}; - int[] yDif = {0,-1,1,0}; - for(int i=0;i=0 && damage < potentialUnlocalized.length) { - if (cachedIS[damage] == null) { - cachedIS[damage] = new ItemStack(WarpDrive.componentItem,1,damage); - } - return cachedIS[damage]; - } - return null; - } - - public void registerRecipes() { - WarpDrive.debugPrint("Registering empty recipe"); - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(0),false,"nrn","r r","nrn", - 'r', Item.redstone, - 'n', Item.goldNugget)); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(1),false,"g","e","c", - 'g', Block.glass, - 'e', Item.enderPearl, - 'c', getIS(0))); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(2),false," g ","ede"," c ", - 'g', Block.glass, - 'e', Item.enderPearl, - 'd', Item.diamond, - 'c', getIS(0))); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(3),false," g ","rtr"," c ", - 'g', Block.glass, - 'r', "dyeBlue", - 't', Block.torchWood, - 'c', getIS(0))); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(4),false," l ","rcr"," l ", - 'l', "dyeWhite", - 'r', Item.coal, - 'c', getIS(0))); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(5),false,"g ","gwr","rwr", - 'g', Item.goldNugget, - 'r', Item.redstone, - 'w', "plankWood")); - - GameRegistry.addRecipe(new ShapedOreRecipe(getIS(6),false,"gig","iri","gig", - 'g', Item.goldNugget, - 'r', Item.redstone, - 'i', Item.ingotIron)); - } - - @Override - public void registerIcons(IconRegister par1IconRegister) { - for(int i = 0; i < potentialUnlocalized.length; i++) { - potentialIcons[i] = par1IconRegister.registerIcon("warpdrive:component" + potentialUnlocalized[i]); - } - } - - @Override - public String getUnlocalizedName(ItemStack itemSt) { - int damage = itemSt.getItemDamage(); - if (damage >= 0 && damage < potentialUnlocalized.length) { - return "item.warpdrive.crafting." + potentialUnlocalized[damage]; - } - return getUnlocalizedName(); - } - - @Override - @SideOnly(Side.CLIENT) - public Icon getIconFromDamage(int damage) { - if (damage >= 0 && damage < potentialUnlocalized.length) { - return potentialIcons[damage]; - } - return potentialIcons[0]; - } - - @Override - @SideOnly(Side.CLIENT) - public void getSubItems(int par1, CreativeTabs par2CreativeTabs, List par3List) { - for(int i = 0; i < potentialUnlocalized.length; i++) - par3List.add(new ItemStack(par1, 1, i)); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockCamera.java b/src/cr0s/WarpDrive/machines/BlockCamera.java deleted file mode 100644 index 9035ef81..00000000 --- a/src/cr0s/WarpDrive/machines/BlockCamera.java +++ /dev/null @@ -1,93 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.CamRegistryItem; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockCamera extends BlockContainer { - private Icon[] iconBuffer; - - private final int ICON_SIDE = 0; - - public BlockCamera(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.Camera"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[1]; - // Solid textures - iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("warpdrive:cameraSide"); - } - - @Override - public Icon getIcon(int side, int metadata) { - return iconBuffer[ICON_SIDE]; - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityCamera(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - // Get camera frequency - TileEntity te = par1World.getBlockTileEntity(x, y, z); - if (te != null && te instanceof TileEntityCamera) { - int frequency = ((TileEntityCamera)te).getFrequency(); - - CamRegistryItem cam = WarpDrive.instance.cams.getCamByFrequency(par1World, frequency); - if (cam == null) { - WarpDrive.instance.cams.printRegistry(par1World); - par5EntityPlayer.addChatMessage(getLocalizedName() + " Frequency '" + frequency + "' is invalid!"); - } else { - par5EntityPlayer.addChatMessage(getLocalizedName() + " Frequency '" + frequency + "' is valid for camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); - } - return true; - } - - return false; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockCloakingCoil.java b/src/cr0s/WarpDrive/machines/BlockCloakingCoil.java deleted file mode 100644 index 1ed9beca..00000000 --- a/src/cr0s/WarpDrive/machines/BlockCloakingCoil.java +++ /dev/null @@ -1,77 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockCloakingCoil extends Block { - private Icon[] iconBuffer; - - public BlockCloakingCoil(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.CloakingCoil"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[3]; - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:cloakCoilSide"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:cloakCoilSideActive"); - iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:cloakCoilTop"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 0) { - return iconBuffer[2]; - } else if (side == 1) { - return iconBuffer[2]; - } - if (metadata == 0) { - return iconBuffer[0]; - } else if (metadata == 1) { - return iconBuffer[1]; - } else { - return null; - } - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { - TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { - te.invalidate(); - } - - super.breakBlock(par1World, par2, par3, par4, par5, par6); - } -} diff --git a/src/cr0s/WarpDrive/machines/BlockCloakingDeviceCore.java b/src/cr0s/WarpDrive/machines/BlockCloakingDeviceCore.java deleted file mode 100644 index df910706..00000000 --- a/src/cr0s/WarpDrive/machines/BlockCloakingDeviceCore.java +++ /dev/null @@ -1,100 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockCloakingDeviceCore extends BlockContainer { - private Icon[] iconBuffer; - - public BlockCloakingDeviceCore(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.CloakingDeviceCore"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[2]; - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:cloakingCoreInactive"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:cloakingCoreActive"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (metadata < iconBuffer.length) { - return iconBuffer[metadata]; - } else { - return null; - } - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityCloakingDeviceCore(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - TileEntityCloakingDeviceCore te = (TileEntityCloakingDeviceCore)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus() + "\n" -// + " Valid? " + te.isValid + " Cloaking? " + te.isCloaking + " Enabled? " + te.isEnabled + "\n" - + ((!te.isValid) ? "Invalid assembly!" : - ((!te.isEnabled) ? "Cloak is disabled" : - ((te.isCloaking) ? "A tier " + te.tier + " cloak is currently covering " + te.volume + " blocks!" : "Cloak needs more power!")))); - return true; - } - - return false; - } - - @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { - TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - - if (te != null && te instanceof TileEntityCloakingDeviceCore) { - ((TileEntityCloakingDeviceCore)te).isEnabled = false; - ((TileEntityCloakingDeviceCore)te).disableCloakingField(); - - te.invalidate(); - } - - super.breakBlock(par1World, par2, par3, par4, par5, par6); - } -} diff --git a/src/cr0s/WarpDrive/machines/BlockLaserCam.java b/src/cr0s/WarpDrive/machines/BlockLaserCam.java deleted file mode 100644 index e1be2900..00000000 --- a/src/cr0s/WarpDrive/machines/BlockLaserCam.java +++ /dev/null @@ -1,91 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.CamRegistryItem; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockLaserCam extends BlockContainer { - private Icon[] iconBuffer; - - private final int ICON_SIDE = 0; - - public BlockLaserCam(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.LaserCamera"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[1]; - // Solid textures - iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("warpdrive:laserSideCam"); - } - - @Override - public Icon getIcon(int side, int metadata) { - return iconBuffer[ICON_SIDE]; - } - - @Override - public TileEntity createNewTileEntity(World parWorld) { - return new TileEntityLaser(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - // Get camera frequency - TileEntity te = par1World.getBlockTileEntity(x, y, z); - if (te != null && te instanceof TileEntityLaser && (par5EntityPlayer.getHeldItem() == null)) { - int beamFrequency = ((TileEntityLaser)te).getBeamFrequency(); - int cameraFrequency = ((TileEntityLaser)te).getCameraFrequency(); - - CamRegistryItem cam = WarpDrive.instance.cams.getCamByFrequency(par1World, cameraFrequency); - par5EntityPlayer.addChatMessage(getLocalizedName() - + ": Beam frequency '" + beamFrequency + "' is " + ((beamFrequency < 0) ? "invalid!":"valid.") - + " Camera frequency '" + cameraFrequency + "' is " + ((cam == null) ? "invalid!":"valid for laser-camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z)); - return true; - } - - return false; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockLaserReactorMonitor.java b/src/cr0s/WarpDrive/machines/BlockLaserReactorMonitor.java deleted file mode 100644 index 63b46418..00000000 --- a/src/cr0s/WarpDrive/machines/BlockLaserReactorMonitor.java +++ /dev/null @@ -1,38 +0,0 @@ -package cr0s.WarpDrive.machines; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -public class BlockLaserReactorMonitor extends BlockContainer { - public BlockLaserReactorMonitor(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.LaserReactorMonitor"); - } - - public BlockLaserReactorMonitor(int id, Material material) { - this(id, 0, material); - } - - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - // Solid textures - blockIcon = par1IconRegister.registerIcon("warpdrive:reactorMonitor"); - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityLaserReactorMonitor(); - } -} diff --git a/src/cr0s/WarpDrive/machines/BlockMiningLaser.java b/src/cr0s/WarpDrive/machines/BlockMiningLaser.java deleted file mode 100644 index 62cbbc03..00000000 --- a/src/cr0s/WarpDrive/machines/BlockMiningLaser.java +++ /dev/null @@ -1,100 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockMiningLaser extends BlockContainer { - private Icon[] iconBuffer; - private final static int ICON_TOP = 5; - public final static int ICON_IDLE = 0; - public final static int ICON_MININGLOWPOWER = 1; - public final static int ICON_MININGPOWERED = 2; - public final static int ICON_SCANNINGLOWPOWER = 3; - public final static int ICON_SCANNINGPOWERED = 4; - - public BlockMiningLaser(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.MiningLaser"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[16]; - // Solid textures - iconBuffer[ICON_TOP ] = par1IconRegister.registerIcon("warpdrive:particleBoosterTopBottom"); - iconBuffer[ICON_IDLE ] = par1IconRegister.registerIcon("warpdrive:miningLaser_idle"); - iconBuffer[ICON_MININGLOWPOWER ] = par1IconRegister.registerIcon("warpdrive:miningLaser_miningLowPower"); - iconBuffer[ICON_MININGPOWERED ] = par1IconRegister.registerIcon("warpdrive:miningLaser_miningPowered"); - iconBuffer[ICON_SCANNINGLOWPOWER] = par1IconRegister.registerIcon("warpdrive:miningLaser_scanningLowPower"); - iconBuffer[ICON_SCANNINGPOWERED ] = par1IconRegister.registerIcon("warpdrive:miningLaser_scanningPowered"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 0 || side == 1) { - return iconBuffer[ICON_TOP]; - } - if (metadata < iconBuffer.length) { - return iconBuffer[metadata]; - } else { - return null; - } - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityMiningLaser(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - TileEntityMiningLaser miningLaser = (TileEntityMiningLaser)par1World.getBlockTileEntity(par2, par3, par4); - - if (miningLaser != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(miningLaser.getStatus()); - return true; - } - - return false; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockMonitor.java b/src/cr0s/WarpDrive/machines/BlockMonitor.java deleted file mode 100644 index 08a563e2..00000000 --- a/src/cr0s/WarpDrive/machines/BlockMonitor.java +++ /dev/null @@ -1,106 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.CamRegistryItem; -import cr0s.WarpDrive.ClientCameraUtils; -import cr0s.WarpDrive.EntityCamera; -import cr0s.WarpDrive.WarpDrive; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockMonitor extends BlockContainer { - private Icon iconFront; - private Icon iconBlock; - - public BlockMonitor(int id) { - super(id, Material.iron); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.Monitor"); - } - - @Override - @SideOnly(Side.CLIENT) - - /** - * From the specified side and block metadata retrieves the blocks texture. Args: side, metadata - */ - public Icon getIcon(int side, int parMetadata) { - int meta = parMetadata & 3; - return side == 2 ? (meta == 0 ? this.iconFront : this.iconBlock) : (side == 3 ? (meta == 2 ? this.iconFront : this.iconBlock) : (side == 4 ? (meta == 3 ? this.iconFront : this.iconBlock) : (side == 5 ? (meta == 1 ? this.iconFront : this.iconBlock) : this.iconBlock))); - } - - /** - * When this method is called, your block should register all the icons it needs with the given IconRegister. This - * is the only chance you get to register icons. - */ - @Override - public void registerIcons(IconRegister reg) { - this.iconFront = reg.registerIcon("warpdrive:monitorFront"); - this.iconBlock = reg.registerIcon("warpdrive:monitorSide"); - } - - /** - * Called when the block is placed in the world. - */ - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack itemstack) { - int dir = Math.round(entityliving.rotationYaw / 90.0F) & 3; - world.setBlockMetadataWithNotify(x, y, z, dir, 3); - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - // Monitor is only reacting client side - if (!FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - // Get camera frequency - TileEntity te = par1World.getBlockTileEntity(x, y, z); - - if (te != null && te instanceof TileEntityMonitor && (par5EntityPlayer.getHeldItem() == null)) { - int frequency = ((TileEntityMonitor)te).getFrequency(); - WarpDrive.instance.cams.removeDeadCams(par1World); - CamRegistryItem cam = WarpDrive.instance.cams.getCamByFrequency(par1World, frequency); - if (cam == null) { - par5EntityPlayer.addChatMessage(getLocalizedName() + " Frequency '" + frequency + "' is invalid or camera is too far!"); - return false; - } else { - par5EntityPlayer.addChatMessage(getLocalizedName() + " Frequency '" + frequency + "' is valid. Viewing camera at " + cam.position.x + ", " + cam.position.y + ", " + cam.position.z); - // Spawn camera entity - EntityCamera e = new EntityCamera(par1World, cam.position, par5EntityPlayer); - par1World.spawnEntityInWorld(e); - e.setPositionAndUpdate(cam.position.x + 0.5D, cam.position.y + 0.5D, cam.position.z + 0.5D); - //e.setPositionAndRotation(camPos.x, camPos.y, camPos.z, entityplayer.rotationYaw, entityplayer.rotationPitch); - WarpDrive.instance.overlayType = cam.type; - ClientCameraUtils.setupViewpoint(par5EntityPlayer, e, x, y, z, blockID, cam.position.x, cam.position.y, cam.position.z, par1World.getBlockId(cam.position.x, cam.position.y, cam.position.z)); - } - } - - return false; - } - - @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { - } - - @Override - public TileEntity createNewTileEntity(World world) { - return new TileEntityMonitor(); - } -} diff --git a/src/cr0s/WarpDrive/machines/BlockParticleBooster.java b/src/cr0s/WarpDrive/machines/BlockParticleBooster.java deleted file mode 100644 index 0b9e7a2f..00000000 --- a/src/cr0s/WarpDrive/machines/BlockParticleBooster.java +++ /dev/null @@ -1,105 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockParticleBooster extends BlockContainer { - private Icon[] iconBuffer; - - public BlockParticleBooster(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.ParticleBooster"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[16]; - iconBuffer[ 0] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide0"); - iconBuffer[ 1] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide1"); - iconBuffer[ 2] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide2"); - iconBuffer[ 3] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide3"); - iconBuffer[ 4] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide4"); - iconBuffer[ 5] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide5"); - iconBuffer[ 6] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide6"); - iconBuffer[ 7] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide7"); - iconBuffer[ 8] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide8"); - iconBuffer[ 9] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide9"); - iconBuffer[10] = par1IconRegister.registerIcon("warpdrive:particleBoosterSide10"); - iconBuffer[11] = par1IconRegister.registerIcon("warpdrive:particleBoosterTopBottom"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 0 || side == 1) { - return iconBuffer[11]; - } - - return iconBuffer[metadata]; - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityParticleBooster(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus()); - return true; - } - - return false; - } - - @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { - TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { - te.invalidate(); - } - - super.breakBlock(par1World, par2, par3, par4, par5, par6); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockPowerLaser.java b/src/cr0s/WarpDrive/machines/BlockPowerLaser.java deleted file mode 100644 index 94f45d45..00000000 --- a/src/cr0s/WarpDrive/machines/BlockPowerLaser.java +++ /dev/null @@ -1,86 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockPowerLaser extends BlockContainer { - static Icon[] iconBuffer = new Icon[16]; - public BlockPowerLaser(int id) { - super(id, Material.iron); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.power.Laser"); - setResistance(100.0F); - } - - @Override - public TileEntity createNewTileEntity(World world) { - return new TileEntityPowerLaser(); - } - - @Override - public void onBlockAdded(World w,int x,int y, int z) { - TileEntity te = w.getBlockTileEntity(x, y, z); - if (te instanceof TileEntityPowerLaser) { - ((TileEntityPowerLaser)te).scanForReactor(); - } - } - - @Override - public void onNeighborBlockChange(World w, int x, int y, int z, int b) { - TileEntity te = w.getBlockTileEntity(x, y, z); - if (te instanceof TileEntityPowerLaser) { - ((TileEntityPowerLaser)te).updateNeighbours(); - } - } - - private static boolean isActive(int side, int meta) { - if (side == 3 && meta == 1) { - return true; - } - - if (side == 2 && meta == 2) { - return true; - } - - if (side == 4 && meta == 4) { - return true; - } - - if (side == 5 && meta == 3) { - return true; - } - return false; - } - - @Override - @SideOnly(Side.CLIENT) - public Icon getIcon(int side, int meta) { - if (side == 0 || side == 1) { - return iconBuffer[0]; - } - - if(isActive(side,meta)) { - return iconBuffer[2]; - } - - return iconBuffer[1]; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:powerLaserTopBottom"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:powerLaserSides"); - iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:powerLaserActive"); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockPowerReactor.java b/src/cr0s/WarpDrive/machines/BlockPowerReactor.java deleted file mode 100644 index 3db9d5c4..00000000 --- a/src/cr0s/WarpDrive/machines/BlockPowerReactor.java +++ /dev/null @@ -1,95 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockPowerReactor extends BlockContainer { - Icon[] iconBuffer = new Icon[17]; - - public BlockPowerReactor(int id) { - super(id, Material.iron); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.power.Reactor"); - } - - @Override - public TileEntity createNewTileEntity(World world) { - return new TileEntityPowerReactor(); - } - - @Override - public void onBlockAdded(World w,int x, int y,int z) { - super.onBlockAdded(w, x, y, z); - - TileEntity te = w.getBlockTileEntity(x, y, z); - if(te instanceof TileEntityPowerReactor) { - ((TileEntityPowerReactor)te).updateNeighbours(); - } - } - - @Override - public void onNeighborBlockChange(World w,int x,int y,int z,int b) { - TileEntity te = w.getBlockTileEntity(x, y, z); - if(te instanceof TileEntityPowerReactor) { - ((TileEntityPowerReactor)te).updateNeighbours(); - } - } - - @Override - public void breakBlock(World w,int x,int y,int z, int oid,int om) { - super.breakBlock(w, x, y, z, oid, om); - - int[] xo = {-2, 2, 0, 0}; - int[] zo = { 0, 0,-2, 2}; - for(int i = 0; i < 4; i++) { - TileEntity te = w.getBlockTileEntity(x+xo[i], y, z+zo[i]); - if(te instanceof TileEntityPowerLaser) { - ((TileEntityPowerLaser)te).unlink(); - } - } - } - - @Override - @SideOnly(Side.CLIENT) - public Icon getIcon(int side, int meta) { - if (side == 0 || side == 1) { - return iconBuffer[16]; - } - if (meta >= 0 && meta < 16) { - return iconBuffer[meta]; - } - return iconBuffer[0]; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer[16] = par1IconRegister.registerIcon("warpdrive:reactorTB"); - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:reactorSide00"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:reactorSide01"); - iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:reactorSide02"); - iconBuffer[3] = par1IconRegister.registerIcon("warpdrive:reactorSide03"); - iconBuffer[4] = par1IconRegister.registerIcon("warpdrive:reactorSide10"); - iconBuffer[5] = par1IconRegister.registerIcon("warpdrive:reactorSide11"); - iconBuffer[6] = par1IconRegister.registerIcon("warpdrive:reactorSide12"); - iconBuffer[7] = par1IconRegister.registerIcon("warpdrive:reactorSide13"); - iconBuffer[8] = par1IconRegister.registerIcon("warpdrive:reactorSide20"); - iconBuffer[9] = par1IconRegister.registerIcon("warpdrive:reactorSide21"); - iconBuffer[10] = par1IconRegister.registerIcon("warpdrive:reactorSide22"); - iconBuffer[11] = par1IconRegister.registerIcon("warpdrive:reactorSide23"); - iconBuffer[12] = par1IconRegister.registerIcon("warpdrive:reactorSide30"); - iconBuffer[13] = par1IconRegister.registerIcon("warpdrive:reactorSide31"); - iconBuffer[14] = par1IconRegister.registerIcon("warpdrive:reactorSide32"); - iconBuffer[15] = par1IconRegister.registerIcon("warpdrive:reactorSide33"); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockProtocol.java b/src/cr0s/WarpDrive/machines/BlockProtocol.java deleted file mode 100644 index fdbe6619..00000000 --- a/src/cr0s/WarpDrive/machines/BlockProtocol.java +++ /dev/null @@ -1,111 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockProtocol extends BlockContainer { - private Icon[] iconBuffer; - - private final int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_TOP = 2, ICON_SIDE_ACTIVATED = 3; - - public BlockProtocol(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.WarpProtocol"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[10]; - // Solid textures - iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("warpdrive:contSideInactive"); - iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("warpdrive:contBottom"); - iconBuffer[ICON_TOP] = par1IconRegister.registerIcon("warpdrive:contTop"); - // Animated textures - iconBuffer[ICON_SIDE_ACTIVATED ] = par1IconRegister.registerIcon("warpdrive:contSideActive0"); - iconBuffer[ICON_SIDE_ACTIVATED + 1] = par1IconRegister.registerIcon("warpdrive:contSideActive1"); - iconBuffer[ICON_SIDE_ACTIVATED + 2] = par1IconRegister.registerIcon("warpdrive:contSideActive2"); - iconBuffer[ICON_SIDE_ACTIVATED + 3] = par1IconRegister.registerIcon("warpdrive:contSideActive3"); - iconBuffer[ICON_SIDE_ACTIVATED + 4] = par1IconRegister.registerIcon("warpdrive:contSideActive4"); - iconBuffer[ICON_SIDE_ACTIVATED + 5] = par1IconRegister.registerIcon("warpdrive:contSideActive5"); - iconBuffer[ICON_SIDE_ACTIVATED + 6] = par1IconRegister.registerIcon("warpdrive:contSideActive6"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 0) { - return iconBuffer[ICON_BOTTOM]; - } else if (side == 1) { - return iconBuffer[ICON_TOP]; - } - - if (metadata == 0) { // Inactive state - return iconBuffer[ICON_INACTIVE_SIDE]; - } else if (metadata > 0) { // Activated, in metadata stored mode number - if (ICON_SIDE_ACTIVATED + metadata - 1 < iconBuffer.length) { - return iconBuffer[ICON_SIDE_ACTIVATED + metadata]; - } else { - return null; - } - } - - return null; - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityProtocol(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - if (par5EntityPlayer.getHeldItem() == null) { - TileEntityProtocol controller = (TileEntityProtocol)par1World.getBlockTileEntity(par2, par3, par4); - if (controller != null) { - controller.attachPlayer(par5EntityPlayer); - par5EntityPlayer.addChatMessage(controller.getBlockType().getLocalizedName() + " Attached players: " + controller.getAttachedPlayersList()); - return true; - } - } - - return false; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockShipScanner.java b/src/cr0s/WarpDrive/machines/BlockShipScanner.java deleted file mode 100644 index d37d9737..00000000 --- a/src/cr0s/WarpDrive/machines/BlockShipScanner.java +++ /dev/null @@ -1,96 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockShipScanner extends BlockContainer { - private Icon[] iconBuffer; - - public BlockShipScanner(int id, int texture, Material material) { - super(id, material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.Scanner"); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[3]; - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:shipScannerUp"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:shipScannerSide"); - iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:contBottom"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 1) { // UP - return iconBuffer[0]; - } else if (side == 0) { // DOWN - return iconBuffer[2]; - } - - return iconBuffer[1]; - } - - @Override - public TileEntity createNewTileEntity(World var1) { - return new TileEntityShipScanner(); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } - - /** - * Called upon block activation (right click on the block.) - */ - @Override - public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return false; - } - - WarpEnergyTE te = (WarpEnergyTE)par1World.getBlockTileEntity(par2, par3, par4); - if (te != null && (par5EntityPlayer.getHeldItem() == null)) { - par5EntityPlayer.addChatMessage(te.getStatus()); - return true; - } - - return false; - } - - @Override - public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { - TileEntity te = par1World.getBlockTileEntity(par2, par3, par4); - if (te != null) { - te.invalidate(); - } - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/BlockTransporter.java b/src/cr0s/WarpDrive/machines/BlockTransporter.java deleted file mode 100644 index 285bda6d..00000000 --- a/src/cr0s/WarpDrive/machines/BlockTransporter.java +++ /dev/null @@ -1,67 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.Random; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import cr0s.WarpDrive.WarpDrive; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IconRegister; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Icon; -import net.minecraft.world.World; - -public class BlockTransporter extends BlockContainer { - - private Icon[] iconBuffer; - - public BlockTransporter(int par1, Material par2Material) { - super(par1, par2Material); - setHardness(0.5F); - setStepSound(Block.soundMetalFootstep); - setCreativeTab(WarpDrive.warpdriveTab); - setUnlocalizedName("warpdrive.machines.Transporter"); - } - - @Override - public TileEntity createNewTileEntity(World world) { - return new TileEntityTransporter(); - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons(IconRegister par1IconRegister) { - iconBuffer = new Icon[3]; - // Solid textures - iconBuffer[0] = par1IconRegister.registerIcon("warpdrive:transporterBottom"); - iconBuffer[1] = par1IconRegister.registerIcon("warpdrive:transporterTop"); - iconBuffer[2] = par1IconRegister.registerIcon("warpdrive:transporterSide"); - } - - @Override - public Icon getIcon(int side, int metadata) { - if (side == 0 || side == 1) { - return iconBuffer[side]; - } - - return iconBuffer[2]; - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - @Override - public int quantityDropped(Random par1Random) { - return 1; - } - - /** - * Returns the ID of the items to drop on destruction. - */ - @Override - public int idDropped(int par1, Random par2Random, int par3) { - return this.blockID; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/TileEntityAbstractLaser.java b/src/cr0s/WarpDrive/machines/TileEntityAbstractLaser.java deleted file mode 100644 index 87fd4d5b..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityAbstractLaser.java +++ /dev/null @@ -1,8 +0,0 @@ -package cr0s.WarpDrive.machines; - - - -public abstract class TileEntityAbstractLaser extends WarpChunkTE -{ - -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityAbstractMiner.java b/src/cr0s/WarpDrive/machines/TileEntityAbstractMiner.java deleted file mode 100644 index 889cb036..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityAbstractMiner.java +++ /dev/null @@ -1,549 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.ArrayList; -import java.util.List; - -import appeng.api.IAEItemStack; -import appeng.api.Util; -import appeng.api.WorldCoord; -import appeng.api.events.GridTileLoadEvent; -import appeng.api.events.GridTileUnloadEvent; -import appeng.api.me.tiles.IGridMachine; -import appeng.api.me.tiles.ITileCable; -import appeng.api.me.util.IGridInterface; -import appeng.api.me.util.IMEInventoryHandler; -import net.minecraft.block.Block; -import net.minecraft.block.BlockFluid; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.ChunkCoordIntPair; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; -import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -import cr0s.WarpDrive.WarpDriveConfig; - -public abstract class TileEntityAbstractMiner extends TileEntityAbstractLaser implements IGridMachine, ITileCable -{ - - //FOR STORAGE - private boolean silkTouch = false; - private int fortuneLevel = 0; - - private TileEntityParticleBooster booster = null; - private Vector3 minerVector; - - Boolean powerStatus = false; - private IGridInterface grid; - private boolean isMEReady = false; - - abstract boolean canSilkTouch(); - abstract int minFortune(); - abstract int maxFortune(); - abstract double laserBelow(); - - abstract float getColorR(); - abstract float getColorG(); - abstract float getColorB(); - - public TileEntityAbstractMiner() - { - super(); - fixMinerVector(); - } - - private void fixMinerVector() - { - if(minerVector == null) - minerVector = new Vector3(xCoord,yCoord-laserBelow(),zCoord); - minerVector.x = xCoord; - minerVector.y = yCoord - (laserBelow()); - minerVector.z = zCoord; - minerVector.translate(0.5); - } - - private List getItemStackFromBlock(int i, int j, int k, int blockID, int blockMeta) - { - Block block = Block.blocksList[blockID]; - if (block == null) - return null; - if (silkTouch(blockID)) - { - if (block.canSilkHarvest(worldObj, null, i, j, k, blockMeta)) - { - ArrayList t = new ArrayList(); - t.add(new ItemStack(blockID, 1, blockMeta)); - return t; - } - } - return block.getBlockDropped(worldObj, i, j, k, blockMeta, fortuneLevel); - } - - protected boolean isOnEarth() - { - return worldObj.provider.dimensionId == 0; - } - - private IInventory findChest() { - TileEntity result = null; - - for(int i = 0; i < 6; i++) { - Vector3 sideOffset = adjacentSideOffsets[i]; - result = worldObj.getBlockTileEntity(xCoord + sideOffset.intX(), yCoord + sideOffset.intY(), zCoord + sideOffset.intZ()); - if (result != null && !(result instanceof TileEntityAbstractMiner) && (result instanceof IInventory)) { - return (IInventory) result; - } - } - return null; - } - - //GETTERSETTERS - - protected int fortune() - { - return fortuneLevel; - } - - protected boolean silkTouch() - { - return silkTouch; - } - - protected boolean silkTouch(int blockID) - { - return silkTouch(); - } - - protected boolean silkTouch(boolean b) - { - silkTouch = canSilkTouch() && b; - return silkTouch(); - } - - protected boolean silkTouch(Object o) - { - return silkTouch(toBool(o)); - } - - protected int fortune(int f) - { - try - { - fortuneLevel = clamp(f,minFortune(),maxFortune()); - } - catch(NumberFormatException e) - { - fortuneLevel = minFortune(); - } - return fortune(); - } - - protected TileEntityParticleBooster booster() - { - if(booster == null) - findFirstBooster(); - return booster; - } - - protected int energy() { - TileEntityParticleBooster te = booster(); - if (te != null) { - return te.getEnergyStored(); - } - return 0; - } - - //DATA RET - - protected int calculateLayerCost() - { - return isOnEarth() ? WarpDriveConfig.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.ML_EU_PER_LAYER_SPACE; - } - - protected int calculateBlockCost() - { - return calculateBlockCost(0); - } - - protected int calculateBlockCost(int blockID) - { - int enPerBlock = isOnEarth() ? WarpDriveConfig.ML_EU_PER_BLOCK_EARTH : WarpDriveConfig.ML_EU_PER_BLOCK_SPACE; - if(silkTouch(blockID)) - return (int) Math.round(enPerBlock * WarpDriveConfig.ML_EU_MUL_SILKTOUCH); - return (int) Math.round(enPerBlock * (Math.pow(WarpDriveConfig.ML_EU_MUL_FORTUNE, fortune()))); - } - - protected boolean isRoomForHarvest() - { - if(isMEReady && grid != null) - return true; - - IInventory inv = findChest(); - if(inv != null) - { - int size = inv.getSizeInventory(); - for(int i=0;i stacks = getItemStackFromBlock(valuable.intX(), valuable.intY(), valuable.intZ(), blockID, blockMeta); - if (stacks != null) - { - for (ItemStack stack : stacks) - { - didPlace = didPlace && dumpToInv(stack) == stack.stackSize; - } - } - mineBlock(valuable,blockID,blockMeta); - return didPlace; - } - else if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID) - // Evaporate water - worldObj.playSoundEffect(valuable.intX() + 0.5D, valuable.intY() + 0.5D, valuable.intZ() + 0.5D, "random.fizz", 0.5F, 2.6F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.8F); - worldObj.setBlockToAir(valuable.intX(), valuable.intY(), valuable.intZ()); - return true; - } - - protected int dumpToInv(ItemStack item) - { - if (grid != null) - return putInGrid(item); - else - return putInChest(findChest(), item); - } - - private int putInGrid(ItemStack itemStackSource) - { - int transferred = 0; - if(isMEReady && grid != null) - { - IMEInventoryHandler cellArray = grid.getCellArray(); - if (cellArray != null) - { - IAEItemStack ret = cellArray.addItems(Util.createItemStack(itemStackSource)); - if (ret != null) - transferred = (int) ret.getStackSize(); - } - } - return transferred; - } - - private static int putInChest(IInventory inventory, ItemStack itemStackSource) - { - if (inventory == null || itemStackSource == null) - { - return 0; - } - - int transferred = 0; - - for (int i = 0; i < inventory.getSizeInventory(); i++) - { - if (!inventory.isItemValidForSlot(i, itemStackSource)) - { - continue; - } - - ItemStack itemStack = inventory.getStackInSlot(i); - - if (itemStack == null || !itemStack.isItemEqual(itemStackSource)) - { - continue; - } - - int transfer = Math.min(itemStackSource.stackSize - transferred, itemStack.getMaxStackSize() - itemStack.stackSize); - itemStack.stackSize += transfer; - transferred += transfer; - - if (transferred == itemStackSource.stackSize) - { - return transferred; - } - } - - for (int i = 0; i < inventory.getSizeInventory(); i++) - { - if (!inventory.isItemValidForSlot(i, itemStackSource)) - { - continue; - } - - ItemStack itemStack = inventory.getStackInSlot(i); - - if (itemStack != null) - { - continue; - } - - int transfer = Math.min(itemStackSource.stackSize - transferred, itemStackSource.getMaxStackSize()); - ItemStack dest = copyWithSize(itemStackSource, transfer); - inventory.setInventorySlotContents(i, dest); - transferred += transfer; - - if (transferred == itemStackSource.stackSize) - { - return transferred; - } - } - - return transferred; - } - - protected boolean consumeEnergyFromBooster(int requiredEnergy, boolean simulate) - { - TileEntityParticleBooster te = booster(); - if (te != null) { - return te.consumeEnergy(requiredEnergy, simulate); - } - return false; - } - - private TileEntityParticleBooster findFirstBooster() - { - TileEntity result; - int[] xPos = {1,-1,0,0,0,0}; - int[] yPos = {0,0,-1,1,0,0}; - int[] zPos = {0,0,0,0,-1,1}; - - for(int i=0;i<6;i++) - { - result = worldObj.getBlockTileEntity(xCoord + xPos[i], yCoord + yPos[i], zCoord + zPos[i]); - - if (result != null && result instanceof TileEntityParticleBooster) - { - booster = (TileEntityParticleBooster) result; - return (TileEntityParticleBooster) result; - } - } - booster = null; - return null; - } - - protected void defineMiningArea(int xSize,int zSize) - { - int xmax, zmax, x1, x2, z1, z2; - int xmin, zmin; - x1 = xCoord + xSize / 2; - x2 = xCoord - xSize / 2; - - if (x1 < x2) - { - xmin = x1; - xmax = x2; - } - else - { - xmin = x2; - xmax = x1; - } - - z1 = zCoord + zSize / 2; - z2 = zCoord - zSize / 2; - - if (z1 < z2) - { - zmin = z1; - zmax = z2; - } - else - { - zmin = z2; - zmax = z1; - } - - defineMiningArea(xmin,zmin,xmax,zmax); - } - - protected void defineMiningArea(int minX, int minZ, int maxX, int maxZ) - { - if(worldObj == null) - return; - ChunkCoordIntPair a = worldObj.getChunkFromBlockCoords(minX, minZ).getChunkCoordIntPair(); - ChunkCoordIntPair b = worldObj.getChunkFromBlockCoords(maxX, maxZ).getChunkCoordIntPair(); - if(minChunk != null && a.equals(minChunk)) - if(maxChunk != null && b.equals(maxChunk)) - return; - if(minChunk != null && b.equals(minChunk)) - if(maxChunk != null && a.equals(maxChunk)) - return; - minChunk = a; - maxChunk = b; - refreshLoading(true); - } - - private static ItemStack copyWithSize(ItemStack itemStack, int newSize) - { - ItemStack ret = itemStack.copy(); - ret.stackSize = newSize; - return ret; - } - - //NBT DATA - @Override - public void readFromNBT(NBTTagCompound tag) - { - super.readFromNBT(tag); - silkTouch = tag.getBoolean("silkTouch"); - fortuneLevel = tag.getInteger("fortuneLevel"); - - minerVector.x = xCoord; - minerVector.y = yCoord - (laserBelow()); - minerVector.z = zCoord; - minerVector = minerVector.translate(0.5); - } - - @Override - public void writeToNBT(NBTTagCompound tag) - { - super.writeToNBT(tag); - tag.setBoolean("silkTouch", silkTouch); - tag.setInteger("fortuneLevel", fortuneLevel); - } - - //AE INTERFACE - @Override - public void setNetworkReady( boolean isReady ) - { - isMEReady = isReady; - } - - @Override - public boolean isMachineActive() - { - return isMEReady; - } - - //OVERRIDES - @Override - public void updateEntity() - { - if(shouldChunkLoad() != areChunksLoaded) - refreshLoading(); - - } - - @Override - public float getPowerDrainPerTick() - { - return 1; - } - - @Override - public void validate() - { - super.validate(); - MinecraftForge.EVENT_BUS.post(new GridTileLoadEvent(this, worldObj, getLocation())); - } - - @Override - public void invalidate() - { - super.invalidate(); - MinecraftForge.EVENT_BUS.post(new GridTileUnloadEvent(this, worldObj, getLocation())); - } - - @Override - public WorldCoord getLocation() - { - return new WorldCoord(xCoord, yCoord, zCoord); - } - - @Override - public boolean isValid() - { - return true; - } - - @Override - public void setPowerStatus(boolean hasPower) - { - powerStatus = hasPower; - } - - @Override - public boolean isPowered() - { - return powerStatus; - } - - @Override - public IGridInterface getGrid() - { - return grid; - } - - @Override - public void setGrid(IGridInterface gi) - { - grid = gi; - } - - @Override - public boolean coveredConnections() - { - return true; - } - - @Override - public World getWorld() - { - return worldObj; - } - -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityAirGenerator.java b/src/cr0s/WarpDrive/machines/TileEntityAirGenerator.java deleted file mode 100644 index 9bc76317..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityAirGenerator.java +++ /dev/null @@ -1,98 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.WarpDriveConfig; -import net.minecraft.nbt.NBTTagCompound; - -public class TileEntityAirGenerator extends WarpEnergyTE { - private final int EU_PER_NEWAIRBLOCK = 12; - private final int EU_PER_EXISTINGAIRBLOCK = 4; // 1 solar = 1 EU/t - private final int MAX_ENERGY_VALUE = 8 * EU_PER_NEWAIRBLOCK; - - private int cooldownTicks = 0; - private final int AIR_GENERATION_TICKS = 40; - private final int START_CONCENTRATION_VALUE = 15; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - // Air generator works only in spaces - if (this.tileEntityInvalid || (worldObj.provider.dimensionId != WarpDriveConfig.G_SPACE_DIMENSION_ID && worldObj.provider.dimensionId != WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID)) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); // set disabled texture - return; - } - - cooldownTicks++; - if (cooldownTicks > AIR_GENERATION_TICKS) { - if (consumeEnergy(EU_PER_NEWAIRBLOCK, true)) { - if (this.blockMetadata != 1) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 2); // set enabled texture - } - } else { - if (this.blockMetadata != 0) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); // set disabled texture - } - } - releaseAir( 1, 0, 0); - releaseAir(-1, 0, 0); - releaseAir( 0, 1, 0); - releaseAir( 0, -1, 0); - releaseAir( 0, 0, 1); - releaseAir( 0, 0, -1); - - cooldownTicks = 0; - } - } - - private void releaseAir(int xOffset, int yOffset, int zOffset) { - int blockId = worldObj.getBlockId(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset); - if (WarpDriveConfig.isAirBlock(worldObj, blockId, xCoord + xOffset, yCoord + yOffset, zCoord + zOffset)) {// can be air - int energy_cost = (blockId != WarpDriveConfig.airID) ? EU_PER_NEWAIRBLOCK : EU_PER_EXISTINGAIRBLOCK; - if (consumeEnergy(energy_cost, true)) {// enough energy - if (worldObj.setBlock(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset, WarpDriveConfig.airID, START_CONCENTRATION_VALUE, 2)) {// needs to renew air or was not maxed out - consumeEnergy(EU_PER_NEWAIRBLOCK, false); - } else { - consumeEnergy(EU_PER_EXISTINGAIRBLOCK, false); - } - } - else - {// low energy => remove air block - if (blockId == WarpDriveConfig.airID){ - int metadata = worldObj.getBlockMetadata(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset); - if (metadata > 4) { - worldObj.setBlockMetadataWithNotify(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset, metadata - 4, 2); - } else if (metadata > 1) { - worldObj.setBlockMetadataWithNotify(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset, 1, 2); - } else { - // worldObj.setBlock(xCoord + xOffset, yCoord + yOffset, zCoord + zOffset, 0, 0, 2); - } - } - } - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - } - - @Override - public int getMaxEnergyStored() { - return MAX_ENERGY_VALUE; - } - - // IEnergySink methods implementation - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityCamera.java b/src/cr0s/WarpDrive/machines/TileEntityCamera.java deleted file mode 100644 index 17572ce3..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityCamera.java +++ /dev/null @@ -1,136 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.*; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.packet.Packet250CustomPayload; -import net.minecraft.server.MinecraftServer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.ChunkPosition; - -public class TileEntityCamera extends TileEntity implements IPeripheral { - private int dx, dz, dy; - private float yaw, pitch; // laser direction - - private int frequency = -1; // beam frequency - - private String[] methodsArray = { - "freq" - }; - - private final int REGISTRY_UPDATE_INTERVAL_SEC = 10; - private int ticks = 0; - - private int packetSendTicks = 20; - - @Override - public void updateEntity() { - // Update frequency on clients - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - packetSendTicks--; - if (packetSendTicks == 0) { - packetSendTicks = 20 * 5; - sendFreqPacket(); - } - return; - } - - ticks++; - if (ticks > 20 * REGISTRY_UPDATE_INTERVAL_SEC) { - ticks = 0; - WarpDrive.instance.cams.updateInRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord), frequency, 0); - } - } - - public int getFrequency() { - return frequency; - } - - public void setFrequency(int parFrequency) { - if (frequency != parFrequency) { - frequency = parFrequency; - WarpDrive.debugPrint("" + this + " Frequency set to " + frequency); - } - WarpDrive.instance.cams.updateInRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord), frequency, 0); - } - - @Override - public void onChunkUnload() { - WarpDrive.instance.cams.removeFromRegistry(worldObj, new ChunkPosition(xCoord, yCoord, zCoord)); - super.onChunkUnload(); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - frequency = tag.getInteger("frequency"); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setInteger("frequency", frequency); - } - - public void sendFreqPacket() { - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(8); - DataOutputStream outputStream = new DataOutputStream(bos); - - try { - outputStream.writeInt(xCoord); - outputStream.writeInt(yCoord); - outputStream.writeInt(zCoord); - outputStream.writeInt(frequency); - } catch (Exception e) { - e.printStackTrace(); - } - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = "WarpDriveFreq"; - packet.data = bos.toByteArray(); - packet.length = bos.size(); - MinecraftServer.getServer().getConfigurationManager().sendToAllNear(xCoord, yCoord, zCoord, 100, worldObj.provider.dimensionId, packet); -// WarpDrive.debugPrint("" + this + " Packet '" + packet.channel + "' sent (" + xCoord + ", " + yCoord + ", " + zCoord + ") '" + frequency + "'"); - } - } - - // IPeripheral methods implementation - @Override - public String getType() { - return "camera"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - if (arguments.length == 1) { - setFrequency(((Double)arguments[0]).intValue()); - } - return new Integer[] { frequency }; - } - - @Override - public void attach(IComputerAccess computer) { - } - - @Override - public void detach(IComputerAccess computer) { - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/TileEntityCloakingDeviceCore.java b/src/cr0s/WarpDrive/machines/TileEntityCloakingDeviceCore.java deleted file mode 100644 index 19a0f139..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityCloakingDeviceCore.java +++ /dev/null @@ -1,466 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import cr0s.WarpDrive.CloakedArea; -import dan200.computercraft.api.ComputerCraftAPI; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.packet.Packet250CustomPayload; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.entity.player.EntityPlayerMP; -import cr0s.WarpDrive.*; - -public class TileEntityCloakingDeviceCore extends WarpEnergyTE implements IPeripheral { - private final int MAX_ENERGY_VALUE = 500000000; // 500kk EU - - private String[] methodsArray = { - "setFieldTier", // 0 setFieldTier(1 or 2) - "isAssemblyValid", // 1 - returns true or false - "getEnergyLevel", // 2 - "enableCloakingField", // 3 enables field if assembled right - "disableCloakingField", // 4 disables cloaking field - "isEnabled" // 5 return true if currently enabled - }; - - public boolean isEnabled = false; - public byte tier = 1; // cloaking field tier, 1 or 2 - - // Spatial cloaking field parameters - public int front, back, up, down, left, right; - public int minX = 0, minY = 0, minZ = 0, maxX = 0, maxY = 0, maxZ = 0; - - public boolean isValid = false; - public boolean isCloaking = false; - public int volume = 0; - private int updateTicks = 0; - private int laserDrawingTicks = 0; - - private boolean soundPlayed = false; - private int soundTicks = 0; - - @Override - public void updateEntity() { - super.updateEntity(); - if (!FMLCommonHandler.instance().getEffectiveSide().isServer()) { - return; - } - - // Reset sound timer - soundTicks++; - if (soundTicks >= 40) { - soundTicks = 0; - soundPlayed = false; - } - - updateTicks--; - if (updateTicks <= 0) { - //System.out.println("" + this + " Updating cloaking state..."); - updateTicks = ((tier == 1) ? 20 : (tier == 2) ? 10 : 20) * WarpDriveConfig.CD_FIELD_REFRESH_INTERVAL_SECONDS; // resetting timer - - isValid = validateAssembly(); - isCloaking = WarpDrive.instance.cloaks.isAreaExists(worldObj, xCoord, yCoord, zCoord); - if (!isEnabled) {// disabled - if (isCloaking) {// disabled, cloaking => stop cloaking - WarpDrive.debugPrint("" + this + " Disabled, cloak field going down..."); - disableCloakingField(); - } else {// disabled, no cloaking - // IDLE - } - } else {// isEnabled - boolean hasEnoughPower = countBlocksAndConsumeEnergy(); - if (!isCloaking) {// enabled, not cloaking - if (hasEnoughPower && isValid) {// enabled, can cloak and able to - setCoilsState(true); - - // Register cloak - WarpDrive.instance.cloaks.addCloakedAreaWorld(worldObj, minX, minY, minZ, maxX, maxY, maxZ, xCoord, yCoord, zCoord, tier); - if (!soundPlayed) { - soundPlayed = true; - worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, "warpdrive:cloak", 4F, 1F); - } - - // Refresh the field - CloakedArea area = WarpDrive.instance.cloaks.getCloakedArea(worldObj, xCoord, yCoord, zCoord); - if (area != null) { - area.sendCloakPacketToPlayersEx(false); // recloak field - } - } else {// enabled, not cloaking but not able to - // IDLE - } - } else {// enabled & cloaked - if (!isValid) {// enabled, cloaking but invalid - WarpDrive.debugPrint("" + this + " Coil(s) lost, cloak field is collapsing..."); - consumeAllEnergy(); - disableCloakingField(); - } else {// enabled, cloaking and valid - if (hasEnoughPower) {// enabled, cloaking and able to - // IDLE - // Refresh the field !!! LemTest 2014-07-12 - CloakedArea area = WarpDrive.instance.cloaks.getCloakedArea(worldObj, xCoord, yCoord, zCoord); - if (area != null) { - area.sendCloakPacketToPlayersEx(false); // recloak field - } - } else {// loosing power - WarpDrive.debugPrint("" + this + " Low power, cloak field is collapsing..."); - disableCloakingField(); - } - } - } - } - } - - if (laserDrawingTicks++ > 100) { - laserDrawingTicks = 0; - - if (isEnabled && isValid) { - drawLasers(); - } - } - } - - public void setCoilsState(boolean enabled) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, (enabled) ? 1 : 0, 2); - - // Directions to check (all six directions: left, right, up, down, front, back) - byte[] dx = { 1, -1, 0, 0, 0, 0 }; - byte[] dy = { 0, 0, -1, 1, 0, 0 }; - byte[] dz = { 0, 0, 0, 0, -1, 1 }; - - for (int i = 0; i < 6; i++) { - searchCoilInDirectionAndSetState(dx[i], dy[i], dz[i], enabled); - } - } - - public void searchCoilInDirectionAndSetState(byte dx, byte dy, byte dz, boolean enabled) { - int coilCount = 0; - for (int i = 0; i < WarpDriveConfig.CD_MAX_CLOAKING_FIELD_SIDE; i++) { - if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.cloakCoilID) { - coilCount++; - if (coilCount > 2) { - return; - } - worldObj.setBlockMetadataWithNotify(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz, (enabled) ? 1 : 0, 2); - } - } - } - - public void searchCoilInDirectionAndDrawLaser(byte dx, byte dy, byte dz) { - final int START_LENGTH = 2; - float r = 0.0f, g = 1.0f, b = 0; - if (tier == 1) { - r = 0.0f; - g = 1.0f; - } else if (tier == 2) { - r = 1.0f; - g = 0.0f; - } - - for (int i = START_LENGTH + 1; i < WarpDriveConfig.CD_MAX_CLOAKING_FIELD_SIDE; i++) { - if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.cloakCoilID) { - sendLaserPacket(new Vector3(this).add(0.5), new Vector3(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz).add(0.5), r, g, b, 110, 0, 100); - } - } - } - - public void drawLasers() { - final int START_LENGTH = 2; - float r = 0.0f, g = 1.0f, b = 0; - if (this.tier == 1) { - r = 0.0f; g = 1.0f; - } else if (this.tier == 2) { - r = 1.0f; g = 0.0f; - } - - // Directions to check (all six directions: left, right, up, down, front, back) - byte[] dx = { 1, -1, 0, 0, 0, 0 }; - byte[] dy = { 0, 0, -1, 1, 0, 0 }; - byte[] dz = { 0, 0, 0, 0, -1, 1 }; - - for (int k = 0; k < 6; k++) { - searchCoilInDirectionAndDrawLaser(dx[k], dy[k], dz[k]); - } - - for (int i = 0; i < 6; i++) { - for (int j = 0; j < 6; j++) { - switch (worldObj.rand.nextInt(6)) { - case 0: - r = 1.0f; - g = b = 0; - break; - case 1: - r = b = 0; - g = 1.0f; - break; - case 2: - r = g = 0; - b = 1.0f; - break; - case 3: - r = b = 0.5f; - g = 0; - break; - case 4: - r = g = 1.0f; - b = 0; - break; - case 5: - r = 1.0f; - b = 0.5f; - g = 0f; - } - - sendLaserPacket(new Vector3(xCoord + START_LENGTH * dx[i], yCoord + START_LENGTH * dy[i], zCoord + START_LENGTH * dz[i]).add(0.5), new Vector3(xCoord + START_LENGTH * dx[j], yCoord + START_LENGTH * dy[j], zCoord + START_LENGTH * dz[j]).add(0.5), r, g, b, 110, 0, 100); - } - } - } - - public void disableCloakingField() { - setCoilsState(false); - if (WarpDrive.instance.cloaks.isAreaExists(worldObj, xCoord, yCoord, zCoord)) { - WarpDrive.instance.cloaks.removeCloakedArea(worldObj, xCoord, yCoord, zCoord); - - if (!soundPlayed) { - soundPlayed = true; - worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, "warpdrive:decloak", 4F, 1F); - } - } - } - public boolean countBlocksAndConsumeEnergy() { - int x, y, z, energyToConsume = 0; - volume = 0; - if (tier == 1) {// tier1 = gaz and air blocks don't count - for (y = minY; y <= maxY; y++) { - for (x = minX; x <= maxX; x++) { - for(z = minZ; z <= maxZ; z++) { - if (!worldObj.isAirBlock(x, y, z)) { - volume++; - } - } - } - } - energyToConsume = volume * WarpDriveConfig.CD_ENERGY_PER_BLOCK_TIER1; - } else {// tier2 = everything counts - for (y = minY; y <= maxY; y++) { - for (x = minX; x <= maxX; x++) { - for(z = minZ; z <= maxZ; z++) { - if (worldObj.getBlockId(x, y, z) != 0) { - volume++; - } - } - } - } - energyToConsume = volume * WarpDriveConfig.CD_ENERGY_PER_BLOCK_TIER2; - } - - //System.out.println("" + this + " Consuming " + energyToConsume + " eU for " + blocksCount + " blocks"); - return consumeEnergy(energyToConsume, false); - } - - public void sendLaserPacket(Vector3 source, Vector3 dest, float r, float g, float b, int age, int energy, int radius) { - Side side = FMLCommonHandler.instance().getEffectiveSide(); - - if (side == Side.SERVER) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(8); - DataOutputStream outputStream = new DataOutputStream(bos); - - try { - // Write source vector - outputStream.writeDouble(source.x); - outputStream.writeDouble(source.y); - outputStream.writeDouble(source.z); - // Write target vector - outputStream.writeDouble(dest.x); - outputStream.writeDouble(dest.y); - outputStream.writeDouble(dest.z); - // Write r, g, b of laser - outputStream.writeFloat(r); - outputStream.writeFloat(g); - outputStream.writeFloat(b); - // Write age - outputStream.writeByte(age); - // Write energy value - outputStream.writeInt(energy); - } catch (Exception ex) { - ex.printStackTrace(); - } - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = "WarpDriveBeam"; - packet.data = bos.toByteArray(); - packet.length = bos.size(); - - // Send packet to all players within cloaked area - List list = worldObj.getEntitiesWithinAABB(EntityPlayerMP.class, AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); - for (Entity e : list) { - if (e != null && e instanceof EntityPlayer) { - ((EntityPlayerMP)e).playerNetServerHandler.sendPacketToPlayer(packet); - } - } - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - this.tier = tag.getByte("tier"); -// this.frequency = tag.getInteger("frequency"); - this.isEnabled = tag.getBoolean("enabled"); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setByte("tier", tier); -// tag.setInteger("frequency", frequency); - tag.setBoolean("enabled", isEnabled); - } - - public int searchCoilInDirection(byte dx, byte dy, byte dz) { - for (int i = 3; i < WarpDriveConfig.CD_MAX_CLOAKING_FIELD_SIDE; i++) { - if (worldObj.getBlockId(xCoord + i * dx, yCoord + i * dy, zCoord + i * dz) == WarpDriveConfig.cloakCoilID) { - return i; - } - } - - return 0; - } - public boolean validateAssembly() { - final int START_LENGTH = 2; // Step length from core block to main coils - - // Directions to check (all six directions: left, right, up, down, front, back) - byte[] dx = { 1, -1, 0, 0, 0, 0 }; - byte[] dy = { 0, 0, -1, 1, 0, 0 }; - byte[] dz = { 0, 0, 0, 0, -1, 1 }; - - for (int i = 0; i < 6; i++) { - if (worldObj.getBlockId(xCoord + START_LENGTH * dx[i], yCoord + START_LENGTH * dy[i], zCoord + START_LENGTH * dz[i]) != WarpDriveConfig.cloakCoilID) { - return false; - } - } - - // Check cloaking field parameters defining coils - this.left = searchCoilInDirection((byte)1, (byte)0, (byte)0) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.left == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - this.right = searchCoilInDirection((byte)-1, (byte)0, (byte)0) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.right == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - - this.up = searchCoilInDirection((byte)0, (byte)1, (byte)0) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.up == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - this.down = searchCoilInDirection((byte)0, (byte)-1, (byte)0) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.down == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - - this.front = searchCoilInDirection((byte)0, (byte)0, (byte)1) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.front == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - this.back = searchCoilInDirection((byte)0, (byte)0, (byte)-1) + WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS; - if (this.back == WarpDriveConfig.CD_COIL_CAPTURE_BLOCKS) return false; - - int x1 = 0, x2 = 0, z1 = 0, z2 = 0; - - - z1 = zCoord - this.back; - z2 = zCoord + this.front; - x1 = xCoord - this.right; - x2 = xCoord + this.left; - - if (x1 < x2) { - this.minX = x1; this.maxX = x2; - } else { - this.minX = x2; this.maxX = x1; - } - - if (z1 < z2) { - this.minZ = z1; this.maxZ = z2; - } else { - this.minZ = z2; this.maxZ = z1; - } - - this.minY = yCoord - this.down; - this.maxY = yCoord + this.up; - - return true; - } - - // CC - // IPeripheral methods implementation - @Override - public String getType() { - return "cloakingdevicecore"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, - int method, Object[] arguments) throws Exception { - switch (method) { - case 0: // setFieldTier(1 or 2) - if (arguments.length == 1) { - if (((Double)arguments[0]).byteValue() != 1 && ((Double)arguments[0]).byteValue() != 2) { - this.tier = 1; - } else { - this.tier = ((Double)arguments[0]).byteValue(); - } - } - break; - - case 1: // isAssemblyValid() - return new Object[] { (boolean)validateAssembly() }; - - case 2: // getEnergyLevel() - return new Object[] { getEnergyStored() }; - - case 3: // enableCloakingField() - this.isEnabled = true; - break; - - case 4: // disableCloakingField() - this.isEnabled = false; - break; - - case 5: // isEnabled() - return new Object[] { this.isEnabled }; - } - - return null; - } - - @Override - public void attach(IComputerAccess computer) { - computer.mount("/cloakingdevicecore", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/cloakingdevicecore")); - computer.mount("/uncloak", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/cloakingdevicecore/uncloak")); - computer.mount("/cloak1", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/cloakingdevicecore/cloak1")); - computer.mount("/cloak2", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/cloakingdevicecore/cloak2")); - } - - @Override - public void detach(IComputerAccess computer) { - } - - @Override - public int getMaxEnergyStored() { - return MAX_ENERGY_VALUE; - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityLaserReactorMonitor.java b/src/cr0s/WarpDrive/machines/TileEntityLaserReactorMonitor.java deleted file mode 100644 index 79377376..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityLaserReactorMonitor.java +++ /dev/null @@ -1,140 +0,0 @@ -package cr0s.WarpDrive.machines; - -import ic2.api.reactor.IReactor; -import ic2.api.reactor.IReactorChamber; - -import java.util.HashSet; -import java.util.Set; - -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -import cr0s.WarpDrive.WarpDriveConfig; -import cr0s.WarpDrive.item.ItemReactorLaserFocus; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChunkCoordinates; - -public class TileEntityLaserReactorMonitor extends TileEntityAbstractLaser { - private final int workRate = 10; - private int ticks = 0; - - private Set findReactors() {//returns either IReactor or IReactorChamber tile entity - int[] xD = {-2, 2, 0, 0, 0, 0}; - int[] yD = { 0, 0,-2, 2, 0, 0}; - int[] zD = { 0, 0, 0, 0,-2, 2}; - Set output = new HashSet(); - for(int i = 0; i < xD.length; i++) { - int xO = xCoord + xD[i]; - int yO = yCoord + yD[i]; - int zO = zCoord + zD[i]; - TileEntity te = worldObj.getBlockTileEntity(xO, yO, zO); - if(te == null) - continue; - - if (te instanceof IReactor) { - output.add(te); - } else if(te instanceof IReactorChamber) { - IReactor reactor = ((IReactorChamber)te).getReactor(); - if(reactor == null) - continue; - - ChunkCoordinates coords = reactor.getPosition(); - - if(Math.abs(coords.posX - xCoord) == 1) - continue; - if(Math.abs(coords.posY - yCoord) == 1) - continue; - if(Math.abs(coords.posZ - zCoord) == 1) - continue; - - output.add(te); - } - } - return output; - } - - private boolean coolReactor(IReactor react) { - boolean didCoolReactor = false; - for(int x = 0; x < 9; x++) { - for(int y = 0; y < 6; y++) { - ItemStack item = react.getItemAt(x, y); - if (item != null) { - if(item.getItem() instanceof ItemReactorLaserFocus) { - int heat = item.getItemDamage(); - int heatRemoval = (int) Math.floor(Math.min(getEnergyStored() / WarpDriveConfig.RM_EU_PER_HEAT, (double) heat)); - if(heatRemoval > 0) { - didCoolReactor = true; - consumeEnergy((int) Math.ceil(heatRemoval * WarpDriveConfig.RM_EU_PER_HEAT), false); - item.setItemDamage(heat - heatRemoval); - } - } - } - } - } - return didCoolReactor; - } - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - ticks++; - if (ticks > workRate) { - ticks = 0; - Vector3 myPos = new Vector3(this).translate(0.5); - Set reactors = findReactors(); - if(reactors.size() == 0) - return; - - for(Object o : reactors) - { - IReactor react = null; - if(o instanceof TileEntity) - { - if(o instanceof IReactor) - react = (IReactor)o; - else if(o instanceof IReactorChamber) - react = ((IReactorChamber)o).getReactor(); - if(react != null) - { - if(coolReactor(react)) - { - TileEntity te = (TileEntity)o; - WarpDrive.sendLaserPacket(worldObj, myPos, new Vector3(te.xCoord,te.yCoord,te.zCoord).translate(0.5D), 0f, 0.8f, 1f, 20, 0, 20); - } - } - } - } - } - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - } - - @Override - public boolean shouldChunkLoad() { - return false; - } - - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.RM_MAX_ENERGY; - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityLaserTreeFarm.java b/src/cr0s/WarpDrive/machines/TileEntityLaserTreeFarm.java deleted file mode 100644 index 09b71f89..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityLaserTreeFarm.java +++ /dev/null @@ -1,384 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.LinkedList; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -import cr0s.WarpDrive.WarpDriveConfig; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -public class TileEntityLaserTreeFarm extends TileEntityAbstractMiner implements IPeripheral { - Boolean active = false; - - private int mode = 0; - private boolean doLeaves = false; - private boolean silkTouchLeaves = false; - private boolean treeTap = false; - - private final int defSize = 8; - private final int scanWait = 40; - private final int mineWait = 4; - private int delayMul = 4; - - private int totalHarvested=0; - - private int scan=0; - private int xSize = defSize; - private int zSize = defSize; - - LinkedList logs; - private int logIndex = 0; - - private String[] methodsArray = { - "start", - "stop", - "area", - "leaves", - "silkTouch", - "silkTouchLeaves", - "treetap", - "state" - }; - - public TileEntityLaserTreeFarm() { - super(); - } - - @Override - public void updateEntity() { - super.updateEntity(); - - if (active) { - scan++; - if (mode == 0) { - if (scan >= scanWait) { - scan = 0; - logs = scanTrees(); - if(logs.size() > 0) - mode = treeTap ? 2 : 1; - logIndex = 0; - } - } else { - if (scan >= mineWait * delayMul) { - scan = 0; - - if (logIndex >= logs.size()) { - mode = 0; - return; - } - Vector3 pos = logs.get(logIndex); - int blockID = worldObj.getBlockId(pos.intX(), pos.intY(), pos.intZ()); - - if (mode == 1) { - int cost = calculateBlockCost(blockID); - if (consumeEnergyFromBooster(cost, true)) { - if (isLog(blockID) || (doLeaves && isLeaf(blockID))) { - delayMul = 1; - if (isRoomForHarvest()) { - if (consumeEnergyFromBooster(cost, false)) { - if (isLog(blockID)) { - delayMul = 4; - totalHarvested++; - } - harvestBlock(pos); - } else { - return; - } - } else { - return; - } - } - logIndex++; - } - } else if(mode == 2) { - int cost = calculateBlockCost(blockID); - if (consumeEnergyFromBooster(cost, true)) { - if (isRoomForHarvest()) { - if (blockID == WarpDriveConfig.IC2_RubberWood) { - int metadata = worldObj.getBlockMetadata(pos.intX(), pos.intY(), pos.intZ()); - if (metadata >= 2 && metadata <= 5) { - WarpDrive.debugPrint("wetspot found"); - if (consumeEnergyFromBooster(cost, false)) { - ItemStack resin = WarpDriveConfig.IC2_Resin.copy(); - resin.stackSize = (int) Math.round(Math.random() * 4); - dumpToInv(resin); - worldObj.setBlockMetadataWithNotify(pos.intX(), pos.intY(), pos.intZ(), metadata+6, 3); - laserBlock(pos); - totalHarvested++; - delayMul = 4; - } else { - return; - } - } else { - delayMul = 1; - } - } else if(isLog(blockID)) { - if (consumeEnergyFromBooster(cost, false)) { - delayMul = 4; - totalHarvested++; - harvestBlock(pos); - } else { - return; - } - } else if(isLeaf(blockID)) { - if (consumeEnergyFromBooster(cost, true)) { - delayMul = 1; - harvestBlock(pos); - } else { - return; - } - } - } else { - return; - } - logIndex++; - } - } - } - } - } - } - - private static boolean isLog(int blockID) { - return WarpDriveConfig.MinerLogs.contains(blockID); - } - - private static boolean isLeaf(int blockID) { - return WarpDriveConfig.MinerLeaves.contains(blockID); - } - - private static void addTree(LinkedList list, Vector3 newTree) { - WarpDrive.debugPrint("Adding tree position:" + newTree.x + "," + newTree.y + "," + newTree.z); - list.add(newTree); - } - - private LinkedList scanTrees() { - int xmax, zmax, x1, x2, z1, z2; - int xmin, zmin; - x1 = xCoord + xSize / 2; - x2 = xCoord - xSize / 2; - xmin = Math.min(x1, x2); - xmax = Math.max(x1, x2); - - z1 = zCoord + zSize / 2; - z2 = zCoord - zSize / 2; - zmin = Math.min(z1, z2); - zmax = Math.max(z1, z2); - - LinkedList logPositions = new LinkedList(); - - for(int x = xmin; x <= xmax; x++) { - for(int z = zmin; z <= zmax; z++) { - int blockID = worldObj.getBlockId(x, yCoord, z); - if (isLog(blockID)) { - Vector3 pos = new Vector3(x, yCoord, z); - logPositions.add(pos); - scanNearby(logPositions, x, yCoord, z, 0); - } - } - } - return logPositions; - } - - private void scanNearby(LinkedList current, int x, int y, int z, int d) { - int[] deltas = {0, -1, 1}; - for(int dx : deltas) { - for(int dy = 1; dy >= 0; dy--) { - for(int dz : deltas) { - int blockID = worldObj.getBlockId(x+dx, y+dy, z+dz); - if (isLog(blockID) || (doLeaves && isLeaf(blockID))) { - Vector3 pos = new Vector3(x + dx, y + dy, z + dz); - if (!current.contains(pos)) { - addTree(current, pos); - if (d < 35) { - scanNearby(current,x+dx,y+dy,z+dz,d+1); - } - } - } - } - } - } - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setInteger("xSize", xSize); - tag.setInteger("zSize", zSize); - tag.setBoolean("doLeaves", doLeaves); - tag.setBoolean("active", active); - tag.setBoolean("treetap", treeTap); - tag.setBoolean("silkTouchLeaves", silkTouchLeaves); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - xSize = tag.getInteger("xSize"); - zSize = tag.getInteger("zSize"); - defineMiningArea(xSize,zSize); - - doLeaves = tag.getBoolean("doLeaves"); - active = tag.getBoolean("active"); - treeTap = tag.getBoolean("treetap"); - silkTouchLeaves = tag.getBoolean("silkTouchLeaves"); - } - - @Override - public boolean shouldChunkLoad() { - return active; - } - - @Override - public String getType() { - return "treefarmLaser"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - String methodStr = methodsArray[method]; - if (methodStr == "start") { - if (!active) { - mode = 0; - totalHarvested = 0; - active = true; - } - return new Boolean[] { true }; - } - - if (methodStr == "stop") { - active = false; - } - - if (methodStr == "area") { - try { - if (arguments.length == 1) { - xSize = clamp(toInt(arguments[0]),3,WarpDriveConfig.TF_MAX_SIZE); - zSize = xSize; - } else if(arguments.length == 2) { - xSize = clamp(toInt(arguments[0]),3,WarpDriveConfig.TF_MAX_SIZE); - zSize = clamp(toInt(arguments[1]),3,WarpDriveConfig.TF_MAX_SIZE); - } - } catch(NumberFormatException e) { - xSize = defSize; - zSize = defSize; - } - defineMiningArea(xSize,zSize); - return new Integer[] { xSize , zSize }; - } - - if (methodStr == "leaves") { - try { - if (arguments.length > 0) { - doLeaves = toBool(arguments[0]); - } - } catch(Exception e) { - - } - return new Boolean[] { doLeaves }; - } - - if (methodStr == "silkTouch") { - try { - silkTouch(arguments[0]); - } catch(Exception e) { - silkTouch(false); - } - return new Object[] { silkTouch() }; - } - - if (methodStr == "silkTouchLeaves") { - try { - if (arguments.length >= 1) { - silkTouchLeaves = toBool(arguments[0]); - } - } catch(Exception e) { - silkTouchLeaves = false; - } - return new Object[] { silkTouchLeaves }; - } - - if (methodStr == "treetap") { - try { - if (arguments.length >= 1) { - treeTap = toBool(arguments[0]); - } - } catch(Exception e) { - treeTap = false; - } - return new Object[] { treeTap }; - } - - if (methodStr == "state") { - String state = active ? (mode==0?"scanning" : (mode == 1 ? "harvesting" : "tapping")) : "inactive"; - return new Object[] { state, xSize, zSize, energy(), totalHarvested }; - } - return null; - } - - @Override - public void attach(IComputerAccess computer) { - } - - @Override - public void detach(IComputerAccess computer) { - } - - //ABSTRACT LASER IMPLEMENTATION - @Override - protected boolean silkTouch(int blockID) { - if (isLeaf(blockID)) { - return silkTouchLeaves; - } - return silkTouch(); - } - - @Override - protected boolean canSilkTouch() { - return true; - } - - @Override - protected int minFortune() { - return 0; - } - - @Override - protected int maxFortune() { - return 0; - } - - @Override - protected double laserBelow() { - return -0.5; - } - - @Override - protected float getColorR() { - return 0.2f; - } - - @Override - protected float getColorG() { - return 0.7f; - } - - @Override - protected float getColorB() { - return 0.4f; - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityLift.java b/src/cr0s/WarpDrive/machines/TileEntityLift.java deleted file mode 100644 index 7d4b1253..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityLift.java +++ /dev/null @@ -1,173 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; - -import java.util.List; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; -import cr0s.WarpDrive.*; - -public class TileEntityLift extends WarpEnergyTE { - private final int MAX_ENERGY_VALUE = 2048; // eU - - private int mode = 0; // 0 - inactive, 1 - up, 2 - down - private int firstUncoveredY; - - private boolean isEnabled = false; - - int ticks = 0; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - if (++ticks > 40) - { - ticks = 0; - - // Switching mode - if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) - { - mode = 2; // down - } - else - { - mode = 1; // up - } - - isEnabled = (worldObj.isAirBlock(xCoord, yCoord + 1, zCoord) && worldObj.isAirBlock(xCoord, yCoord + 2, zCoord)); - - if (getEnergyStored() != MAX_ENERGY_VALUE || !isEnabled) { - mode = 0; - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2); // disabled - return; - } - - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, mode, 2); // current mode - - // Launch a beam: search non-air blocks under lift - for (int ny = yCoord - 1; ny > 0; ny--) { - int blockId = worldObj.getBlockId(xCoord, ny, zCoord); - // 63 & 68 = signs - if (blockId != 0 && blockId != 63 && blockId != 68 && !WarpDriveConfig.isAirBlock(worldObj, blockId, xCoord, ny, zCoord)) { - firstUncoveredY = ny; - break; - } - } - - if (yCoord - firstUncoveredY > 0) { - if (mode == 1) { - WarpDrive.instance.sendLaserPacket(worldObj, new Vector3(this).translate(0.5D), new Vector3(xCoord, firstUncoveredY, zCoord).translate(0.5D), 0f, 1f, 0f, 40, 0, 100); - } else if (mode == 2) { - WarpDrive.instance.sendLaserPacket(worldObj, new Vector3(this).translate(0.5D), new Vector3(xCoord, firstUncoveredY, zCoord).translate(0.5D), 0f, 0f, 1f, 40, 0, 100); - } - } - - liftEntity(); - } - } - - public void liftEntity() - { - int xmax, zmax, x1, x2, z1, z2; - int xmin, zmin; - final int CUBE_SIDE = 2; - x1 = xCoord + CUBE_SIDE / 2; - x2 = xCoord - CUBE_SIDE / 2; - - if (x1 < x2) - { - xmin = x1; - xmax = x2; - } - else - { - xmin = x2; - xmax = x1; - } - - z1 = zCoord + CUBE_SIDE / 2; - z2 = zCoord - CUBE_SIDE / 2; - - if (z1 < z2) - { - zmin = z1; - zmax = z2; - } - else - { - zmin = z2; - zmax = z1; - } - - // Lift up - if (mode == 1) - { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(xmin + 0.3, firstUncoveredY, zmin + 0.3, xmax - 0.3, yCoord, zmax - 0.3); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, aabb); - - if (list != null) // up - { - for (Object o : list) - { - if (o != null && o instanceof EntityLivingBase) - { - ((EntityLivingBase)o).setPositionAndUpdate(xCoord + 0.5f, yCoord + 1, zCoord + 0.5f); - WarpDrive.sendLaserPacket(worldObj, new Vector3(this).translate(0.5), new Vector3(xCoord, firstUncoveredY, zCoord).translate(0.5), 1F, 1F, 0F, 40, 0, 100); - worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); - consumeAllEnergy(); - return; - } - } - } - } - else if (mode == 2) // down - { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(xmin + 0.3, yCoord, zmin + 0.3, xmax - 0.3, yCoord + 2, zmax - 0.3); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, aabb); - - if (list != null) - { - for (Object o : list) - { - if (o != null && o instanceof EntityLivingBase) - { - ((EntityLivingBase)o).setPositionAndUpdate(xCoord + 0.5f, firstUncoveredY + 1, zCoord + 0.5f); - WarpDrive.sendLaserPacket(worldObj, new Vector3(this).translate(0.5), new Vector3(xCoord, firstUncoveredY + 1, zCoord).translate(0.5), 1F, 1F, 0F, 40, 0, 100); - worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); - consumeAllEnergy(); - return; - } - } - } - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) - { - super.readFromNBT(tag); - } - - @Override - public void writeToNBT(NBTTagCompound tag) - { - super.writeToNBT(tag); - } - - // IEnergySink methods implementation - @Override - public int getMaxEnergyStored() { - return MAX_ENERGY_VALUE; - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityMiningLaser.java b/src/cr0s/WarpDrive/machines/TileEntityMiningLaser.java deleted file mode 100644 index 51b1aba4..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityMiningLaser.java +++ /dev/null @@ -1,795 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import dan200.computercraft.api.ComputerCraftAPI; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.block.BlockFluid; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.inventory.IInventory; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fluids.FluidRegistry; -import appeng.api.WorldCoord; -import appeng.api.IAEItemStack; -import appeng.api.Util; -import appeng.api.events.GridTileLoadEvent; -import appeng.api.events.GridTileUnloadEvent; -import appeng.api.me.tiles.IGridMachine; -import appeng.api.me.tiles.ITileCable; -import appeng.api.me.util.IGridInterface; -import appeng.api.me.util.IMEInventoryHandler; -import cr0s.WarpDrive.*; - -public class TileEntityMiningLaser extends TileEntity implements IPeripheral, IGridMachine, ITileCable { - Boolean powerStatus = false; - private IGridInterface grid; - - private int dx, dz, dy; - private boolean isMining() { - return currentState != STATE_IDLE; - } - private boolean isQuarry = false; - private boolean useDeiterium = false; - private boolean AENetworkReady = false; - - private String[] methodsArray = { - "mine", //0 - "stop", //1 - "isMining", //2 - "quarry", //3 - "state", //4 - "offset" //5 - }; - - private int delayTicksWarmup = 0; - private int delayTicksScan = 0; - private int delayTicksMine = 0; - private final int STATE_IDLE = 0; - private final int STATE_WARMUP = 1; - private final int STATE_SCANNING = 2; - private final int STATE_MINING = 3; - private int currentState = 0; // 0 - scan next layer, 1 - collect valuables - private boolean enoughPower = false; - private int currentLayer; - - private ArrayList valuablesInLayer = new ArrayList(); - private int valuableIndex = 0; - - private int layerOffset = 1; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - if (currentState == STATE_IDLE) { - delayTicksWarmup = 0; - delayTicksScan = 0; - delayTicksMine = 0; - updateMetadata(BlockMiningLaser.ICON_IDLE); - return; - } - - boolean isOnEarth = (worldObj.provider.dimensionId == 0); - - Vector3 minerVector = new Vector3(xCoord + 0.5D, yCoord, zCoord + 0.5D); - - if (currentState == STATE_WARMUP) { // warming up - delayTicksWarmup++; - updateMetadata(BlockMiningLaser.ICON_SCANNINGLOWPOWER); - if (delayTicksWarmup >= WarpDriveConfig.ML_WARMUP_DELAY_TICKS) { - delayTicksScan = 0; - currentState = STATE_SCANNING; - updateMetadata(BlockMiningLaser.ICON_SCANNINGLOWPOWER); - return; - } - } else if (currentState == STATE_SCANNING) { // scanning - delayTicksScan++; - if (delayTicksScan == 1) { - // check power level - enoughPower = consumeEnergyPacketFromBooster(isOnEarth ? WarpDriveConfig.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.ML_EU_PER_LAYER_SPACE, true); - if (!enoughPower) { - updateMetadata(BlockMiningLaser.ICON_SCANNINGLOWPOWER); - delayTicksScan = 0; - return; - } else { - updateMetadata(BlockMiningLaser.ICON_SCANNINGPOWERED); - } - // show current layer - int age = Math.max(40, 5 * WarpDriveConfig.ML_SCAN_DELAY_TICKS); - double xmax = xCoord + WarpDriveConfig.ML_MAX_RADIUS + 1.0D; - double xmin = xCoord - WarpDriveConfig.ML_MAX_RADIUS + 0.0D; - double zmax = zCoord + WarpDriveConfig.ML_MAX_RADIUS + 1.0D; - double zmin = zCoord - WarpDriveConfig.ML_MAX_RADIUS + 0.0D; - double y = currentLayer + 1.0D; - WarpDrive.sendLaserPacket(worldObj, new Vector3(xmin, y, zmin), new Vector3(xmax, y, zmin), 0.3F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, new Vector3(xmax, y, zmin), new Vector3(xmax, y, zmax), 0.3F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, new Vector3(xmax, y, zmax), new Vector3(xmin, y, zmax), 0.3F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, new Vector3(xmin, y, zmax), new Vector3(xmin, y, zmin), 0.3F, 0.0F, 1.0F, age, 0, 50); - } else if (delayTicksScan >= WarpDriveConfig.ML_SCAN_DELAY_TICKS) { - delayTicksScan = 0; - if (currentLayer <= 0) { - stop(); - return; - } - // consume power - enoughPower = consumeEnergyPacketFromBooster(isOnEarth ? WarpDriveConfig.ML_EU_PER_LAYER_EARTH : WarpDriveConfig.ML_EU_PER_LAYER_SPACE, false); - if (!enoughPower) { - updateMetadata(BlockMiningLaser.ICON_SCANNINGLOWPOWER); - return; - } else { - updateMetadata(BlockMiningLaser.ICON_SCANNINGPOWERED); - } - // scan - scanLayer(); - if (valuablesInLayer.size() > 0) { - int r = (int)Math.ceil(WarpDriveConfig.ML_MAX_RADIUS / 2.0D); - int offset = (yCoord - currentLayer) % (2 * r); - int age = Math.max(20, Math.round(2.5F * WarpDriveConfig.ML_SCAN_DELAY_TICKS)); - double y = currentLayer + 1.0D; - WarpDrive.sendLaserPacket(worldObj, minerVector, new Vector3(xCoord - r + offset, y, zCoord + r ).translate(0.3D), 0.0F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, minerVector, new Vector3(xCoord + r , y, zCoord + r - offset).translate(0.3D), 0.0F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, minerVector, new Vector3(xCoord + r - offset, y, zCoord - r ).translate(0.3D), 0.0F, 0.0F, 1.0F, age, 0, 50); - WarpDrive.sendLaserPacket(worldObj, minerVector, new Vector3(xCoord - r , y, zCoord - r + offset).translate(0.3D), 0.0F, 0.0F, 1.0F, age, 0, 50); - worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:hilaser", 4F, 1F); - delayTicksMine = 0; - currentState = STATE_MINING; - updateMetadata(BlockMiningLaser.ICON_MININGPOWERED); - return; - } else { - worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F); - currentLayer--; - } - } - } else if (currentState == STATE_MINING) { // mining - delayTicksMine++; - if (delayTicksMine >= WarpDriveConfig.ML_MINE_DELAY_TICKS) { - delayTicksMine = 0; - - if (valuableIndex >= valuablesInLayer.size()) { - delayTicksScan = 0; - currentState = STATE_SCANNING; - updateMetadata(BlockMiningLaser.ICON_SCANNINGPOWERED); - // rescan same layer - scanLayer(); - if (valuablesInLayer.size() <= 0) { - currentLayer--; - } - return; - } - - // consume power - enoughPower = consumeEnergyPacketFromBooster(isOnEarth ? WarpDriveConfig.ML_EU_PER_BLOCK_EARTH : WarpDriveConfig.ML_EU_PER_BLOCK_SPACE, false); - if (!enoughPower) { - updateMetadata(BlockMiningLaser.ICON_MININGLOWPOWER); - return; - } else { - updateMetadata(BlockMiningLaser.ICON_MININGPOWERED); - } - - //System.out.println("[ML] Mining: " + (valuableIndex + 1) + "/" + valuablesInLayer.size()); - Vector3 valuable = valuablesInLayer.get(valuableIndex); - valuableIndex++; - // Mine valuable ore - int blockID = worldObj.getBlockId(valuable.intX(), valuable.intY(), valuable.intZ()); - // Skip if block is too hard or its empty block (check again in case it changed) - if (!canDig(blockID, valuable.intX(), valuable.intY(), valuable.intZ())) { - delayTicksMine = Math.round(WarpDriveConfig.ML_MINE_DELAY_TICKS * 0.8F); - } - int age = Math.max(10, Math.round((4 + worldObj.rand.nextFloat()) * WarpDriveConfig.ML_MINE_DELAY_TICKS)); - WarpDrive.sendLaserPacket(worldObj, minerVector, new Vector3(valuable.intX(), valuable.intY(), valuable.intZ()).translate(0.5D), 1.0F, 1.0F, 0.0F, age, 0, 50); - worldObj.playSoundEffect(xCoord + 0.5f, yCoord, zCoord + 0.5f, "warpdrive:lowlaser", 4F, 1F); - harvestBlock(valuable); - } - } - } - - private void updateMetadata(int metadata) { - int blockId = worldObj.getBlockId(xCoord, yCoord, zCoord); - if (blockId == WarpDriveConfig.miningLaserID) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 2); - } - } - - private void stop() { - // WarpDrive.debugPrint("" + this + " Stop requested"); - currentState = STATE_IDLE; - updateMetadata(BlockMiningLaser.ICON_IDLE); - } - - private boolean canDig(int blockID, int x, int y, int z) { - // ignore air - if (WarpDriveConfig.isAirBlock(worldObj, blockID, x, y, z)) { - return false; - } - // check blacklist - if (blockID == Block.bedrock.blockID) { - return false; - } - if (WarpDriveConfig.forceFieldBlocks.contains(blockID)) { - stop(); - return false; - } - // check whitelist - if (WarpDriveConfig.MinerOres.contains(blockID)) { - return true; - } - // check default - if ( (Block.blocksList[blockID] != null) && (Block.blocksList[blockID].blockResistance <= Block.obsidian.blockResistance) ) { - return true; - } - // WarpDrive.debugPrint("" + this + " Rejecting " + blockID + " at (" + x + ", " + y + ", " + z + ")"); - return false; - } - - private void harvestBlock(Vector3 valuable) { - int blockID = worldObj.getBlockId(valuable.intX(), valuable.intY(), valuable.intZ()); - int blockMeta = worldObj.getBlockMetadata(valuable.intX(), valuable.intY(), valuable.intZ()); - if (Block.blocksList[blockID] != null && (Block.blocksList[blockID] instanceof BlockFluid)) { - // Evaporate fluid - worldObj.playSoundEffect(valuable.intX() + 0.5D, valuable.intY() + 0.5D, valuable.intZ() + 0.5D, "random.fizz", 0.5F, 2.6F + (worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.8F); - } else { - List stacks = getItemStackFromBlock(valuable.intX(), valuable.intY(), valuable.intZ(), blockID, blockMeta); - if (stacks != null) { - boolean overflow = false; - for (ItemStack stack : stacks) { - if (grid != null && AENetworkReady) { - putInGrid(stack); - } else { - if (!putInChest(findChest(), stack)) { - WarpDrive.debugPrint("" + this + " Overflow detected"); - overflow = true; - } - } - } - if (overflow) { - stop(); - } - } - // standard harvest block effect - worldObj.playAuxSFXAtEntity(null, 2001, valuable.intX(), valuable.intY(), valuable.intZ(), blockID + (blockMeta << 12)); - } - worldObj.setBlockToAir(valuable.intX(), valuable.intY(), valuable.intZ()); - } - - private IInventory findChest() { - TileEntity result = null; - result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); - if (result != null && result instanceof IInventory) { - return (IInventory) result; - } - - result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); - if (result != null && result instanceof IInventory) { - return (IInventory) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); - if (result != null && result instanceof IInventory) { - return (IInventory) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); - if (result != null && result instanceof IInventory) { - return (IInventory) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - if (result != null && result instanceof IInventory) { - return (IInventory) result; - } - - return null; - } - - public List getItemStackFromBlock(int i, int j, int k, int blockID, int blockMeta) - { - Block block = Block.blocksList[blockID]; - if (block == null) - return null; - if (useDeiterium && grid != null && AENetworkReady) - { - IMEInventoryHandler cellArray = grid.getCellArray(); - if (cellArray != null && block.canSilkHarvest(worldObj, null, i, j, k, blockMeta)) { - int consume = isQuarry ? 15 : 1000; - - IAEItemStack entryToAEIS1 = null; - long contained1 = 0; - if (WarpDriveConfig.AEExtra_fluidDrive != null) { - entryToAEIS1 = Util.createItemStack(new ItemStack(WarpDriveConfig.AEExtra_fluidDrive, consume, FluidRegistry.getFluidID("deuterium"))); - contained1 = cellArray.countOfItemType(entryToAEIS1); - } - IAEItemStack entryToAEIS2 = null; - long contained2 = 0; - if (WarpDriveConfig.IC2_fluidCell != null) { - entryToAEIS2 = Util.createItemStack(new ItemStack(WarpDriveConfig.IC2_fluidCell, consume, FluidRegistry.getFluidID("deuterium"))); - contained2 = cellArray.countOfItemType(entryToAEIS2); - } - IAEItemStack entryToAEIS3 = null; - long contained3 = 0; - if (WarpDriveConfig.AS_deuteriumCell != 0) { - entryToAEIS3 = Util.createItemStack(new ItemStack(WarpDriveConfig.AS_deuteriumCell, consume, FluidRegistry.getFluidID("deuterium"))); - contained3 = cellArray.countOfItemType(entryToAEIS3); - } - - if (contained1 + contained2 + contained3 >= consume) { - if (contained1 > 0) { - cellArray.extractItems(entryToAEIS1); - } - if (contained2 > 0 && contained1 < consume) { - entryToAEIS2 = Util.createItemStack(new ItemStack(WarpDriveConfig.IC2_fluidCell, (int)(consume - contained2), FluidRegistry.getFluidID("deuterium"))); - cellArray.extractItems(entryToAEIS2); - } - if (contained3 > 0 && contained1 + contained2 < consume) { - entryToAEIS3 = Util.createItemStack(new ItemStack(WarpDriveConfig.AS_deuteriumCell, (int)(consume - contained1 - contained2), FluidRegistry.getFluidID("deuterium"))); - cellArray.extractItems(entryToAEIS3); - } - - ArrayList t = new ArrayList(); - t.add(new ItemStack(blockID, 1, blockMeta)); - return t; - } - } - } - return block.getBlockDropped(worldObj, i, j, k, blockMeta, 0); - } - - public int putInGrid(ItemStack itemStackSource) - { - int transferred = itemStackSource.stackSize; - IMEInventoryHandler cellArray = grid.getCellArray(); - if (cellArray != null) - { - IAEItemStack ret = cellArray.addItems(Util.createItemStack(itemStackSource)); - if (ret != null) - transferred -= ret.getStackSize(); - } - return transferred; - } - - public boolean putInChest(IInventory inventory, ItemStack itemStackSource) { - if (itemStackSource == null) { - stop(); - return false; - } - - int qtyLeft = itemStackSource.stackSize; - int transfer; - - if (inventory != null) { - // fill existing stacks first - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (!inventory.isItemValidForSlot(i, itemStackSource)) { - continue; - } - - ItemStack itemStack = inventory.getStackInSlot(i); - if (itemStack == null || !itemStack.isItemEqual(itemStackSource)) { - continue; - } - - transfer = Math.min(qtyLeft, itemStack.getMaxStackSize() - itemStack.stackSize); - itemStack.stackSize += transfer; - qtyLeft -= transfer; - if (qtyLeft <= 0) { - return true; - } - } - - // put remaining in empty slot - for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (!inventory.isItemValidForSlot(i, itemStackSource)) { - continue; - } - - ItemStack itemStack = inventory.getStackInSlot(i); - if (itemStack != null) { - continue; - } - - transfer = Math.min(qtyLeft, itemStackSource.getMaxStackSize()); - ItemStack dest = copyWithSize(itemStackSource, transfer); - inventory.setInventorySlotContents(i, dest); - qtyLeft -= transfer; - - if (qtyLeft <= 0) { - return true; - } - } - } - - while (qtyLeft > 0) { - transfer = Math.min(qtyLeft, itemStackSource.getMaxStackSize()); - ItemStack dropItemStack = copyWithSize(itemStackSource, transfer); - EntityItem itemEnt = new EntityItem(worldObj, xCoord + 0.5D, yCoord + 1.0D, zCoord + 0.5D, dropItemStack); - worldObj.spawnEntityInWorld(itemEnt); - qtyLeft -= transfer; - } - - return false; - } - - public static ItemStack copyWithSize(ItemStack itemStack, int newSize) - { - ItemStack ret = itemStack.copy(); - ret.stackSize = newSize; - return ret; - } - - private void scanLayer() { - //System.out.println("Scanning layer"); - valuablesInLayer.clear(); - valuableIndex = 0; - int radius, x, z, blockID; - int xmax, zmax; - int xmin, zmin; - - // Search for valuable blocks - x = xCoord; - z = zCoord; - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - for (radius = 1; radius <= WarpDriveConfig.ML_MAX_RADIUS; radius++) { - xmax = xCoord + radius; - xmin = xCoord - radius; - zmax = zCoord + radius; - zmin = zCoord - radius; - x = xCoord; - z = zmin; - for (; x <= xmax; x++) { - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - } - x = xmax; - z++; - for (; z <= zmax; z++) { - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - } - x--; - z = zmax; - for (; x >= xmin; x--) { - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - } - x = xmin; - z--; - for (; z > zmin; z--) { - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - } - x = xmin; - z = zmin; - for (; x < xCoord; x++) { - blockID = worldObj.getBlockId(x, currentLayer, z); - if (canDig(blockID, x, currentLayer, z)) { - if (isQuarry || WarpDriveConfig.MinerOres.contains(blockID)) {// Quarry collects all blocks or only collect valuables blocks - valuablesInLayer.add(new Vector3(x, currentLayer, z)); - } - } - } - } - - //System.out.println("" + this + " Found " + valuablesInLayer.size() + " valuables"); - } - - private int getEnergyLevel() { - TileEntityParticleBooster booster = findFirstBooster(); - if (booster != null) { - return booster.getEnergyStored(); - } else { - return 0; - } - } - - private boolean consumeEnergyPacketFromBooster(int amount, boolean simulate) { - TileEntityParticleBooster booster = findFirstBooster(); - if (booster != null) { - return booster.consumeEnergy(amount, simulate); - } else { - return false; - } - } - - private TileEntityParticleBooster findFirstBooster() { - TileEntity result; - result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); - - if (result != null && result instanceof TileEntityParticleBooster) - { - dx = 1; - dz = 0; - dy = 0; - return (TileEntityParticleBooster) result; - } - - result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); - - if (result != null && result instanceof TileEntityParticleBooster) - { - dx = -1; - dz = 0; - dy = 0; - return (TileEntityParticleBooster) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); - - if (result != null && result instanceof TileEntityParticleBooster) - { - dx = 0; - dz = 1; - dy = 0; - return (TileEntityParticleBooster) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); - - if (result != null && result instanceof TileEntityParticleBooster) - { - dx = 0; - dz = -1; - dy = 0; - return (TileEntityParticleBooster) result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - - if (result != null && result instanceof TileEntityParticleBooster) - { - dx = 0; - dz = 0; - dy = 1; - return (TileEntityParticleBooster) result; - } - - return null; - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - currentState = tag.getInteger("currentState"); - isQuarry = tag.getBoolean("isQuarry"); - currentLayer = tag.getInteger("currentLayer"); - useDeiterium = tag.getBoolean("useDeiterium"); - if (currentState == STATE_MINING) { - scanLayer(); - } - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setInteger("currentState", currentState); - tag.setBoolean("isQuarry", isQuarry); - tag.setInteger("currentLayer", currentLayer); - tag.setBoolean("useDeiterium", useDeiterium); - } - - // ComputerCraft - // IPeripheral methods implementation - @Override - public String getType() { - return "mininglaser"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - switch (method) { - case 0: // Mine() - if (isMining()) { - return new Boolean[] { false }; - } - - isQuarry = false; - delayTicksWarmup = 0; - currentState = STATE_WARMUP; - currentLayer = yCoord - layerOffset - 1; - useDeiterium = (arguments.length == 1 && FluidRegistry.isFluidRegistered("deuterium")); - return new Boolean[] { true }; - - case 1: // stop() - stop(); - break; - - case 2: // isMining() - return new Boolean[] { isMining() }; - - case 3: // Quarry() - if (isMining()) { - return new Boolean[] { false }; - } - - isQuarry = true; - delayTicksScan = 0; - currentState = STATE_WARMUP; - currentLayer = yCoord - layerOffset - 1; - useDeiterium = (arguments.length == 1 && FluidRegistry.isFluidRegistered("deuterium")); - return new Boolean[] { true }; - - case 4: // State is: state, energy, currentLayer, valuablesMined, valuablesInLayer = getMinerState() - int energy = getEnergyLevel(); - String status = getStatus(); - Integer retValuablesInLayer, retValuablesMined; - if (isMining()) { - retValuablesInLayer = valuablesInLayer.size(); - retValuablesMined = valuableIndex; - - return new Object[] {status, energy, currentLayer, retValuablesMined, retValuablesInLayer}; - } - return new Object[] {status, energy, currentLayer, 0, 0}; - - case 5: // Offset - if (arguments.length == 1) { - try { - layerOffset = Math.min(256, Math.abs(((Double)arguments[0]).intValue())); - } catch(Exception e) { - return new Integer[] { layerOffset }; - } - } - return new Integer[] { layerOffset }; - } - return null; - } - - public String getStatus() { - int energy = 0; - energy = getEnergyLevel(); - String state = "IDLE (not mining)"; - if (currentState == STATE_IDLE) { - state = "IDLE (not mining)"; - } else if (currentState == STATE_WARMUP) { - state = "Warming up..."; - } else if (currentState == STATE_SCANNING) { - if (isQuarry) { - state = "Scanning all"; - } else { - state = "Scanning ores"; - } - } else if (currentState == STATE_MINING) { - if (isQuarry) { - state = "Mining all"; - } else { - state = "Mining ores"; - } - if (useDeiterium) { - state = state + " using Deuterium"; - } - } - if (energy <= 0) { - state = state + " - Out of energy"; - } else if (((currentState == STATE_SCANNING) || (currentState == STATE_MINING)) && !enoughPower) { - state = state + " - Not enough power"; - } - return state; - } - - @Override - public void attach(IComputerAccess computer) { - computer.mount("/mininglaser", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/mininglaser")); - computer.mount("/mine", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/mininglaser/mine")); - computer.mount("/stop", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/mininglaser/stop")); - } - - @Override - public void detach(IComputerAccess computer) { - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } - - // Applied Energistics @Override - - @Override - public float getPowerDrainPerTick() { - return 1; - } - - @Override - public void validate() { - super.validate(); - MinecraftForge.EVENT_BUS.post(new GridTileLoadEvent(this, worldObj, getLocation())); - } - - @Override - public void invalidate() { - super.invalidate(); - MinecraftForge.EVENT_BUS.post(new GridTileUnloadEvent(this, worldObj, getLocation())); - } - - @Override - public WorldCoord getLocation() { - return new WorldCoord(xCoord, yCoord, zCoord); - } - - @Override - public boolean isValid() { - return true; - } - - @Override - public void setPowerStatus(boolean hasPower) { - powerStatus = hasPower; - } - - @Override - public boolean isPowered() { - return powerStatus; - } - - @Override - public IGridInterface getGrid() { - return grid; - } - - @Override - public void setGrid(IGridInterface parGrid) { - grid = parGrid; - } - - @Override - public World getWorld() { - return worldObj; - } - - @Override - public boolean coveredConnections() { - return true; - } - - @Override - public void setNetworkReady( boolean isReady ) { - AENetworkReady = isReady; - } - - @Override - public boolean isMachineActive() { - return isMining(); - } - - @Override - public String toString() { - return String.format("%s @ \'%s\' %d, %d, %d", new Object[] { - getClass().getSimpleName(), - worldObj == null ? "~NULL~" : worldObj.getWorldInfo().getWorldName(), - Integer.valueOf(xCoord), Integer.valueOf(yCoord), Integer.valueOf(zCoord)}); - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityMonitor.java b/src/cr0s/WarpDrive/machines/TileEntityMonitor.java deleted file mode 100644 index d9e718c2..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityMonitor.java +++ /dev/null @@ -1,116 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.WarpDrive; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.packet.Packet250CustomPayload; -import net.minecraft.server.MinecraftServer; -import net.minecraft.tileentity.TileEntity; - -public class TileEntityMonitor extends TileEntity implements IPeripheral { - private int frequency = -1; - - private String[] methodsArray = - { - "freq" - }; - - private int packetSendTicks = 20; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - packetSendTicks--; - if (packetSendTicks == 0) { - packetSendTicks = 20 * 5; - sendFreqPacket(); - } - return; - } - } - - public int getFrequency() { - return frequency; - } - - public void setFrequency(int parFrequency) { - if (frequency != parFrequency) { - frequency = parFrequency; - WarpDrive.debugPrint("" + this + " Monitor frequency set to " + frequency); - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - frequency = tag.getInteger("frequency"); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setInteger("frequency", frequency); - } - - // IPeripheral methods implementation - @Override - public String getType() { - return "monitor"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - if (arguments.length == 1) { - setFrequency(((Double)arguments[0]).intValue()); - } - return new Integer[] { frequency }; - } - - public void sendFreqPacket() { - if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(8); - DataOutputStream outputStream = new DataOutputStream(bos); - - try { - outputStream.writeInt(xCoord); - outputStream.writeInt(yCoord); - outputStream.writeInt(zCoord); - outputStream.writeInt(frequency); - } catch (Exception e) { - e.printStackTrace(); - } - - Packet250CustomPayload packet = new Packet250CustomPayload(); - packet.channel = "WarpDriveFreq"; - packet.data = bos.toByteArray(); - packet.length = bos.size(); - MinecraftServer.getServer().getConfigurationManager().sendToAllNear(xCoord, yCoord, zCoord, 100, worldObj.provider.dimensionId, packet); -// WarpDrive.debugPrint("" + this + " Packet '" + packet.channel + "' sent (" + xCoord + ", " + yCoord + ", " + zCoord + ") '" + frequency + "'"); - } - } - - @Override - public void attach(IComputerAccess computer) { - } - - @Override - public void detach(IComputerAccess computer) { - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityParticleBooster.java b/src/cr0s/WarpDrive/machines/TileEntityParticleBooster.java deleted file mode 100644 index c8efb3cf..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityParticleBooster.java +++ /dev/null @@ -1,46 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; - -import net.minecraft.nbt.NBTTagCompound; -import cr0s.WarpDrive.*; - -public class TileEntityParticleBooster extends WarpEnergyTE { - private int ticks = 0; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - ticks++; - if (ticks > 20) { - ticks = 0; - - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, Math.max(0, Math.min(10, Math.round((getEnergyStored() * 10) / WarpDriveConfig.PB_MAX_ENERGY_VALUE))), 3); - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - } - - // IEnergySink methods implementation - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.PB_MAX_ENERGY_VALUE; - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityPowerLaser.java b/src/cr0s/WarpDrive/machines/TileEntityPowerLaser.java deleted file mode 100644 index 914f396b..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityPowerLaser.java +++ /dev/null @@ -1,215 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.ForgeDirection; - -public class TileEntityPowerLaser extends TileEntityAbstractLaser implements IPeripheral { - Vector3 myVec; - Vector3 reactorVec; - ForgeDirection side = ForgeDirection.UNKNOWN; - TileEntityParticleBooster booster; - TileEntityPowerReactor reactor; - - boolean useLaser = false; - boolean doOnce = false; - - String[] methodArray = { - "energy", - "hasReactor", - "side", - "sendLaser", - "help" - }; - - @Override - public boolean shouldChunkLoad() { - return false; - } - - public TileEntityPowerReactor scanForReactor() { - reactor = null; - TileEntity te; - //I AM ON THE NORTH SIDE - side = ForgeDirection.UNKNOWN; - te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 2); - if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord, yCoord, zCoord + 1)) { - side = ForgeDirection.NORTH; - reactor = (TileEntityPowerReactor) te; - } - - //I AM ON THE SOUTH SIDE - te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 2); - if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord, yCoord, zCoord - 1)) { - side = ForgeDirection.SOUTH; - reactor = (TileEntityPowerReactor) te; - } - - //I AM ON THE WEST SIDE - te = worldObj.getBlockTileEntity(xCoord + 2, yCoord, zCoord); - if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord + 1, yCoord, zCoord)) { - side = ForgeDirection.WEST; - reactor = (TileEntityPowerReactor) te; - } - - //I AM ON THE EAST SIDE - te = worldObj.getBlockTileEntity(xCoord - 2, yCoord, zCoord); - if (te instanceof TileEntityPowerReactor && worldObj.isAirBlock(xCoord - 1, yCoord, zCoord)) { - side = ForgeDirection.EAST; - reactor = (TileEntityPowerReactor) te; - } - - setMetadata(); - - if (reactor != null) { - reactorVec = new Vector3(reactor).translate(0.5); - } - return reactor; - } - - private void setMetadata() { - int meta = 0; - if(side != ForgeDirection.UNKNOWN) { - meta = side.ordinal() - 1; - } - //WarpDrive.debugPrint("META:" + meta); - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, meta, 3); - } - - public TileEntityParticleBooster scanForBooster() { - booster = null; - TileEntity te; - te = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - if (te != null && te instanceof TileEntityParticleBooster) { - booster = (TileEntityParticleBooster)te; - } - - te = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord); - if (te != null && te instanceof TileEntityParticleBooster) { - booster = (TileEntityParticleBooster)te; - } - - return booster; - } - - @Override - public void updateEntity() { - if (doOnce == false) { - scanForReactor(); - scanForBooster(); - myVec = new Vector3(this).translate(0.5); - doOnce = true; - } - - if (useLaser == true) { - WarpDrive.sendLaserPacket(worldObj, myVec, reactorVec, 0.1F, 0.2F, 1.0F, 25, 50, 100); - useLaser = false; - } - } - - public void unlink() { - side = ForgeDirection.UNKNOWN; - setMetadata(); - } - - public void updateNeighbours() { - scanForBooster(); - scanForReactor(); - } - - private void laserReactor(int amount) { - if (amount <= 0) { - return; - } - - scanForBooster(); - scanForReactor(); - if(booster == null) - return; - if(reactor == null) - return; - if (booster.consumeEnergy(amount, false)) { - // WarpDrive.debugPrint("ReactorLaser on " + side.toString() +" side sending " + amount); - useLaser = true; - reactor.decreaseInstability(side, (int)(amount * this.RF_PER_INTERNAL)); - } - } - - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - } - - @Override - public String getType() { - return "warpdriveReactorLaser"; - } - - @Override - public String[] getMethodNames() { - return methodArray; - } - - private static String helpStr(Object[] args) { - if (args.length > 0) { - String arg = args[0].toString().toLowerCase(); - if (arg.equals("energy")) { - return WarpDrive.defEnergyStr; - } else if(arg.equals("hasReactor")) { - return "hasReactor(): returns true if the laser can see a reactor and false otherwise"; - } else if(arg.equals("sendlaser")) { - return "sendLaser(int): sends a laser of energy int to the reactor"; - } else if(arg.equals("side")) { - return "side(): returns 0-3 depending on which side of the reactor its on"; - } - } - return WarpDrive.defHelpStr; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context,int methodID, Object[] arguments) throws Exception { - String method = methodArray[methodID]; - if (method.equals("energy")) { - scanForBooster(); - if (booster == null) { - return new Object[] { 0,0 }; - } else { - return new Object[] { booster.getEnergyStored(), booster.getMaxEnergyStored() }; - } - } else if (method.equals("hasReactor")) { - return new Object[] { scanForReactor() != null }; - } else if (method.equals("sendLaser")) { - if (arguments.length >= 1) { - laserReactor(toInt(arguments[0])); - } - } else if(method.equals("help")) { - return new Object[] {helpStr(arguments)}; - } else if(method.equals("side")) { - return new Object[] { side.ordinal() - 2 }; - } - return null; - } - - @Override - public void attach(IComputerAccess computer) { - } - - @Override - public void detach(IComputerAccess computer) { - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/TileEntityPowerReactor.java b/src/cr0s/WarpDrive/machines/TileEntityPowerReactor.java deleted file mode 100644 index 03740d74..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityPowerReactor.java +++ /dev/null @@ -1,599 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.HashMap; -import java.util.Random; -import java.util.Set; - -import cofh.api.energy.IEnergyHandler; -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.WarpDrive; -import cr0s.WarpDrive.WarpDriveConfig; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.entity.Entity; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.ForgeDirection; - -public class TileEntityPowerReactor extends WarpEnergyTE implements IPeripheral { - private int containedEnergy = 0; - private static int tickTime; - private static int maxLasers; - private static int minGen; - - private int tickCount = 0; - - private double[] instabilityValues = new double[4]; // no instability = 0, explosion = 100 - private int lasersReceived = 0; - private int lastGenerationRate = 0; - private int releasedThisTick = 0; // amount of energy released during current tick update - private int releasedThisCycle = 0; // amount of energy released during current cycle - private int releasedLastCycle = 0; - - private boolean hold = true; // hold updates and power output until reactor is controlled (i.e. don't explode on chunk-loading while computer is booting) - private boolean active = false; - private static final int MODE_DONT_RELEASE = 0; - private static final int MODE_MANUAL_RELEASE = 1; - private static final int MODE_RELEASE_ABOVE = 2; - private static final int MODE_RELEASE_AT_RATE = 3; - private static final String[] MODE_STRING = {"OFF", "MANUAL", "ABOVE", "RATE"}; - private int releaseMode = 0; - private int releaseRate = 0; - private int releaseAbove = 0; - - private boolean init = false; - - IEnergyHandler aboveConnection; - IEnergyHandler belowConnection; - - private String[] methodArray = { - "getActive", - "setActive", // boolean - "energy", // returns energy, maxenergy - "instability", // returns ins0,1,2,3 - "release", // releases all energy - "releaseRate", // releases energy when more than arg0 is produced - "releaseAbove", // releases any energy above arg0 amount - "help" // returns help on arg0 function - }; - private HashMap connectedComputers = new HashMap(); - - { - for(int i = 0; i < 4; i++) { - instabilityValues[i] = 0; - } - - tickTime = WarpDriveConfig.PR_TICK_TIME; - maxLasers = WarpDriveConfig.PR_MAX_LASERS; - minGen = 4; - } - - private void increaseInstability(ForgeDirection from, boolean isNatural) { - if (canInterface(from) || hold) { - return; - } - - int side = from.ordinal() - 2; - if (containedEnergy > tickTime * minGen) { - double amountToIncrease = tickTime * Math.max(0.005D, Math.pow(worldObj.rand.nextDouble() * (containedEnergy / 4), 0.1) * 0.1); - //WarpDrive.debugPrint("InsInc" + amountToIncrease); - instabilityValues[side] += amountToIncrease * (isNatural ? 1.0D : 0.25D); - } else { - double amountToDecrease = tickTime * Math.max(0.005D, instabilityValues[side] * 0.02D); - instabilityValues[side] = Math.max(0.0D, instabilityValues[side] - amountToDecrease); - } - } - - private void increaseInstability(boolean isNatural) { - increaseInstability(ForgeDirection.NORTH, isNatural); - increaseInstability(ForgeDirection.SOUTH, isNatural); - increaseInstability(ForgeDirection.EAST, isNatural); - increaseInstability(ForgeDirection.WEST, isNatural); - } - - public void decreaseInstability(ForgeDirection from, int amount) { - if (canInterface(from)) { - return; - } - - // laser is active => start updating reactor - hold = false; - - if (amount <= 1) { - return; - } - - lasersReceived++; - - if (lasersReceived <= maxLasers) { - double consumeRateIncrease = 1 + Math.pow(Math.E, lastGenerationRate / 63095); // FIXME Math.pow(this.getMaxEnergyStored(), 0.6D) - double randomVariation = 0.4 + worldObj.rand.nextDouble(); - double amountToRemove = Math.min(Math.pow(amount * randomVariation, (1.0 / 3)) * consumeRateIncrease, 75); - int side = from.ordinal() - 2; - // WarpDrive.debugPrint("Instability on " + from.toString() + " decreased by " + String.format("%.1f", amountToRemove) + " after consumming " + amount); - instabilityValues[side] = Math.max(0, instabilityValues[side] - amountToRemove); - } else { - WarpDrive.debugPrint("Too many lasers received, instability increasing..."); - increaseInstability(from, false); - increaseInstability(false); - } - updateSideTextures(); - } - - public void generateEnergy() { - double stabilityOffset = 0.5; - for(int i = 0; i < 4; i++) { - stabilityOffset *= Math.max(0.01D, instabilityValues[i] / 100.0D); - } - - //WarpDrive.debugPrint("INSOFF" + stabilityOffset); - - if (active) {// producing, instability increase output, you want to take the risk - int amountToGenerate = (int)( tickTime * (0.5D + stabilityOffset) * (minGen + Math.ceil(Math.pow(containedEnergy, 0.6D))) ); - containedEnergy = Math.min(containedEnergy + amountToGenerate, getMaxEnergyStored()); - lastGenerationRate = amountToGenerate / tickTime; - } else {// decaying over 20s without producing power, you better have power for those lasers - int amountToDecay = (int)( tickTime * (1.0D - stabilityOffset) * (minGen + containedEnergy * 0.01D) ); - containedEnergy = Math.max(0, containedEnergy - amountToDecay); - lastGenerationRate = 0; - } - } - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - outputPower(); - releasedThisTick = 0; - - tickCount++; - if (tickCount % tickTime != 0) { - return; - } - tickCount = 0; - releasedLastCycle = releasedThisCycle; - releasedThisCycle = 0; - - if (!init) { - init = true; - updateNeighbours(); - } - - if (!active) { - lasersReceived = Math.max(0, lasersReceived - 2); - } else { - lasersReceived = 0; - } - updateSideTextures(); - - // unstable at all time - if (shouldExplode()) { - explode(); - } - increaseInstability(true); - - generateEnergy(); - - sendEvent("reactorPulse", new Object[] { lastGenerationRate }); - } - - private void explode() { - // remove blocks randomly up to 6 blocks around (breaking whatever protection is there) - int radius = (int) Math.floor(0.6D * Math.pow(containedEnergy, 0.125)); - WarpDrive.debugPrint(this + " Explosion radius: " + radius); - if (radius > 1) { - double c = 0.05 * Math.pow(containedEnergy, 0.125); // chance of a block being destroyed (ranges from 0.5 to 0.05) - WarpDrive.debugPrint(this + " Chance of removal: " + c); - for(int x = xCoord - radius; x < xCoord + radius; x++) { - for(int y = yCoord - radius; y < yCoord + radius; y++) { - for(int z = zCoord - radius; z < zCoord + radius; z++) { - if (z != zCoord || y != yCoord || x != xCoord) { - if (worldObj.rand.nextDouble() < c) { - worldObj.setBlockToAir(x, y, z); - } - } - } - } - } - } - // remove reactor - worldObj.setBlockToAir(xCoord, yCoord, zCoord); - // set a few TnT augmented around reactor - for (int i = 0; i < 3; i++) { - worldObj.newExplosion((Entity) null, - xCoord + worldObj.rand.nextInt(3) - 0.5D, - yCoord + worldObj.rand.nextInt(3) - 0.5D, - zCoord + worldObj.rand.nextInt(3) - 0.5D, - 4.0F + worldObj.rand.nextInt(3), - true, true); - } - } - - private void updateSideTextures() { - double maxInstability = 0.0D; - for (Double ins:instabilityValues) { - if (ins > maxInstability) { - maxInstability = ins; - } - } - int instabilityNibble = (int) Math.max(0, Math.min(3, Math.round( maxInstability / 25.0D))); - int energyNibble = (int) Math.max(0, Math.min(3, Math.round( 4.0D * containedEnergy / getMaxEnergyStored()))); - - int metadata = 4 * instabilityNibble + energyNibble; - // WarpDrive.debugPrint("updateSideTextures " + metadata); - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 3); - } - - private boolean shouldExplode() { - boolean exploding = false; - for(int i = 0; i < 4; i++) { - exploding = exploding || (instabilityValues[i] >= 100); - } - - if (exploding) { - active = false; - WarpDrive.debugPrint("EXPLODE!"); - } - return exploding; - } - - //Takes the arguments passed by function call and returns an appropriate string - private static String helpStr(Object[] args) { - if (args.length > 0) { - String arg = args[0].toString().toLowerCase(); - if (arg.equals("getactive")) { - return "getActive(): returns true if the reactor is active and false otherwise"; - } else if (arg.equals("setactive")) { - return "setActive(bool): activates the reactor if passed true and deactivates if passed false"; - } else if (arg.equals("energy")) { - return WarpDrive.defEnergyStr; - } else if (arg.equals("instability")) { - return "instability(): returns the 4 instability values (100 is the point when the reactor explodes)"; - } else if (arg.equals("release")) { - return "release(bool): sets the reactor to output all energy or disables outputting of energy"; - } else if (arg.equals("releaserate")) { - return "releaseRate(int): sets the reactor to try to release exactly int/tick"; - } else if (arg.equals("releaseabove")) { - return "releaseAbove(int): releases all energy above stored int"; - } - } - return WarpDrive.defHelpStr; - } - - public void updateNeighbours() { - TileEntity te; - IEnergyHandler ieh; - te = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - - boolean valid = false; - if (te != null) { - if (te instanceof IEnergyHandler) { - ieh = (IEnergyHandler)te; - if (ieh.canInterface(ForgeDirection.DOWN)) { - aboveConnection = ieh; - valid = true; - } - } - } - if (!valid) { - aboveConnection = null; - } - - valid = false; - te = worldObj.getBlockTileEntity(xCoord, yCoord - 1, zCoord); - if (te != null) { - if (te instanceof IEnergyHandler) { - ieh = (IEnergyHandler)te; - if (ieh.canInterface(ForgeDirection.UP)) { - WarpDrive.debugPrint("a network"); - belowConnection = ieh; - valid = true; - } - } - } - if (!valid) { - belowConnection = null; - } - - int[] xo = { 0, 0,-2, 2}; - int[] zo = { 2,-2, 0, 0}; - - for(int i = 0; i < 4; i++) { - te = worldObj.getBlockTileEntity(xCoord + xo[i], yCoord, zCoord + zo[i]); - if (te instanceof TileEntityPowerLaser) { - ((TileEntityPowerLaser)te).scanForReactor(); - } - } - } - - private void outputPower(IEnergyHandler ieh, ForgeDirection dir) { - int potentialRelease = getPotentialReleaseAmount(); - if (potentialRelease > 0) { - int amountToDump = ieh.receiveEnergy(dir, potentialRelease, true); - if (amountToDump > 0) { - int dumped = ieh.receiveEnergy(dir, amountToDump, false); - containedEnergy -= dumped; - releasedThisTick += dumped; - releasedThisCycle += dumped; - // WarpDrive.debugPrint(this + " outputed " + dumped + " RF, down to " + containedEnergy); - } - } - } - - private void outputPower() { - if (aboveConnection != null) { - outputPower(aboveConnection, ForgeDirection.DOWN); - } - - if (belowConnection != null) { - outputPower(belowConnection, ForgeDirection.UP); - } - } - - //COMPUTER INTERFACES - @Override - public String getType() { - return "warpdriveReactor"; - } - - @Override - public String[] getMethodNames() { - return methodArray; - } - - @Override - public void attach(IComputerAccess computer) { - int id = computer.getID(); - connectedComputers.put(id, computer); - } - - @Override - public void detach(IComputerAccess computer) { - int id = computer.getID(); - if (connectedComputers.containsKey(id)) { - connectedComputers.remove(id); - } - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int methodID, Object[] arguments) throws Exception { - if (methodID < 0 || methodID >= methodArray.length) { - return null; - } - - // computer is alive => start updating reactor - hold = false; - - String methodName = methodArray[methodID]; - - if (methodName.equals("getActive")) { - if (releaseMode == MODE_DONT_RELEASE || releaseMode == MODE_MANUAL_RELEASE) { - return new Object[] { active, MODE_STRING[releaseMode], 0 }; - } else if (releaseMode == MODE_RELEASE_ABOVE) { - return new Object[] { active, MODE_STRING[releaseMode], releaseAbove }; - } else { - return new Object[] { active, MODE_STRING[releaseMode], releaseRate }; - } - } else if (methodName.equals("setActive")) { - boolean activate = false; - try { - activate = toBool(arguments[0]); - } catch(Exception e) { - throw new Exception("Function expects an boolean value"); - } - if (active && !activate) { - sendEvent("reactorDeactivation", null); - } else if(!active && activate) { - sendEvent("reactorActivation", null); - } - active = activate; - } else if (methodName.equals("energy")) { - return new Object[] { containedEnergy, getMaxEnergyStored(), releasedLastCycle / tickTime, aboveConnection != null, belowConnection != null }; - } else if (methodName.equals("instability")) { - Object[] retVal = new Object[4]; - for(int i = 0; i < 4; i++) { - retVal[i] = instabilityValues[i]; - } - return retVal; - } else if(methodName.equals("release")) { - boolean doRelease = false; - if (arguments.length > 0) { - try { - doRelease = toBool(arguments[0]); - } catch(Exception e) { - throw new Exception("Function expects an boolean value"); - } - - releaseMode = doRelease ? MODE_MANUAL_RELEASE : MODE_DONT_RELEASE; - releaseAbove = 0; - releaseRate = 0; - } - return new Object[] { releaseMode != MODE_DONT_RELEASE }; - } else if(methodName.equals("releaseRate")) { - int rate = -1; - try { - rate = toInt(arguments[0]); - } catch(Exception e) { - throw new Exception("Function expects an integer value"); - } - - if (rate <= 0) { - releaseMode = MODE_DONT_RELEASE; - releaseRate = 0; - } else { -/* releaseAbove = (int)Math.ceil(Math.pow(rate, 1.0 / 0.6)); - WarpDrive.debugPrint("releaseAbove " + releaseAbove); - releaseMode = MODE_RELEASE_ABOVE;/**/ - // player has to adjust it - releaseRate = rate; - releaseMode = MODE_RELEASE_AT_RATE; - } - - return new Object[] { MODE_STRING[releaseMode], releaseRate }; - } else if(methodName.equals("releaseAbove")) { - int above = -1; - try { - above = toInt(arguments[0]); - } catch(Exception e) { - throw new Exception("Function expects an integer value"); - } - - if (above <= 0) { - releaseMode = 0; - releaseAbove = MODE_DONT_RELEASE; - } else { - releaseMode = MODE_RELEASE_ABOVE; - releaseAbove = above; - } - - return new Object[] { MODE_STRING[releaseMode], releaseAbove }; - } else if (methodName.equals("debugLaser")) { - //WarpDrive.debugPrint("debugMethod"); - int side = toInt(arguments[0]); - int amount = toInt(arguments[1]); - - ForgeDirection d; - if (side == 0) { - d = ForgeDirection.NORTH; - } else if (side == 1) { - d = ForgeDirection.SOUTH; - } else if (side == 2) { - d = ForgeDirection.WEST; - } else if (side == 3) { - d = ForgeDirection.EAST; - } else { - d = ForgeDirection.UP; - } - - if (amount < containedEnergy) { - containedEnergy -= amount; - decreaseInstability(d,amount); - } - } else if (methodName.equals("help")) { - return new Object[] { helpStr(arguments) }; - } - - return null; - } - - private void sendEvent(String eventName, Object[] arguments) { - // WarpDrive.debugPrint("" + this + " Sending event '" + eventName + "'"); - Set keys = connectedComputers.keySet(); - for(Integer key:keys) { - IComputerAccess comp = connectedComputers.get(key); - comp.queueEvent(eventName, arguments); - } - } - - //POWER INTERFACES - @Override - public boolean canInterface(ForgeDirection from) { - if(from.equals(ForgeDirection.UP) || from.equals(ForgeDirection.DOWN)) { - return true; - } - return false; - } - - private int getPotentialReleaseAmount() { - if (hold) {// still loading/booting => hold output - return 0; - } - int capacity = Math.max(0, 2 * lastGenerationRate - releasedThisTick); - if (releaseMode == MODE_MANUAL_RELEASE) { - return Math.min(Math.max(0, containedEnergy ), capacity); - } else if (releaseMode == MODE_RELEASE_ABOVE) { - return Math.min(Math.max(0, containedEnergy - releaseAbove), capacity); - } else if (releaseMode == MODE_RELEASE_AT_RATE) { - int remainingRate = Math.max(0, releaseRate - releasedThisTick); - return Math.min(Math.max(0, containedEnergy ), Math.min(remainingRate, capacity)); - } - return 0; - } - - @Override - public int receiveEnergy(ForgeDirection from, int amount, boolean sim) { - return 0; - } - - @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { - int dumped; - if (!canInterface(from)) { - return 0; - } - - dumped = Math.min(maxExtract, getPotentialReleaseAmount()); - if (!simulate) { - releasedThisTick += dumped; - releasedThisCycle += dumped; - containedEnergy = Math.max(0, containedEnergy - dumped); - // WarpDrive.debugPrint(this + " extracted " + dumped + " RF, down to " + containedEnergy); - } - - return dumped; - } - - @Override - public int getEnergyStored() { - return containedEnergy; - } - - @Override - public int getEnergyStored(ForgeDirection from) { - if (canInterface(from)) { - return getEnergyStored(); - } - return 0; - } - - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.PR_MAX_ENERGY; - } - - @Override - public int getMaxEnergyStored(ForgeDirection from) { - if (canInterface(from)) { - return getMaxEnergyStored(); - } - return 0; - } - - //NBT INTERFACES - @Override - public void writeToNBT(NBTTagCompound nbt) { - super.writeToNBT(nbt); - nbt.setInteger("energy", containedEnergy); - nbt.setInteger("releaseMode", releaseMode); - nbt.setInteger("releaseRate", releaseRate); - nbt.setInteger("releaseAbove", releaseAbove); - nbt.setDouble("i0", instabilityValues[0]); - nbt.setDouble("i1", instabilityValues[1]); - nbt.setDouble("i2", instabilityValues[2]); - nbt.setDouble("i3", instabilityValues[3]); - nbt.setBoolean("active", active); - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - super.readFromNBT(nbt); - containedEnergy = nbt.getInteger("energy"); - releaseMode = nbt.getInteger("releaseMode"); - releaseRate = nbt.getInteger("releaseRate"); - releaseAbove = nbt.getInteger("releaseAbove"); - instabilityValues[0] = nbt.getDouble("i0"); - instabilityValues[1] = nbt.getDouble("i1"); - instabilityValues[2] = nbt.getDouble("i2"); - instabilityValues[3] = nbt.getDouble("i3"); - active = nbt.getBoolean("active"); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/TileEntityProtocol.java b/src/cr0s/WarpDrive/machines/TileEntityProtocol.java deleted file mode 100644 index 6d8dc968..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityProtocol.java +++ /dev/null @@ -1,670 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import dan200.computercraft.api.ComputerCraftAPI; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.DamageSource; -import cr0s.WarpDrive.*; - -/** - * Protocol block tile entity - * @author Cr0s - */ -public class TileEntityProtocol extends TileEntity implements IPeripheral -{ - // Variables - private int distance = 0; - private int direction = 0; - private int mode = 0; - - private boolean jumpFlag = false; - private boolean summonFlag = false; - private String toSummon = ""; - - private String targetJumpgateName = ""; - - // Gabarits - private int front, right, up; - private int back, left, down; - - // Player attaching - public ArrayList players = new ArrayList(); - public String playersString = ""; - - private String beaconFrequency = ""; - - boolean ready = false; // Ready to operate (valid assembly) - - public String[] methodsArray = { - "dim_getp", "dim_setp", // 0, 1 - "dim_getn", "dim_setn", // 2, 3 - "set_mode", "set_distance", "set_direction", // 4, 5, 6 - "get_attached_players", "summon", "summon_all", // 7, 8, 9 - "get_x", "get_y", "get_z", // 10, 11, 12 - "get_energy_level", "do_jump", "get_ship_size", // 13, 14, 15 - "set_beacon_frequency", "get_dx", "get_dz", // 16, 17, 18 - "set_core_frequency", "is_in_space", "is_in_hyperspace", // 19, 20, 21 - "set_target_jumpgate", // 22 - "isAttached" // 23 - }; - - private int ticks = 0; - private final int BLOCK_UPDATE_INTERVAL = 20 * 3; // 3 seconds - - private TileEntityReactor core = null; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - - if (++ticks >= BLOCK_UPDATE_INTERVAL) { - core = findCoreBlock(); - if (core != null) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, mode, 1 + 2); // Activated - } else { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); // Inactive - } - - ticks = 0; - } - } - - private void setJumpDistance(int distance) { - System.out.println("Setting jump distance: " + distance); - this.distance = distance; - } - - private void setMode(int mode) { - // System.out.println("Setting mode: " + mode); - this.mode = mode; - } - - private void setDirection(int dir) { - if (dir == 1) { - this.direction = -1; - } else if (dir == 2) { - this.direction = -2; - } else if (dir == 255) { - this.direction = 270; - } else { - this.direction = dir; - } - //WarpDrive.debugPrint("" + this + " Direction set to " + this.direction); - } - - private void doJump() { - if (core != null) { - // Adding random ticks to warmup - core.randomWarmupAddition = worldObj.rand.nextInt(WarpDriveConfig.WC_WARMUP_RANDOM_TICKS); - } else { - WarpDrive.debugPrint("" + this + " doJump without a core"); - } - - setJumpFlag(true); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - setMode(tag.getInteger("mode")); - setFront(tag.getInteger("front")); - setRight(tag.getInteger("right")); - setUp(tag.getInteger("up")); - setBack(tag.getInteger("back")); - setLeft(tag.getInteger("left")); - setDown(tag.getInteger("down")); - setDistance(tag.getInteger("distance")); - setDirection(tag.getInteger("direction")); - playersString = tag.getString("players"); - updatePlayersList(); - setBeaconFrequency(tag.getString("bfreq")); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - updatePlayersString(); - tag.setString("players", playersString); - tag.setInteger("mode", this.mode); - tag.setInteger("front", this.front); - tag.setInteger("right", this.right); - tag.setInteger("up", this.up); - tag.setInteger("back", this.back); - tag.setInteger("left", this.left); - tag.setInteger("down", this.down); - tag.setInteger("distance", this.distance); - tag.setInteger("direction", this.direction); - tag.setString("bfreq", getBeaconFrequency()); - // FIXME: shouldn't we save boolean jumpFlag, boolean summonFlag, String toSummon, String targetJumpgateName? - } - - public void attachPlayer(EntityPlayer entityPlayer) { - for (int i = 0; i < players.size(); i++) { - String nick = players.get(i); - - if (entityPlayer.username.equals(nick)) { - entityPlayer.addChatMessage(getBlockType().getLocalizedName() + " Detached."); - players.remove(i); - return; - } - } - - entityPlayer.attackEntityFrom(DamageSource.generic, 1); - players.add(entityPlayer.username); - updatePlayersString(); - entityPlayer.addChatMessage(getBlockType().getLocalizedName() + " Successfully attached."); - } - - public void updatePlayersString() { - String nick; - this.playersString = ""; - - for (int i = 0; i < players.size(); i++) { - nick = players.get(i); - this.playersString += nick + "|"; - } - } - - public void updatePlayersList() { - String[] playersArray = playersString.split("\\|"); - - for (int i = 0; i < playersArray.length; i++) { - String nick = playersArray[i]; - - if (!nick.isEmpty()) { - players.add(nick); - } - } - } - - public String getAttachedPlayersList() { - StringBuilder list = new StringBuilder(""); - - for (int i = 0; i < this.players.size(); i++) { - String nick = this.players.get(i); - list.append(nick + ((i == this.players.size() - 1) ? "" : ", ")); - } - - if (players.isEmpty()) { - list = new StringBuilder(""); - } - - return list.toString(); - } - - /** - * @return the jumpFlag - */ - public boolean isJumpFlag() { - return jumpFlag; - } - - /** - * @param jumpFlag the jumpFlag to set - */ - public void setJumpFlag(boolean jumpFlag) { - WarpDrive.debugPrint("" + this + " setJumpFlag(" + jumpFlag + ")"); - this.jumpFlag = jumpFlag; - } - - /** - * @return the front - */ - public int getFront() { - return front; - } - - /** - * @param front the front to set - */ - public void setFront(int front) { - this.front = front; - } - - /** - * @return the right - */ - public int getRight() { - return right; - } - - /** - * @param right the right to set - */ - public void setRight(int right) { - this.right = right; - } - - /** - * @return the up - */ - public int getUp() { - return up; - } - - /** - * @param up the up to set - */ - public void setUp(int up) { - this.up = up; - } - - /** - * @return the back - */ - public int getBack() { - return back; - } - - /** - * @param back the back to set - */ - public void setBack(int back) { - this.back = back; - } - - /** - * @return the left - */ - public int getLeft() { - return left; - } - - /** - * @param left the left to set - */ - public void setLeft(int left) { - this.left = left; - } - - /** - * @return the down - */ - public int getDown() { - return down; - } - - /** - * @param down the down to set - */ - public void setDown(int down) { - this.down = down; - } - - public void setDistance(int distance) { - this.distance = distance; - } - - public int getDistance() - { - return this.distance; - } - - /** - * @return the mode - */ - public int getMode() { - return mode; - } - - /** - * @return the direction - */ - public int getDirection() { - return direction; - } - - /** - * @return the summonFlag - */ - public boolean isSummonAllFlag() { - return summonFlag; - } - - /** - * @param summonFlag the summonFlag to set - */ - public void setSummonAllFlag(boolean summonFlag) { - this.summonFlag = summonFlag; - } - - @Override - public String getType() { - return "warpcore"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public void attach(IComputerAccess computer) { - computer.mount("/warpcontroller", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/warpcontroller")); - computer.mount("/startup", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/warpcontroller/startup")); - } - - @Override - public void detach(IComputerAccess computer) { - } - - /** - * @return the toSummon - */ - public String getToSummon() { - return toSummon; - } - - /** - * @param toSummon the toSummon to set - */ - public void setToSummon(String toSummon) { - this.toSummon = toSummon; - } - - /** - * @return the beaconFrequency - */ - public String getBeaconFrequency() { - return beaconFrequency; - } - - /** - * @param beaconFrequency the beaconFrequency to set - */ - public void setBeaconFrequency(String beaconFrequency) { - //WarpDrive.debugPrint("Setting beacon frequency: " + beaconFrequency); - this.beaconFrequency = beaconFrequency; - } - - private TileEntityReactor findCoreBlock() { - TileEntity te; - - te = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); - if (te != null && te instanceof TileEntityReactor) { - return (TileEntityReactor)te; - } - - te = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); - if (te != null && te instanceof TileEntityReactor) { - return (TileEntityReactor)te; - } - - te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); - if (te != null && te instanceof TileEntityReactor) { - return (TileEntityReactor)te; - } - - te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); - if (te != null && te instanceof TileEntityReactor) { - return (TileEntityReactor)te; - } - - return null; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - int argInt0, argInt1, argInt2; - //WarpDrive.debugPrint("[ProtoBlock] Method " + method + " " + methodsArray[method] + " called!"); - switch (method) { - case 0: // dim_getp () - return new Integer[] { getFront(), getRight(), getUp() }; - - case 1: // dim_setp (front, right, up) - if (arguments.length != 3) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - argInt1 = ((Double)arguments[1]).intValue(); - argInt2 = ((Double)arguments[2]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - if (argInt0 < 0 || argInt1 < 0 || argInt2 < 0) { - return new Integer[] { -1 }; - } - - System.out.println("Setting positive gabarits: f: " + argInt0 + " r: " + argInt1 + " u: " + argInt2); - setFront(((Double)arguments[0]).intValue()); - setRight(((Double)arguments[1]).intValue()); - setUp(((Double)arguments[2]).intValue()); - WarpDrive.instance.warpCores.removeDeadCores(); - break; - - case 2: // dim_getn () - return new Integer[] { getBack(), getLeft(), getDown() }; - - case 3: // dim_setn (back, left, down) - if (arguments.length != 3) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - argInt1 = ((Double)arguments[1]).intValue(); - argInt2 = ((Double)arguments[2]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - if (argInt0 < 0 || argInt1 < 0 || argInt2 < 0) { - return new Integer[] { -1 }; - } - - System.out.println("Setting negative gabarits: b: " + argInt0 + " l: " + argInt1 + " d: " + argInt2); - setBack(argInt0); - setLeft(argInt1); - setDown(argInt2); - WarpDrive.instance.warpCores.removeDeadCores(); - break; - - case 4: // set_mode (mode) - if (arguments.length != 1) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - - setMode(argInt0); - break; - - case 5: // set_distance (distance) - if (arguments.length != 1) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - - setJumpDistance(argInt0); - break; - - case 6: // set_direction (dir) - if (arguments.length != 1) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - - setDirection(argInt0); - break; - - case 7: // get_attached_players - String list = ""; - - for (int i = 0; i < this.players.size(); i++) { - String nick = this.players.get(i); - list += nick + ((i == this.players.size() - 1) ? "" : ","); - } - - if (players.isEmpty()) { - list = ""; - } - - return new Object[] { list }; - - case 8: // summon - if (arguments.length != 1) { - return new Integer[] { -1 }; - } - try { - argInt0 = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Integer[] { -1 }; - } - - if (argInt0 >= 0 && argInt0 < players.size()) { - setToSummon(players.get(argInt0)); - } - break; - - case 9: // summon_all - this.setSummonAllFlag(true); - break; - - case 10: // get_x - if (core == null) { - return null; - } - - return new Object[] { core.xCoord }; - - case 11: // get_y - if (core == null) { - return null; - } - - return new Object[] { core.yCoord }; - - case 12: // get_z - if (core == null) { - return null; - } - - return new Object[] { core.zCoord }; - - case 13: // get_energy_value - if (core == null) { - return null; - } - - return new Object[] { (core.getEnergyStored() ) }; - - case 14: // do_jump - doJump(); - break; - - case 15: // get_ship_size - if (core != null) { - StringBuilder reason = new StringBuilder(); - try { - if (!core.validateShipSpatialParameters(reason)) { - core.messageToAllPlayersOnShip(reason.toString()); - return null; - } - return new Object[] { core.shipVolume }; - } catch(Exception e) { - if (WarpDriveConfig.debugMode) { - e.printStackTrace(); - } - return null; - } - } - break; - - case 16: // set_beacon_frequency - if (arguments.length != 1) { - return new Integer[] { -1 }; - } - - setBeaconFrequency((String)arguments[0]); - break; - - case 17: // get_dx - if (core != null) { - return new Object[] { core.dx }; - } - break; - - case 18: // get_dz - if (core != null) { - return new Object[] { core.dz }; - } - break; - - case 19: // set_core_frequency - if (arguments.length == 1 && (core != null)) { - core.coreFrequency = ((String)arguments[0]).replace("/", "").replace(".", "").replace("\\", "."); - } - break; - - case 20: // is_in_space - return new Boolean[] { worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID }; - - case 21: // is_in_hyperspace - return new Boolean[] { worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID }; - - case 22: // set_target_jumpgate - if (arguments.length == 1) { - setTargetJumpgateName((String)arguments[0]); - } - break; - - case 23: // isAttached - if (core != null) { - return new Object[] { (boolean)(core.controller != null) }; - } - break; - } - - return new Integer[] { 0 }; - } - - /** - * @return the targetJumpgateName - */ - public String getTargetJumpgateName() - { - return targetJumpgateName; - } - - /** - * @param targetJumpgateName the targetJumpgateName to set - */ - public void setTargetJumpgateName(String targetJumpgateName) - { - this.targetJumpgateName = targetJumpgateName; - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } - - @Override - public String toString() { - return String.format("%s \'%s\' @ \'%s\' %d, %d, %d", new Object[] { - getClass().getSimpleName(), - core == null ? beaconFrequency : core.coreFrequency, - worldObj == null ? "~NULL~" : worldObj.getWorldInfo().getWorldName(), - Integer.valueOf(xCoord), Integer.valueOf(yCoord), Integer.valueOf(zCoord)}); - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityRadar.java b/src/cr0s/WarpDrive/machines/TileEntityRadar.java deleted file mode 100644 index 8977268b..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityRadar.java +++ /dev/null @@ -1,174 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cpw.mods.fml.common.FMLCommonHandler; -import dan200.computercraft.api.ComputerCraftAPI; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -import java.util.ArrayList; - -import net.minecraft.nbt.NBTTagCompound; -import cr0s.WarpDrive.*; - -public class TileEntityRadar extends WarpEnergyTE implements IPeripheral { - private String[] methodsArray = - { - "scanRay", // 0 - "scanRadius", // 1 - "getResultsCount", // 2 - "getResult", // 3 - "getEnergyLevel", // 4 - "pos" // 5 - }; - - private ArrayList results; - - private int scanRadius = 0; - private int cooldownTime = 0; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - try { - if (worldObj.getBlockMetadata(xCoord, yCoord, zCoord) == 2) { - cooldownTime++; - if (cooldownTime > (20 * ((scanRadius / 1000) + 1))) { - WarpDrive.debugPrint("" + this + " Scanning over " + scanRadius + " radius..."); - WarpDrive.instance.warpCores.removeDeadCores(); - results = WarpDrive.instance.warpCores.searchWarpCoresInRadius(xCoord, yCoord, zCoord, scanRadius); - WarpDrive.debugPrint("" + this + " Scan found " + results.size() + " results"); - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); - cooldownTime = 0; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - } - - // IPeripheral methods implementation - @Override - public String getType() { - return "radar"; - } - - @Override - public String[] getMethodNames() { - return methodsArray; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - switch (method) { - case 0: // scanRay (toX, toY, toZ) - return new Object[] { -1 }; - - case 1: // scanRadius (radius) - if (arguments.length != 1) { - return new Boolean[] { false }; - } - int radius; - try { - radius = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Boolean[] { false }; - } - - if (radius <= 0 || radius > 10000) { - scanRadius = 0; - results = null; - return new Boolean[] { false }; - } - if (!consumeEnergy(Math.max(radius, 100) * Math.max(radius, 100), false)) { - results = null; - return new Boolean[] { false }; - } - - // Begin searching - scanRadius = radius; - cooldownTime = 0; - results = null; - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 2, 1 + 2); - return new Boolean[] { true }; - - case 2: // getResultsCount - if (results != null) { - return new Integer[] { results.size() }; - } - return new Integer[] { 0 }; - - case 3: // getResult - if (arguments.length == 1 && (results != null)) { - int index; - try { - index = ((Double)arguments[0]).intValue(); - } catch(Exception e) { - return new Object[] { "FAIL", 0, 0, 0 }; - } - if (index >= 0 && index < results.size()) { - TileEntityReactor res = results.get(index); - if (res != null) - { - int yAddition = (res.worldObj.provider.dimensionId == WarpDriveConfig.G_SPACE_DIMENSION_ID) ? 256 : (res.worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) ? 512 : 0; - return new Object[] { res.coreFrequency, res.xCoord, res.yCoord + yAddition, res.zCoord }; - } - } - } - return new Object[] { "FAIL", 0, 0, 0 }; - - case 4: // getEnergyLevel - return new Integer[] { getEnergyStored() }; - - case 5: // Pos - return new Integer[] { xCoord, yCoord, zCoord }; - } - - return null; - } - - @Override - public void attach(IComputerAccess computer) { - computer.mount("/radar", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/radar")); - computer.mount("/scan", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/radar/scan")); - computer.mount("/ping", ComputerCraftAPI.createResourceMount(WarpDrive.class, "warpdrive", "lua/radar/ping")); - if (worldObj.getBlockMetadata(xCoord, yCoord, zCoord) == 0) { - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); - } - } - - @Override - public void detach(IComputerAccess computer) { - // worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); - } - - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.WR_MAX_ENERGY_VALUE; - } - - // IEnergySink methods implementation - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityReactor.java b/src/cr0s/WarpDrive/machines/TileEntityReactor.java deleted file mode 100644 index cba74fc3..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityReactor.java +++ /dev/null @@ -1,1082 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionEffect; -import net.minecraft.server.MinecraftServer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityChest; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MathHelper; -import net.minecraft.world.WorldServer; -import net.minecraftforge.common.DimensionManager; -import cpw.mods.fml.common.FMLCommonHandler; -import cr0s.WarpDrive.*; - -/** - * @author Cr0s - */ -public class TileEntityReactor extends WarpEnergyTE -{ - public Boolean ready; - - public Boolean launchState = false; - - public final int JUMP_UP = -1; - public final int JUMP_DOWN = -2; - int dx, dz; - int direction; - int distance; - - public int maxX, maxY, maxZ; - public int minX, minY, minZ; - - public int shipFront, shipBack; - public int shipLeft, shipRight; - public int shipUp, shipDown; - public int shipLength; - public int shipVolume; - private int currentMode = 0; - - private static final byte MODE_TELEPORT = 3; -// private static final byte MODE_IDLE = 0; - private static final byte MODE_BASIC_JUMP = 1; // 0-128 - private static final byte MODE_LONG_JUMP = 2; // 0-12800 - private static final byte MODE_BEACON_JUMP = 4; // Jump ship by beacon - private static final byte MODE_HYPERSPACE = 5; // Jump to Hyperspace - private static final byte MODE_GATE_JUMP = 6; // Jump via jumpgate - - private int warmupTime = 0; - private int cooldownTime = 0; - public int randomWarmupAddition = 0; - - private int chestTeleportUpdateTicks = 0; - private int registryUpdateTicks = 0; - public String coreFrequency = "default"; - - public int isolationBlocksCount = 0; - public int isolationUpdateTicks = 0; - - public TileEntityProtocol controller; - - private boolean soundPlayed = false; - - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - super.updateEntity(); - - // Always cooldown - if (cooldownTime > 0) { - cooldownTime--; - warmupTime = 0; - } - - // Update state - if (cooldownTime > 0) { // cooling down (2) - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 2, 1 + 2); - } else if (controller == null) { // not connected (0) - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); - } else if (controller.isJumpFlag() || this.controller.isSummonAllFlag() || !this.controller.getToSummon().isEmpty()) { // active (1) - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 1, 1 + 2); - } else { // inactive - worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 1 + 2); - } - - // Update warp core in cores registry - if (++registryUpdateTicks > WarpDriveConfig.WC_CORES_REGISTRY_UPDATE_INTERVAL_SECONDS * 20) { - registryUpdateTicks = 0; - WarpDrive.instance.warpCores.updateInRegistry(this); -// WarpDrive.instance.registry.printRegistry(); -// WarpDrive.debugPrint("" + this + " controller is " + controller + ", warmupTime " + warmupTime + ", currentMode " + currentMode + ", jumpFlag " + (controller == null ? "NA" : controller.isJumpFlag()) + ", cooldownTime " + cooldownTime); - - TileEntity c = findControllerBlock(); - if (c == null) { - controller = null; - warmupTime = 0; - soundPlayed = false; - return; - } - controller = (TileEntityProtocol)c; - } - - if (++isolationUpdateTicks > WarpDriveConfig.WC_ISOLATION_UPDATE_INTERVAL_SECONDS * 20) { - isolationUpdateTicks = 0; - updateIsolationState(); - } - - if (controller == null) { - return; - } - - currentMode = controller.getMode(); - - StringBuilder reason = new StringBuilder(); - - if ((controller.isJumpFlag() && (isolationUpdateTicks == 1)) || this.controller.isSummonAllFlag() || !this.controller.getToSummon().isEmpty()) { - if (!validateShipSpatialParameters(reason)) { - if (controller.isJumpFlag()) { - controller.setJumpFlag(false); - messageToAllPlayersOnShip(reason.toString()); - } - warmupTime = 0; - soundPlayed = false; - return; - } - - if (this.controller.isSummonAllFlag()) { - summonPlayers(); - controller.setSummonAllFlag(false); - } else if (!this.controller.getToSummon().isEmpty()) { - summonSinglePlayer(this.controller.getToSummon()); - this.controller.setToSummon(""); - } - } - - switch (currentMode) { - case MODE_TELEPORT: - if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) { - if (isChestSummonMode()) { - chestTeleportUpdateTicks++; - if (chestTeleportUpdateTicks >= 20) { - summonPlayersByChestCode(); - chestTeleportUpdateTicks = 0; - } - } else { - teleportPlayersToSpace(); - } - } else { - chestTeleportUpdateTicks = 0; - } - break; - - case MODE_BASIC_JUMP: - case MODE_LONG_JUMP: - case MODE_BEACON_JUMP: - case MODE_HYPERSPACE: - case MODE_GATE_JUMP: - if (controller.isJumpFlag()) { - // Compute warm-up time - int targetCooldown = 0; - switch (currentMode) { - case MODE_BASIC_JUMP: - case MODE_LONG_JUMP: - if (distance < 50) { - targetCooldown = (WarpDriveConfig.WC_WARMUP_SHORTJUMP_SECONDS) * 20 / 3; - } else { - targetCooldown = (WarpDriveConfig.WC_WARMUP_LONGJUMP_SECONDS) * 20; - } - break; - - case MODE_BEACON_JUMP: - case MODE_HYPERSPACE: - case MODE_GATE_JUMP: - default: - targetCooldown = (WarpDriveConfig.WC_WARMUP_LONGJUMP_SECONDS) * 20; - break; - } - // Select best sound file and adjust offset - int soundThreshold = 0; - String soundFile = ""; - if (targetCooldown < 10 * 20) { - soundThreshold = targetCooldown - 4 * 20; - soundFile = "warpdrive:warp_4s"; - } else if (targetCooldown > 29 * 20) { - soundThreshold = targetCooldown - 30 * 20; - soundFile = "warpdrive:warp_30s"; - } else { - soundThreshold = targetCooldown - 10 * 20; - soundFile = "warpdrive:warp_10s"; - } - // Add random duration - soundThreshold += randomWarmupAddition; - - // Check cooldown time - if (cooldownTime > 0) { - if (cooldownTime % 20 == 0) { - int seconds = cooldownTime / 20; - if ((seconds < 5) || ((seconds < 30) && (seconds % 5 == 0)) || (seconds % 10 == 0)) { - messageToAllPlayersOnShip("Warp core is cooling down... " + cooldownTime / 20 + "s to go..."); - } - } - return; - } - - // Set up activated animation - if (warmupTime == 0) { - messageToAllPlayersOnShip("Running pre-jump checklist..."); - - // update ship parameters - if (!validateShipSpatialParameters(reason)) { - controller.setJumpFlag(false); - messageToAllPlayersOnShip(reason.toString()); - return; - } - makePlayersOnShipDrunk(targetCooldown + WarpDriveConfig.WC_WARMUP_RANDOM_TICKS); - } - - if (!soundPlayed && (soundThreshold > warmupTime)) { - worldObj.playSoundEffect(xCoord + 0.5f, yCoord + 0.5f, zCoord + 0.5f, soundFile, 4F, 1F); - soundPlayed = true; - } - - // Awaiting cool-down time - if (warmupTime < (targetCooldown + randomWarmupAddition)) { - warmupTime++; - return; - } - - warmupTime = 0; - soundPlayed = false; - - if (!validateShipSpatialParameters(reason)) { - controller.setJumpFlag(false); - messageToAllPlayersOnShip(reason.toString()); - return; - } - - if (WarpDrive.instance.warpCores.isWarpCoreIntersectsWithOthers(this)) { - controller.setJumpFlag(false); - messageToAllPlayersOnShip("Warp field intersects with other ship's field. Cannot jump."); - return; - } - - if (WarpDrive.instance.cloaks.isInCloak(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, false)) { - controller.setJumpFlag(false); - messageToAllPlayersOnShip("Core is inside a cloaking field. Aborting. Disable cloaking field to jump!"); - return; - } - - doJump(); - cooldownTime = WarpDriveConfig.WC_COOLDOWN_INTERVAL_SECONDS * 20; - controller.setJumpFlag(false); - } else { - warmupTime = 0; - } - break; - } - } - - public void messageToAllPlayersOnShip(String msg) { - AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX + 0.99D, this.maxY + 0.99D, this.maxZ + 0.99D); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); - - System.out.println("" + (FMLCommonHandler.instance().getEffectiveSide().isClient() ? "Client":"Server") + this + " messageToAllPlayersOnShip: " + msg); - for (Object o : list) { - if (o == null || !(o instanceof EntityPlayer)) { - continue; - } - - ((EntityPlayer)o).addChatMessage("[" + (coreFrequency.length() > 0 ? coreFrequency : "WarpCore") + "] " + msg); - } - } - - private void updateIsolationState() - { - // Search block in cube around core with side 10 - int xmax, ymax, zmax, x1, x2, z1, z2; - int xmin, ymin, zmin; - final int ISOLATION_CUBE_SIDE = 6; - x1 = xCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); - x2 = xCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); - - if (x1 < x2) - { - xmin = x1; - xmax = x2; - } - else - { - xmin = x2; - xmax = x1; - } - - z1 = zCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); - z2 = zCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); - - if (z1 < z2) - { - zmin = z1; - zmax = z2; - } - else - { - zmin = z2; - zmax = z1; - } - - ymax = yCoord + ((ISOLATION_CUBE_SIDE / 2) - 1); - ymin = yCoord - ((ISOLATION_CUBE_SIDE / 2) - 1); - this.isolationBlocksCount = 0; - - // Search for warp isolation blocks - for (int y = ymin; y <= ymax; y++) - { - for (int x = xmin; x <= xmax; x++) - { - for (int z = zmin; z <= zmax; z++) - { - if (worldObj.getBlockId(x, y, z) == WarpDriveConfig.isolationID) - { - this.isolationBlocksCount++; - } - } - } - } - } - - private void makePlayersOnShipDrunk(int tickDuration) { - AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); - - for (Object o : list) { - if (o == null || !(o instanceof EntityPlayer)) { - continue; - } - - // Set "drunk" effect - ((EntityPlayer)o).addPotionEffect(new PotionEffect(Potion.confusion.id, tickDuration, 0, true)); - } - } - - private void summonPlayers() - { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); - - for (int i = 0; i < controller.players.size(); i++) - { - String nick = controller.players.get(i); - EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(nick); - - if (player != null && !testBB(aabb, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))) - { - summonPlayer(player, xCoord + dx, yCoord, zCoord + dz); - } - } - } - - private void summonSinglePlayer(String nickname) - { - AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ); - - for (int i = 0; i < controller.players.size(); i++) - { - String nick = controller.players.get(i); - EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(nick); - - if (player != null && nick.equals(nickname) && !testBB(aabb, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))) - { - summonPlayer(player, xCoord + dx, yCoord, zCoord + dz); - return; - } - } - } - - private void summonPlayer(EntityPlayerMP player, int x, int y, int z) { - if (consumeEnergy(WarpDriveConfig.WC_ENERGY_PER_ENTITY_TO_SPACE, false)) { - player.setPositionAndUpdate(x, y, z); - - if (player.dimension != worldObj.provider.dimensionId) { - player.mcServer.getConfigurationManager().transferPlayerToDimension(player, this.worldObj.provider.dimensionId, new SpaceTeleporter(DimensionManager.getWorld(this.worldObj.provider.dimensionId), 0, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ))); - } - } - } - - public boolean validateShipSpatialParameters(StringBuilder reason) { - if (controller == null) { - reason.append("TileEntityReactor.validateShipSpatialParameters: no controller detected!"); - return false; - } - direction = controller.getDirection(); - shipFront = controller.getFront(); - shipRight = controller.getRight(); - shipUp = controller.getUp(); - shipBack = controller.getBack(); - shipLeft = controller.getLeft(); - shipDown = controller.getDown(); - distance = Math.min(WarpDriveConfig.WC_MAX_JUMP_DISTANCE, controller.getDistance()); - - int x1 = 0, x2 = 0, z1 = 0, z2 = 0; - - if (Math.abs(dx) > 0) { - if (dx == 1) { - x1 = xCoord - shipBack; - x2 = xCoord + shipFront; - z1 = zCoord - shipLeft; - z2 = zCoord + shipRight; - } else { - x1 = xCoord - shipFront; - x2 = xCoord + shipBack; - z1 = zCoord - shipRight; - z2 = zCoord + shipLeft; - } - } else if (Math.abs(dz) > 0) { - if (dz == 1) { - z1 = zCoord - shipBack; - z2 = zCoord + shipFront; - x1 = xCoord - shipRight; - x2 = xCoord + shipLeft; - } else { - z1 = zCoord - shipFront; - z2 = zCoord + shipBack; - x1 = xCoord - shipLeft; - x2 = xCoord + shipRight; - } - } - - if (x1 < x2) { - minX = x1; - maxX = x2; - } else { - minX = x2; - maxX = x1; - } - - if (z1 < z2) { - minZ = z1; - maxZ = z2; - } else { - minZ = z2; - maxZ = z1; - } - - minY = yCoord - shipDown; - maxY = yCoord + shipUp; - shipLength = 0; - - switch (direction) { - case 0: - case 180: - shipLength = shipBack + shipFront; - break; - - case 90: - case 270: - shipLength = shipLeft + shipRight; - break; - - case -1: - case -2: - shipLength = shipDown + shipUp; - break; - - default: - reason.append("Invalid jump direction " + direction); - return false; - } - - // Ship side is too big - if ((shipBack + shipFront) > WarpDriveConfig.WC_MAX_SHIP_SIDE || (shipLeft + shipRight) > WarpDriveConfig.WC_MAX_SHIP_SIDE || (shipDown + shipUp) > WarpDriveConfig.WC_MAX_SHIP_SIDE) { - reason.append("Ship is too big (max is " + WarpDriveConfig.WC_MAX_SHIP_SIDE + " per side)"); - return false; - } - - this.shipVolume = computeRealShipVolume(); - - if (shipVolume > WarpDriveConfig.WC_MAX_SHIP_VOLUME_ON_SURFACE && worldObj.provider.dimensionId == 0) { - reason.append("Ship is too big for the overworld (max is " + WarpDriveConfig.WC_MAX_SHIP_VOLUME_ON_SURFACE + " blocks)"); - return false; - } - - return true; - } - - private void doBeaconJump() - { - // Search beacon coordinates - String freq = controller.getBeaconFrequency(); - int beaconX = 0, beaconZ = 0; - boolean isBeaconFound = false; - EntityPlayerMP player; - - for (int i = 0; i < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); i++) - { - player = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(i); - - // Skip players from other dimensions - if (player.dimension != worldObj.provider.dimensionId) - { - continue; - } - - TileEntity te = worldObj.getBlockTileEntity(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY) - 1, MathHelper.floor_double(player.posZ)); - - if (te != null && (te instanceof TileEntityProtocol)) - { - if (((TileEntityProtocol)te).getBeaconFrequency().equals(freq)) - { - beaconX = te.xCoord; - beaconZ = te.zCoord; - isBeaconFound = true; - break; - } - } - } - - // Now make jump to a beacon - if (isBeaconFound) { - // Consume energy - if (consumeEnergy(calculateRequiredEnergy(currentMode, shipVolume, distance), false)) { - System.out.println("" + this + " Moving ship to beacon (" + beaconX + "; " + yCoord + "; " + beaconZ + ")"); - EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, dx, dz, this, false, 1, 0, true, beaconX, yCoord, beaconZ); - jump.maxX = maxX; - jump.minX = minX; - jump.maxZ = maxZ; - jump.minZ = minZ; - jump.maxY = maxY; - jump.minY = minY; - jump.shipLength = shipLength; - jump.on = true; - worldObj.spawnEntityInWorld(jump); - } else { - messageToAllPlayersOnShip("Insufficient energy level"); - } - } else { - System.out.println("" + this + " Beacon '" + freq + "' is unknown."); - } - } - - private boolean isShipInJumpgate(JumpGate jg, StringBuilder reason) - { - AxisAlignedBB aabb = jg.getGateAABB(); - WarpDrive.debugPrint("[TEWarpCore] Jumpgate " + jg.name + " AABB is " + aabb); - int countBlocksInside = 0; - int countBlocksTotal = 0; - - if (aabb.isVecInside(worldObj.getWorldVec3Pool().getVecFromPool(maxX - minX, maxY - minY, maxZ - minZ))) - { - return true; - } - - for (int x = minX; x <= maxX; x++) - { - for (int z = minZ; z <= maxZ; z++) - { - for (int y = minY; y <= maxY; y++) - { - int blockID = worldObj.getBlockId(x, y, z); - - if (worldObj.isAirBlock(x, y, z) && (blockID != WarpDriveConfig.airID)) - { - continue; - } - if (aabb.minX <= x && aabb.maxX >= x && aabb.minY <= y && aabb.maxY >= y && aabb.minZ <= z && aabb.maxZ >= z) - { - countBlocksInside++; - } - countBlocksTotal++; - } - } - } - - float percent = 0F; - if (shipVolume != 0) - { - percent = Math.round((((countBlocksInside * 1.0F) / shipVolume) * 100.0F) * 10.0F) / 10.0F; - } - if (shipVolume != countBlocksTotal) - { - System.out.println("" + this + " Ship volume has changed from " + shipVolume + " to " + countBlocksTotal + " blocks"); - } - WarpDrive.debugPrint("Ship has " + countBlocksInside + " / " + shipVolume + " blocks (" + percent + "%) in jumpgate '" + jg.name + "'"); - // At least 80% of ship must be inside jumpgate - if (percent > 80F) - { - return true; - } - else if (percent <= 0.001) - { - reason.append("Ship is not inside a jumpgate. Jump rejected. Nearest jumpgate is " + jg.toNiceString()); - return false; - } - else - { - reason.append("Ship is only " + percent + "% inside a jumpgate. Sorry, we'll loose too much crew as is, jump rejected."); - return false; - } - } - - private boolean isFreePlaceForShip(int destX, int destY, int destZ) - { - int newX, newY, newZ; - - if (destY + shipUp > 255 || destY - shipDown < 5) - { - return false; - } - - int moveX = destX - xCoord; - int moveY = destY - yCoord; - int moveZ = destZ - zCoord; - - for (int x = minX; x <= maxX; x++) - { - for (int z = minZ; z <= maxZ; z++) - { - for (int y = minY; y <= maxY; y++) - { - if (!worldObj.isAirBlock(x, y, z)) - { - newX = moveX + x; - newY = moveY + y; - newZ = moveZ + z; - - if (!worldObj.isAirBlock(newX, newY, newZ)) - { - return false; - } - } - } - } - } - - return true; - } - - private void doGateJump() - { - // Search nearest jump-gate - String gateName = controller.getTargetJumpgateName(); - JumpGate targetGate = WarpDrive.instance.jumpGates.findGateByName(gateName); - - if (targetGate == null) - { - messageToAllPlayersOnShip("Destination jumpgate '" + gateName + "' is unknown. Check jumpgate name."); - this.controller.setJumpFlag(false); - return; - } - - // Now make jump to a beacon - int gateX = targetGate.xCoord; - int gateY = targetGate.yCoord; - int gateZ = targetGate.zCoord; - int destX = gateX; - int destY = gateY; - int destZ = gateZ; - JumpGate nearestGate = WarpDrive.instance.jumpGates.findNearestGate(xCoord, yCoord, zCoord); - - StringBuilder reason = new StringBuilder(); - if (!isShipInJumpgate(nearestGate, reason)) - { - messageToAllPlayersOnShip(reason.toString()); - this.controller.setJumpFlag(false); - return; - } - - // If gate is blocked by obstacle - if (!isFreePlaceForShip(gateX, gateY, gateZ)) - { - // Randomize destination coordinates and check for collision with obstacles around jumpgate - // Try to find good place for ship - int numTries = 10; // num tries to check for collision - boolean placeFound = false; - - for (; numTries > 0; numTries--) - { - // randomize destination coordinates around jumpgate - destX = gateX + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(100)); - destZ = gateZ + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(100)); - destY = gateY + ((worldObj.rand.nextBoolean()) ? -1 : 1) * (20 + worldObj.rand.nextInt(50)); - - // check for collision - if (isFreePlaceForShip(destX, destY, destZ)) - { - placeFound = true; - break; - } - } - - if (!placeFound) - { - messageToAllPlayersOnShip("Destination gate is blocked by obstacles. Aborting..."); - this.controller.setJumpFlag(false); - return; - } - - System.out.println("[GATE] Place found over " + (10 - numTries) + " tries."); - } - - // Consume energy - if (consumeEnergy(calculateRequiredEnergy(currentMode, shipVolume, distance), false)) { - System.out.println("[TE-WC] Moving ship to a place around gate '" + targetGate.name + "' (" + destX + "; " + destY + "; " + destZ + ")"); - EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, dx, dz, this, false, 1, 0, true, destX, destY, destZ); - jump.maxX = maxX; - jump.minX = minX; - jump.maxZ = maxZ; - jump.minZ = minZ; - jump.maxY = maxY; - jump.minY = minY; - jump.shipLength = shipLength; - jump.on = true; - worldObj.spawnEntityInWorld(jump); - } else { - messageToAllPlayersOnShip("Insufficient energy level"); - } - } - - private void doJump() { - int requiredEnergy = calculateRequiredEnergy(currentMode, shipVolume, distance); - - if (!consumeEnergy(requiredEnergy, true)) { - messageToAllPlayersOnShip("Insufficient energy to jump! Core is currently charged with " + getEnergyStored() + " EU while jump requires " + requiredEnergy + " EU"); - this.controller.setJumpFlag(false); - return; - } - - String shipInfo = "" + shipVolume + " blocks inside (" + minX + ", " + minY + ", " + minZ + ") to (" + maxX + ", " + maxY + ", " + maxZ + ")"; - if (currentMode == this.MODE_GATE_JUMP) { - System.out.println("" + this + " Performing gate jump of " + shipInfo); - doGateJump(); - return; - } else if (currentMode == this.MODE_BEACON_JUMP) { - System.out.println("" + this + " Performing beacon jump of " + shipInfo); - doBeaconJump(); - return; - } else if (currentMode == this.MODE_HYPERSPACE) { - System.out.println("" + this + " Performing hyperspace jump of " + shipInfo); - - // Check ship size for hyper-space jump - if (shipVolume < WarpDriveConfig.WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE) { - JumpGate nearestGate = null; - if (WarpDrive.instance.jumpGates == null) { - System.out.println("" + this + " WarpDrive.instance.jumpGates is NULL!"); - } else { - nearestGate = WarpDrive.instance.jumpGates.findNearestGate(xCoord, yCoord, zCoord); - } - - StringBuilder reason = new StringBuilder(); - if (nearestGate == null || !isShipInJumpgate(nearestGate, reason)) { - this.messageToAllPlayersOnShip("Ship is too small (" + shipVolume + "/" + WarpDriveConfig.WC_MIN_SHIP_VOLUME_FOR_HYPERSPACE + "). Insufficient ship mass to open hyperspace portal. Use a jumpgate to reach or exit hyperspace."); - this.controller.setJumpFlag(false); - return; - } - } - } else if (currentMode == this.MODE_BASIC_JUMP) { - System.out.println("" + this + " Performing basic jump of " + shipInfo + " toward direction " + direction + " over " + distance + " blocks."); - } else if (currentMode == this.MODE_LONG_JUMP) { - System.out.println("" + this + " Performing long jump of " + shipInfo + " toward direction " + direction + " over " + distance + " blocks."); - } else { - System.out.println("" + this + " Performing some jump #" + currentMode + " of " + shipInfo); - } - - if (currentMode == this.MODE_BASIC_JUMP || currentMode == this.MODE_LONG_JUMP || currentMode == MODE_HYPERSPACE) { - if (!consumeEnergy(requiredEnergy, false)) { - messageToAllPlayersOnShip("Insufficient energy level"); - return; - } - - if (this.currentMode == this.MODE_BASIC_JUMP) { - distance += shipLength; - } - - if (currentMode == this.MODE_LONG_JUMP && (direction != -1) && (direction != -2)) { - if (worldObj.provider.dimensionId == WarpDriveConfig.G_HYPERSPACE_DIMENSION_ID) { - distance *= 100; - } - } - - WarpDrive.debugPrint("" + this + " Distance adjusted to " + distance + " blocks."); - EntityJump jump = new EntityJump(worldObj, xCoord, yCoord, zCoord, dx, dz, this, (currentMode == MODE_HYPERSPACE), distance, direction, false, 0, 0, 0); - jump.maxX = maxX; - jump.minX = minX; - jump.maxZ = maxZ; - jump.minZ = minZ; - jump.maxY = maxY; - jump.minY = minY; - jump.shipLength = shipLength; - jump.on = true; - worldObj.spawnEntityInWorld(jump); - } - } - - private void teleportPlayersToSpace() { - if (worldObj.provider.dimensionId != WarpDriveConfig.G_SPACE_DIMENSION_ID) { - AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(xCoord - 2, yCoord - 1, zCoord - 2, xCoord + 2, yCoord + 4, zCoord + 2); - List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb); - - WorldServer spaceWorld = DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID); - for (Object o : list) { - if (!consumeEnergy(WarpDriveConfig.WC_ENERGY_PER_ENTITY_TO_SPACE, false)) { - return; - } - - Entity entity = (Entity) o; - int x = MathHelper.floor_double(entity.posX); - int z = MathHelper.floor_double(entity.posZ); - //int y = MathHelper.floor_double(entity.posY); - final int WOOL_BLOCK_ID = 35; - int newY; - - for (newY = 254; newY > 0; newY--) { - if (spaceWorld.getBlockId(x, newY, z) == WOOL_BLOCK_ID) { - break; - } - } - - if (newY <= 0) { - newY = 254; - } - - if (entity instanceof EntityPlayerMP) { - ((EntityPlayerMP) entity).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) entity), WarpDriveConfig.G_SPACE_DIMENSION_ID, new SpaceTeleporter(DimensionManager.getWorld(WarpDriveConfig.G_SPACE_DIMENSION_ID), 0, x, 256, z)); - - if (spaceWorld.isAirBlock(x, newY, z)) { - spaceWorld.setBlock(x , newY, z , Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x + 1, newY, z , Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x - 1, newY, z , Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x , newY, z + 1, Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x , newY, z - 1, Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x + 1, newY, z + 1, Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x - 1, newY, z - 1, Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x + 1, newY, z - 1, Block.stone.blockID, 0, 2); - spaceWorld.setBlock(x - 1, newY, z + 1, Block.stone.blockID, 0, 2); - } - - ((EntityPlayerMP) entity).setPositionAndUpdate(x + 0.5D, newY + 2.0D, z + 0.5D); - } - } - } - } - - private void summonPlayersByChestCode() - { - if (worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord) == null) - { - return; - } - - TileEntityChest chest = (TileEntityChest)worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - EntityPlayerMP player; - - for (int i = 0; i < MinecraftServer.getServer().getConfigurationManager().playerEntityList.size(); i++) - { - player = (EntityPlayerMP)MinecraftServer.getServer().getConfigurationManager().playerEntityList.get(i); - - if (checkPlayerInventory(chest, player)) - { - System.out.println("" + this + " Summoning " + player.username); - summonPlayer(player, xCoord, yCoord + 2, zCoord); - } - } - } - - private static boolean checkPlayerInventory(TileEntityChest chest, EntityPlayerMP player) { - Boolean result = false; - final int MIN_KEY_LENGTH = 5; - int keyLength = 0; - - for (int index = 0; index < chest.getSizeInventory(); index++) { - ItemStack chestItem = chest.getStackInSlot(index); - ItemStack playerItem = player.inventory.getStackInSlot(9 + index); - - if (chestItem == null) { - continue; - } - - if (playerItem == null || chestItem.itemID != playerItem.itemID || chestItem.getItemDamage() != playerItem.getItemDamage() || chestItem.stackSize != playerItem.stackSize) { - return false; - } else { - result = true; - } - - keyLength++; - } - - if (keyLength < MIN_KEY_LENGTH) { - System.out.println("[ChestCode] Key is too short: " + keyLength + " < " + MIN_KEY_LENGTH); - return false; - } - - return result; - } - - private Boolean isChestSummonMode() - { - TileEntity te = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord); - - if (te != null) - { - return (te instanceof TileEntityChest); - } - - return false; - } - - private static boolean testBB(AxisAlignedBB axisalignedbb, int x, int y, int z) - { - return axisalignedbb.minX <= x && axisalignedbb.maxX >= x && axisalignedbb.minY <= y && axisalignedbb.maxY >= y && axisalignedbb.minZ <= z && axisalignedbb.maxZ >= z; - } - - @Override - public String getStatus() { - return getBlockType().getLocalizedName() + " '" + coreFrequency + "' energy level is " + getEnergyStored() + " EU." + ((cooldownTime <= 0) ? "" : (" " + (cooldownTime / 20) + " s left of cooldown.")); - } - - private static int calculateRequiredEnergy(int currentMode, int shipVolume, int jumpDistance) { - switch (currentMode) { - case MODE_TELEPORT: - return WarpDriveConfig.WC_ENERGY_PER_ENTITY_TO_SPACE; - - case MODE_BASIC_JUMP: - return (WarpDriveConfig.WC_ENERGY_PER_BLOCK_MODE1 * shipVolume) + (WarpDriveConfig.WC_ENERGY_PER_DISTANCE_MODE1 * jumpDistance); - - case MODE_LONG_JUMP: - return (WarpDriveConfig.WC_ENERGY_PER_BLOCK_MODE2 * shipVolume) + (WarpDriveConfig.WC_ENERGY_PER_DISTANCE_MODE2 * jumpDistance); - - case MODE_HYPERSPACE: - return WarpDriveConfig.WC_MAX_ENERGY_VALUE / 10; // 10% of maximum - - case MODE_BEACON_JUMP: - return WarpDriveConfig.WC_MAX_ENERGY_VALUE / 2; // half of maximum - - case MODE_GATE_JUMP: - return 2 * shipVolume; - } - - return WarpDriveConfig.WC_MAX_ENERGY_VALUE; - } - - private int computeRealShipVolume() { - int realShipVolume = 0; - - try { - for (int x = minX; x <= maxX; x++) { - for (int z = minZ; z <= maxZ; z++) { - for (int y = minY; y <= maxY; y++) { - int blockID = worldObj.getBlockId(x, y, z); - - if (WarpDriveConfig.isAirBlock(worldObj, blockID, x, y, z) && (blockID != WarpDriveConfig.airID)) { - continue; - } - - realShipVolume++; - } - } - } - } catch(Exception e) { - e.printStackTrace(); - } - - return realShipVolume; - } - - private TileEntity findControllerBlock() - { - TileEntity result; - result = worldObj.getBlockTileEntity(xCoord + 1, yCoord, zCoord); - - if (result != null && result instanceof TileEntityProtocol) - { - dx = 1; - dz = 0; - return result; - } - - result = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord); - - if (result != null && result instanceof TileEntityProtocol) - { - dx = -1; - dz = 0; - return result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord + 1); - - if (result != null && result instanceof TileEntityProtocol) - { - dx = 0; - dz = 1; - return result; - } - - result = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1); - - if (result != null && result instanceof TileEntityProtocol) - { - dx = 0; - dz = -1; - return result; - } - - return null; - } - - public int getCooldown() { - return cooldownTime; - } - - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.WC_MAX_ENERGY_VALUE; - } - - @Override - public double demandedEnergyUnits() { - if (this.controller != null && controller.getMode() == 0) { - return 0.0D; - } - - return super.demandedEnergyUnits(); - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } - - @Override - public void readFromNBT(NBTTagCompound tag) - { - super.readFromNBT(tag); - coreFrequency = tag.getString("corefrequency"); - isolationBlocksCount = tag.getInteger("isolation"); - cooldownTime = tag.getInteger("cooldownTime"); - WarpDrive.instance.warpCores.updateInRegistry(this); - } - - @Override - public void writeToNBT(NBTTagCompound tag) - { - super.writeToNBT(tag); - tag.setString("corefrequency", coreFrequency); - tag.setInteger("isolation", isolationBlocksCount); - tag.setInteger("cooldownTime", cooldownTime); - } - - @Override - public void onChunkUnload() { - WarpDrive.instance.warpCores.removeFromRegistry(this); - super.onChunkUnload(); - } - - @Override - public void validate() { - super.validate(); - WarpDrive.instance.warpCores.updateInRegistry(this); - } - - @Override - public void invalidate() { - WarpDrive.instance.warpCores.removeFromRegistry(this); - super.invalidate(); - } - - @Override - public String toString() { - return String.format("%s \'%s\' @ \'%s\' %d, %d, %d", new Object[] { - getClass().getSimpleName(), - coreFrequency, - worldObj == null ? "~NULL~" : worldObj.getWorldInfo().getWorldName(), - Integer.valueOf(xCoord), Integer.valueOf(yCoord), Integer.valueOf(zCoord)}); - } -} diff --git a/src/cr0s/WarpDrive/machines/TileEntityTransporter.java b/src/cr0s/WarpDrive/machines/TileEntityTransporter.java deleted file mode 100644 index 9c63a786..00000000 --- a/src/cr0s/WarpDrive/machines/TileEntityTransporter.java +++ /dev/null @@ -1,435 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.ArrayList; -import java.util.List; - -import cr0s.WarpDrive.Vector3; -import cr0s.WarpDrive.WarpDrive; -import cr0s.WarpDrive.WarpDriveConfig; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.ChatMessageComponent; -import net.minecraft.util.DamageSource; -import net.minecraftforge.common.ForgeDirection; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.peripheral.IPeripheral; - -public class TileEntityTransporter extends WarpEnergyTE implements IPeripheral -{ - private double scanRange=2; - - private int scanDist = 4; - private double powerBoost = 1; - private double baseLockStrength=-1; - private double lockStrengthMul = 1; - private boolean isLocked=false; - - private final static Vector3 centreOnMe = new Vector3(0.5D, 1.0D, 0.5D); - private Vector3 sourceVec = new Vector3(); - private Vector3 destVec = new Vector3(); - - private TeleporterDamage teleDam = new TeleporterDamage("teleporter"); - - private String[] methodArray = { - "source", - "dest", - "lock", - "release", - "lockStrength", - "energize", - "energy", - "powerBoost", - "energyCost", - "help" }; - - @Override - public int getMaxEnergyStored() { - return WarpDriveConfig.TR_MAX_ENERGY; - } - - @Override - public void updateEntity() { - super.updateEntity(); - - if(isLocked) { - if(lockStrengthMul > 0.8) { - lockStrengthMul *= 0.995; - } else { - lockStrengthMul*= 0.98; - } - } - } - - // IPeripheral overrides - @Override - public String getType() { - return "transporter"; - } - - private static String helpStr(Object[] function) { - if (function != null && function.length > 0) { - String fun = function[0].toString().toLowerCase(); - if(fun.equals("source")) { - if(WarpDriveConfig.TR_RELATIVE_COORDS) { - return "source(x,y,z): sets the coordinates (relative to the transporter) to teleport from\ndest(): returns the relative x,y,z coordinates of the source"; - } else { - return "source(x,y,z): sets the absolute coordinates to teleport from\ndest(): returns the x,y,z coordinates of the source"; - } - } else if(fun.equals("dest")) { - if(WarpDriveConfig.TR_RELATIVE_COORDS) { - return "dest(x,y,z): sets the coordinates (relative to the transporter) to teleport to\ndest(): returns the relative x,y,z coordinates of the destination"; - } else { - return "dest(x,y,z): sets the absolute coordinates to teleport to\ndest(): returns the x,y,z coordinates of the destination"; - } - } else if(fun.equals("lock")) { - return "lock(): locks the source and dest coordinates in and returns the lock strength (float)"; - } else if(fun.equals("release")) { - return "release(): releases the current lock"; - } else if(fun.equals("lockstrength")) { - return "lockStrength(): returns the current lock strength (float)"; - } else if(fun.equals("energize")) { - return "energize(): attempts to teleport all entities at source to dest. Returns the number of entities transported (-1 indicates a problem)."; - } else if(fun.equals("powerboost")) { - return "powerBoost(boostAmount): sets the level of power to use (1 being default), returns the level of power\npowerBoost(): returns the level of power"; - } else if(fun.equals("energycost")) { - return "energyCost(): returns the amount of energy it will take for a single entity to transport with the current settings"; - } - } - return WarpDrive.defHelpStr; - } - - @Override - public String[] getMethodNames() { - return methodArray; - } - - private Object[] setVec3(boolean src,Object... arguments) { - Vector3 vec = src ? sourceVec : destVec; - - if (vec == null) { - Vector3 sV = WarpDriveConfig.TR_RELATIVE_COORDS ? new Vector3(this) : new Vector3(0,0,0); - if(src) - sourceVec = sV; - else - destVec = sV; - vec = src ? sourceVec : destVec; - } - - try { - if (arguments.length >= 3) { - unlock(); - vec.x = toDouble(arguments[0]); - vec.y = toDouble(arguments[1]); - vec.z = toDouble(arguments[2]); - } else if(arguments.length == 1) { - unlock(); - if(WarpDriveConfig.TR_RELATIVE_COORDS) { - vec.x = centreOnMe.x; - vec.y = centreOnMe.y; - vec.z = centreOnMe.z; - } else { - vec.x = xCoord + centreOnMe.x; - vec.y = yCoord + centreOnMe.y; - vec.z = zCoord + centreOnMe.z; - } - } - } catch(NumberFormatException e) { - return setVec3(src,"this"); - } - return new Object[] { vec.x, vec.y, vec.z }; - } - - @Override - public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception { - String str = methodArray[method]; - if (str == "energy") { - return new Object[] { getEnergyStored(), getMaxEnergyStored() }; - } - - if (str == "source") { - return setVec3(true,arguments); - } - - if (str == "dest") { - return setVec3(false,arguments); - } - - if (str == "lock") { - return new Object[] { lock(sourceVec, destVec) }; - } - - if(str == "release") - { - unlock(); - return null; - } - - if(str == "lockStrength") { - return new Object[] { getLockStrength() }; - } - - if(str == "energize") { - return new Object[] { energize () }; - } - - if(str == "powerBoost") { - try - { - if(arguments.length >= 1) - powerBoost = clamp(toDouble(arguments[0]),1,WarpDriveConfig.TR_MAX_BOOST_MUL); - } - catch(NumberFormatException e) - { - powerBoost = 1; - } - return new Object[] { powerBoost }; - } - - if (str == "energyCost") { - return new Object[] { energyCost() }; - } - - if (str == "help") { - return new Object[] { helpStr(arguments) }; - } - - return null; - } - - private Integer energyCost() { - if (sourceVec != null && destVec != null) { - return (int) Math.ceil(Math.pow(3, powerBoost - 1) * WarpDriveConfig.TR_EU_PER_METRE * sourceVec.distanceTo(destVec)); - } - return null; - } - - private int energize() { - if (isLocked) { - int count = 0; - double ls = getLockStrength(); - WarpDrive.debugPrint("LS:" + getLockStrength()); - ArrayList entitiesToTransport = findEntities(sourceVec, ls); - Integer energyReq = energyCost(); - if (energyReq == null) { - return -1; - } - Vector3 modDest = destVec.clone().translate(centreOnMe); - for(Entity ent : entitiesToTransport) { - WarpDrive.debugPrint("" + this + " Handling entity " + ent.getEntityName()); - if (consumeEnergy(energyReq, false)) { - WarpDrive.debugPrint("" + this + " Energy taken"); - inflictNegativeEffect(ent, ls); - transportEnt(ent, modDest); - count++; - } else { - break; - } - } - return count; - } - return -1; - } - - private void transportEnt(Entity ent, Vector3 dest) { - if (ent instanceof EntityLivingBase) { - EntityLivingBase livingEnt = (EntityLivingBase) ent; - if (WarpDriveConfig.TR_RELATIVE_COORDS) { - livingEnt.setPositionAndUpdate(xCoord+dest.x, yCoord+dest.y, zCoord+dest.z); - } else { - livingEnt.setPositionAndUpdate(dest.x, dest.y, dest.z); - } - } else { - if (WarpDriveConfig.TR_RELATIVE_COORDS) { - ent.setPosition(xCoord+dest.x, yCoord+dest.y, zCoord+dest.z); - } else { - ent.setPosition(dest.x, dest.y, dest.z); - } - } - } - - private void inflictNegativeEffect(Entity ent, double lockStrength) { - double value = Math.random() + lockStrength; - - WarpDrive.debugPrint("TRANSPORTER INFLICTION: " + value); - if (value < 0.1) { - ent.attackEntityFrom(teleDam, 1000); - } - - if (value < 0.2) { - ent.attackEntityFrom(teleDam, 10); - } - - if (value < 0.5) { - ent.attackEntityFrom(teleDam, 1); - } - } - - private double beaconScan(int xV, int yV, int zV) // FIXME: never used - { - double beacon = 0; - for(int x=xV-scanDist;x<=xV+scanDist;x++) - { - for(int y=yV-scanDist;y<=yV+scanDist;y++) - { - if(y < 0 || y > 254) - continue; - - for(int z=xV-scanDist;z<=xV+scanDist;z++) - { - if(worldObj.getBlockId(x, y, z) != WarpDriveConfig.transportBeaconID) - continue; - double dist = Math.abs(x - xV) + Math.abs(y - yV) + Math.abs(z - zV); - - if(worldObj.getBlockMetadata(x, y, z) == 0) - beacon += 1/dist; - else - beacon -= 1/dist; - } - } - } - return beacon; - } - - private double calculatePower(Vector3 d) - { - Vector3 myCoords; - if(WarpDriveConfig.TR_RELATIVE_COORDS) - myCoords = centreOnMe; - else - myCoords = new Vector3(this).translate(centreOnMe); - return calculatePower(myCoords,d); - } - - private static double calculatePower(Vector3 s, Vector3 d) - { - double dist = s.distanceTo(d); - return clamp(Math.pow(Math.E, -dist / 100) * (1/dist),0,1); - } - - private static double min(double... ds) - { - double curMin = Double.MAX_VALUE; - for(double d: ds) - curMin = Math.min(curMin, d); - return curMin; - } - - private double getLockStrength() { - if (isLocked) { - return clamp(baseLockStrength * lockStrengthMul * Math.pow(2, powerBoost - 1), 0, 1); - } - return -1; - } - - private void unlock() { - isLocked = false; - baseLockStrength = 0; - } - - private double lock(Vector3 source,Vector3 dest) { - if (source != null && dest != null) { - double basePower = min(calculatePower(source),calculatePower(dest),calculatePower(source,dest)); - baseLockStrength = basePower; - lockStrengthMul = 1; - isLocked = true; - WarpDrive.debugPrint(baseLockStrength + "," + getLockStrength()); - return getLockStrength(); - } else { - unlock(); - return 0; - } - } - - private AxisAlignedBB getAABB() { - Vector3 tS = new Vector3(this); - Vector3 bS = new Vector3(this); - Vector3 scanPos = new Vector3( scanRange/2, 2, scanRange/2); - Vector3 scanNeg = new Vector3(-scanRange/2,-1,-scanRange/2); - if(WarpDriveConfig.TR_RELATIVE_COORDS) { - tS.translate(sourceVec).translate(scanPos); - bS.translate(sourceVec).translate(scanNeg); - } else { - tS = sourceVec.clone().translate(scanPos); - bS = sourceVec.clone().translate(scanNeg); - } - return AxisAlignedBB.getBoundingBox(bS.x,bS.y,bS.z,tS.x,tS.y,tS.z); - } - - private ArrayList findEntities(Vector3 source, double lockStrength) { - AxisAlignedBB bb = getAABB(); - WarpDrive.debugPrint("Transporter:" +bb.toString()); - List data = worldObj.getEntitiesWithinAABBExcludingEntity(null, bb); - ArrayList output = new ArrayList(data.size()); - for(Object ent : data) { - if (lockStrength >= 1 || worldObj.rand.nextDouble() < lockStrength) {// If weak lock, don't transport - WarpDrive.debugPrint("" + this + " Entity '" + ent.toString() + "' found and added"); - if (ent instanceof Entity) { - output.add((Entity) ent); - } - } else { - WarpDrive.debugPrint("" + this + " Entity '" + ent.toString() + "' discarded"); - } - } - return output; - } - - @Override - public void attach(IComputerAccess computer) {} - - @Override - public void detach(IComputerAccess computer) {} - - @Override - public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) { - if (direction.equals(ForgeDirection.UP)) - return false; - return super.acceptsEnergyFrom(emitter, direction); - } - - @Override - public int getMaxSafeInput() { - return Integer.MAX_VALUE; - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setDouble("powerBoost", powerBoost); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - powerBoost = tag.getDouble("powerBoost"); - } - - class TeleporterDamage extends DamageSource { - protected TeleporterDamage(String par1Str) { - super(par1Str); - } - - @Override - public ChatMessageComponent getDeathMessage(EntityLivingBase e) { - String mess = ""; - if(e instanceof EntityPlayer || e instanceof EntityPlayerMP) { - mess = ((EntityPlayer) e).username + " was killed by a teleporter malfunction"; - } else { - mess = e.getEntityName() + " was killed by a teleporter malfunction"; - } - - WarpDrive.debugPrint(mess); - return ChatMessageComponent.createFromText(mess); - } - } - - @Override - public boolean equals(IPeripheral other) { - return other == this; - } -} diff --git a/src/cr0s/WarpDrive/machines/WarpChunkTE.java b/src/cr0s/WarpDrive/machines/WarpChunkTE.java deleted file mode 100644 index 6c56fd5e..00000000 --- a/src/cr0s/WarpDrive/machines/WarpChunkTE.java +++ /dev/null @@ -1,177 +0,0 @@ -package cr0s.WarpDrive.machines; - -import java.util.ArrayList; -import com.google.common.collect.ImmutableSet; - -import cr0s.WarpDrive.WarpDrive; - -import net.minecraft.world.ChunkCoordIntPair; -import net.minecraftforge.common.ForgeChunkManager; -import net.minecraftforge.common.ForgeChunkManager.Ticket; - -public abstract class WarpChunkTE extends WarpEnergyTE -{ - private ArrayList ticketList = new ArrayList(); - - public abstract boolean shouldChunkLoad(); - protected ChunkCoordIntPair minChunk = null; - protected ChunkCoordIntPair maxChunk = null; - - boolean areChunksLoaded = false; - boolean isRefreshing = false; - - public void refreshLoading(boolean force) - { - if(isRefreshing) - return; - - isRefreshing = true; - boolean load = shouldChunkLoad(); - if(ticketList.size() != 0) - { - if(load && (!areChunksLoaded || force)) - { - int ticketSize = ticketList.get(0).getMaxChunkListDepth(); - ArrayList chunkList = getChunksToLoad(); - int numTicketsRequired = (int) Math.ceil((double) chunkList.size() / ticketSize); - if(ticketList.size() != numTicketsRequired) - { - for(int i=ticketList.size();i= ticketSize) - { - chunkInTick = 0; - tickNum++; - t = ticketList.get(tickNum); - } - - WarpDrive.debugPrint("Attempting to force chunk" + chunk); - ForgeChunkManager.forceChunk(t, chunk); - chunkInTick++; - } - areChunksLoaded = true; - } - else if(!load) - { - for(Ticket ticket:ticketList) - { - ImmutableSet chunks = ticket.getChunkList(); - for(ChunkCoordIntPair chunk:chunks) - ForgeChunkManager.unforceChunk(ticket, chunk); - - ForgeChunkManager.releaseTicket(ticket); - WarpDrive.instance.removeTicket(ticket); - } - ticketList.clear(); - areChunksLoaded = false; - } - } - else if(load) - { - WarpDrive.instance.registerChunkLoadTE(this); - } - isRefreshing = false; - } - - public void refreshLoading() - { - refreshLoading(false); - } - - public void giveTicket(Ticket t) - { - ticketList.add(t); - } - - private static int dX(int dir) - { - if (dir == 1) - return 1; - else if (dir == 3) - return -1; - return 0; - } - - private static int dZ(int dir) - { - if (dir == 0) - return 1; - else if (dir == 2) - return -1; - return 0; - } - - public ArrayList getChunksFromCentre(ChunkCoordIntPair chunkA,ChunkCoordIntPair chunkB) - { - if(!shouldChunkLoad()) - return null; - int minX = Math.min(chunkA.chunkXPos, chunkB.chunkXPos); - int maxX = Math.max(chunkA.chunkXPos, chunkB.chunkXPos); - int minZ = Math.min(chunkA.chunkZPos, chunkB.chunkZPos); - int maxZ = Math.max(chunkA.chunkZPos, chunkB.chunkZPos); - WarpDrive.debugPrint("From " + minX + "," + minZ + " to " + maxX + "," + maxZ); - - //REMOVE ODD SIZES - int deltaX = (maxX - minX + 1); - int deltaZ = (maxZ - minZ + 1); - WarpDrive.debugPrint("Allocating Block: " + deltaX + "," + deltaZ); - - maxX = minX + deltaX - 1; - maxZ = minZ + deltaZ - 1; - WarpDrive.debugPrint("From " + minX + "," + minZ + " to " + maxX + "," + maxZ); - - int maxEnts = (deltaX) * (deltaZ); - ArrayList chunkList = new ArrayList(maxEnts); - - int dir = 1; - int x = minX; - int z = maxZ; - for(int i=0;i maxX || x+dX < minX || z+dZ > maxZ || z+dZ < minZ) - { - dir++; - if(dir >= 4) - dir = 0; - dX = dX(dir); - dZ = dZ(dir); - - if(dX == 1) - minX++; - if(dX == -1) - maxX--; - if(dZ == 1) - minZ++; - if(dZ == -1) - maxZ--; - - } - x += dX; - z += dZ; - } - - return chunkList; - } - - public ArrayList getChunksToLoad() - { - if(minChunk == null || maxChunk == null) - { - ArrayList chunkList = new ArrayList(1); - chunkList.add(this.worldObj.getChunkFromBlockCoords(xCoord, zCoord).getChunkCoordIntPair()); - return chunkList; - } - return getChunksFromCentre(minChunk,maxChunk); - } -} diff --git a/src/cr0s/WarpDrive/machines/WarpEnergyTE.java b/src/cr0s/WarpDrive/machines/WarpEnergyTE.java deleted file mode 100644 index f6ee99d3..00000000 --- a/src/cr0s/WarpDrive/machines/WarpEnergyTE.java +++ /dev/null @@ -1,167 +0,0 @@ -package cr0s.WarpDrive.machines; - -import ic2.api.energy.event.EnergyTileLoadEvent; -import ic2.api.energy.event.EnergyTileUnloadEvent; -import ic2.api.energy.tile.IEnergySink; -import cofh.api.energy.IEnergyHandler; -import cpw.mods.fml.common.FMLCommonHandler; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.ForgeDirection; -import net.minecraftforge.common.MinecraftForge; - -public abstract class WarpEnergyTE extends WarpTE implements IEnergyHandler, IEnergySink { - protected boolean addedToEnergyNet = false; - protected int energyStored_internal = 0; - protected static final double EU_PER_INTERNAL = 1.0D; - protected static final double RF_PER_INTERNAL = 1800.0D / 437.5D; - - // WarpDrive methods - public int getEnergyStored() { - return energyStored_internal; - } - - public int getMaxEnergyStored() { - return 0; - } - - protected boolean consumeEnergy(int amount, boolean simulate) { - if(getEnergyStored() >= amount) { - if (!simulate) { - energyStored_internal -= amount; - } - return true; - } - return false; - } - - protected int consumeAllEnergy() { - int temp = energyStored_internal; - energyStored_internal = 0; - return temp; - } - - public Object[] getEnergyObject() { - return new Object[]{ getEnergyStored(), getMaxEnergyStored() }; - } - - public String getStatus() { - if (getMaxEnergyStored() != 0) { - return getBlockType().getLocalizedName() + " energy level is " + getEnergyStored() + "/" + getMaxEnergyStored() + " EU."; - } else { - return getBlockType().getLocalizedName(); - } - } - - // Common overrides - @Override - public void updateEntity() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - return; - } - - if (!addedToEnergyNet) { - MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this)); - addedToEnergyNet = true; - } - } - - @Override - public void onChunkUnload() { - if (addedToEnergyNet) { - MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); - addedToEnergyNet = false; - } - - super.onChunkUnload(); - } - - @Override - public void invalidate() { - if (addedToEnergyNet) { - MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this)); - addedToEnergyNet = false; - } - - super.invalidate(); - } - - // IndustrialCraft overrides - @Override - public double demandedEnergyUnits() { - return Math.max(0.0D, getMaxEnergyStored() - energyStored_internal) * EU_PER_INTERNAL; - } - - @Override - public double injectEnergyUnits(ForgeDirection directionFrom, double amount) { - double leftover = 0; - energyStored_internal += Math.round(amount) / EU_PER_INTERNAL; - - if (energyStored_internal > getMaxEnergyStored()) { - leftover = (energyStored_internal - getMaxEnergyStored()); - energyStored_internal = getMaxEnergyStored(); - } - - return leftover * EU_PER_INTERNAL; - } - - @Override - public int getMaxSafeInput() { - return 0; - } - - @Override - public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction) { - return getMaxSafeInput() != 0; - } - - // ThermalExpansion overrides - @Override - public int getEnergyStored(ForgeDirection from) { - return (int)Math.round(getEnergyStored() * RF_PER_INTERNAL); - } - - @Override - public int getMaxEnergyStored(ForgeDirection from) { - return (int)Math.round(getMaxEnergyStored() * RF_PER_INTERNAL); - } - - @Override - public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { - int maxStored = getMaxEnergyStored(from); - if (maxStored == 0) { - return 0; - } - int energyStored = getEnergyStored(from); - - int toAdd = Math.min(maxReceive, maxStored - energyStored); - if (!simulate) { - energyStored_internal = (int)Math.min(getMaxEnergyStored(), energyStored_internal + toAdd / RF_PER_INTERNAL); - } - - return toAdd; - } - - @Override - public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { - return 0; - } - - @Override - public boolean canInterface(ForgeDirection from) { - return (getMaxEnergyStored() != 0); - } - - // Forge overrides - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - this.energyStored_internal = tag.getInteger("energy"); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - tag.setInteger("energy", this.energyStored_internal); - } -} \ No newline at end of file diff --git a/src/cr0s/WarpDrive/machines/WarpTE.java b/src/cr0s/WarpDrive/machines/WarpTE.java deleted file mode 100644 index de31461a..00000000 --- a/src/cr0s/WarpDrive/machines/WarpTE.java +++ /dev/null @@ -1,51 +0,0 @@ -package cr0s.WarpDrive.machines; - -import cr0s.WarpDrive.Vector3; -import net.minecraft.tileentity.TileEntity; - -public abstract class WarpTE extends TileEntity -{ - public static final Vector3[] adjacentSideOffsets = new Vector3[6]; - static - { - adjacentSideOffsets[0] = new Vector3( 0, 0, 1); - adjacentSideOffsets[1] = new Vector3( 0, 0,-1); - adjacentSideOffsets[2] = new Vector3( 0, 1, 0); - adjacentSideOffsets[3] = new Vector3( 0,-1, 0); - adjacentSideOffsets[4] = new Vector3( 1, 0, 0); - adjacentSideOffsets[5] = new Vector3(-1, 0, 0); - } - - protected static int toInt(double d) { - return (int) Math.round(d); - } - - protected static int toInt(Object o) { - return toInt(toDouble(o)); - } - - protected static double toDouble(Object o) { - return Double.parseDouble(o.toString()); - } - - protected static boolean toBool(Object o) { - if (o == null) { - return false; - } - if (o instanceof Boolean) { - return ((Boolean) o); - } - if (o.toString() == "true" || o.toString() == "1.0" || o.toString() == "1" || o.toString() == "y" || o.toString() == "yes") { - return true; - } - return false; - } - - protected static int clamp(int a, int min, int max) { - return Math.min(max, Math.max(a, min)); - } - - protected static double clamp(double a, double min, double max) { - return Math.min(max, Math.max(a, min)); - } -} diff --git a/src/cr0s/serverMods/AntiFallDamage.java b/src/cr0s/serverMods/AntiFallDamage.java new file mode 100644 index 00000000..059fa6c3 --- /dev/null +++ b/src/cr0s/serverMods/AntiFallDamage.java @@ -0,0 +1,42 @@ +package cr0s.serverMods; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.MathHelper; +import net.minecraftforge.event.ForgeSubscribe; +import net.minecraftforge.event.entity.living.LivingFallEvent; + +/** + * Гашение урона при падении с джетпаком или квантовыми бутсами + * @author Cr0s + */ +public class AntiFallDamage +{ + private final int JETPACK_ID = 29954; + private final int ELECTRIC_JETPACK_ID = 29953; + private final int QUANTUM_BOOTS_ID = 29915; + + @ForgeSubscribe + public void livingFall(LivingFallEvent event) + { + EntityLivingBase entity = event.entityLiving; + float distance = event.distance; + + if (entity instanceof EntityPlayer) + { + EntityPlayer player = (EntityPlayer) entity; + int check = MathHelper.ceiling_float_int(distance - 3.0F); + + if (check > 0) // Падение может нанести урон + { + // Проверяем наличие защиты + if ((player.getCurrentArmor(0) != null && player.getCurrentArmor(0).itemID == QUANTUM_BOOTS_ID) || + (player.getCurrentArmor(2) != null && player.getCurrentArmor(2).itemID == JETPACK_ID) || + (player.getCurrentArmor(2) != null && player.getCurrentArmor(2).itemID == ELECTRIC_JETPACK_ID)) + { + event.setCanceled(true); // Блокируем падение, если защита есть + } + } + } + } +} diff --git a/src/cr0s/serverMods/CommonProxy.java b/src/cr0s/serverMods/CommonProxy.java new file mode 100644 index 00000000..36d96e05 --- /dev/null +++ b/src/cr0s/serverMods/CommonProxy.java @@ -0,0 +1,9 @@ +package cr0s.serverMods; + +public class CommonProxy +{ + // some code goes here + public void setupLoginHook() + { + } +} \ No newline at end of file diff --git a/src/cr0s/serverMods/LoginHookClass.java b/src/cr0s/serverMods/LoginHookClass.java new file mode 100644 index 00000000..db624d92 --- /dev/null +++ b/src/cr0s/serverMods/LoginHookClass.java @@ -0,0 +1,135 @@ +package cr0s.serverMods; + +import cpw.mods.fml.common.network.IConnectionHandler; +import cpw.mods.fml.common.network.Player; +import java.io.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import net.minecraft.network.INetworkManager; +import net.minecraft.network.NetLoginHandler; +import net.minecraft.network.packet.NetHandler; +import net.minecraft.network.packet.Packet1Login; +import net.minecraft.server.MinecraftServer; +import com.google.common.base.Strings; + +public class LoginHookClass implements IConnectionHandler +{ + private String checkLogin(String s) throws FileNotFoundException, IOException + { + if (s.indexOf(".") == -1 || s.split("\\.").length != 2) + return "Никнейм и пароль должны быть разделены точками."; + + if (!s.matches("^[a-zA-Z0-9_.]+$")) + return "Имя пользователя или пароль содержат недопустимые символы."; + + String s4 = s.split("\\.")[0].trim(); + String s5 = s.split("\\.")[1].trim(); + + if (s4.length() < 2 && !s4.equals("Q")) + return "Имя пользователя слишком короткое."; + + if (s5.length() < 3) + return "Пароль слишком короткий."; + + if (s4.length() > 15) + return "Слишком длинный логин! (>15)"; + + BufferedReader bufferedreader = new BufferedReader(new FileReader(MinecraftServer.getServer().getFile("users.txt"))); + + String s1; + + while ((s1 = bufferedreader.readLine()) != null) + { + String s2; + String s3; + + try + { + s2 = s1.split("\\.")[0]; + s3 = s1.split("\\.")[1]; + } + catch (Exception exception) + { + bufferedreader.close(); + return "login.password error, database is corrupted."; + } + + if (s2.toLowerCase().equals(s4.toLowerCase())) + { + if (!s3.equals(s5)) + { + System.out.println((new StringBuilder()).append(s).append(" failed to login (pwd: ").append(s3).append(")").toString()); + bufferedreader.close(); + return "Неправильный пароль!"; + } + else + { + bufferedreader.close(); + return ""; + } + } + } + + bufferedreader.close(); + PrintWriter printwriter = new PrintWriter(new FileWriter(MinecraftServer.getServer().getFile("users.txt"), true)); + printwriter.println(s); + printwriter.close(); + return ""; + } + + @Override + public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager) + { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager) + { + String kickReason = ""; + String s = netHandler.clientUsername; + + try + { + kickReason = checkLogin(s); + System.out.println("[SERVER MODS] Logging in user: " + s + " Result: " + kickReason); + } + catch (FileNotFoundException ex) + { + Logger.getLogger(LoginHookClass.class.getName()).log(Level.SEVERE, null, ex); + } + catch (IOException ex) + { + Logger.getLogger(LoginHookClass.class.getName()).log(Level.SEVERE, null, ex); + } + + if (Strings.isNullOrEmpty(kickReason)) + netHandler.clientUsername = s.split("\\.")[0]; + + return kickReason; + } + + @Override + public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager) + { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager) + { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void connectionClosed(INetworkManager manager) + { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login) + { + //throw new UnsupportedOperationException("Not supported yet."); + } +} \ No newline at end of file diff --git a/src/cr0s/serverMods/ServerMods.java b/src/cr0s/serverMods/ServerMods.java new file mode 100644 index 00000000..0b043886 --- /dev/null +++ b/src/cr0s/serverMods/ServerMods.java @@ -0,0 +1,47 @@ +package cr0s.serverMods; + +import cpw.mods.fml.common.Mod; +import cpw.mods.fml.common.Mod.Init; +import cpw.mods.fml.common.Mod.Instance; +import cpw.mods.fml.common.Mod.PostInit; +import cpw.mods.fml.common.Mod.PreInit; +import cpw.mods.fml.common.event.FMLInitializationEvent; +import cpw.mods.fml.common.event.FMLPostInitializationEvent; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; +import cpw.mods.fml.common.network.NetworkMod; +import net.minecraftforge.common.MinecraftForge; +import cr0s.WarpDrive.SpaceEventHandler; + +@Mod(modid = "ServerMods", name = "ServerMods", version = "0.0.1") +@NetworkMod(clientSideRequired = false, serverSideRequired = true, connectionHandler = LoginHookClass.class) + +/** + * @author Cr0s + */ +public class ServerMods +{ + // The instance of your mod that Forge uses. + @Instance("ServerMods") + public static ServerMods instance; + + @PreInit + public void preInit(FMLPreInitializationEvent event) + { + // Stub Method + } + + @Init + public void load(FMLInitializationEvent event) + { + // Включить авторизацию (включается автоматически) + //proxy.setupLoginHook(); + // Снять урон от падения с джетпаком и крузис-тапками + MinecraftForge.EVENT_BUS.register(new AntiFallDamage()); + } + + @PostInit + public void postInit(FMLPostInitializationEvent event) + { + // Stub Method + } +} \ No newline at end of file diff --git a/src/mcmod.info b/src/mcmod.info deleted file mode 100644 index 478681d9..00000000 --- a/src/mcmod.info +++ /dev/null @@ -1,21 +0,0 @@ -[ -{ - "modid": "warpdrive", - "name": "WarpDrive", - "description": "Create your own space ship from any blocks (excluding bedrock) and sail it trough space. -Explore the space dimension: asteroids (filled with ores), asteroid fields, gas clouds, planetoids, stars, and NPC-ships. -Jump to hyperspace for long-range traveling! -Set up laser cannons on your ship to fight with other players' ships, or craft a mining laser to collect valuable resources on Earth or in space. -Cloak your ship, base or a space station from your enemies! -And lots more!", - "version": "1.2.5.0", - "mcversion": "1.6.4", - "url": "http://www.minecraftforum.net/topic/1444954-", - "updateUrl": "http://files.minecraftforge.net/SecretRoomsMod/SecretRoomsMod-universal-latest.zip", - "authors": ["Cr0s", "DarkholmeTenk", "drpepper240", "ZLOFENIX", "LemADEC"], - "credits": "Original concept and implementation by Cr0s, modified by ZLOFENIX, DarkholmeTenk & drpepper240. Merged, bugfixed and ported to WWM by LemADEC.", - "logoFile": "", - "screenshots": [], - "dependencies": [] -} -]