Completely overhaul the Advanced Memory Card (#29)

* Move mode change button to the side.

- Mode change now on the side w/ resize button
- Some code cleanup
- New description (en only for now), texture.

* Update ae2 to beta-204

* Add OC/Pneumaticraft support

* Create a proxy for client/server

Mostly for convenience of getting icons and other GUI elements.

* Large refactor to make way for "refresh" functionality

Features:
- New "refresh" capability (no button available yet) so the
client can have an updated GUI.
- The player can now control which types to be queried/displayed.

A great number of changes were made to allow this to happen to the mod
internally, as started from the last commit.

- P2PCache has been revisited. Instead of being a one-time instantiation,
the cache can now be queried from the client many times.

- Network has changed. Instead of sending an ItemStack (as previously), we
keep that info locally and send a byte only instead, so that should save
some network traffic.

- New packet for sending the refresh signal has been made. Other packets
send a "type" discriminator to make way for the typing feature.

Because I was lazy and didn't separate the commits, here are some other
changes made:
- Cleaned up a bit of the code to make it easier to read. This includes
code I've written before...
- Some name refactors. Some of the names were (mine) were quite frankly,
bad.

Signed-off-by: Firenoo <[email protected]>

* More cleanup + texture for type change

Some more code cleanup (spacing and labels)

* Disable ability to use copy outputs when output selected

Because it doesn't work, and has strange behavior, this is being disabled
for now (possibly forever).

* Remove unused method + remove unused imports

* Add unbinding mode

+ tooltip explanation

* Add type to filter options

* Add enUS localization

* Add refresh button, and prevent excessive packet spam.

Packets are sent only once every 250 ms to avoid DDOSing someone.
Accomplishes this by adding a new scheduled executor.

* Add the ability to change P2P types from the GUI

* tooltip was actually lying, now it's lying less

* Fix CME from resizing GUI, and add patterns to drops when changing P2P interface type

CME caused by iterating over the button list. Clicking on resize button forces
the GUI to reset, so the button list changes and causes the CME.

P2P interfaces now drop their items if changing their type from the GUI.

* Make the refresh icon look a little less like MSPaint

Also minor change to tooltip when changing types.

---------

Signed-off-by: Firenoo <[email protected]>
This commit is contained in:
firenoo authored and GitHub committed 2023-05-15 17:29:14 +02:00
1 parent 1c1b9bda29
commit f5a23d1a3b
33 files changed
+1420 -347

No files matched your search

@@ -1,17 +1,14 @@
package com.projecturanus.betterp2p
import com.projecturanus.betterp2p.client.render.RenderHandler
import com.projecturanus.betterp2p.config.BetterP2PConfig
import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard
import com.projecturanus.betterp2p.network.ModNetwork
import com.projecturanus.betterp2p.network.ServerPlayerDisconnectHandler
import cpw.mods.fml.common.Mod
import cpw.mods.fml.common.SidedProxy
import cpw.mods.fml.common.event.FMLPostInitializationEvent
import cpw.mods.fml.common.event.FMLPreInitializationEvent
import cpw.mods.fml.common.event.FMLServerStoppedEvent
import cpw.mods.fml.common.registry.GameRegistry
import cpw.mods.fml.relauncher.FMLLaunchHandler
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.ShapelessRecipes
import net.minecraftforge.common.config.Configuration
import org.apache.logging.log4j.Logger
@@ -25,8 +22,10 @@ const val MODID = "betterp2p"
*/
@Mod(modid = MODID, version = MODVER, modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", dependencies = "required-after:appliedenergistics2; required-after:forgelin;")
object BetterP2P {
lateinit var logger: Logger
lateinit var logger: Logger
@SidedProxy(serverSide = "com.projecturanus.betterp2p.CommonProxy", clientSide = "com.projecturanus.betterp2p.ClientProxy")
lateinit var proxy: CommonProxy
@Mod.EventHandler
fun preInit(event: FMLPreInitializationEvent) {
logger = event.modLog
@@ -37,13 +36,11 @@ object BetterP2P {
@Mod.EventHandler
fun postInit(event: FMLPostInitializationEvent) {
ServerPlayerDisconnectHandler.register()
if(FMLLaunchHandler.side().isClient()) {
RenderHandler.register()
}
GameRegistry.addRecipe(ShapelessRecipes(ItemStack(ItemAdvancedMemoryCard), listOf(
GameRegistry.findItemStack("appliedenergistics2", "item.ToolNetworkTool", 1),
GameRegistry.findItemStack("appliedenergistics2", "item.ToolMemoryCard", 1)
)))
proxy.postInit()
}
@Mod.EventHandler
fun onServerStopped(event: FMLServerStoppedEvent) {
ModNetwork.stop()
}
}
@@ -0,0 +1,206 @@
package com.projecturanus.betterp2p
import appeng.api.AEApi
import appeng.api.config.TunnelType
import appeng.api.definitions.IItemDefinition
import appeng.parts.p2p.PartP2PGT5Power
import appeng.parts.p2p.PartP2PIC2Power
import appeng.parts.p2p.PartP2PInterface
import appeng.parts.p2p.PartP2PItems
import appeng.parts.p2p.PartP2PLight
import appeng.parts.p2p.PartP2PLiquids
import appeng.parts.p2p.PartP2POpenComputers
import appeng.parts.p2p.PartP2PPressure
import appeng.parts.p2p.PartP2PRFPower
import appeng.parts.p2p.PartP2PRedstone
import appeng.parts.p2p.PartP2PTunnel
import appeng.parts.p2p.PartP2PTunnelME
import com.projecturanus.betterp2p.client.render.RenderHandler
import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard
import com.projecturanus.betterp2p.network.ServerPlayerDisconnectHandler
import com.projecturanus.betterp2p.util.p2p.ClientTunnelInfo
import com.projecturanus.betterp2p.util.p2p.TunnelInfo
import cpw.mods.fml.common.registry.GameRegistry
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.ShapelessRecipes
import net.minecraft.util.IIcon
/**
* A proxy for the server
*/
open class CommonProxy {
/**
* Tunnels available in this instance. These are used to communicate p2p
* information between server/client.
*/
protected val tunnelTypes = mutableMapOf<Class<*>, TunnelInfo>()
/**
* Same as above, but maps ints -> tunnel info.
*/
protected val tunnelIndices = mutableMapOf<Int, TunnelInfo>()
open fun postInit() {
ServerPlayerDisconnectHandler.register()
GameRegistry.addRecipe(ShapelessRecipes(ItemStack(ItemAdvancedMemoryCard), listOf(
AEApi.instance().definitions().items().networkTool().maybeStack(1).get(),
AEApi.instance().definitions().items().memoryCard().maybeStack(1).get())))
initTunnels()
}
/**
* Discover what tunnels are available.
*/
open fun initTunnels() {
val partDefs = AEApi.instance().definitions().parts()
registerTunnel(
def = partDefs.p2PTunnelME(),
type = TunnelType.ME,
classType = PartP2PTunnelME::class.java)
registerTunnel(
def = partDefs.p2PTunnelEU(),
type = TunnelType.IC2_POWER,
classType = PartP2PIC2Power::class.java)
registerTunnel(
def = partDefs.p2PTunnelRF(),
type = TunnelType.RF_POWER,
classType = PartP2PRFPower::class.java)
registerTunnel(
def = partDefs.p2PTunnelRedstone(),
type = TunnelType.REDSTONE,
classType = PartP2PRedstone::class.java)
registerTunnel(
def = partDefs.p2PTunnelLiquids(),
type = TunnelType.FLUID,
classType = PartP2PLiquids::class.java)
registerTunnel(
def = partDefs.p2PTunnelItems(),
type = TunnelType.ITEM,
classType = PartP2PItems::class.java)
registerTunnel(
def = partDefs.p2PTunnelLight(),
type = TunnelType.LIGHT,
classType = PartP2PLight::class.java)
registerTunnel(
def = partDefs.p2PTunnelOpenComputers(),
type = TunnelType.COMPUTER_MESSAGE,
classType = PartP2POpenComputers::class.java)
registerTunnel(
def = partDefs.p2PTunnelPneumaticCraft(),
type = TunnelType.PRESSURE,
classType = PartP2PPressure::class.java)
registerTunnel(
def = partDefs.p2PTunnelGregtech(),
type = TunnelType.GT_POWER,
classType = PartP2PGT5Power::class.java)
registerTunnel(
def = partDefs.p2PTunnelMEInterface(),
type = TunnelType.ME_INTERFACE,
classType = PartP2PInterface::class.java)
}
private fun registerTunnel(def: IItemDefinition, type: TunnelType, classType: Class<out PartP2PTunnel<*>>) {
if (def.isEnabled) {
val stack = def.maybeStack(1).get()
val info = TunnelInfo(type.ordinal, stack, classType)
tunnelTypes[classType] = info
tunnelIndices[type.ordinal] = info
}
}
fun getP2PFromIndex(index: Int): TunnelInfo? {
return tunnelIndices[index]
}
fun getP2PFromClass(clazz: Class<*>): TunnelInfo? {
return tunnelTypes[clazz]
}
fun getP2PTypeList(): List<TunnelInfo> {
return tunnelIndices.values.toList()
}
}
/**
* A proxy for the client
*/
class ClientProxy: CommonProxy() {
override fun postInit() {
RenderHandler.register()
super.postInit()
}
/**
* Keeps a cache of icons to use in GUI.
*/
override fun initTunnels() {
val partDefs = AEApi.instance().definitions().parts()
registerTunnel(
def = partDefs.p2PTunnelME(),
type = TunnelType.ME,
classType = PartP2PTunnelME::class.java,
icon = { PartP2PTunnelME(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelEU(),
type = TunnelType.IC2_POWER,
classType = PartP2PIC2Power::class.java,
icon = { PartP2PIC2Power(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelRF(),
type = TunnelType.RF_POWER,
classType = PartP2PRFPower::class.java,
icon = { PartP2PRFPower(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelRedstone(),
type = TunnelType.REDSTONE,
classType = PartP2PRedstone::class.java,
icon = { PartP2PRedstone(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelLiquids(),
type = TunnelType.FLUID,
classType = PartP2PLiquids::class.java,
icon = { PartP2PLiquids(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelItems(),
type = TunnelType.ITEM,
classType = PartP2PItems::class.java,
icon = { PartP2PItems(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelLight(),
type = TunnelType.LIGHT,
classType = PartP2PLight::class.java,
icon = { PartP2PLight(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelOpenComputers(),
type = TunnelType.COMPUTER_MESSAGE,
classType = PartP2POpenComputers::class.java,
icon = { PartP2POpenComputers(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelPneumaticCraft(),
type = TunnelType.PRESSURE,
classType = PartP2PPressure::class.java,
icon = { PartP2PPressure(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelGregtech(),
type = TunnelType.GT_POWER,
classType = PartP2PGT5Power::class.java,
icon = { PartP2PGT5Power(it).typeTexture })
registerTunnel(
def = partDefs.p2PTunnelMEInterface(),
type = TunnelType.ME_INTERFACE,
classType = PartP2PInterface::class.java,
icon = { PartP2PInterface(it).typeTexture })
}
private inline fun registerTunnel(def: IItemDefinition,
type: TunnelType,
classType: Class<out PartP2PTunnel<*>>,
crossinline icon: (ItemStack) -> IIcon) {
if (def.isEnabled) {
val stack = def.maybeStack(1).get()
val info = ClientTunnelInfo(type.ordinal, stack, classType) { icon(stack) }
tunnelTypes[classType] = info
tunnelIndices[type.ordinal] = info
}
}
}
@@ -2,9 +2,11 @@ package com.projecturanus.betterp2p.capability
import com.projecturanus.betterp2p.client.gui.widget.GuiScale
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import com.projecturanus.betterp2p.network.NONE
import com.projecturanus.betterp2p.network.NONE_SELECTED
data class MemoryInfo(var selectedEntry: Long = NONE,
const val TUNNEL_ANY: Int = -1
data class MemoryInfo(var selectedEntry: Long = NONE_SELECTED,
var frequency: Long = 0,
var mode: BetterMemoryCardModes = BetterMemoryCardModes.OUTPUT,
var gui: GuiScale = GuiScale.DYNAMIC)
var gui: GuiScale = GuiScale.DYNAMIC,
var type: Int = TUNNEL_ANY)
@@ -1,14 +1,25 @@
package com.projecturanus.betterp2p.client.gui
import appeng.client.gui.widgets.MEGuiTextField
import appeng.parts.p2p.PartP2PGT5Power
import appeng.parts.p2p.PartP2PInterface
import appeng.parts.p2p.PartP2PLiquids
import appeng.parts.p2p.PartP2PRedstone
import appeng.parts.p2p.PartP2PTunnelME
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.client.ClientCache
import com.projecturanus.betterp2p.client.TextureBound
import com.projecturanus.betterp2p.client.gui.widget.*
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import com.projecturanus.betterp2p.item.MAX_TOOLTIP_LENGTH
import com.projecturanus.betterp2p.network.*
import com.projecturanus.betterp2p.util.p2p.ClientTunnelInfo
import com.projecturanus.betterp2p.util.p2p.TunnelInfo
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.FontRenderer
import net.minecraft.client.gui.GuiButton
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.renderer.Tessellator
import net.minecraft.client.resources.I18n
@@ -16,18 +27,12 @@ import net.minecraft.util.ResourceLocation
import org.lwjgl.input.Keyboard
import org.lwjgl.input.Mouse
import org.lwjgl.opengl.GL11
import java.util.*
const val GUI_WIDTH = 288
const val GUI_TEX_HEIGHT = 264
class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
private lateinit var _guiLeft: Lazy<Int>
private var guiLeft: Int
get() = _guiLeft.value
set(value) {
_guiLeft = lazyOf(value)
}
private var guiLeft: Int = 0
private lateinit var _guiTop: Lazy<Int>
private var guiTop: Int
@@ -39,9 +44,6 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
private val tableX = 9
private val tableY = 19
private var scale = msg.memoryInfo.gui
private val resizeButton: WidgetButton
private var _ySize: Lazy<Int> = lazy { 242 }
private var ySize: Int
get() = _ySize.value
@@ -49,20 +51,29 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
_ySize = lazy { value }
}
private var scale = msg.memoryInfo.gui
private val resizeButton: WidgetButton
private var mode = msg.memoryInfo.mode
private val modeButton: WidgetButton
private var type: ClientTunnelInfo? = BetterP2P.proxy.getP2PFromIndex(msg.memoryInfo.type) as? ClientTunnelInfo
private val typeButton: WidgetButton
private val refreshButton: WidgetButton
private val scrollBar: WidgetScrollBar
private val searchBar: MEGuiTextField
private val infos = InfoList(msg.infos.map(::InfoWrapper), ::searchText)
private val typeSelector: WidgetTypeSelector
private val searchText: String
get() = searchBar.text
private var col: WidgetP2PColumn
private val descriptionLines: MutableList<String> = mutableListOf()
private var mode = msg.memoryInfo.mode
private var modeString = getModeString()
private val modeButton by lazy { GuiButton(0, 0, 0, 256, 20, modeString) }
private val sortRules: List<String> by lazy {
listOf(
"§b§n" + I18n.format("gui.advanced_memory_card.sortinfo1"),
@@ -70,7 +81,8 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
"§6@out§7 - " + I18n.format("gui.advanced_memory_card.sortinfo3"),
"§a@b§7 - " + I18n.format("gui.advanced_memory_card.sortinfo4"),
"§c@u§7 - " + I18n.format("gui.advanced_memory_card.sortinfo5"),
"§7" + I18n.format("gui.advanced_memory_card.sortinfo6")
"§e@type=<name1>[;<name2>;]...§7 - " + I18n.format("gui.advanced_memory_card.sortinfo6"),
"§7" + I18n.format("gui.advanced_memory_card.sortinfo7")
)
}
@@ -84,23 +96,221 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
col = WidgetP2PColumn(this, infos,0, 0,
::selectedInfo, ::mode, scrollBar)
searchBar = MEGuiTextField(100, 10)
resizeButton = object: WidgetButton(this, 0, 0, 32, 32, { scale.unlocalizedName }) {
override fun mousePressed(mouseX: Int, mouseY: Int) {
resizeButton = object: WidgetButton(this, 0, 0, 32, 32) {
override fun mousePressed(mouseX: Int, mouseY: Int, button: Int): Boolean {
if (super.mousePressed(mc, mouseX, mouseY)) {
scale = when(scale) {
GuiScale.DYNAMIC -> GuiScale.SMALL
GuiScale.SMALL -> GuiScale.NORMAL
GuiScale.NORMAL -> GuiScale.LARGE
GuiScale.LARGE -> GuiScale.DYNAMIC
if (button == 0) {
scale = when (scale) {
GuiScale.DYNAMIC -> GuiScale.SMALL
GuiScale.SMALL -> GuiScale.NORMAL
GuiScale.NORMAL -> GuiScale.LARGE
GuiScale.LARGE -> GuiScale.DYNAMIC
}
} else if (button == 1) {
scale = when (scale) {
GuiScale.DYNAMIC -> GuiScale.LARGE
GuiScale.LARGE -> GuiScale.NORMAL
GuiScale.NORMAL -> GuiScale.SMALL
GuiScale.SMALL -> GuiScale.DYNAMIC
}
}
initGui()
super.func_146113_a(mc.soundHandler)
return true
}
return false
}
}
modeButton = object: WidgetButton(this, 0, 0, 32, 32) {
val modeDescriptions: List<List<String>> = listOf(
fmtTooltips(
title = BetterMemoryCardModes.OUTPUT.unlocalizedName,
keys = BetterMemoryCardModes.OUTPUT.unlocalizedDesc,
maxChars = MAX_TOOLTIP_LENGTH,
),
fmtTooltips(
title = BetterMemoryCardModes.INPUT.unlocalizedName,
keys = BetterMemoryCardModes.INPUT.unlocalizedDesc,
maxChars = MAX_TOOLTIP_LENGTH,
),
fmtTooltips(
title = BetterMemoryCardModes.COPY.unlocalizedName,
keys = BetterMemoryCardModes.COPY.unlocalizedDesc,
maxChars = MAX_TOOLTIP_LENGTH,
),
fmtTooltips(
title = BetterMemoryCardModes.UNBIND.unlocalizedName,
keys = BetterMemoryCardModes.UNBIND.unlocalizedDesc,
maxChars = MAX_TOOLTIP_LENGTH,
)
)
init {
hoverText = modeDescriptions[mode.ordinal]
}
override fun mousePressed(mouseX: Int, mouseY: Int, button: Int): Boolean {
if (super.mousePressed(mc, mouseX, mouseY)) {
mode = when (button) {
0 -> mode.next()
1 -> mode.next(true)
else -> return false
}
hoverText = modeDescriptions[mode.ordinal]
setTexCoords((mode.ordinal + 3) * 32.0, 232.0)
syncMemoryInfo()
super.func_146113_a(mc.soundHandler)
return true
}
return false
}
}
typeButton = object: WidgetButton(this, 0, 0, 32, 32), ITypeReceiver {
val types = BetterP2P.proxy.getP2PTypeList()
private var index =
if (type != null) {
types.first { it.index == type?.index}.index
} else {
types.size
}
private val me = BetterP2P.proxy.getP2PFromClass(PartP2PTunnelME::class.java) as ClientTunnelInfo
private val fluid = BetterP2P.proxy.getP2PFromClass(PartP2PLiquids::class.java) as ClientTunnelInfo
private val redstone = BetterP2P.proxy.getP2PFromClass(PartP2PRedstone::class.java) as ClientTunnelInfo
init {
hoverText = if (type == null) {
mutableListOf(
I18n.format("gui.advanced_memory_card.types.filtered",
I18n.format("gui.advanced_memory_card.types.any")))
} else {
mutableListOf(
I18n.format("gui.advanced_memory_card.types.filtered", "§a" + type!!.stack.displayName))
}
}
private fun nextType(reverse: Boolean): ClientTunnelInfo? {
// range: [0, types.size]
return if (reverse) {
index = (index - 1).mod(types.size + 1)
types.getOrNull(index) as? ClientTunnelInfo
} else {
index = (index + 1).mod(types.size + 1)
types.getOrNull(index) as? ClientTunnelInfo
}
}
override fun mousePressed(mouseX: Int, mouseY: Int, button: Int): Boolean {
if (super.mousePressed(mc, mouseX, mouseY)) {
if (button == 1) {
// open type selector?
openTypeSelector(this, true)
return true
} else {
type = nextType(false)
}
commitType()
return true
}
return false
}
override fun draw(mc: Minecraft, mouseX: Int, mouseY: Int, partialTicks: Float) {
val tessellator = Tessellator.instance
drawBG(tessellator, mouseX, mouseY, partialTicks)
if (type != null) {
drawBlockIcon(mc, type!!.icon(), type!!.stack.iconIndex,
x = this.xPosition + 2,
y = this.yPosition + 2,
width = 28.0,
height = 28.0)
} else {
drawBlockIcon(mc, redstone.icon(), types[0].stack.iconIndex,
x = this.xPosition + 12,
y = this.yPosition + 12,
width = 18.0,
height = 18.0)
drawBlockIcon(mc, fluid.icon(), types[0].stack.iconIndex,
x = this.xPosition + 7,
y = this.yPosition + 7,
width = 18.0,
height = 18.0)
drawBlockIcon(mc, me.icon(), types[0].stack.iconIndex,
x = this.xPosition + 2,
y = this.yPosition + 2,
width = 18.0,
height = 18.0)
}
}
private fun commitType() {
if (type == null) {
(hoverText as MutableList)[0] = I18n.format("gui.advanced_memory_card.types.filtered",
I18n.format("gui.advanced_memory_card.types.any"))
} else {
(hoverText as MutableList)[0] =
I18n.format("gui.advanced_memory_card.types.filtered", "§a" + type!!.stack.displayName)
}
ModNetwork.channel.sendToServer(C2SRefreshP2PList(type?.index ?: TUNNEL_ANY))
super.func_146113_a(mc.soundHandler)
}
override fun accept(type: ClientTunnelInfo?) {
this.index = type?.index ?: TUNNEL_ANY
gui.type = type
commitType()
gui.closeTypeSelector()
}
override fun x(): Int {
return guiLeft
}
override fun y(): Int {
return this.yPosition
}
}
refreshButton = object: WidgetButton(this, 0, 0, 32, 32) {
override fun mousePressed(mouseX: Int, mouseY: Int, button: Int): Boolean {
if (super.mousePressed(mc, mouseX, mouseY)) {
ModNetwork.channel.sendToServer(C2SRefreshP2PList(type?.index ?: TUNNEL_ANY))
return true
}
return false
}
}
val typeSelectorList = mutableListOf<ClientTunnelInfo>()
var toAdd = BetterP2P.proxy.getP2PFromClass(PartP2PTunnelME::class.java) as? ClientTunnelInfo
if (toAdd != null) {
typeSelectorList.add(toAdd)
}
toAdd = BetterP2P.proxy.getP2PFromClass(PartP2PLiquids::class.java) as? ClientTunnelInfo
if (toAdd != null) {
typeSelectorList.add(toAdd)
}
toAdd = BetterP2P.proxy.getP2PFromClass(PartP2PGT5Power::class.java) as? ClientTunnelInfo
if (toAdd != null) {
typeSelectorList.add(toAdd)
}
toAdd = BetterP2P.proxy.getP2PFromClass(PartP2PInterface::class.java) as? ClientTunnelInfo
if (toAdd != null) {
typeSelectorList.add(toAdd)
}
BetterP2P.proxy.getP2PTypeList().forEach {
if (!typeSelectorList.contains(it)) {
typeSelectorList.add(it as ClientTunnelInfo)
}
}
typeSelector = WidgetTypeSelector(0, 0, typeSelectorList)
typeSelector.parent = typeButton
}
// Note this is called on resize too.
/**
* Called on resize. Initializes GUI elements.
*/
override fun initGui() {
super.initGui()
checkInfo()
@@ -108,6 +318,7 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
if (scale.minHeight > h) {
scale = GuiScale.DYNAMIC
}
resizeButton.hoverText = listOf(I18n.format(scale.unlocalizedName))
val numEntries = scale.size(height - 75)
ySize = (numEntries * P2PEntryConstants.HEIGHT) + 75 + (numEntries - 1)
guiTop = (h - ySize) / 2
@@ -126,23 +337,52 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
col.resize(scale, h - 75)
col.setPosition(guiLeft + tableX, guiTop + tableY)
modeButton.xPosition = guiLeft + 8
modeButton.yPosition = guiTop + ySize - 52
resizeButton.setPosition(guiLeft - 32, guiTop + 2)
resizeButton.setTexCoords(scale.ordinal * 32.0, 200.0)
buttonList.add(resizeButton)
modeButton.setPosition(guiLeft - 32, guiTop + 34)
modeButton.setTexCoords((mode.ordinal + 3) * 32.0, 232.0)
buttonList.add(modeButton)
typeButton.setPosition(guiLeft - 32, guiTop + 66)
buttonList.add(typeButton)
refreshButton.setPosition(guiLeft - 32, guiTop + 98)
refreshButton.setTexCoords(32 * 5.0, 200.0)
buttonList.add(refreshButton)
if (typeSelector.parent != typeButton) {
closeTypeSelector()
} else {
typeSelector.setPos(typeSelector.parent.x(), typeSelector.parent.y())
}
infos.refresh()
checkInfo()
refreshOverlay()
col.entries.forEach { it.updateButtonVisibility() }
}
fun openTypeSelector(parent: ITypeReceiver, useAny: Boolean) {
typeSelector.parent = parent
typeSelector.setPos(parent.x(), parent.y())
typeSelector.useAny = useAny
typeSelector.visible = true
}
fun closeTypeSelector() {
typeSelector.visible = false
}
private fun checkInfo() {
infos.filtered.forEach { it.error = false }
// A P2P entry is considered "errored" if it is an output, and has no inputs.
infos.filtered.groupBy { it.frequency }.filter { it.value.none { x -> !x.output } }.forEach { it.value.forEach { info ->
info.error = true
} }
infos.filtered.forEach {
it.error = it.frequency != 0L && if (it.output) {
col.findInput(it.frequency) == null
} else {
col.findOutput(it.frequency) == null
}
}
}
fun refreshInfo(infos: List<P2PInfo>) {
@@ -152,15 +392,8 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
}
private fun syncMemoryInfo() {
ModNetwork.channel.sendToServer(C2SUpdateInfo(MemoryInfo(infos.selectedEntry, selectedInfo?.frequency ?: 0, mode, scale)))
}
private fun drawInformation() {
var y = 214
for (line in descriptionLines) {
fontRendererObj.drawString(line, guiLeft + 8, modeButton.yPosition + 20 + 3, 0)
y += fontRendererObj.FONT_HEIGHT
}
ModNetwork.channel.sendToServer(
C2SUpdateInfo(MemoryInfo(infos.selectedEntry, selectedInfo?.frequency ?: 0, mode, scale, type?.index ?: TUNNEL_ANY)))
}
override fun onGuiClosed() {
@@ -175,47 +408,42 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
drawBackground()
// Draw the stuff that resets GL state first
fontRendererObj.drawString(I18n.format("item.advanced_memory_card.name"), guiLeft + tableX, guiTop + 6, 0)
if (modeButton.func_146115_a()) {
descriptionLines.clear()
descriptionLines += I18n.format("gui.advanced_memory_card.desc.mode", I18n.format("gui.advanced_memory_card.mode.${mode.next().name.lowercase(Locale.getDefault())}"))
} else {
descriptionLines.clear()
}
drawInformation()
searchBar.drawTextBox()
resizeButton.draw(mc, mouseX, mouseY, partialTicks)
modeButton.drawButton(mc, mouseX, mouseY)
buttonList.forEach { it as WidgetButton
it.draw(mc, mouseX, mouseY, partialTicks)
}
// Now do our drawing
// Now draw our P2P entries
GL11.glPushAttrib(GL11.GL_BLEND or GL11.GL_TEXTURE_2D or GL11.GL_COLOR)
GL11.glEnable(GL11.GL_BLEND)
GL11.glEnable(GL11.GL_TEXTURE_2D)
GL11.glColor3f(255f, 255f, 255f)
scrollBar.draw(this)
col.render(this, mouseX, mouseY, partialTicks)
col.render(mouseX, mouseY, partialTicks)
// The GL state is already messed up here by string drawing but oh well
GL11.glPopAttrib()
if (searchBar.isMouseIn(mouseX, mouseY)) {
drawHoveringText(sortRules, guiLeft, guiTop + ySize - 40, fontRendererObj)
} else if (resizeButton.isHovering(mouseX, mouseY)) {
drawHoveringText(listOf(I18n.format(resizeButton.hoverText())), mouseX, mouseY, fontRendererObj)
} else {
col.mouseHovered(mouseX, mouseY)
if (typeSelector.visible) {
typeSelector.render(this, mouseX, mouseY, partialTicks)
return
}
var drewHoverText = false
run finished@ {
buttonList.forEach { it as WidgetButton
if (it.isHovering(mouseX, mouseY)) {
drawHoveringText(it.hoverText, mouseX, mouseY + 10, fontRendererObj)
drewHoverText = true
return@finished
}
}
}
if (!drewHoverText) {
if (searchBar.isMouseIn(mouseX, mouseY)) {
drawHoveringText(sortRules, guiLeft, guiTop + ySize - 40, fontRendererObj)
} else {
col.mouseHovered(mouseX, mouseY)
}
}
super.drawScreen(mouseX, mouseY, partialTicks)
}
private fun switchMode() {
// Switch mode
mode = mode.next()
modeString = getModeString()
modeButton.displayString = modeString
syncMemoryInfo()
}
private fun getModeString(): String {
return I18n.format("gui.advanced_memory_card.mode.${mode.name.lowercase(Locale.getDefault())}")
}
/**
@@ -246,13 +474,18 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
}
override fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) {
col.mouseClicked(mouseX, mouseY, mouseButton)
if (modeButton.mousePressed(mc, mouseX, mouseY)) {
switchMode()
modeButton.func_146113_a(mc.soundHandler)
if (typeSelector.visible) {
typeSelector.mousePressed(mouseX, mouseY, mouseButton)
return
}
col.mouseClicked(mouseX, mouseY, mouseButton)
scrollBar.click(mouseX, mouseY)
resizeButton.mousePressed(mouseX, mouseY)
for (button in buttonList) {
button as WidgetButton
if (button.mousePressed(mouseX, mouseY, mouseButton)) {
return
}
}
searchBar.mouseClicked(mouseX, mouseY, mouseButton)
if (mouseButton == 1 && searchBar.isMouseIn(mouseX, mouseY)) {
this.searchBar.text = ""
@@ -273,11 +506,7 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
override fun handleMouseInput() {
super.handleMouseInput()
val i = Mouse.getEventDWheel()
if (i != 0 && isShiftKeyDown()) {
// val x = Mouse.getEventX() * width / mc.displayWidth
// val y = height - Mouse.getEventY() * height / mc.displayHeight - 1
// this.mouseWheelEvent(x, y, i / Math.abs(i))
} else if (i != 0) {
if (i != 0) {
scrollBar.wheel(i)
col.finishRename()
}
@@ -296,21 +525,30 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
bindTexture(BACKGROUND)
val tessellator = Tessellator.instance
// Draw the top part
drawTexturedQuad(tessellator, guiLeft.toDouble(), guiTop.toDouble(),
(guiLeft + GUI_WIDTH).toDouble(), guiTop + 60.0,
drawTexturedQuad(tessellator,
x0 = guiLeft.toDouble(),
y0 = guiTop.toDouble(),
x1 = (guiLeft + GUI_WIDTH).toDouble(),
y1 = guiTop + 60.0,
u0 = 0.0, v0 = 0.0,
u1 = 1.0, v1 = 60.0 / GUI_TEX_HEIGHT)
// Draw P2P segments
val p2pHeight = P2PEntryConstants.HEIGHT + 1.0
for (i in 0 until scale.size(ySize - 75) - 2) {
drawTexturedQuad(tessellator, guiLeft.toDouble(), guiTop + 60.0 + p2pHeight * i,
(guiLeft + GUI_WIDTH).toDouble(), guiTop + 60.0 + p2pHeight * (i + 1),
drawTexturedQuad(tessellator,
x0 = guiLeft.toDouble(),
y0 = guiTop + 60.0 + p2pHeight * i,
x1 = (guiLeft + GUI_WIDTH).toDouble(),
y1 = guiTop + 60.0 + p2pHeight * (i + 1),
u0 = 0.0, v0 = 60.0 / GUI_TEX_HEIGHT,
u1 = 1.0, v1 = 102.0 / GUI_TEX_HEIGHT)
}
// Draw Bottom
drawTexturedQuad(tessellator, guiLeft.toDouble(), guiTop + ySize - 98.0,
(guiLeft + GUI_WIDTH).toDouble(), (guiTop + ySize).toDouble(),
drawTexturedQuad(tessellator,
x0 = guiLeft.toDouble(),
y0 = guiTop + ySize - 98.0,
x1 = (guiLeft + GUI_WIDTH).toDouble(),
y1 = (guiTop + ySize).toDouble(),
u0 = 0.0, v0 = 102.0 / GUI_TEX_HEIGHT,
u1 = 1.0, v1 = 200.0 / GUI_TEX_HEIGHT)
}
@@ -320,6 +558,10 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
}
override fun keyTyped(char: Char, key: Int) {
if (key == Keyboard.KEY_ESCAPE && typeSelector.visible) {
closeTypeSelector()
return
}
if (key == Keyboard.KEY_LSHIFT || col.keyTyped(char, key)) return
if (!(char.isWhitespace() && searchBar.text.isEmpty()) && searchBar.textboxKeyTyped(char, key)){
infos.refilter()
@@ -334,4 +576,38 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
public override fun drawHoveringText(textLines: List<Any?>?, x: Int, y: Int, font: FontRenderer?) {
super.drawHoveringText(textLines, x, y, font)
}
fun getTypeID(): Int {
return type?.index ?: TUNNEL_ANY
}
}
/**
* Format multiple lines of tooltips by the given max chars.
*/
fun fmtTooltips(title: String, vararg keys: String, maxChars: Int): List<String> {
val result: MutableList<String> = mutableListOf()
result.add(I18n.format(title))
for (key in keys) {
val words = I18n.format(key).split(' ')
var i = 0
if (key.length < maxChars) {
result.add(key)
}
while (i < words.size) {
val s = StringBuilder()
perWord@
while (s.length < maxChars) {
s.append(words[i])
i += 1
if (i >= words.size) break@perWord
s.append(" ")
}
if (!s.startsWith('§')) {
s.insert(0, "§7")
}
result.add(s.toString())
}
}
return result
}
@@ -1,7 +1,12 @@
package com.projecturanus.betterp2p.client.gui
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.OpenGlHelper
import net.minecraft.client.renderer.Tessellator
import net.minecraft.util.ResourceLocation
import net.minecraft.util.IIcon
import org.lwjgl.opengl.GL11
/**
* Draws a textured quad.
@@ -11,7 +16,10 @@ import net.minecraft.util.ResourceLocation
* u0, v0 - top left texture corner
* u1, v1 - bottom right texture corner
*/
fun drawTexturedQuad(tessellator: Tessellator, x0 : Double, y0: Double, x1: Double, y1: Double, u0: Double, v0: Double, u1: Double, v1: Double) {
@SideOnly(Side.CLIENT)
fun drawTexturedQuad(tessellator: Tessellator,
x0: Double, y0: Double, x1: Double, y1: Double,
u0: Double, v0: Double, u1: Double, v1: Double) {
tessellator.startDrawingQuads()
tessellator.addVertexWithUV(x0, y1, 0.0, u0, v1)
tessellator.addVertexWithUV(x1, y1, 0.0, u1, v1)
@@ -19,3 +27,32 @@ fun drawTexturedQuad(tessellator: Tessellator, x0 : Double, y0: Double, x1: Doub
tessellator.addVertexWithUV(x0, y0, 0.0, u0, v0)
tessellator.draw()
}
/**
* Draw the icon on the Block Texture Atlas
*/
fun drawBlockIcon(mc: Minecraft, icon: IIcon, overlay: IIcon,
x: Int, y: Int, width: Double = 16.0, height: Double = 16.0) {
val tessellator = Tessellator.instance
mc.textureManager.bindTexture(mc.renderEngine.getResourceLocation(0))
GL11.glPushAttrib(GL11.GL_BLEND or GL11.GL_TEXTURE_2D or GL11.GL_COLOR)
GL11.glEnable(GL11.GL_BLEND)
GL11.glEnable(GL11.GL_TEXTURE_2D)
GL11.glColor3f(255f, 255f, 255f)
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0)
drawTexturedQuad(tessellator,
x0 = x.toDouble() + 2,
y0 = y.toDouble() + 2,
x1 = x + width - 2,
y1 = y + height - 2,
u0 = icon.minU.toDouble(), v0 = icon.minV.toDouble(),
u1 = icon.maxU.toDouble(), v1 = icon.maxV.toDouble())
drawTexturedQuad(tessellator,
x0 = x.toDouble(),
y0 = y.toDouble(),
x1 = x + width,
y1 = y + height,
u0 = overlay.minU.toDouble(), v0 = overlay.minV.toDouble(),
u1 = overlay.maxU.toDouble(), v1 = overlay.maxV.toDouble())
GL11.glPopAttrib()
}
@@ -1,11 +1,14 @@
package com.projecturanus.betterp2p.client.gui
import com.projecturanus.betterp2p.BetterP2P
/**
* Extend the default filtering. Holds information about the search filter.
*
* There are 3 modes of filtering:
* There are 4 modes of filtering:
* - By input/output: Using `@in/@out` filters by input/output respectively.
* - By bound/unbound: Use `@b` or `@u` filters by input/output respectively.
* - By bound/unbound: Using `@b` or `@u` filters by bound/unbound respectively.
* - By type: Using `@types=<type1>;<type2>;...` filters by type.
* - By name: Use the name
* If someone comes and says "sort by freq pls" then we can add it at that time
*/
@@ -23,28 +26,42 @@ class InfoFilter {
fun updateFilter(query: String) {
val tokens = SEARCH_REGEX.findAll(query)
activeFilters.clear()
var bind: String
tokens.forEach {
when {
it.value.matches(Filter.INPUT.pattern) -> {
activeFilters.putIfAbsent(Filter.INPUT, null)
}
it.value.matches(Filter.OUTPUT.pattern) -> {
activeFilters.putIfAbsent(Filter.OUTPUT, null)
}
it.value.matches(Filter.BOUND.pattern) -> {
activeFilters.putIfAbsent(Filter.BOUND, null)
}
it.value.matches(Filter.UNBOUND.pattern) -> {
activeFilters.putIfAbsent(Filter.UNBOUND, null)
}
it.value.isBlank() -> {}
else -> {
activeFilters.putIfAbsent(Filter.NAME, mutableListOf())
when {
it.groups[1] != null -> activeFilters[Filter.NAME]!!.add(it.groups[1]!!.value)
it.groups[2] != null -> activeFilters[Filter.NAME]!!.add(it.groups[2]!!.value)
else -> activeFilters[Filter.NAME]!!.add(it.value)
val token = it.value
// If we don't start with a tag, skip all these regexes
if (token.startsWith("@")) {
when {
it.value.matches(Filter.INPUT.pattern) -> {
activeFilters.putIfAbsent(Filter.INPUT, null)
}
it.value.matches(Filter.OUTPUT.pattern) -> {
activeFilters.putIfAbsent(Filter.OUTPUT, null)
}
it.value.matches(Filter.BOUND.pattern) -> {
activeFilters.putIfAbsent(Filter.BOUND, null)
}
it.value.matches(Filter.UNBOUND.pattern) -> {
activeFilters.putIfAbsent(Filter.UNBOUND, null)
}
it.value.matches(Filter.TYPE.pattern) -> {
val result = Filter.TYPE.pattern.find(it.value)!!
val l = mutableListOf<String>()
activeFilters.putIfAbsent(Filter.TYPE, l)
val types = result.groupValues[1].split(";")
types.forEach(l::add)
}
it.value.isBlank() -> {}
else -> {
}
}
} else {
val l = mutableListOf<String>()
activeFilters.putIfAbsent(Filter.NAME, l)
when {
it.groups[1] != null -> l.add(it.groups[1]!!.value)
it.groups[2] != null -> l.add(it.groups[2]!!.value)
else -> activeFilters[Filter.NAME]!!.add(it.value)
}
}
}
@@ -60,6 +77,15 @@ enum class Filter(val pattern: Regex, val filter: (InfoWrapper, List<String>?) -
OUTPUT("\\A@out\\z".toRegex(), { it, _ -> it.output }),
BOUND("\\A@b\\z".toRegex(), { it, _ -> it.frequency != 0L }),
UNBOUND("\\A@u\\z".toRegex(), { it, _ -> it.frequency == 0L || it.error }),
TYPE("\\A@types*=(.+)\\z".toRegex(), filter@{ it, strs ->
val tags = BetterP2P.proxy.getP2PFromIndex(it.type)!!.dispName.lowercase()
for (f in strs!!) {
if (tags.contains(f.lowercase())) {
return@filter true
}
}
false
}),
NAME("\"?.+\"?".toRegex(), filter@{ it, strs ->
val name = it.name.lowercase()
for (f in strs!!) {
@@ -1,8 +1,6 @@
package com.projecturanus.betterp2p.client.gui
import com.projecturanus.betterp2p.network.NONE
import com.projecturanus.betterp2p.network.hashP2P
import kotlin.math.absoluteValue
import com.projecturanus.betterp2p.network.NONE_SELECTED
import kotlin.reflect.KProperty0
/**
@@ -43,7 +41,7 @@ class InfoList (initList: Collection<InfoWrapper>,
val selectedInfo: InfoWrapper?
get() = masterMap[selectedEntry]
var selectedEntry: Long = NONE
var selectedEntry: Long = NONE_SELECTED
val size: Int
get() = masterMap.size
@@ -99,7 +97,7 @@ class InfoList (initList: Collection<InfoWrapper>,
}
-(hits * hits) + name.length
}
else -> it.frequency + Short.MAX_VALUE
else -> it.frequency + Short.MAX_VALUE - (if (it.output) 0 else 1)
}
}
}
@@ -143,7 +141,7 @@ class InfoList (initList: Collection<InfoWrapper>,
if (masterMap.containsKey(hashCode)) {
selectedEntry = hashCode
} else {
selectedEntry = NONE
selectedEntry = NONE_SELECTED
}
}
}
@@ -1,20 +1,12 @@
package com.projecturanus.betterp2p.client.gui
import appeng.api.parts.IPart
import appeng.api.parts.IPartItem
import appeng.api.parts.PartItemStack
import appeng.me.GridNode
import appeng.parts.p2p.PartP2PTunnel
import appeng.parts.p2p.PartP2PTunnelME
import appeng.tile.networking.TileCableBus
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.network.P2PInfo
import com.projecturanus.betterp2p.network.hashP2P
import com.projecturanus.betterp2p.util.p2p.ClientTunnelInfo
import net.minecraft.client.gui.GuiButton
import net.minecraft.client.resources.I18n
import net.minecraft.init.Blocks
import net.minecraft.item.ItemStack
import net.minecraft.util.IIcon
import net.minecraftforge.common.DimensionManager
import net.minecraftforge.common.util.ForgeDirection
class InfoWrapper(info: P2PInfo) {
@@ -22,7 +14,16 @@ class InfoWrapper(info: P2PInfo) {
val code: Long by lazy {
hashP2P(posX, posY, posZ, facing.ordinal, dim)
}
val frequency: Long = info.frequency
var frequency: Long = info.frequency
set(value) {
if (error || value == 0L) {
hoverInfo[4] = "§c" + I18n.format("gui.advanced_memory_card.p2p_status.unbound")
} else {
hoverInfo[4] = "§a" + I18n.format("gui.advanced_memory_card.p2p_status.bound")
}
field = value
}
val hasChannel = info.hasChannel
val posX: Int = info.posX
val posY: Int = info.posY
@@ -30,11 +31,17 @@ class InfoWrapper(info: P2PInfo) {
val dim: Int = info.world
val facing: ForgeDirection = info.facing
val output: Boolean = info.output
val type: Int = info.type
/**
* The backing icon (quartz, iron, etc)
*/
val icon: IIcon
val overlay: IIcon
val typeName: String
/**
* The p2p overlay texture (frame)
*/
val overlay: IIcon
val description: String
val freqDisplay: String by lazy {
@@ -53,7 +60,7 @@ class InfoWrapper(info: P2PInfo) {
}
}
val hoverInfo: List<String>
val hoverInfo: MutableList<String>
val channels: String? by lazy {
if (info.channels >= 0) {
@@ -69,52 +76,36 @@ class InfoWrapper(info: P2PInfo) {
// Widgets
val bindButton = GuiButton(0, 0, 0, 34, 20, I18n.format("gui.advanced_memory_card.bind"))
val renameButton = GuiButton(0, 0, 0, 0, 0,"")
val unbindButton = GuiButton(0, 0, 0, 34, 20, I18n.format("gui.advanced_memory_card.unbind"))
init {
val p: IPart? = (info.stack.item as? IPartItem)?.createPartFromItemStack(info.stack)
if (p is PartP2PTunnel<*>) {
icon = p.typeTexture
overlay = info.stack.iconIndex
typeName =
info.stack.item.getItemStackDisplayName(info.stack).split(" - ").getOrNull(1)
?: "§c<Something broke...>"
description = buildString {
append("Type: ")
append(typeName)
append(" - ")
if (output)
append(I18n.format("gui.advanced_memory_card.desc.mode.output"))
else
append(I18n.format("gui.advanced_memory_card.desc.mode.input"))
}
val online = info.hasChannel
hoverInfo = mutableListOf(
"§bP2P - $typeName",
"§e" + I18n.format("gui.advanced_memory_card.pos", info.posX, info.posY, info.posZ),
"§e" + I18n.format("gui.advanced_memory_card.side", info.facing.name),
"§e" + I18n.format("gui.advanced_memory_card.dim", info.world)
)
if (error || frequency == 0L) {
hoverInfo.add("§c" + I18n.format("gui.advanced_memory_card.p2p_status.unbound"))
} else {
hoverInfo.add("§a" + I18n.format("gui.advanced_memory_card.p2p_status.bound"))
}
if (!online) hoverInfo.add("§c" + I18n.format("gui.advanced_memory_card.p2p_status.offline"))
} else {
icon = Blocks.air.getIcon(0, 0)
overlay = Blocks.air.getIcon(0, 0)
typeName = "§c<Something broke...>"
description = "§c<Unknown>"
hoverInfo = mutableListOf(
"§b$typeName§r",
"§e" + I18n.format("gui.advanced_memory_card.pos", info.posX, info.posY, info.posZ),
"§e" + I18n.format("gui.advanced_memory_card.side", info.facing.name),
"§e" + I18n.format("gui.advanced_memory_card.dim", info.world)
)
val p2pType: ClientTunnelInfo = BetterP2P.proxy.getP2PFromIndex(info.type) as ClientTunnelInfo
icon = p2pType.icon()
overlay = p2pType.stack.iconIndex
description = buildString {
append("Type: ")
append(p2pType.dispName)
append(" - ")
if (output)
append(I18n.format("gui.advanced_memory_card.p2p_status.output"))
else
append(I18n.format("gui.advanced_memory_card.p2p_status.input"))
}
val online = info.hasChannel
hoverInfo = mutableListOf(
"§bP2P - ${p2pType.dispName}",
"§e" + I18n.format("gui.advanced_memory_card.pos", info.posX, info.posY, info.posZ),
"§e" + I18n.format("gui.advanced_memory_card.side", info.facing.name),
"§e" + I18n.format("gui.advanced_memory_card.dim", info.world)
)
if (error || frequency == 0L) {
hoverInfo.add("§c" + I18n.format("gui.advanced_memory_card.p2p_status.unbound"))
} else {
hoverInfo.add("§a" + I18n.format("gui.advanced_memory_card.p2p_status.bound"))
}
if (!online) hoverInfo.add("§c" + I18n.format("gui.advanced_memory_card.p2p_status.offline"))
}
override fun hashCode(): Int {
return code.hashCode()
}
@@ -1,6 +1,5 @@
package com.projecturanus.betterp2p.client.gui.widget
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.client.gui.GUI_TEX_HEIGHT
import com.projecturanus.betterp2p.client.gui.GUI_WIDTH
import com.projecturanus.betterp2p.client.gui.GuiAdvancedMemoryCard
@@ -19,16 +18,26 @@ import org.lwjgl.opengl.GL11
* @param height
* @param hoverText - unlocalized text to display when mouse hovering
*/
abstract class WidgetButton(val gui: GuiAdvancedMemoryCard, x: Int, y: Int, width: Int, height: Int,
val hoverText: () -> String): GuiButton(0, x, y, width, height, "") {
abstract class WidgetButton(val gui: GuiAdvancedMemoryCard, x: Int, y: Int, width: Int, height: Int):
GuiButton(0, x, y, width, height, "") {
private var texX = 0.0
private var texY = 0.0
var hoverText: List<String> = listOf()
abstract fun mousePressed(mouseX: Int, mouseY: Int)
abstract fun mousePressed(mouseX: Int, mouseY: Int, button: Int): Boolean
fun draw(mc: Minecraft?, mouseX: Int, mouseY: Int, partialTicks: Float) {
open fun draw(mc: Minecraft, mouseX: Int, mouseY: Int, partialTicks: Float) {
val tessellator = Tessellator.instance
drawBG(tessellator, mouseX, mouseY, partialTicks)
// Draw button icon
drawTexturedQuad(tessellator, xPosition + 1.0, yPosition + 1.0,
xPosition + width - 1.0, yPosition + height - 1.0,
u0 = texX / GUI_WIDTH, v0 = texY / GUI_TEX_HEIGHT,
u1 = (texX + width) / GUI_WIDTH, v1 = (texY + height) / GUI_TEX_HEIGHT)
}
open fun drawBG(tessellator: Tessellator, mouseX: Int, mouseY: Int, partialTicks: Float) {
gui.bindTexture(gui.BACKGROUND)
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f)
field_146123_n = mouseX >= xPosition && mouseY >= yPosition && mouseX < xPosition + width && mouseY < yPosition + height
@@ -36,17 +45,15 @@ abstract class WidgetButton(val gui: GuiAdvancedMemoryCard, x: Int, y: Int, widt
GL11.glEnable(GL11.GL_BLEND)
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0)
// Draw button backdrop
drawTexturedQuad(tessellator, xPosition.toDouble(), yPosition.toDouble(),
(xPosition + width).toDouble(), (yPosition + height).toDouble(),
u0 = (32.0 * k) / GUI_WIDTH, v0 = (232.0) / GUI_TEX_HEIGHT,
u1 = (32.0 * (k + 1)) / GUI_WIDTH, v1 = (232.0 + height) / GUI_TEX_HEIGHT)
// Draw button icon
drawTexturedQuad(tessellator, xPosition.toDouble(), yPosition.toDouble(),
(xPosition + width).toDouble(), (yPosition + height).toDouble(),
u0 = texX / GUI_WIDTH, v0 = texY / GUI_TEX_HEIGHT,
u1 = (texX + width) / GUI_WIDTH, v1 = (texY + height) / GUI_TEX_HEIGHT)
drawTexturedQuad(tessellator,
x0 = xPosition.toDouble(),
y0 = yPosition.toDouble(),
x1 = (xPosition + width).toDouble(),
y1 = (yPosition + height).toDouble(),
u0 = (32.0 * k) / GUI_WIDTH, v0 = (232.0) / GUI_TEX_HEIGHT,
u1 = (32.0 * (k + 1)) / GUI_WIDTH, v1 = (232.0 + height) / GUI_TEX_HEIGHT)
}
fun setPosition(x: Int, y: Int) {
this.xPosition = x
this.yPosition = y
@@ -38,9 +38,9 @@ class WidgetP2PColumn(private val gui: GuiAdvancedMemoryCard,
fun resize(scale: GuiScale, availableHeight: Int) {
entries.clear()
for (i in 0 until scale.size(availableHeight)) {
val widget = WidgetP2PDevice( selectedInfo, mode,
val widget = WidgetP2PDevice(selectedInfo, mode,
{ infos.filtered.getOrNull(i + scrollBar.currentScroll) },
x, y + i * (P2PEntryConstants.HEIGHT + 1))
gui, x, y + i * (P2PEntryConstants.HEIGHT + 1))
entries.add(widget)
}
}
@@ -90,13 +90,17 @@ class WidgetP2PColumn(private val gui: GuiAdvancedMemoryCard,
renameBar.info = info
}
private fun onSelectButtonClicked(info: InfoWrapper) {
gui.selectInfo(info.code)
private fun onSelectButtonClicked(widget: WidgetP2PDevice, info: InfoWrapper, mouseButton: Int) {
if (mouseButton == 1) {
gui.openTypeSelector(widget, false)
} else if (selectedInfo.get() != info) {
gui.selectInfo(info.code)
}
info.bindButton.func_146113_a(gui.mc.soundHandler)
}
private fun onBindButtonClicked(info: InfoWrapper) {
if (infos.selectedEntry == NONE) return
if (infos.selectedEntry == NONE_SELECTED) return
when (mode()) {
BetterMemoryCardModes.INPUT -> {
BetterP2P.logger.debug("Bind ${info.code} as input")
@@ -111,19 +115,34 @@ class WidgetP2PColumn(private val gui: GuiAdvancedMemoryCard,
if (input != null)
ModNetwork.channel.sendToServer(C2SLinkP2P(input.code, info.code))
}
else -> {
BetterP2P.logger.debug("Somehow bind button was pressed while in UNBIND mode.")
}
}
info.bindButton.func_146113_a(gui.mc.soundHandler)
}
private fun findInput(frequency: Long?) =
private fun onUnbindButtonClicked(info: InfoWrapper) {
if (info.frequency != 0L) {
ModNetwork.channel.sendToServer(C2SUnlinkP2P(info.code, gui.getTypeID()))
info.frequency = 0L
}
}
fun findInput(frequency: Long?) =
infos.filtered.find { it.frequency == frequency && !it.output }
fun findOutput(frequency: Long?) =
infos.filtered.find { it.frequency == frequency && it.output }
fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) {
var clickRenameButton = false
for ((index,widget) in entries.withIndex()) {
for ((index, widget) in entries.withIndex()) {
val info = widget.infoSupplier()
if (info?.bindButton?.mousePressed(gui.mc, mouseX, mouseY) == true) {
onBindButtonClicked(widget.infoSupplier()!!)
} else if (info?.unbindButton?.mousePressed(gui.mc, mouseX, mouseY) == true) {
onUnbindButtonClicked(widget.infoSupplier()!!)
} else if (mouseX > widget.x.toDouble() + 50 && mouseX < widget.x.toDouble() + 50 + 160 &&
mouseY > widget.y.toDouble() + 1 && mouseY < widget.y + 1 + 13 &&
widget.infoSupplier() != null) {
@@ -134,10 +153,9 @@ class WidgetP2PColumn(private val gui: GuiAdvancedMemoryCard,
onRenameButtonClicked(widget.infoSupplier()!!, index)
clickRenameButton = true
} else if (mouseX > widget.x && mouseX < widget.x + P2PEntryConstants.WIDTH &&
mouseY > widget.y && mouseY < widget.y + P2PEntryConstants.HEIGHT &&
info != null && selectedInfo.get() != info
) {
onSelectButtonClicked(info)
mouseY > widget.y && mouseY < widget.y + P2PEntryConstants.HEIGHT &&
info != null) {
onSelectButtonClicked(widget, info, mouseButton)
}
}
renameBar.mouseClicked(mouseX,mouseY,mouseButton)
@@ -178,9 +196,9 @@ class WidgetP2PColumn(private val gui: GuiAdvancedMemoryCard,
return false
}
fun render(gui: GuiAdvancedMemoryCard, mouseX: Int, mouseY: Int, partialTicks: Float) {
fun render(mouseX: Int, mouseY: Int, partialTicks: Float) {
for (widget in entries) {
widget.render(gui, mouseX, mouseY, partialTicks)
widget.render(mouseX, mouseY, partialTicks)
}
renameBar.drawTextBox()
}
@@ -1,12 +1,15 @@
package com.projecturanus.betterp2p.client.gui.widget
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.client.gui.*
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import com.projecturanus.betterp2p.network.C2STypeChange
import com.projecturanus.betterp2p.network.ModNetwork
import com.projecturanus.betterp2p.util.p2p.ClientTunnelInfo
import com.projecturanus.betterp2p.util.p2p.TunnelInfo
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.renderer.OpenGlHelper
import net.minecraft.client.renderer.Tessellator
import net.minecraft.client.resources.I18n
import net.minecraft.util.IIcon
import org.lwjgl.opengl.GL11
import kotlin.reflect.KProperty0
@@ -20,14 +23,49 @@ object P2PEntryConstants {
const val LEFT_ALIGN = 24
}
class WidgetP2PDevice(private val selectedInfoProperty: KProperty0<InfoWrapper?>, val modeSupplier: () -> BetterMemoryCardModes, val infoSupplier: () -> InfoWrapper?, var x: Int, var y: Int): Widget() {
class WidgetP2PDevice(private val selectedInfoProperty: KProperty0<InfoWrapper?>,
val modeSupplier: () -> BetterMemoryCardModes,
val infoSupplier: () -> InfoWrapper?,
val gui: GuiAdvancedMemoryCard,
var x: Int, var y: Int): Widget(), ITypeReceiver {
var renderNameTextField = true
private val selectedInfo: InfoWrapper?
get() = selectedInfoProperty.get()
fun render(gui: GuiAdvancedMemoryCard, mouseX: Int, mouseY: Int, partialTicks: Float) {
/**
* Update the button visibility
*/
fun updateButtonVisibility() {
val info = infoSupplier() ?: return
val mode = modeSupplier()
if (selectedInfo == null) {
// No selected, so we don't show buttons
info.bindButton.enabled = false
info.unbindButton.enabled = false
} else if (mode == BetterMemoryCardModes.UNBIND) {
// Only unbinds allowed in unbind mode
info.bindButton.enabled = false
info.unbindButton.enabled = info.frequency != 0L
} else if (mode == BetterMemoryCardModes.COPY &&
((!info.output && info.frequency != 0L) || selectedInfo!!.output)) {
// Copy mode
// If this info is (input && set freq) || selected info is an output
// Disable all buttons
info.bindButton.enabled = false
info.unbindButton.enabled = false
} else {
// Other modes:
// Bind allowed only if currently not selected && selected is unbound; OR not bound to selected
info.bindButton.enabled = info.code != selectedInfo!!.code &&
(selectedInfo!!.frequency == 0L ||
info.frequency != selectedInfo!!.frequency)
info.unbindButton.enabled = false
}
}
fun render(mouseX: Int, mouseY: Int, partialTicks: Float) {
val info = infoSupplier()
if (info != null) {
// Draw the background first
@@ -45,7 +83,7 @@ class WidgetP2PDevice(private val selectedInfoProperty: KProperty0<InfoWrapper?>
}
GL11.glColor3f(255f, 255f, 255f)
// Draw our icons...
drawIcon(gui, info.icon!!, info.overlay!!, x + 3, y + 3)
drawBlockIcon(gui.mc, info.icon, info.overlay, x + 3, y + 3)
gui.bindTexture(gui.BACKGROUND)
if (info.output) {
drawTexturedQuad(Tessellator.instance, x.toDouble(), y + 4.0, x + 16.0, y + 20.0,
@@ -74,16 +112,7 @@ class WidgetP2PDevice(private val selectedInfoProperty: KProperty0<InfoWrapper?>
if (info.channels != null) {
fontRenderer.drawString(info.channels, leftAlign, y + 33, 0)
}
if (selectedInfo == null) {
info.bindButton.enabled = false
} else {
info.bindButton.enabled = info.code != selectedInfo?.code
}
val mode = modeSupplier()
if (mode == BetterMemoryCardModes.COPY && !info.output && info.frequency != 0.toLong()) {
info.bindButton.enabled = false
}
updateButtonVisibility()
drawButtons(gui, info, mouseX, mouseY, partialTicks)
}
}
@@ -93,30 +122,31 @@ class WidgetP2PDevice(private val selectedInfoProperty: KProperty0<InfoWrapper?>
info.renameButton.width = 120
info.renameButton.yPosition = y + 1
info.renameButton.height = 12
if (!info.bindButton.enabled) {
info.bindButton.enabled = false
} else if (info.bindButton.enabled) {
if (info.bindButton.enabled) {
info.bindButton.enabled = true
info.bindButton.xPosition = x + 190
info.bindButton.width = 56
info.bindButton.yPosition = y + 14
info.bindButton.drawButton(gui.mc, mouseX, mouseY)
} else if (!info.bindButton.enabled) {
// TODO Unbind
info.bindButton.enabled = false
} else if (info.unbindButton.enabled) {
info.unbindButton.enabled = true
info.unbindButton.xPosition = x + 190
info.unbindButton.width = 56
info.unbindButton.yPosition = y + 14
info.unbindButton.drawButton(gui.mc, mouseX, mouseY)
}
}
private fun drawIcon(gui: GuiAdvancedMemoryCard, icon: IIcon, overlay: IIcon, x: Int, y: Int) {
val tessellator = Tessellator.instance
gui.mc.renderEngine.bindTexture(gui.mc.renderEngine.getResourceLocation(0))
GL11.glPushAttrib(GL11.GL_BLEND or GL11.GL_TEXTURE_2D or GL11.GL_COLOR)
GL11.glEnable(GL11.GL_BLEND)
GL11.glEnable(GL11.GL_TEXTURE_2D)
GL11.glColor3f(255f, 255f, 255f)
OpenGlHelper.glBlendFunc(770, 771, 1, 0)
drawTexturedQuad(tessellator, x.toDouble() + 1, y.toDouble() + 1, x + 15.0, y + 15.0, icon.minU.toDouble(), icon.minV.toDouble(), icon.maxU.toDouble(), icon.maxV.toDouble())
drawTexturedQuad(tessellator, x.toDouble(), y.toDouble(), x + 16.0, y + 16.0, overlay.minU.toDouble(), overlay.minV.toDouble(), overlay.maxU.toDouble(), overlay.maxV.toDouble())
GL11.glPopAttrib()
override fun accept(type: ClientTunnelInfo?) {
ModNetwork.channel.sendToServer(C2STypeChange(type?.index ?: TUNNEL_ANY, infoSupplier()!!.code))
gui.closeTypeSelector()
}
override fun x(): Int {
return this.x + 40
}
override fun y(): Int {
return this.y
}
}
@@ -0,0 +1,96 @@
package com.projecturanus.betterp2p.client.gui.widget
import com.projecturanus.betterp2p.client.gui.GuiAdvancedMemoryCard
import com.projecturanus.betterp2p.client.gui.drawBlockIcon
import com.projecturanus.betterp2p.util.p2p.ClientTunnelInfo
import com.projecturanus.betterp2p.util.p2p.TunnelInfo
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.resources.I18n
import net.minecraft.init.Blocks
import kotlin.math.min
const val ICONS_PER_ROW = 5
/**
* Select a type.
*/
class WidgetTypeSelector(var x: Int, var y: Int,
val p2pTypes: List<ClientTunnelInfo>): Widget() {
var visible = false
val width: Int
val height: Int
var hoveredIdx: Int = 0
var useAny = false
/**
* Feeds the input into this parent.
*/
lateinit var parent: ITypeReceiver
private val translated: List<List<String>>
init {
val typeCount = p2pTypes.size //we'll use 5 icons per row?
width = min(ICONS_PER_ROW, typeCount) * 18 + 8
height = (typeCount + ICONS_PER_ROW - 1) * 18 / ICONS_PER_ROW + 8
val list = p2pTypes.map { listOf(it.dispName) }.toMutableList()
list.add(listOf(I18n.format("gui.advanced_memory_card.types.any")))
translated = list
}
fun render(gui: GuiAdvancedMemoryCard, mouseX: Int, mouseY: Int, partialTicks: Float) {
// Background
GuiScreen.drawRect(x, y, x + width, y + height, 0xAA000000.toInt())
hoveredIdx = -1
for ((i, type) in p2pTypes.withIndex()) {
val iconPosX = x + 4 + (i % ICONS_PER_ROW) * 18
val iconPosY = y + 4 + (i / ICONS_PER_ROW) * 18
val iconHover = mouseX > iconPosX && mouseX < iconPosX + 18 && mouseY > iconPosY && mouseY < iconPosY + 18
if (iconHover) {
hoveredIdx = i
GuiScreen.drawRect(iconPosX, iconPosY, iconPosX + 18, iconPosY + 18, 0xFF00FF00.toInt())
}
drawBlockIcon(gui.mc, type.icon(), type.stack.iconIndex,
x = iconPosX + 1,
y = iconPosY + 1)
}
if (useAny) {
val iconPosX = x + 4 + (p2pTypes.size % ICONS_PER_ROW) * 18
val iconPosY = y + 4 + (p2pTypes.size / ICONS_PER_ROW) * 18
val iconHover = mouseX > iconPosX && mouseX < iconPosX + 18 && mouseY > iconPosY && mouseY < iconPosY + 18
if (iconHover) {
hoveredIdx = p2pTypes.size
GuiScreen.drawRect(iconPosX, iconPosY, iconPosX + 18, iconPosY + 18, 0xFF00FF00.toInt())
}
drawBlockIcon(gui.mc, Blocks.coal_block.getIcon(0, 0), p2pTypes[0].stack.iconIndex,
x = iconPosX + 1,
y = iconPosY + 1)
gui.mc.fontRenderer.drawString("?", iconPosX + 6, iconPosY + 6, 0xFFFF0000.toInt())
}
if (hoveredIdx != -1) {
gui.drawHoveringText(translated[hoveredIdx], mouseX, mouseY, gui.mc.fontRenderer)
}
}
fun setPos(x: Int, y: Int) {
this.x = x
this.y = y
}
fun mousePressed(mouseX: Int, mouseY: Int, mouseButton: Int) {
if (mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height) {
// now check which one we clicked on
if (hoveredIdx == -1) return
parent.accept(p2pTypes.getOrNull(hoveredIdx))
} else {
this.visible = false
}
}
}
interface ITypeReceiver {
fun accept(type: ClientTunnelInfo?)
fun x(): Int
fun y(): Int
}
@@ -1,22 +1,47 @@
package com.projecturanus.betterp2p.item
enum class BetterMemoryCardModes {
const val MAX_TOOLTIP_LENGTH = 40
enum class BetterMemoryCardModes(val unlocalizedName: String, vararg val unlocalizedDesc: String) {
/**
* Select an input P2P and bind its output
*/
OUTPUT,
OUTPUT("gui.advanced_memory_card.mode.output",
"gui.advanced_memory_card.mode.output.desc.1",
"gui.advanced_memory_card.mode.output.desc.2",
"gui.advanced_memory_card.mode.output.desc.3"
),
/**
* Select an output P2P and bind its input
*/
INPUT,
INPUT("gui.advanced_memory_card.mode.input",
"gui.advanced_memory_card.mode.input.desc.1",
"gui.advanced_memory_card.mode.input.desc.2",
"gui.advanced_memory_card.mode.input.desc.3"
),
/**
* Copy same output frequency
*/
COPY;
COPY("gui.advanced_memory_card.mode.copy",
"gui.advanced_memory_card.mode.copy.desc.1",
"gui.advanced_memory_card.mode.copy.desc.2",
"gui.advanced_memory_card.mode.copy.desc.3",
"gui.advanced_memory_card.mode.copy.desc.4",
),
fun next(): BetterMemoryCardModes {
return values()[ordinal.plus(1) % values().size]
/**
* Unbind/reset frequencies
*/
UNBIND("gui.advanced_memory_card.mode.unbind",
"gui.advanced_memory_card.mode.unbind.desc.1",
"gui.advanced_memory_card.mode.unbind.desc.2");
fun next(reverse: Boolean = false): BetterMemoryCardModes {
if (reverse) {
return values()[(ordinal - 1).mod(values().size)]
}
return values()[(ordinal + 1).mod(values().size)]
}
}
@@ -5,17 +5,17 @@ import appeng.core.CreativeTab
import appeng.parts.p2p.PartP2PTunnel
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.client.ClientCache
import com.projecturanus.betterp2p.client.gui.widget.GuiScale
import com.projecturanus.betterp2p.network.ModNetwork
import com.projecturanus.betterp2p.network.NONE
import com.projecturanus.betterp2p.network.NONE_SELECTED
import com.projecturanus.betterp2p.network.S2CListP2P
import com.projecturanus.betterp2p.network.hashP2P
import com.projecturanus.betterp2p.util.getPart
import com.projecturanus.betterp2p.util.p2p.P2PCache
import com.projecturanus.betterp2p.util.p2p.P2PStatus
import com.projecturanus.betterp2p.util.p2p.areP2PEqual
import com.projecturanus.betterp2p.util.p2p.toInfo
import com.projecturanus.betterp2p.util.p2p.getTypeIndex
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.renderer.texture.IIconRegister
@@ -44,10 +44,7 @@ object ItemAdvancedMemoryCard : Item() {
private fun sendStatus(status: P2PStatus, info: MemoryInfo, player: EntityPlayerMP) {
P2PCache.statusMap[player.uniqueID] = status
ModNetwork.channel.sendTo(
S2CListP2P(status.listP2P.values.map { p2p -> p2p.toInfo() }, info),
player
)
ModNetwork.channel.sendTo(S2CListP2P(status.refresh(info.type), info), player)
}
@SideOnly(Side.CLIENT)
@@ -75,22 +72,27 @@ object ItemAdvancedMemoryCard : Item() {
val part = getPart(w, x, y, z, hx, hy, hz)
val stack = player.heldItem
val info = getInfo(stack)
val type: Int
val status: P2PStatus
if (part is PartP2PTunnel<*>) {
val status = P2PStatus(player, part.gridNode.grid, part)
val p2p = status.listP2P.values.firstOrNull { areP2PEqual(it, status.targetP2P) }
if (p2p != null) {
info.selectedEntry = hashP2P(p2p)
writeInfo(stack, info)
sendStatus(status, info, player as EntityPlayerMP)
return true
type = part.getTypeIndex()
status = P2PStatus(part.gridNode.grid, player, type)
info.selectedEntry = hashP2P(part)
} else {
type = TUNNEL_ANY
status = if (part != null) {
// If we have a PartP2PTunnelME, it looks at the P2P grid node,
// so we should use the part instead.
P2PStatus(part.gridNode.grid, player, type)
} else {
// Fall back to the tile entity.
P2PStatus(te.getGridNode(ForgeDirection.getOrientation(side)).grid, player, type)
}
info.selectedEntry = NONE_SELECTED
}
// Fallback to sending the whole network
val node = te.getGridNode(ForgeDirection.getOrientation(side))!!
info.selectedEntry = NONE
info.type = type
writeInfo(stack, info)
sendStatus(P2PStatus(player, node.grid), info, player as EntityPlayerMP)
sendStatus(status, info, player as EntityPlayerMP)
return true
}
}
@@ -112,7 +114,7 @@ object ItemAdvancedMemoryCard : Item() {
if (stack.tagCompound == null) stack.tagCompound = NBTTagCompound()
val compound = stack.tagCompound!!
if (!compound.hasKey("gui")) compound.setByte("gui", GuiScale.DYNAMIC.ordinal.toByte())
if (!compound.hasKey("selectedIndex", Constants.NBT.TAG_LONG)) compound.setLong("selectedIndex", NONE)
if (!compound.hasKey("selectedIndex", Constants.NBT.TAG_LONG)) compound.setLong("selectedIndex", NONE_SELECTED)
return MemoryInfo(compound.getLong("selectedIndex"), compound.getLong("frequency"), BetterMemoryCardModes.values()[compound.getInteger("mode")], GuiScale.values()[compound.getByte("gui").toInt()])
}
@@ -3,7 +3,7 @@ package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
class C2SLinkP2P(var input: Long = NONE, var output: Long = NONE): IMessage {
class C2SLinkP2P(var input: Long = NONE_SELECTED, var output: Long = NONE_SELECTED): IMessage {
override fun fromBytes(buf: ByteBuf) {
input = buf.readLong()
output = buf.readLong()
@@ -0,0 +1,45 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.util.listAllGridP2P
import com.projecturanus.betterp2p.util.listTargetGridP2P
import com.projecturanus.betterp2p.util.p2p.P2PCache
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
import cpw.mods.fml.common.network.simpleimpl.MessageContext
import io.netty.buffer.ByteBuf
/**
* Send a request to the server to refresh the p2p list with the
* given type.
*/
class C2SRefreshP2PList(var type: Int = TUNNEL_ANY): IMessage {
override fun fromBytes(buf: ByteBuf) {
type = buf.readByte().toInt()
}
override fun toBytes(buf: ByteBuf) {
buf.writeByte(type)
}
}
/**
* Client -> C2SRefreshP2P -> Server
* Handler on server side
*/
class ServerRefreshP2PListHandler : IMessageHandler<C2SRefreshP2PList, IMessage?> {
override fun onMessage(message: C2SRefreshP2PList, ctx: MessageContext): S2CListP2P? {
if (!P2PCache.statusMap.containsKey(ctx.serverHandler.playerEntity.uniqueID)) return null
val status = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID]!!
status.lastP2PType = message.type
val tunnelType = BetterP2P.proxy.getP2PFromIndex(message.type)
if (tunnelType != null) {
listTargetGridP2P(status.grid, status.player, tunnelType.clazz)
} else {
listAllGridP2P(status.grid, status.player)
}
ModNetwork.queueP2PListUpdate(status, ctx.serverHandler.playerEntity)
return null
}
}
@@ -0,0 +1,36 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.util.p2p.P2PCache
import com.projecturanus.betterp2p.util.p2p.changeAllP2Ps
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
import cpw.mods.fml.common.network.simpleimpl.MessageContext
import io.netty.buffer.ByteBuf
class C2STypeChange(var newType: Int = TUNNEL_ANY, var p2p: Long = NONE_SELECTED): IMessage {
override fun fromBytes(buf: ByteBuf) {
newType = buf.readByte().toInt()
p2p = buf.readLong()
}
override fun toBytes(buf: ByteBuf) {
buf.writeByte(newType)
buf.writeLong(p2p)
}
}
class ServerTypeChangeHandler : IMessageHandler<C2STypeChange, S2CListP2P?> {
override fun onMessage(message: C2STypeChange, ctx: MessageContext): S2CListP2P? {
if (message.newType == TUNNEL_ANY) return null
val status = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID] ?: return null
val tunnel = status.listP2P[message.p2p] ?: return null
val type = BetterP2P.proxy.getP2PFromIndex(message.newType) ?: return null
val newTunnel = changeAllP2Ps(tunnel, type, ctx.serverHandler.playerEntity)
if (newTunnel) {
ModNetwork.queueP2PListUpdate(status, ctx.serverHandler.playerEntity)
}
return null
}
}
@@ -0,0 +1,48 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.util.listAllGridP2P
import com.projecturanus.betterp2p.util.listTargetGridP2P
import com.projecturanus.betterp2p.util.p2p.P2PCache
import com.projecturanus.betterp2p.util.p2p.unlinkP2P
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
import cpw.mods.fml.common.network.simpleimpl.MessageContext
import io.netty.buffer.ByteBuf
/**
* Unlink input from outputs message (set freq to 0)
*/
class C2SUnlinkP2P(var p2pId: Long = NONE_SELECTED, var type: Int = TUNNEL_ANY): IMessage {
override fun fromBytes(buf: ByteBuf) {
p2pId = buf.readLong()
type = buf.readByte().toInt()
}
override fun toBytes(buf: ByteBuf) {
buf.writeLong(p2pId)
buf.writeByte(type)
}
}
/**
* Client -> C2SUnlinkP2P -> Server
* Handler on server side
*/
class ServerUnlinkP2PHandler : IMessageHandler<C2SUnlinkP2P, S2CListP2P?> {
override fun onMessage(message: C2SUnlinkP2P, ctx: MessageContext): S2CListP2P? {
val status = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID] ?: return null
unlinkP2P(ctx.serverHandler.playerEntity, message.p2pId, status)
status.lastP2PType = message.type
val tunnelType = BetterP2P.proxy.getP2PFromIndex(message.type)
if (tunnelType != null) {
listTargetGridP2P(status.grid, status.player, tunnelType.clazz)
} else {
listAllGridP2P(status.grid, status.player)
}
ModNetwork.queueP2PListUpdate(status, ctx.serverHandler.playerEntity)
return null
}
}
@@ -11,14 +11,29 @@ fun writeMemoryInfo(buf: ByteBuf, info: MemoryInfo) {
buf.writeLong(info.frequency)
buf.writeInt(info.mode.ordinal)
buf.writeByte(info.gui.ordinal)
buf.writeByte(info.type)
}
fun readMemoryInfo(buf: ByteBuf): MemoryInfo {
return MemoryInfo(buf.readLong(), buf.readLong(),
BetterMemoryCardModes.values()[buf.readInt()],
GuiScale.values()[buf.readByte().toInt()])
val selectedEntry = buf.readLong()
val frequency = buf.readLong()
val mode = try {
BetterMemoryCardModes.values()[buf.readInt()]
} catch (e: Exception) {
BetterMemoryCardModes.OUTPUT
}
val gui = try {
GuiScale.values()[buf.readByte().toInt()]
} catch (e: ArrayIndexOutOfBoundsException) {
GuiScale.DYNAMIC
}
val type = buf.readByte().toInt()
return MemoryInfo(selectedEntry, frequency, mode, gui, type)
}
/**
* Request from client -> server
*/
class C2SUpdateInfo(var info: MemoryInfo = MemoryInfo()) : IMessage {
override fun fromBytes(buf: ByteBuf) {
info = readMemoryInfo(buf)
@@ -47,4 +47,4 @@ private fun xorCollapse12(input: Int): Int {
/**
* Using `0x80000000` to represent none is selected (aka MSB set)
*/
const val NONE: Long = Long.MIN_VALUE
const val NONE_SELECTED: Long = Long.MIN_VALUE
@@ -1,12 +1,22 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.util.p2p.P2PStatus
import cpw.mods.fml.common.network.NetworkRegistry
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
import cpw.mods.fml.relauncher.Side
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import java.util.UUID
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadFactory
import java.util.concurrent.TimeUnit
object ModNetwork {
val channel: SimpleNetworkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel(MODID)
private var netCache: MutableMap<UUID, NetworkState> = mutableMapOf()
private lateinit var networkWorker: ScheduledThreadPoolExecutor
fun registerNetwork() {
channel.registerMessage(ClientOpenGuiHandler::class.java, S2CListP2P::class.java, 0, Side.CLIENT)
@@ -14,7 +24,57 @@ object ModNetwork {
channel.registerMessage(ServerLinkP2PHandler::class.java, C2SLinkP2P::class.java, 2, Side.SERVER)
channel.registerMessage(ServerCloseGuiHandler::class.java, C2SCloseGui::class.java, 3, Side.SERVER)
channel.registerMessage(ServerUpdateInfoHandler::class.java, C2SUpdateInfo::class.java, 4, Side.SERVER)
channel.registerMessage(ServerTransportHandler::class.java,C2STransportPlayer::class.java,5,Side.SERVER)
channel.registerMessage(ServerRenameP2PTunnel::class.java,C2SP2PTunnelInfo::class.java,6,Side.SERVER)
channel.registerMessage(ServerTransportHandler::class.java, C2STransportPlayer::class.java, 5, Side.SERVER)
channel.registerMessage(ServerRenameP2PTunnel::class.java, C2SP2PTunnelInfo::class.java, 6, Side.SERVER)
channel.registerMessage(ServerRefreshP2PListHandler::class.java, C2SRefreshP2PList::class.java, 7, Side.SERVER)
channel.registerMessage(ServerUnlinkP2PHandler::class.java, C2SUnlinkP2P::class.java, 8, Side.SERVER)
channel.registerMessage(ServerTypeChangeHandler::class.java, C2STypeChange::class.java, 9, Side.SERVER)
networkWorker = ScheduledThreadPoolExecutor(1, ThreadFactory {
val th = Thread(it)
th.name = "BetterP2P-NetworkWorker"
th.isDaemon = true
th.priority = Thread.MIN_PRIORITY
th
})
}
/**
* Utility function that asks for a p2p update. Multiple requests are bundled into 1.
*/
fun queueP2PListUpdate(status: P2PStatus, player: EntityPlayer, info: MemoryInfo? = null) {
synchronized(netCache) {
val state = netCache.getOrPut(player.uniqueID) { NetworkState() }
if (state.updateReady + NETWORK_CD < System.currentTimeMillis()) {
channel.sendTo(S2CListP2P(status.refresh(status.lastP2PType)), player as EntityPlayerMP)
state.updateReady = System.currentTimeMillis() + NETWORK_CD
} else if (!state.updatePending) {
state.updatePending = true
networkWorker.schedule({
if (info == null) {
channel.sendTo(S2CListP2P(status.refresh(status.lastP2PType)), player as EntityPlayerMP)
} else {
channel.sendTo(S2CListP2P(status.refresh(status.lastP2PType), info), player as EntityPlayerMP)
}
synchronized(netCache) {
state.updatePending = false
}
}, state.updateReady - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
}
}
}
fun stop() {
networkWorker.shutdown()
}
}
internal data class NetworkState(
internal var updatePending: Boolean = false,
internal var updateReady: Long = System.currentTimeMillis()
)
/**
* Network cooldown time in milliseconds
*/
const val NETWORK_CD = 250L
@@ -1,7 +1,6 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.client.gui.InfoWrapper
import net.minecraft.item.ItemStack
import net.minecraftforge.common.util.ForgeDirection
class P2PInfo(val frequency: Long,
@@ -13,12 +12,15 @@ class P2PInfo(val frequency: Long,
val name: String,
val output: Boolean,
val hasChannel: Boolean,
val channels: Int, //# of channels if ME P2P, or -1 else
val stack: ItemStack) {
// # of channels if ME P2P, or -1 else
val channels: Int,
// type of p2p, corresponds to registry in proxy
val type: Int) {
override fun hashCode(): Int {
return hashP2P(posX, posY, posZ, facing.ordinal, world).hashCode()
}
override fun equals(other: Any?): Boolean {
return if (other is InfoWrapper) {
this.posX == other.posX &&
@@ -29,5 +31,4 @@ class P2PInfo(val frequency: Long,
false
}
}
}
@@ -2,8 +2,6 @@ package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraftforge.common.util.ForgeDirection
fun readInfo(buf: ByteBuf): P2PInfo {
@@ -20,13 +18,9 @@ fun readInfo(buf: ByteBuf): P2PInfo {
}
val output = buf.readBoolean()
val hasChannel = buf.readBoolean()
val channels = buf.readInt()
val compound = NBTTagCompound()
compound.setShort("id", buf.readShort())
compound.setShort("Damage", buf.readShort())
compound.setShort("Count", 1)
val stack = ItemStack.loadItemStackFromNBT(compound);
return P2PInfo(freq, posX, posY, posZ,world, facing, name, output, hasChannel, channels, stack)
val channels = buf.readByte().toInt()
val type = buf.readByte().toInt()
return P2PInfo(freq, posX, posY, posZ,world, facing, name, output, hasChannel, channels, type)
}
fun writeInfo(buf: ByteBuf, info: P2PInfo) {
@@ -42,11 +36,8 @@ fun writeInfo(buf: ByteBuf, info: P2PInfo) {
}
buf.writeBoolean(info.output)
buf.writeBoolean(info.hasChannel)
buf.writeInt(info.channels)
val compound = NBTTagCompound()
info.stack.writeToNBT(compound)
buf.writeShort(compound.getShort("id").toInt())
buf.writeShort(compound.getShort("Damage").toInt())
buf.writeByte(info.channels)
buf.writeByte(info.type)
}
class S2CRefreshInfo(var infos: List<P2PInfo> = emptyList()) : IMessage {
@@ -1,7 +1,6 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.util.p2p.P2PCache
import com.projecturanus.betterp2p.util.p2p.toInfo
import com.projecturanus.betterp2p.util.p2p.linkP2P
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
@@ -9,14 +8,13 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext
class ServerLinkP2PHandler : IMessageHandler<C2SLinkP2P, IMessage?> {
override fun onMessage(message: C2SLinkP2P, ctx: MessageContext): IMessage? {
if (!P2PCache.statusMap.containsKey(ctx.serverHandler.playerEntity.uniqueID)) return null
val status = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID]!!
val status = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID] ?: return null
val result = linkP2P(ctx.serverHandler.playerEntity, message.input, message.output, status)
if (result != null) {
status.listP2P[message.input] = result.first
status.listP2P[message.output] = result.second
ModNetwork.channel.sendTo(S2CRefreshInfo(status.listP2P.values.map { it.toInfo() }), ctx.serverHandler.playerEntity)
ModNetwork.queueP2PListUpdate(status, ctx.serverHandler.playerEntity)
}
return null
}
@@ -3,8 +3,7 @@ import appeng.api.networking.IGridHost
import appeng.api.parts.IPartHost
import appeng.parts.p2p.PartP2PTunnel
import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard
import com.projecturanus.betterp2p.util.p2p.P2PStatus
import com.projecturanus.betterp2p.util.p2p.toInfo
import com.projecturanus.betterp2p.util.p2p.P2PCache
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
import cpw.mods.fml.common.network.simpleimpl.MessageContext
@@ -13,18 +12,18 @@ import net.minecraft.world.World
import net.minecraftforge.common.DimensionManager
import net.minecraftforge.common.util.ForgeDirection
/**
* Handler for renaming p2p tunnels.
*/
class ServerRenameP2PTunnel : IMessageHandler<C2SP2PTunnelInfo, IMessage?> {
override fun onMessage(message: C2SP2PTunnelInfo, ctx: MessageContext): IMessage? {
val world: World = DimensionManager.getWorld(message.info.world)
val te: TileEntity = world.getTileEntity(message.info.posX,message.info.posY,message.info.posZ)
val player = ctx.serverHandler.playerEntity
val te: TileEntity = world.getTileEntity(message.info.posX, message.info.posY, message.info.posZ)
val cache = P2PCache.statusMap[ctx.serverHandler.playerEntity.uniqueID] ?: return null
if (te is IGridHost && te.getGridNode(ForgeDirection.getOrientation(message.info.side)) != null) {
val p = (te as IPartHost).getPart(ForgeDirection.getOrientation(message.info.side)) as PartP2PTunnel<*>
val p = (te as IPartHost).getPart(ForgeDirection.getOrientation(message.info.side)) as PartP2PTunnel<*>
p.customName = message.info.name
ModNetwork.channel.sendTo(S2CListP2P(
P2PStatus(player, p.gridNode.grid,p).listP2P.values.map { it.toInfo() },
ItemAdvancedMemoryCard.getInfo(player.heldItem)
),player)
ModNetwork.queueP2PListUpdate(cache, ctx.serverHandler.playerEntity, ItemAdvancedMemoryCard.getInfo(cache.player.heldItem))
}
return null
}
@@ -51,6 +51,15 @@ fun listTargetGridP2P(grid: IGrid?, player: EntityPlayer, clazz: Class<out PartP
return grid?.getMachines(clazz)?.map { it.machine as PartP2PTunnel<*> }?.toList() ?: emptyList()
}
fun listAllGridP2P(grid: IGrid?, player: EntityPlayer): List<PartP2PTunnel<*>> {
if (grid is ISecurityGrid && !grid.hasPermission(player, SecurityPermissions.BUILD))
return emptyList()
val classes = grid?.machinesClasses?.filter { c -> c.superclass == PartP2PTunnel::class.java } ?: emptyList()
val ret: MutableList<PartP2PTunnel<*>> = mutableListOf()
classes.forEach{ c -> ret.addAll(grid?.getMachines(c)?.map { it.machine as PartP2PTunnel<*> } ?: emptyList()) }
return ret
}
val AEBasePart.facingPosX: Int?
get() =
host?.location?.x?.and(side?.offsetX ?: EnumFacing.UP.frontOffsetX)
@@ -2,25 +2,53 @@ package com.projecturanus.betterp2p.util.p2p
import appeng.api.networking.IGrid
import appeng.parts.p2p.PartP2PTunnel
import appeng.parts.p2p.PartP2PTunnelME
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.network.P2PInfo
import com.projecturanus.betterp2p.network.hashP2P
import com.projecturanus.betterp2p.util.listTargetGridP2P
import com.projecturanus.betterp2p.util.listAllGridP2P
import net.minecraft.entity.player.EntityPlayer
class P2PStatus(player: EntityPlayer, grid: IGrid, val targetP2P: PartP2PTunnel<*>? = null) {
/**
* When the player uses the adv memory card, this is cached on the server side
* to provide access to the Grid when the player performs actions in the GUI.
*/
class P2PStatus(val grid: IGrid, val player: EntityPlayer, type: Int) {
/**
* The P2P list. This is a list of all P2Ps, and only the requested
* ones are sent.
*/
val listP2P: MutableMap<Long, PartP2PTunnel<*>> = mutableMapOf()
init {
listTargetGridP2P(grid, player, targetP2P?.javaClass ?: PartP2PTunnelME::class.java)
.forEach { listP2P[hashP2P(it)] = it }
}
}
/**
* Server copy of the p2p currently selected in client
*/
var lastP2PType: Int = type
fun areP2PEqual(a: PartP2PTunnel<*>?, b: PartP2PTunnel<*>?): Boolean {
if (a == b) {
return true;
} else if(a != null && b != null) {
return hashP2P(a) == hashP2P(b)
/**
* Refreshes the p2p list
*/
private fun rebuildList() {
listP2P.clear()
listAllGridP2P(grid, player).forEach { listP2P[hashP2P(it)] = it }
}
/**
* Refreshes and gets the p2p list of the targeted type
* @param type if TUNNEL_ANY or invalid, returns the full list; else
* filters the list to the targeted type
*/
fun refresh(type: Int): List<P2PInfo> {
rebuildList()
return if (type == TUNNEL_ANY) {
listP2P.values.map { it.toInfo() }
} else {
listP2P.values.mapNotNull {
if ((BetterP2P.proxy.getP2PFromClass(it.javaClass)?.index ?: TUNNEL_ANY) == type) {
it.toInfo()
} else null
}
}
}
return false;
}
@@ -5,14 +5,16 @@ import appeng.api.networking.IGrid
import appeng.api.networking.security.ISecurityGrid
import appeng.api.parts.IPart
import appeng.api.parts.PartItemStack
import appeng.helpers.DualityInterface
import appeng.me.GridAccessException
import appeng.me.GridNode
import appeng.me.cache.P2PCache
import appeng.parts.automation.UpgradeInventory
import appeng.parts.p2p.PartP2PInterface
import appeng.parts.p2p.PartP2PTunnel
import appeng.tile.inventory.AppEngInternalInventory
import appeng.util.Platform
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.capability.TUNNEL_ANY
import com.projecturanus.betterp2p.network.P2PInfo
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
@@ -21,8 +23,8 @@ import net.minecraftforge.common.util.ForgeDirection
fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P2PStatus) : Pair<PartP2PTunnel<*>, PartP2PTunnel<*>>? {
// If these calls mess up we have bigger problems...
val input = status.listP2P[inputIndex]!!
val output = status.listP2P[outputIndex]!!
val input = status.listP2P[inputIndex] ?: return null
var output = status.listP2P[outputIndex] ?: return null
val grid: IGrid? = input.gridNode?.grid
if (grid is ISecurityGrid) {
@@ -33,8 +35,8 @@ fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P
// TODO Change to exception
if (input.javaClass != output.javaClass) {
// Cannot pair two different type of P2P
return null
//change output to input
output = changeP2P(output, BetterP2P.proxy.getP2PFromClass(input.javaClass)!!, player) ?: return null
}
if (input == output) {
// Network loop
@@ -97,6 +99,88 @@ fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P
return inputResult to outputResult
}
fun unlinkP2P(player: EntityPlayer, p2pIndex: Long, status: P2PStatus): PartP2PTunnel<*>? {
if (status.grid is ISecurityGrid) {
if (!status.grid.hasPermission(player, SecurityPermissions.BUILD) ||
!status.grid.hasPermission(player, SecurityPermissions.SECURITY)) {
return null
}
}
val tunnel = status.listP2P[p2pIndex] ?: return null
val oldFreq = tunnel.frequency
if (oldFreq == 0L) {
return tunnel
}
updateP2P(tunnel, 0L, false, player, tunnel.customName)
return tunnel
}
/**
* Converts one P2P into the type
*/
fun changeP2P(tunnel: PartP2PTunnel<*>, newType: TunnelInfo, player: EntityPlayer): PartP2PTunnel<*>? {
val grid = tunnel.gridNode.grid
if (grid is ISecurityGrid) {
if (!grid.hasPermission(player, SecurityPermissions.BUILD) ||
!grid.hasPermission(player, SecurityPermissions.SECURITY)) {
return null
}
}
if (BetterP2P.proxy.getP2PFromClass(tunnel.javaClass) == newType) {
return null
}
if (tunnel is PartP2PInterface) {
// For output, drop items.
val dropItems = mutableListOf<ItemStack>()
val patternsOut = tunnel.interfaceDuality.patterns as AppEngInternalInventory
dropItems.addAll(patternsOut)
Platform.spawnDrops(player.worldObj, tunnel.location.x, tunnel.location.y, tunnel.location.z, dropItems)
}
val host = tunnel.host
host.removePart(tunnel.side, false)
val dir = host.addPart(newType.stack, tunnel.side, player)
val newPart = host.getPart(dir)
if (newPart is PartP2PTunnel<*>) {
newPart.outputProperty = tunnel.isOutput
try {
val p2p: P2PCache = newPart.proxy.p2P
p2p.updateFreq(newPart, tunnel.frequency)
return newPart
} catch (e: GridAccessException) {
// :P
}
}
return null
}
/**
* Converts all connected P2Ps to a new type
*/
fun changeAllP2Ps(tunnel: PartP2PTunnel<*>, newType: TunnelInfo, player: EntityPlayer): Boolean {
val grid = tunnel.gridNode.grid
if (grid is ISecurityGrid) {
if (!grid.hasPermission(player, SecurityPermissions.BUILD) ||
!grid.hasPermission(player, SecurityPermissions.SECURITY)) {
return false
}
}
try {
if (tunnel.isOutput && tunnel.input != null) {
return changeAllP2Ps(tunnel.input, newType, player)
} else {
val outputs = tunnel.outputs.toMutableList()
changeP2P(tunnel, newType, player)
for (o in outputs) {
changeP2P(o, newType, player)
}
return true
}
} catch (e: GridAccessException) {
// :P
}
return false
}
/**
* Due to Applied Energistics' limit
*/
@@ -146,4 +230,11 @@ val PartP2PTunnel<*>.hasChannel
fun PartP2PTunnel<*>.toInfo()
= P2PInfo(frequency, location.x, location.y, location.z, location.dimension, side,
customName, isOutput, hasChannel, (externalFacingNode as? GridNode)?.usedChannels() ?: -1,
getItemStack(PartItemStack.Wrench))
getTypeIndex())
/**
* Get the type index or use TUNNEL_ANY
*/
fun PartP2PTunnel<*>.getTypeIndex()
= BetterP2P.proxy.getP2PFromClass(this.javaClass)?.index ?: TUNNEL_ANY
@@ -0,0 +1,20 @@
package com.projecturanus.betterp2p.util.p2p
import appeng.parts.p2p.PartP2PTunnel
import net.minecraft.item.ItemStack
import net.minecraft.util.IIcon
/**
* Common tunnel info to be used on server
*/
open class TunnelInfo(val index: Int, val stack: ItemStack, val clazz: Class<out PartP2PTunnel<*>>) {
val dispName: String =
stack.item.getItemStackDisplayName(stack).split(" - ").getOrNull(1) ?: "§c<Unknown P2P Type>"
}
/**
* Client tunnel info contains icon info too. Because textures are not
* loaded until after postInit, we need to use a supplier, unfortunately.
*/
class ClientTunnelInfo(index: Int, stack: ItemStack, clazz: Class<out PartP2PTunnel<*>>,
val icon: () -> IIcon): TunnelInfo(index, stack, clazz)