This commit is contained in:
GlodBlock committed 2022-01-30 14:36:19 +08:00
commit c6fb85c7f4
64 files changed
+4275

No files matched your search

@@ -0,0 +1,43 @@
package com.projecturanus.betterp2p
import appeng.items.tools.ToolMemoryCard
import appeng.items.tools.ToolNetworkTool
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.event.FMLPostInitializationEvent
import cpw.mods.fml.common.event.FMLPreInitializationEvent
import cpw.mods.fml.common.registry.GameRegistry
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.ShapelessRecipes
import net.minecraftforge.common.config.Configuration
import org.apache.logging.log4j.Logger
const val MODID = "betterp2p"
/**
* Better P2P is created by LasmGratel.
* GlodBlock backported this to 1.7.10.
*/
@Mod(modid = MODID, modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", dependencies = "required-after: appliedenergistics2; required-after: forgelin;")
object BetterP2P {
lateinit var logger: Logger
@Mod.EventHandler
fun preInit(event: FMLPreInitializationEvent) {
logger = event.modLog
ModNetwork.registerNetwork()
BetterP2PConfig.loadConfig(Configuration(event.suggestedConfigurationFile))
GameRegistry.registerItem(ItemAdvancedMemoryCard, "advanced_memory_card", MODID)
GameRegistry.addRecipe(ShapelessRecipes(ItemStack(ItemAdvancedMemoryCard), listOf(ItemStack(ToolNetworkTool()), ItemStack(ToolMemoryCard()))))
}
@Mod.EventHandler
fun postInit(event: FMLPostInitializationEvent) {
ServerPlayerDisconnectHandler.register()
RenderHandler.register()
}
}
@@ -0,0 +1,7 @@
package com.projecturanus.betterp2p.capability
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
data class MemoryInfo(var selectedIndex: Int = -1,
var frequency: Long = 0,
var mode: BetterMemoryCardModes = BetterMemoryCardModes.OUTPUT)
@@ -0,0 +1,15 @@
package com.projecturanus.betterp2p.client
import net.minecraft.util.EnumFacing
object ClientCache {
val positions = mutableListOf<Pair<List<Int?>, EnumFacing>>()
var selectedPosition: List<Int?>? = null
var selectedFacing: EnumFacing? = null
fun clear() {
positions.clear()
selectedPosition = null
selectedFacing = null
}
}
@@ -0,0 +1,5 @@
package com.projecturanus.betterp2p.client
interface TextureBound {
fun bindTexture(modid: String, location: String)
}
@@ -0,0 +1,251 @@
package com.projecturanus.betterp2p.client.gui
import com.projecturanus.betterp2p.BetterP2P
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.client.ClientCache
import com.projecturanus.betterp2p.client.TextureBound
import com.projecturanus.betterp2p.client.gui.widget.WidgetP2PDevice
import com.projecturanus.betterp2p.client.gui.widget.WidgetScrollBar
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import com.projecturanus.betterp2p.network.*
import net.minecraft.client.gui.GuiButton
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.resources.I18n
import net.minecraft.util.ResourceLocation
import org.lwjgl.input.Mouse
class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound {
private val outputColor = 0x4566ccff
private val selectedColor = 0x4545DA75
private val errorColor = 0x45DA4527
private val inactiveColor = 0x45FFEA05
private val xSize = 238
private val ySize = 206
private val guiLeft: Int by lazy { (width - this.xSize) / 2 }
private val guiTop: Int by lazy { (height - this.ySize) / 2 }
private val tableX = 9
private val tableY = 19
private val rowWidth = 203
private val rowHeight = 22
private var selectedIndex = -1
private lateinit var scrollBar: WidgetScrollBar
private val infos = msg.infos.map(::InfoWrapper).toMutableList()
private var sortedInfo = infos.toList()
private var selectedInfo: InfoWrapper?
get() = infos.getOrNull(selectedIndex)
set(value) {
selectedIndex = value?.index ?: -1
}
private val widgetDevices: List<WidgetP2PDevice>
private var infoOnScreen: List<InfoWrapper>
private val descriptionLines: MutableList<String> = mutableListOf()
private var mode = msg.memoryInfo.mode
private var modeString = getModeString()
private val modeButton by lazy { GuiButton(0, guiLeft + 8, guiTop + 140, 205, 20, modeString) }
init {
selectInfo(msg.memoryInfo.selectedIndex)
sortInfo()
infoOnScreen = sortedInfo.take(5)
val list = mutableListOf<WidgetP2PDevice>()
for (i in 0..4) {
list += WidgetP2PDevice(::selectedInfo, ::mode, { sortedInfo.getOrNull(i + scrollBar.currentScroll) }, 0, 0)
}
widgetDevices = list.toList()
}
override fun initGui() {
super.initGui()
checkInfo()
scrollBar = WidgetScrollBar()
scrollBar.displayX = guiLeft + 218
scrollBar.displayY = guiTop + 19
scrollBar.height = 114
scrollBar.setRange(0, infos.size.coerceIn(0..(infos.size-5).coerceAtLeast(0)), 23)
for (i in 0..4) {
widgetDevices[i].x = guiLeft + tableX
widgetDevices[i].y = guiTop + tableY + 23 * i
}
}
fun sortInfo() {
sortedInfo = infos.sortedBy {
if (it.index == selectedIndex) {
-2 // Put the selected p2p in the front
} else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency && !it.output) {
-3 // Put input in the beginning
} else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency) {
-1 // Put same frequency in the front
} else {
it.frequency + Short.MAX_VALUE
}
}
}
fun checkInfo() {
infos.forEach { it.error = false }
infos.groupBy { it.frequency }.filter { it.value.none { x -> !x.output } }.forEach { it.value.forEach { info ->
info.error = true
} }
}
fun refreshInfo(infos: List<P2PInfo>) {
for (info in infos) {
val wrapper = InfoWrapper(info)
this.infos[info.index] = wrapper
}
checkInfo()
sortInfo()
refreshOverlay()
}
fun syncMemoryInfo() {
ModNetwork.channel.sendToServer(C2SUpdateInfo(MemoryInfo(selectedIndex, selectedInfo?.frequency ?: 0, mode)))
}
fun drawInformation() {
val x = 8
var y = 170
for (line in descriptionLines) {
fontRendererObj.drawString(line, guiLeft + x, guiTop + y, 0)
y += fontRendererObj.FONT_HEIGHT
}
}
override fun onGuiClosed() {
syncMemoryInfo()
ModNetwork.channel.sendToServer(C2SCloseGui())
}
override fun drawScreen(mouseX: Int, mouseY: Int, partialTicks: Float) {
drawDefaultBackground()
drawBackground()
scrollBar.draw(this)
for (widget in widgetDevices) {
widget.render(this, mouseX, mouseY, partialTicks)
}
modeButton.drawButton(mc, mouseX, mouseY)
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.toLowerCase()}"))
} else {
descriptionLines.clear()
}
drawInformation()
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.toLowerCase()}")
}
fun findInput(frequency: Long) =
infos.find { it.frequency == frequency && !it.output }
fun selectInfo(index: Int) {
selectedIndex = index
syncMemoryInfo()
refreshOverlay()
}
fun refreshOverlay() {
ClientCache.selectedPosition = arrayListOf(selectedInfo?.posX, selectedInfo?.posY, selectedInfo?.posZ)
ClientCache.selectedFacing = selectedInfo?.facing
ClientCache.positions.clear()
ClientCache.positions.addAll(infos.filter { it.frequency == selectedInfo?.frequency && it != selectedInfo }.map { arrayListOf(it.posX, it.posY, it.posZ) to it.facing })
}
private fun onSelectButtonClicked(info: InfoWrapper) {
selectInfo(info.index)
}
private fun onBindButtonClicked(info: InfoWrapper) {
if (selectedIndex == -1) return
when (mode) {
BetterMemoryCardModes.INPUT -> {
BetterP2P.logger.debug("Bind ${info.index} as input")
ModNetwork.channel.sendToServer(C2SLinkP2P(info.index, selectedIndex))
}
BetterMemoryCardModes.OUTPUT -> {
BetterP2P.logger.debug("Bind ${info.index} as output")
ModNetwork.channel.sendToServer(C2SLinkP2P(selectedIndex, info.index))
}
BetterMemoryCardModes.COPY -> {
val input = selectedInfo?.frequency?.let { findInput(it) }
if (input != null)
ModNetwork.channel.sendToServer(C2SLinkP2P(input.index, info.index))
}
}
}
override fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) {
for (widget in widgetDevices) {
val info = widget.infoSupplier()
if (info?.selectButton?.mousePressed(mc, mouseX, mouseY) == true)
onSelectButtonClicked(widget.infoSupplier()!!)
else if (info?.bindButton?.mousePressed(mc, mouseX, mouseY) == true)
onBindButtonClicked(widget.infoSupplier()!!)
}
if (modeButton.mousePressed(mc, mouseX, mouseY)) {
switchMode()
}
scrollBar.click(mouseX, mouseY)
super.mouseClicked(mouseX, mouseY, mouseButton)
}
override fun mouseClickMove(mouseX: Int, mouseY: Int, clickedMouseButton: Int, timeSinceLastClick: Long) {
scrollBar.click(mouseX, mouseY)
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)
}
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) {
scrollBar.wheel(i)
}
}
override fun bindTexture(modid: String, location: String) {
val loc = ResourceLocation(modid, location)
mc.textureManager.bindTexture(loc)
}
private fun drawBackground() {
bindTexture(MODID, "textures/gui/advanced_memory_card.png")
drawTexturedModalRect(guiLeft, guiTop, 0, 0, this.xSize, this.ySize)
}
override fun doesGuiPauseGame(): Boolean {
return false
}
}
@@ -0,0 +1,13 @@
package com.projecturanus.betterp2p.client.gui
enum class InfoSortStrategy(val comparator: (InfoWrapper, InfoWrapper) -> Int) : Comparator<InfoWrapper> {
DEFAULT({ o1, o2 ->
o1.frequency.compareTo(o2.frequency)
}),
BY_FREQUENCY({ o1, o2 ->
o1.frequency.compareTo(o2.frequency)
}),
;
override fun compare(o1: InfoWrapper, o2: InfoWrapper): Int = comparator(o1, o2)
}
@@ -0,0 +1,39 @@
package com.projecturanus.betterp2p.client.gui
import com.projecturanus.betterp2p.network.P2PInfo
import net.minecraft.client.gui.GuiButton
import net.minecraft.client.resources.I18n
import net.minecraft.util.EnumFacing
class InfoWrapper(info: P2PInfo) {
// Basic information
val index: Int = info.index
val frequency: Long = info.frequency
val hasChannel = info.hasChannel
val posX: Int = info.posX
val posY: Int = info.posY
val posZ: Int = info.posZ
val facing: EnumFacing = info.facing
val description: String
val output: Boolean = info.output
var error: Boolean = false
// Widgets
val selectButton = GuiButton(0, 0, 0, 34, 20, I18n.format("gui.advanced_memory_card.select"))
val bindButton = GuiButton(0, 0, 0, 34, 20, I18n.format("gui.advanced_memory_card.bind"))
init {
description = buildString {
append("P2P ")
if (output)
append(I18n.format("gui.advanced_memory_card.desc.mode.output"))
else
append(I18n.format("gui.advanced_memory_card.desc.mode.input"))
append(" - ")
if (info.frequency.toInt() == 0)
append(I18n.format("gui.advanced_memory_card.desc.not_set"))
else
append(info.frequency.toString())
}
}
}
@@ -0,0 +1,37 @@
package com.projecturanus.betterp2p.client.gui.widget
import net.minecraft.client.gui.Gui
open class Widget {
fun drawHorizontalLine(startX: Int, endX: Int, y: Int, color: Int) {
var startX = startX
var endX = endX
if (endX < startX) {
val i = startX
startX = endX
endX = i
}
Gui.drawRect(startX, y, endX + 1, y + 1, color)
}
/**
* Draw a 1 pixel wide vertical line. Args : x, y1, y2, color
*/
fun drawVerticalLine(x: Int, startY: Int, endY: Int, color: Int) {
var startY = startY
var endY = endY
if (endY < startY) {
val i = startY
startY = endY
endY = i
}
Gui.drawRect(x, startY + 1, x + 1, endY, color)
}
fun drawRectBorder(left: Int, top: Int, width: Int, height: Int, stroke: Int) {
drawHorizontalLine(left, left + width, top, stroke)
drawHorizontalLine(left, left + width, top + height, stroke)
drawVerticalLine(left, top, top + height, stroke)
drawVerticalLine(left + width, top, top + height, stroke)
}
}
@@ -0,0 +1,111 @@
package com.projecturanus.betterp2p.client.gui.widget
import com.projecturanus.betterp2p.client.gui.InfoWrapper
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.resources.I18n
import java.awt.Color
import kotlin.reflect.KMutableProperty0
class WidgetP2PDevice(private val selectedInfoProperty: KMutableProperty0<InfoWrapper?>, val modeSupplier: () -> BetterMemoryCardModes, val infoSupplier: () -> InfoWrapper?, var x: Int, var y: Int): Widget() {
private val outputColor = 0x4566ccff
private val selectedColor = 0x4545DA75
private val errorColor = 0x45DA4527
private val inactiveColor = 0x45FFEA05
private val rowWidth = 203
private val rowHeight = 22
private var selectedInfo: InfoWrapper?
get() = selectedInfoProperty.get()
set(value) {
selectedInfoProperty.set(value)
}
fun render(gui: GuiScreen, mouseX: Int, mouseY: Int, partialTicks: Float) {
val info = infoSupplier()
if (info != null) {
val fontRenderer = gui.mc.fontRenderer
if (selectedInfo?.index == info.index)
GuiScreen.drawRect(x, y, x + rowWidth, y + rowHeight, selectedColor)
else if (info.error) {
// P2P output without an input
GuiScreen.drawRect(x, y, x + rowWidth, y + rowHeight, errorColor)
}
else if (!info.hasChannel && info.frequency != 0.toLong()) {
// No channel
GuiScreen.drawRect(x, y, x + rowWidth, y + rowHeight, inactiveColor)
}
else if (selectedInfo?.frequency == info.frequency && info.frequency != 0.toLong()) {
// Show same frequency
GuiScreen.drawRect(x, y, x + rowWidth, y + rowHeight, outputColor)
}
fontRenderer.drawString(info.description, x + 24, y + 3, 0)
fontRenderer.drawString(I18n.format("gui.advanced_memory_card.pos", info.posX, info.posY, info.posZ), x + 24, y + 12, 0)
if (selectedInfo == null) {
info.bindButton.enabled = false
info.selectButton.enabled = true
} else if (info.index != selectedInfo?.index) {
info.bindButton.enabled = true
info.selectButton.enabled = true
} else {
// TODO Unbind
info.bindButton.enabled = false
info.selectButton.enabled = false
}
val mode = modeSupplier()
if (mode == BetterMemoryCardModes.COPY && !info.output && info.frequency != 0.toLong()) {
info.bindButton.enabled = false
}
drawButtons(gui, info, mouseX, mouseY, partialTicks)
drawP2PColors(gui, info.frequency, x, y)
}
}
private fun drawP2PColors(gui: GuiScreen, frequency: Long, x: Int, y: Int) {
drawRectBorder(x + 9, y + 9, 3, 3, Color.BLACK.rgb)
for (row in 0..1) {
for (col in 0..1) {
for (colorIndex in 0..3) {
val offsetX: Int = colorIndex % 2
val offsetY: Int = colorIndex / 2
drawHorizontalLine(x + 7 + col * 6 + offsetX, x + 8 + col * 6 + offsetX, y + 7 + row * 6 + offsetY, Color.BLACK.rgb)
}
drawRectBorder(x + 6 + col * 6, y + 6 + row * 6, 3, 3, Color.BLACK.rgb)
}
}
}
private fun drawButtons(gui: GuiScreen, info: InfoWrapper, mouseX: Int, mouseY: Int, partialTicks: Float) {
if (!info.bindButton.enabled && info.selectButton.enabled) {
info.bindButton.enabled = false
info.selectButton.enabled = true
info.selectButton.xPosition = x + 166
info.selectButton.yPosition = y + 1
info.selectButton.drawButton(gui.mc, mouseX, mouseY)
} else if (info.bindButton.enabled && info.selectButton.enabled) {
info.bindButton.enabled = true
info.selectButton.enabled = true
// Select button on the left
info.selectButton.xPosition = x + 130
info.selectButton.yPosition = y + 1
info.selectButton.drawButton(gui.mc, mouseX, mouseY)
// Bind button on the right
info.bindButton.xPosition = x + 166
info.bindButton.yPosition = y + 1
info.bindButton.drawButton(gui.mc, mouseX, mouseY)
} else if (!info.selectButton.enabled && !info.bindButton.enabled) {
// TODO Unbind
info.bindButton.enabled = false
info.selectButton.enabled = false
}
}
}
@@ -0,0 +1,69 @@
package com.projecturanus.betterp2p.client.gui.widget
import com.projecturanus.betterp2p.client.TextureBound
import net.minecraft.client.gui.Gui
class WidgetScrollBar {
var displayX = 0
var displayY = 0
var width = 12
var height = 16
var pageSize = 1
var maxScroll = 0
var minScroll = 0
var onScroll: () -> Unit = {}
var currentScroll = 0
fun <T> draw(g: T) where T: TextureBound, T: Gui {
g.bindTexture("minecraft", "textures/gui/container/creative_inventory/tabs.png")
if (getRange() == 0) {
g.drawTexturedModalRect(displayX, displayY, 232 + width, 0, width, 15)
} else {
val offset = (currentScroll - minScroll) * (height - 15) / getRange()
g.drawTexturedModalRect(displayX, offset + displayY, 232, 0, width, 15)
}
}
private fun getRange(): Int {
return maxScroll - minScroll
}
fun setRange(min: Int, max: Int, pageSize: Int) {
minScroll = min
maxScroll = max
this.pageSize = pageSize
if (minScroll > maxScroll) {
maxScroll = minScroll
}
applyRange()
}
private fun applyRange() {
currentScroll = currentScroll.coerceAtMost(maxScroll).coerceAtLeast(minScroll)
onScroll()
}
fun click(x: Int, y: Int) {
if (getRange() == 0) {
return
}
if (x > displayX && x <= displayX + width) {
if (y > displayY && y <= displayY + height) {
currentScroll = y - displayY
currentScroll = minScroll + currentScroll * 2 * getRange() / height
currentScroll = currentScroll + 1 shr 1
applyRange()
}
}
}
fun wheel(delta: Int) {
var delta = delta
delta = (-delta).coerceAtMost(1).coerceAtLeast(-1)
currentScroll += delta
applyRange()
}
}
@@ -0,0 +1,211 @@
package com.projecturanus.betterp2p.client.render;
import com.projecturanus.betterp2p.util.GlStateManager;
import kotlin.Pair;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import org.lwjgl.opengl.GL11;
import java.util.Collection;
import java.util.List;
/**
* Everything in this inner class is From a mod that has MIT license owned by romelo333 and maintained by McJty
*
* License is here: https://github.com/romelo333/notenoughwands1.8.8/blob/master/LICENSE
*
* Specific source of code from the GenericWand class:
* https://github.com/romelo333/notenoughwands1.8.8/blob/20952f50e7c1ab3fd676ed3da302666295e3cac8/src/main/java/romelo333/notenoughwands/Items/GenericWand.java
*
* Version 1.1: Edited to support rotation
*/
public class OutlineRenderer {
public static void renderOutlines(RenderWorldLastEvent evt, EntityPlayer p, Collection<List<Integer>> coordinates, int r, int g, int b) {
double doubleX = p.lastTickPosX + (p.posX - p.lastTickPosX);
double doubleY = p.lastTickPosY + (p.posY - p.lastTickPosY);
double doubleZ = p.lastTickPosZ + (p.posZ - p.lastTickPosZ);
GlStateManager.pushAttrib();
GlStateManager.disableDepth();
GlStateManager.disableTexture2D();
GlStateManager.disableLighting();
GlStateManager.depthMask(false);
GlStateManager.pushMatrix();
GlStateManager.translate(-doubleX, -doubleY, -doubleZ);
renderOutlines(coordinates, r, g, b, 4);
GlStateManager.popMatrix();
GlStateManager.popAttrib();
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.depthMask(true);
}
private static void renderOutlines(Collection<List<Integer>> coordinates, int r, int g, int b, int thickness) {
Tessellator tessellator = Tessellator.instance;
// net.minecraft.client.renderer.VertexBuffer
//BufferBuilder buffer = tessellator.getBuffer();
tessellator.startDrawing(GL11.GL_LINES);
// GlStateManager.color(r / 255.0f, g / 255.0f, b / 255.0f);
GL11.glLineWidth(thickness);
for (List<Integer> coordinate : coordinates) {
float x = coordinate.get(0);
float y = coordinate.get(1);
float z = coordinate.get(2);
renderHighLightedBlocksOutline(tessellator, x, y, z, r, g, b, 255); // .02f
}
tessellator.draw();
}
public static void renderHighLightedBlocksOutline(Tessellator tessellator, float mx, float my, float mz, int r, int g, int b, int a) {
tessellator.setColorRGBA(r, g, b, a);
tessellator.addVertex(mx, my, mz);
tessellator.addVertex(mx + 1, my, mz);
tessellator.addVertex(mx, my, mz);
tessellator.addVertex(mx, my + 1, mz);
tessellator.addVertex(mx, my, mz);
tessellator.addVertex(mx, my, mz + 1);
tessellator.addVertex(mx + 1, my + 1, mz + 1);
tessellator.addVertex(mx, my + 1, mz + 1);
tessellator.addVertex(mx + 1, my + 1, mz + 1);
tessellator.addVertex(mx + 1, my, mz + 1);
tessellator.addVertex(mx + 1, my + 1, mz + 1);
tessellator.addVertex(mx + 1, my + 1, mz);
tessellator.addVertex(mx, my + 1, mz);
tessellator.addVertex(mx, my + 1, mz + 1);
tessellator.addVertex(mx, my + 1, mz);
tessellator.addVertex(mx + 1, my + 1, mz);
tessellator.addVertex(mx + 1, my, mz);
tessellator.addVertex(mx + 1, my, mz + 1);
tessellator.addVertex(mx + 1, my, mz);
tessellator.addVertex(mx + 1, my + 1, mz);
tessellator.addVertex(mx, my, mz + 1);
tessellator.addVertex(mx + 1, my, mz + 1);
tessellator.addVertex(mx, my, mz + 1);
tessellator.addVertex(mx, my + 1, mz + 1);
}
public static void renderOutlinesWithFacing(RenderWorldLastEvent evt, EntityPlayer p, Collection<Pair<List<Integer>, EnumFacing>> coordinates, int r, int g, int b) {
double doubleX = p.lastTickPosX + (p.posX - p.lastTickPosX);
double doubleY = p.lastTickPosY + (p.posY - p.lastTickPosY);
double doubleZ = p.lastTickPosZ + (p.posZ - p.lastTickPosZ);
GlStateManager.pushAttrib();
GlStateManager.disableDepth();
GlStateManager.disableTexture2D();
GlStateManager.disableLighting();
GlStateManager.depthMask(false);
renderOutlinesWithFacing(coordinates, -doubleX, -doubleY, -doubleZ, r, g, b, 4);
GlStateManager.popAttrib();
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.depthMask(true);
}
private static void renderOutlinesWithFacing(Collection<Pair<List<Integer>, EnumFacing>> coordinates, double x, double y, double z, int r, int g, int b, int thickness) {
Tessellator tessellator = Tessellator.instance;
//BufferBuilder buffer = tessellator.getBuffer();
for (Pair<List<Integer>, EnumFacing> coordinate : coordinates) {
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
tessellator.startDrawing(GL11.GL_LINES);
GL11.glLineWidth(thickness);
List<Integer> pos = coordinate.component1();
EnumFacing facing = coordinate.component2();
tessellator.setTranslation(pos.get(0), pos.get(1), pos.get(2));
renderHighLightedBlocksOutlineForFacing(tessellator, r, g, b, 255);
tessellator.setTranslation(0, 0, 0);
GlStateManager.translate(pos.get(0), pos.get(1), pos.get(2));
GlStateManager.translate(0.5, 0.5, 0.5);
switch (facing) {
case DOWN:
GL11.glRotated(90, 0, 1, 0);
GL11.glRotated(90, 0, 0, 1);
break;
case UP:
GL11.glRotated(90, 0, 1, 0);
GL11.glRotated(270, 0, 0, 1);
break;
case NORTH:
GL11.glRotated(-90, 0, 1, 0);
break;
case SOUTH:
GL11.glRotated(90, 0, 1, 0);
break;
case EAST:
GL11.glRotated(180, 0, 0, 1);
break;
case WEST:
break;
}
int[] west_matrix = {1, 0, 0, 0, 1, 0, 0, 0, 1};
int[] east_matrix = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
int[] north_matrix = {0, 0, -1, 0, 1, 0, 1, 0, 0};
int[] south_matrix = {0, 0, 1, 0, 1, 0, -1, 0, 0};
GlStateManager.translate(-0.5, -0.5, -0.5);
GlStateManager.translate(-pos.get(0), -pos.get(1), -pos.get(2));
tessellator.draw();
GlStateManager.popMatrix();
}
}
public static void renderHighLightedBlocksOutlineForFacing(Tessellator tessellator,
int r, int g, int b, int a) {
double minX = 0;
double minY = 0.125;
double minZ = 0.125;
double maxX = 0.1875;
double maxY = 0.875;
double maxZ = 0.875;
tessellator.setColorRGBA(r, g, b, a);
tessellator.addVertex(minX, minY, minZ);
tessellator.addVertex(maxX, minY, minZ);
tessellator.addVertex(minX, minY, minZ);
tessellator.addVertex(minX, maxY, minZ);
tessellator.addVertex(minX, minY, minZ);
tessellator.addVertex(minX, minY, maxZ);
tessellator.addVertex(maxX, maxY, maxZ);
tessellator.addVertex(minX, maxY, maxZ);
tessellator.addVertex(maxX, maxY, maxZ);
tessellator.addVertex(maxX, minY, maxZ);
tessellator.addVertex(maxX, maxY, maxZ);
tessellator.addVertex(maxX, maxY, minZ);
tessellator.addVertex(minX, maxY, minZ);
tessellator.addVertex(minX, maxY, maxZ);
tessellator.addVertex(minX, maxY, minZ);
tessellator.addVertex(maxX, maxY, minZ);
tessellator.addVertex(maxX, minY, minZ);
tessellator.addVertex(maxX, minY, maxZ);
tessellator.addVertex(maxX, minY, minZ);
tessellator.addVertex(maxX, maxY, minZ);
tessellator.addVertex(minX, minY, maxZ);
tessellator.addVertex(maxX, minY, maxZ);
tessellator.addVertex(minX, minY, maxZ);
tessellator.addVertex(minX, maxY, maxZ);
}
}
@@ -0,0 +1,47 @@
package com.projecturanus.betterp2p.client.render;
import com.projecturanus.betterp2p.client.ClientCache;
import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import kotlin.Pair;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import java.util.ArrayList;
import java.util.List;
public class RenderHandler {
@SubscribeEvent
public void renderOverlays(RenderWorldLastEvent event) {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player.getHeldItem() != null && player.getHeldItem().getItem() == ItemAdvancedMemoryCard.INSTANCE) {
if (!ClientCache.INSTANCE.getPositions().isEmpty() || ClientCache.INSTANCE.getSelectedPosition() != null) {
if (ClientCache.INSTANCE.getSelectedPosition() != null) {
List<Pair<List<Integer>, EnumFacing>> tmp = new ArrayList<>();
tmp.add(new Pair<>(ClientCache.INSTANCE.getSelectedPosition(), ClientCache.INSTANCE.getSelectedFacing()));
OutlineRenderer.renderOutlinesWithFacing(
event,
player,
tmp,
0x45,
0xDA,
0x75
);
}
OutlineRenderer.renderOutlinesWithFacing(event, player, ClientCache.INSTANCE.getPositions(), 0x66, 0xCC, 0xFF);
}
}
}
public static void register() {
RenderHandler handler = new RenderHandler();
MinecraftForge.EVENT_BUS.register(handler);
FMLCommonHandler.instance().bus().register(handler);
}
}
@@ -0,0 +1,148 @@
package com.projecturanus.betterp2p.client.render;
import com.projecturanus.betterp2p.util.GlStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
/**
* Functions from this inner class are not authored by me (Sam Bassett aka Lothrazar) they are from BuildersGuides by
*
* @author Ipsis
*
* All credit goes to author for this
*
* Source code: https://github.com/Ipsis/BuildersGuides Source License https://github.com/Ipsis/BuildersGuides/blob/master/COPYING.LESSER
*
* I used and modified two functions from this library https://github.com/Ipsis/BuildersGuides/blob/master/src/main/java/ipsis/buildersguides/util/RenderUtils.java
*
*
*/
@SuppressWarnings("serial")
public class ShadowRenderer {
public static void renderBlockPos(List<Integer> p, List<Integer> center, double relX, double relY, double relZ, float red, float green, float blue) {
if (p == null) {
return;
}
renderBlockList(new ArrayList<List<Integer>>() {
{
add(p);
}
}, center, relX, relY, relZ, red, green, blue);
}
public static void renderBlockPhantom(World world, final List<Integer> pos, ItemStack stack, final double relX, final double relY, final double relZ,
List<Integer> target, boolean isSolid) {
if (stack.getItem() instanceof ItemBlock) {
int stateFromStack = stack.getItemDamage();
renderBlockPhantom(world, pos, stateFromStack, relX, relY, relZ, target, isSolid);
}
}
public static void renderBlockPhantom(World world, final List<Integer> pos, int state, final double relX, final double relY, final double relZ, List<Integer> target, boolean isSolid) {
int xOffset = target.get(0) - pos.get(0);
int yOffset = target.get(1) - pos.get(1);
int zOffset = target.get(2) - pos.get(2);
//final BlockRendererDispatcher blockRenderer = Minecraft.getMinecraft().getBlockRendererDispatcher();
Tessellator tessellator = Tessellator.instance;
//BufferBuilder bufferBuilder = tessellator.getBuffer();
GlStateManager.pushMatrix();
//this first translate is to make relative to TE and everything
GlStateManager.translate(relX + 0.5F, relY + 0.5F, relZ + 0.5F);
RenderHelper.disableStandardItemLighting();
if (!isSolid) {
GlStateManager.blendFunc(770, 775);
GlStateManager.enableBlend();
GlStateManager.disableCull();
}
tessellator.startDrawing(GL11.GL_QUADS);
//move into frame and then back to zero - so world relative
tessellator.setTranslation(-0.5 - pos.get(0) + xOffset, -.5 - pos.get(1) + yOffset, -.5 - pos.get(2) + zOffset);
Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
//TODO: pos below is the targetPos, other rel and pos are TE
//blockRenderer.getBlockModelRenderer().renderModel(world, model, state, pos, bufferBuilder, false);
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
tessellator.draw();
RenderHelper.enableStandardItemLighting();
GlStateManager.popMatrix();
}
public static void renderBlockList(List<List<Integer>> blockPosList, List<Integer> center, double relX, double relY, double relZ, float red, float green, float blue) {
GlStateManager.pushAttrib();
GlStateManager.pushMatrix();
// translate to center or te
GlStateManager.translate(relX + 0.5F, relY + 0.5F, relZ + 0.5F);
GlStateManager.disableLighting(); // so colors are correct
GlStateManager.disableTexture2D(); // no texturing needed
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.enableBlend();
float alpha = 0.5F;
GlStateManager.color(red, green, blue, alpha);
if (Minecraft.isAmbientOcclusionEnabled())
GlStateManager.shadeModel(GL11.GL_SMOOTH);
else
GlStateManager.shadeModel(GL11.GL_FLAT);
for (List<Integer> p : blockPosList) {
GlStateManager.pushMatrix();
GlStateManager.translate(
(center.get(0) - p.get(0)) * -1.0F,
(center.get(1) - p.get(1)) * -1.0F,
(center.get(2) - p.get(2)) * -1.0F);
shadedCube(0.4F);
GlStateManager.popMatrix();
}
GlStateManager.disableBlend();
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.popMatrix();
GlStateManager.popAttrib();
}
private static void shadedCube(float scale) {
float size = 1.0F * scale;
Tessellator tessellator = Tessellator.instance;
//BufferBuilder worldRenderer = tessellator.getBuffer();
// Front - anticlockwise vertices
// Back - clockwise vertices
tessellator.startDrawing(GL11.GL_QUADS);
// xy anti-clockwise - front
tessellator.addVertex(-size, -size, size);
tessellator.addVertex(size, -size, size);
tessellator.addVertex(size, size, size);
tessellator.addVertex(-size, size, size);
// xy clockwise - back
tessellator.addVertex(-size, -size, -size);
tessellator.addVertex(-size, size, -size);
tessellator.addVertex(size, size, -size);
tessellator.addVertex(size, -size, -size);
// anti-clockwise - left
tessellator.addVertex(-size, -size, -size);
tessellator.addVertex(-size, -size, size);
tessellator.addVertex(-size, size, size);
tessellator.addVertex(-size, size, -size);
// clockwise - right
tessellator.addVertex(size, -size, -size);
tessellator.addVertex(size, size, -size);
tessellator.addVertex(size, size, size);
tessellator.addVertex(size, -size, size);
// anticlockwise - top
tessellator.addVertex(-size, size, -size);
tessellator.addVertex(-size, size, size);
tessellator.addVertex(size, size, size);
tessellator.addVertex(size, size, -size);
// clockwise - bottom
tessellator.addVertex(-size, -size, -size);
tessellator.addVertex(size, -size, -size);
tessellator.addVertex(size, -size, size);
tessellator.addVertex(-size, -size, size);
tessellator.draw();
}
}
@@ -0,0 +1,84 @@
package com.projecturanus.betterp2p.client.render
import com.projecturanus.betterp2p.util.GlStateManager
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.Tessellator
import org.lwjgl.opengl.GL11
/**
* Render things in world
* Author: Cyclic
*/
object WorldRenderer {
fun renderBlockList(blockPosList: List<List<Int>>, center: List<Int>, relX: Double, relY: Double, relZ: Double, red: Float, green: Float, blue: Float) {
GlStateManager.pushAttrib()
GlStateManager.pushMatrix()
// translate to center or te
GlStateManager.translate(relX + 0.5F, relY + 0.5F, relZ + 0.5F)
GlStateManager.disableLighting() // so colors are correct
GlStateManager.disableTexture2D() // no texturing needed
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA)
GlStateManager.enableBlend()
val alpha = 0.5F
GlStateManager.color(red, green, blue, alpha)
if (Minecraft.isAmbientOcclusionEnabled())
GlStateManager.shadeModel(GL11.GL_SMOOTH)
else
GlStateManager.shadeModel(GL11.GL_FLAT)
for (p in blockPosList) {
GlStateManager.pushMatrix()
GlStateManager.translate(
(center[0] - p[0]) * -1.0F,
(center[1] - p[1]) * -1.0F,
(center[2] - p[2]) * -1.0F)
shadedCube(0.4F)
GlStateManager.popMatrix()
}
GlStateManager.disableBlend()
GlStateManager.enableTexture2D()
GlStateManager.enableLighting()
GlStateManager.popMatrix()
GlStateManager.popAttrib()
}
fun shadedCube(scale: Float) {
val size = 1.0 * scale
val tessellator = Tessellator.instance
//val worldRenderer = tessellator.buffer
// Front - anticlockwise vertices
// Back - clockwise vertices
tessellator.startDrawing(GL11.GL_QUADS)
// xy anti-clockwise - front
tessellator.addVertex(-size, -size, size)
tessellator.addVertex(size, -size, size)
tessellator.addVertex(size, size, size)
tessellator.addVertex(-size, size, size)
// xy clockwise - back
tessellator.addVertex(-size, -size, -size)
tessellator.addVertex(-size, size, -size)
tessellator.addVertex(size, size, -size)
tessellator.addVertex(size, -size, -size)
// anti-clockwise - left
tessellator.addVertex(-size, -size, -size)
tessellator.addVertex(-size, -size, size)
tessellator.addVertex(-size, size, size)
tessellator.addVertex(-size, size, -size)
// clockwise - right
tessellator.addVertex(size, -size, -size)
tessellator.addVertex(size, size, -size)
tessellator.addVertex(size, size, size)
tessellator.addVertex(size, -size, size)
// anticlockwise - top
tessellator.addVertex(-size, size, -size)
tessellator.addVertex(-size, size, size)
tessellator.addVertex(size, size, size)
tessellator.addVertex(size, size, -size)
// clockwise - bottom
tessellator.addVertex(-size, -size, -size)
tessellator.addVertex(size, -size, -size)
tessellator.addVertex(size, -size, size)
tessellator.addVertex(-size, -size, size)
tessellator.draw()
}
}
@@ -0,0 +1,16 @@
package com.projecturanus.betterp2p.config
import net.minecraftforge.common.config.Configuration
object BetterP2PConfig {
val client = ClientConfig()
fun loadConfig(config: Configuration) {
config.load()
client.autoRefresh = config.getBoolean("autoRefresh", "client", true, "Auto refresh the P2P status")
}
class ClientConfig {
var autoRefresh: Boolean = true
}
}
@@ -0,0 +1,22 @@
package com.projecturanus.betterp2p.item
enum class BetterMemoryCardModes {
/**
* Select an input P2P and bind its output
*/
OUTPUT,
/**
* Select an output P2P and bind its input
*/
INPUT,
/**
* Copy same output frequency
*/
COPY;
fun next(): BetterMemoryCardModes {
return values()[ordinal.plus(1) % values().size]
}
}
@@ -0,0 +1,119 @@
package com.projecturanus.betterp2p.item
import appeng.api.networking.IGridHost
import appeng.core.CreativeTab
import appeng.parts.p2p.PartP2PTunnel
import com.projecturanus.betterp2p.MODID
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.client.ClientCache
import com.projecturanus.betterp2p.network.ModNetwork
import com.projecturanus.betterp2p.network.S2CListP2P
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.getInfo
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.renderer.texture.IIconRegister
import net.minecraft.entity.Entity
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.nbt.NBTTagCompound
import net.minecraft.util.StatCollector
import net.minecraft.world.World
import net.minecraftforge.common.util.ForgeDirection
object ItemAdvancedMemoryCard : Item() {
init {
maxStackSize = 1
unlocalizedName = "advanced_memory_card"
creativeTab = CreativeTab.instance
}
override fun onUpdate(stack: ItemStack, worldIn: World, entityIn: Entity, itemSlot: Int, isSelected: Boolean) {
super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected)
}
private fun sendStatus(status: P2PStatus, info: MemoryInfo, player: EntityPlayerMP) {
P2PCache.statusMap[player.uniqueID] = status
ModNetwork.channel.sendTo(
S2CListP2P(status.listP2P.mapIndexed { index, p2p -> p2p.getInfo(index) }, info),
player
)
}
@SideOnly(Side.CLIENT)
override fun addInformation(stack: ItemStack, player: EntityPlayer, tooltip: MutableList<Any?>, boolean: Boolean) {
val info = getInfo(stack)
tooltip += StatCollector.translateToLocal("gui.advanced_memory_card.mode.${info.mode.name.toLowerCase()}")
}
@SideOnly(Side.CLIENT)
private fun clearClientCache() {
ClientCache.clear()
}
override fun onItemRightClick(itemstack: ItemStack, worldIn: World, playerIn: EntityPlayer): ItemStack {
if (playerIn.isSneaking && worldIn.isRemote) {
clearClientCache()
}
return super.onItemRightClick(itemstack, worldIn, playerIn)
}
override fun onItemUse(itemstack: ItemStack, player: EntityPlayer, w: World, x: Int, y: Int, z: Int, side: Int, hx: Float, hy: Float, hz: Float): Boolean {
if (!w.isRemote) {
val te = w.getTileEntity(x, y, z)
if (te is IGridHost && te.getGridNode(ForgeDirection.getOrientation(side)) != null) {
val part = getPart(w, x, y, z, hx, hy, hz)
val stack = player.heldItem
val info = getInfo(stack)
if (part is PartP2PTunnel<*>) {
val status = P2PStatus(player, 0, part.gridNode.grid, part)
info.selectedIndex = status.listP2P.indexOfFirst { it == status.targetP2P }
writeInfo(stack, info)
sendStatus(status, info, player as EntityPlayerMP)
return true
} else {
val node = te.getGridNode(ForgeDirection.getOrientation(side))!!
info.selectedIndex = -1
writeInfo(stack, info)
sendStatus(P2PStatus(player, 0, node.grid), info, player as EntityPlayerMP)
return true
}
}
}
return false
}
override fun doesSneakBypassUse(world: World?, x: Int, y: Int, z: Int, player: EntityPlayer?): Boolean {
return true
}
@SideOnly(Side.CLIENT)
override fun registerIcons(ri: IIconRegister) {
itemIcon = ri.registerIcon("$MODID:advanced_memory_card")
}
fun getInfo(stack: ItemStack): MemoryInfo {
if (stack.item != this) throw ClassCastException("Cannot cast ${stack.item.javaClass.name} to ${javaClass.name}")
if (stack.tagCompound == null) stack.tagCompound = NBTTagCompound()
val compound = stack.tagCompound!!
if (!compound.hasKey("selectedIndex")) compound.setInteger("selectedIndex", -1)
return MemoryInfo(compound.getInteger("selectedIndex"), compound.getLong("frequency"), BetterMemoryCardModes.values()[compound.getInteger("mode")])
}
fun writeInfo(stack: ItemStack, info: MemoryInfo) {
if (stack.item != this) throw ClassCastException("Cannot cast ${stack.item.javaClass.name} to ${javaClass.name}")
if (stack.tagCompound == null) stack.tagCompound = NBTTagCompound()
val compound = stack.tagCompound!!
compound.setInteger("selectedIndex", info.selectedIndex)
compound.setLong("frequency", info.frequency)
compound.setInteger("mode", info.mode.ordinal)
}
}
@@ -0,0 +1,24 @@
package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
class AEPartLocationMessage(var x: Int = 0, var y: Int = 0, var z: Int = 0, var hitX: Float = 0f, var hitY: Float = 0f, var hitZ: Float = 0f): IMessage {
override fun fromBytes(buf: ByteBuf) {
x = buf.readInt()
y = buf.readInt()
z = buf.readInt()
hitX = buf.readFloat()
hitY = buf.readFloat()
hitZ = buf.readFloat()
}
override fun toBytes(buf: ByteBuf) {
buf.writeInt(x)
buf.writeInt(y)
buf.writeInt(z)
buf.writeFloat(hitX)
buf.writeFloat(hitY)
buf.writeFloat(hitZ)
}
}
@@ -0,0 +1,13 @@
package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
class C2SCloseGui : IMessage {
override fun fromBytes(buf: ByteBuf) {
}
override fun toBytes(buf: ByteBuf) {
}
}
@@ -0,0 +1,16 @@
package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
class C2SLinkP2P(var input: Int = -1, var output: Int = -1): IMessage {
override fun fromBytes(buf: ByteBuf) {
input = buf.readInt()
output = buf.readInt()
}
override fun toBytes(buf: ByteBuf) {
buf.writeInt(input)
buf.writeInt(output)
}
}
@@ -0,0 +1,26 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.capability.MemoryInfo
import com.projecturanus.betterp2p.item.BetterMemoryCardModes
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
fun writeMemoryInfo(buf: ByteBuf, info: MemoryInfo) {
buf.writeInt(info.selectedIndex)
buf.writeLong(info.frequency)
buf.writeInt(info.mode.ordinal)
}
fun readMemoryInfo(buf: ByteBuf): MemoryInfo {
return MemoryInfo(buf.readInt(), buf.readLong(), BetterMemoryCardModes.values()[buf.readInt()])
}
class C2SUpdateInfo(var info: MemoryInfo = MemoryInfo()) : IMessage {
override fun fromBytes(buf: ByteBuf) {
info = readMemoryInfo(buf)
}
override fun toBytes(buf: ByteBuf) {
writeMemoryInfo(buf, info)
}
}
@@ -0,0 +1,17 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.client.gui.GuiAdvancedMemoryCard
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 cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.Minecraft
class ClientOpenGuiHandler : IMessageHandler<S2CListP2P, IMessage?> {
@SideOnly(Side.CLIENT)
override fun onMessage(message: S2CListP2P, ctx: MessageContext): IMessage? {
Minecraft.getMinecraft().displayGuiScreen(GuiAdvancedMemoryCard(message))
return null
}
}
@@ -0,0 +1,20 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.client.gui.GuiAdvancedMemoryCard
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 cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.client.Minecraft
class ClientRefreshInfoHandler : IMessageHandler<S2CRefreshInfo, IMessage?> {
@SideOnly(Side.CLIENT)
override fun onMessage(message: S2CRefreshInfo, ctx: MessageContext): IMessage? {
val gui = Minecraft.getMinecraft().currentScreen
if (gui is GuiAdvancedMemoryCard) {
gui.refreshInfo(message.infos)
}
return null
}
}
@@ -0,0 +1,19 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.MODID
import cpw.mods.fml.common.network.NetworkRegistry
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
import cpw.mods.fml.relauncher.Side
object ModNetwork {
val channel: SimpleNetworkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel(MODID)
fun registerNetwork() {
channel.registerMessage(ClientOpenGuiHandler::class.java, S2CListP2P::class.java, 0, Side.CLIENT)
channel.registerMessage(ClientRefreshInfoHandler::class.java, S2CRefreshInfo::class.java, 1, Side.CLIENT)
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)
}
}
@@ -0,0 +1,6 @@
package com.projecturanus.betterp2p.network
import net.minecraft.util.EnumFacing
class P2PInfo(val index: Int, val frequency: Long, val posX: Int, val posY: Int, val posZ: Int, val facing: EnumFacing, val output: Boolean, val hasChannel: Boolean) {
}
@@ -0,0 +1,26 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.capability.MemoryInfo
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
class S2CListP2P(var infos: List<P2PInfo> = emptyList(),
var memoryInfo: MemoryInfo = MemoryInfo()) : IMessage {
override fun fromBytes(buf: ByteBuf) {
val length = buf.readInt()
val list = ArrayList<P2PInfo>(length)
for (i in 0 until length) {
list += readInfo(buf)
}
infos = list
memoryInfo = readMemoryInfo(buf)
}
override fun toBytes(buf: ByteBuf) {
buf.writeInt(infos.size)
for (info in infos) {
writeInfo(buf, info)
}
writeMemoryInfo(buf, memoryInfo)
}
}
@@ -0,0 +1,44 @@
package com.projecturanus.betterp2p.network
import cpw.mods.fml.common.network.simpleimpl.IMessage
import io.netty.buffer.ByteBuf
import net.minecraft.util.EnumFacing
fun readInfo(buf: ByteBuf): P2PInfo {
val index = buf.readInt()
val freq = buf.readLong()
val posX = buf.readInt()
val posY = buf.readInt()
val posZ = buf.readInt()
val facing = EnumFacing.values()[buf.readInt()]
return P2PInfo(index, freq, posX, posY, posZ, facing, buf.readBoolean(), buf.readBoolean())
}
fun writeInfo(buf: ByteBuf, info: P2PInfo) {
buf.writeInt(info.index)
buf.writeLong(info.frequency)
buf.writeInt(info.posX)
buf.writeInt(info.posY)
buf.writeInt(info.posZ)
buf.writeInt(info.facing.ordinal)
buf.writeBoolean(info.output)
buf.writeBoolean(info.hasChannel)
}
class S2CRefreshInfo(var infos: List<P2PInfo> = emptyList()) : IMessage {
override fun fromBytes(buf: ByteBuf) {
val length = buf.readInt()
val list = ArrayList<P2PInfo>(length)
for (i in 0 until length) {
list += readInfo(buf)
}
infos = list
}
override fun toBytes(buf: ByteBuf) {
buf.writeInt(infos.size)
for (info in infos) {
writeInfo(buf, info)
}
}
}
@@ -0,0 +1,14 @@
package com.projecturanus.betterp2p.network
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
class ServerCloseGuiHandler : IMessageHandler<C2SCloseGui, IMessage?> {
override fun onMessage(message: C2SCloseGui, ctx: MessageContext): IMessage? {
P2PCache.statusMap.remove(ctx.serverHandler.playerEntity.uniqueID)
return null
}
}
@@ -0,0 +1,23 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.util.p2p.P2PCache
import com.projecturanus.betterp2p.util.p2p.getInfo
import com.projecturanus.betterp2p.util.p2p.linkP2P
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
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 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(listOf(result.first.getInfo(message.input), result.second.getInfo(message.output))), ctx.serverHandler.playerEntity)
}
return null
}
}
@@ -0,0 +1,21 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.util.p2p.P2PCache
import cpw.mods.fml.common.FMLCommonHandler
import cpw.mods.fml.common.eventhandler.SubscribeEvent
import cpw.mods.fml.common.gameevent.PlayerEvent
import net.minecraftforge.common.MinecraftForge
object ServerPlayerDisconnectHandler {
@SubscribeEvent
fun onLoggedOut(event: PlayerEvent.PlayerLoggedOutEvent) {
P2PCache.statusMap.remove(event.player.uniqueID)
}
fun register() {
val handler = ServerPlayerDisconnectHandler
MinecraftForge.EVENT_BUS.register(handler)
FMLCommonHandler.instance().bus().register(handler)
}
}
@@ -0,0 +1,17 @@
package com.projecturanus.betterp2p.network
import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard
import cpw.mods.fml.common.network.simpleimpl.IMessage
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler
import cpw.mods.fml.common.network.simpleimpl.MessageContext
class ServerUpdateInfoHandler : IMessageHandler<C2SUpdateInfo, IMessage?> {
override fun onMessage(message: C2SUpdateInfo, ctx: MessageContext): IMessage? {
val player = ctx.serverHandler.playerEntity
val stack = player.heldItem
if (stack.item is ItemAdvancedMemoryCard) {
ItemAdvancedMemoryCard.writeInfo(stack, message.info)
}
return null
}
}
@@ -0,0 +1,76 @@
package com.projecturanus.betterp2p.util
import appeng.api.config.SecurityPermissions
import appeng.api.networking.IGrid
import appeng.api.networking.security.ISecurityGrid
import appeng.api.parts.IPart
import appeng.api.parts.IPartHost
import appeng.api.parts.SelectedPart
import appeng.parts.AEBasePart
import appeng.parts.ICableBusContainer
import appeng.parts.p2p.PartP2PTunnel
import appeng.tile.networking.TileCableBus
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraft.util.Vec3
import net.minecraft.world.IBlockAccess
/**
* @see appeng.block.networking.BlockCableBus.cb
*/
fun getCableBus(w: IBlockAccess, posX: Int, posY: Int, posZ: Int): ICableBusContainer? {
val te = w.getTileEntity(posX, posY, posZ)
var out: ICableBusContainer? = null
if (te is TileCableBus) {
out = te.cableBus
}
return out
}
fun getPart(w: IBlockAccess, posX: Int, posY: Int, posZ: Int, hitX: Float, hitY: Float, hitZ: Float): IPart? {
val vec = Vec3.createVectorHelper(hitX.toDouble(), hitY.toDouble(), hitZ.toDouble())
val te = w.getTileEntity(posX, posY, posZ)
if (te !is IPartHost) return null
val p: SelectedPart? = (te as IPartHost).selectPart(vec)
return p?.part
}
/**
* Return a list of p2p in the part's target grid
* @param grid Grid
* @param player Player to check permission
* @param clazz P2P class type
* @return a list of p2p tunnel in the target grid, or an empty list
*/
fun listTargetGridP2P(grid: IGrid?, player: EntityPlayer, clazz: Class<out PartP2PTunnel<*>>): List<PartP2PTunnel<*>> {
if (grid is ISecurityGrid)
if (!grid.hasPermission(player, SecurityPermissions.BUILD))
return emptyList()
return grid?.getMachines(clazz)?.map { it.machine as PartP2PTunnel<*> }?.toList() ?: emptyList()
}
val AEBasePart.facingPosX: Int?
get() =
host?.location?.x?.and(side?.offsetX ?: EnumFacing.UP.frontOffsetX)
val AEBasePart.facingPosY: Int?
get() =
host?.location?.y?.and(side?.offsetY ?: EnumFacing.UP.frontOffsetY)
val AEBasePart.facingPosZ: Int?
get() =
host?.location?.z?.and(side?.offsetZ ?: EnumFacing.UP.frontOffsetZ)
val AEBasePart.facingTile: TileEntity?
get() {
if (host.isInWorld) {
val posX = facingPosX
val posY = facingPosY
val posZ = facingPosZ
if (posX != null && posY != null && posZ != null)
return host?.location?.world?.getTileEntity(posX, posY, posZ)
}
return null
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,3 @@
package com.projecturanus.betterp2p.util.p2p
class LinkException(message: String? = null) : RuntimeException(message)
@@ -0,0 +1,10 @@
package com.projecturanus.betterp2p.util.p2p
import java.util.*
/**
* Cache P2P status for client to use
*/
object P2PCache {
val statusMap: MutableMap<UUID, P2PStatus> = Collections.synchronizedMap(WeakHashMap())
}
@@ -0,0 +1,11 @@
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.util.listTargetGridP2P
import net.minecraft.entity.player.EntityPlayer
class P2PStatus(player: EntityPlayer, val id: Int, val grid: IGrid, val targetP2P: PartP2PTunnel<*>? = null) {
val listP2P: MutableList<PartP2PTunnel<*>> = listTargetGridP2P(grid, player, targetP2P?.javaClass ?: PartP2PTunnelME::class.java).toMutableList()
}
@@ -0,0 +1,100 @@
package com.projecturanus.betterp2p.util.p2p
import appeng.api.config.SecurityPermissions
import appeng.api.networking.IGrid
import appeng.api.networking.security.ISecurityGrid
import appeng.api.parts.IPart
import appeng.api.parts.PartItemStack
import appeng.me.GridAccessException
import appeng.parts.p2p.PartP2PTunnel
import appeng.util.Platform
import com.projecturanus.betterp2p.network.P2PInfo
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.util.ForgeDirection
fun linkP2P(player: EntityPlayer, inputIndex: Int, outputIndex: Int, status: P2PStatus) : Pair<PartP2PTunnel<*>, PartP2PTunnel<*>>? {
val input = status.listP2P[inputIndex]
val output = status.listP2P[outputIndex]
val grid: IGrid? = input.gridNode?.grid
if (grid is ISecurityGrid) {
if (!grid.hasPermission(player, SecurityPermissions.BUILD)) {
return null
}
}
// TODO Change to exception
if (input.javaClass != output.javaClass) {
// Cannot pair two different type of P2P
return null
}
if (input == output) {
// Network loop
return null
}
var frequency = input.frequency
val cache = input.proxy.p2P
// TODO reduce changes
if (input.frequency.toInt() == 0 || input.isOutput) {
frequency = System.currentTimeMillis()
updateP2P(input, frequency, false)
}
if (cache.getInput(frequency) != null) {
val originalInput = cache.getInput(frequency)
if (originalInput != input)
updateP2P(originalInput, frequency, true)
}
return updateP2P(input, frequency, false) to updateP2P(output, frequency, true)
}
/**
* Due to Applied Energistics' limit
*/
fun updateP2P(tunnel: PartP2PTunnel<*>, frequency: Long, output: Boolean): PartP2PTunnel<*> {
val side = tunnel.side
tunnel.host.removePart(side, true)
val data = NBTTagCompound()
val p2pItem: ItemStack = tunnel.getItemStack(PartItemStack.Wrench)
val type: String = p2pItem.unlocalizedName
tunnel.outputProperty = output
p2pItem.writeToNBT(data)
data.setLong("freq", frequency)
val newType = ItemStack.loadItemStackFromNBT(data)
val dir: ForgeDirection = tunnel.host?.addPart(newType, side, null) ?: throw RuntimeException("Cannot bind")
val newBus: IPart = tunnel.host.getPart(dir)
if (newBus is PartP2PTunnel<*>) {
newBus.outputProperty = output
try {
val p2p = newBus.proxy.p2P
p2p.updateFreq(newBus, frequency)
} catch (e: GridAccessException) {
// :P
}
newBus.onTunnelNetworkChange()
return newBus
} else {
throw RuntimeException("Cannot bind")
}
}
var PartP2PTunnel<*>.outputProperty
get() = isOutput
set(value) {
val field = PartP2PTunnel::class.java.getDeclaredField("output")
field.isAccessible = true
field.setBoolean(this, value)
}
val PartP2PTunnel<*>.hasChannel
get() = isPowered && isActive
fun PartP2PTunnel<*>.getInfo(index: Int)
= P2PInfo(index, frequency, location.x, location.y, location.z, EnumFacing.getFront(side.ordinal), isOutput, hasChannel)