port PlaySession to NetworkConnection

This commit is contained in:
Moritz Zwerger 2024-08-01 19:48:58 +02:00
parent 9c5d1cbf7a
commit aaa195cdc6
No known key found for this signature in database
GPG Key ID: 5CAD791931B09AC4
58 changed files with 172 additions and 147 deletions

View File

@ -202,7 +202,7 @@ abstract class Container(
if (!force && session.player.items.opened == this) { if (!force && session.player.items.opened == this) {
session.player.items.opened = null session.player.items.opened = null
session.network.send(CloseContainerC2SP(id)) session.connection.send(CloseContainerC2SP(id))
} }
session.events.fire(ContainerCloseEvent(session, this)) session.events.fire(ContainerCloseEvent(session, this))

View File

@ -33,7 +33,7 @@ class CloneContainerAction(
this.copied = stack this.copied = stack
// TODO (1.18.2): use creative inventory packet // TODO (1.18.2): use creative inventory packet
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 3, 0, container.actions.createId(this), slotsOf(), stack)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 3, 0, container.actions.createId(this), slotsOf(), stack))
container.floatingItem = stack container.floatingItem = stack
} }

View File

@ -40,7 +40,7 @@ class DropContainerAction(
} }
val actionId = container.actions.createId(this) val actionId = container.actions.createId(this)
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 4, if (stack) 1 else 0, actionId, slotsOf(slot to item), null)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 4, if (stack) 1 else 0, actionId, slotsOf(slot to item), null))
// TODO (1.18.2): use creative inventory packet // TODO (1.18.2): use creative inventory packet
container.commit() container.commit()

View File

@ -96,7 +96,7 @@ class FastMoveContainerAction(
} }
} }
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, this.slot, 1, 0, container.actions.createId(this), changes, null)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, this.slot, 1, 0, container.actions.createId(this), changes, null))
} finally { } finally {
container.commit() container.commit()
} }

View File

@ -67,7 +67,7 @@ class PickAllContainerAction(
return return
} }
container.floatingItem = floating container.floatingItem = floating
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, this.slot, 6, 0, container.actions.createId(this), changes, floating)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, this.slot, 6, 0, container.actions.createId(this), changes, floating))
} finally { } finally {
container.commit() container.commit()
} }

View File

@ -47,7 +47,7 @@ class SimpleContainerAction(
} }
container.floatingItem = floatingItem container.floatingItem = floatingItem
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to item), floatingItem)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to item), floatingItem))
} }
private fun putItem(session: PlaySession, containerId: Int, container: Container, floatingItem: ItemStack) { private fun putItem(session: PlaySession, containerId: Int, container: Container, floatingItem: ItemStack) {
@ -59,7 +59,7 @@ class SimpleContainerAction(
} else { } else {
floatingItem.item._count-- // don't use decrease, item + container is already locked floatingItem.item._count-- // don't use decrease, item + container is already locked
} }
return session.network.send(ContainerClickC2SP(containerId, container.serverRevision, null, 0, count.ordinal, container.actions.createId(this), slotsOf(), null)) return session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, null, 0, count.ordinal, container.actions.createId(this), slotsOf(), null))
} }
var target = container[slot] var target = container[slot]
val slotType = container.getSlotType(slot) val slotType = container.getSlotType(slot)
@ -93,7 +93,7 @@ class SimpleContainerAction(
} else { } else {
container.floatingItem = null container.floatingItem = null
} }
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to target), container.floatingItem)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to target), container.floatingItem))
return return
} }
if (target != null && slotType?.canRemove(container, slot, target) != true) { if (target != null && slotType?.canRemove(container, slot, target) != true) {
@ -109,13 +109,13 @@ class SimpleContainerAction(
if (count == ContainerCounts.ALL || (!matches && target != null)) { if (count == ContainerCounts.ALL || (!matches && target != null)) {
container.floatingItem = target container.floatingItem = target
container[slot] = floatingItem container[slot] = floatingItem
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to floatingItem), target)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to floatingItem), target))
} else { } else {
floatingItem.item.count-- floatingItem.item.count--
container.floatingItem = floatingItem container.floatingItem = floatingItem
target = floatingItem.copy(count = 1) target = floatingItem.copy(count = 1)
container[slot] = target container[slot] = target
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to target), floatingItem)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, slot, 0, count.ordinal, container.actions.createId(this), slotsOf(slot to target), floatingItem))
} }
} }

View File

@ -37,7 +37,7 @@ class SlotSwapContainerAction(
container[this.sourceId] = target container[this.sourceId] = target
container[targetId] = source container[targetId] = source
session.network.send(ContainerClickC2SP(containerId, container.serverRevision, sourceId, 2, this.target.button, container.actions.createId(this), slotsOf(sourceId to target, targetId to source), source)) session.connection.send(ContainerClickC2SP(containerId, container.serverRevision, sourceId, 2, this.target.button, container.actions.createId(this), slotsOf(sourceId to target, targetId to source), source))
} finally { } finally {
container.commit() container.commit()

View File

@ -99,7 +99,7 @@ class EnchantingContainer(session: PlaySession, type: ContainerType, title: Chat
throw IllegalStateException("Can not enchant $index!") throw IllegalStateException("Can not enchant $index!")
} }
val id = this.id ?: return val id = this.id ?: return
session.network.send(ContainerButtonC2SP(id, index)) session.connection.send(ContainerButtonC2SP(id, index))
} }
private object LapislazuliSlot : SlotType { private object LapislazuliSlot : SlotType {

View File

@ -105,7 +105,7 @@ class PlayerInventory(
override fun onOpen() { override fun onOpen() {
if (session.version < V_17W13B) { if (session.version < V_17W13B) {
session.network.send(ClientActionC2SP(ClientActionC2SP.ClientActions.OPEN_INVENTORY)) session.connection.send(ClientActionC2SP(ClientActionC2SP.ClientActions.OPEN_INVENTORY))
} }
} }

View File

@ -50,7 +50,7 @@ class MovementPacketSender(
if (this.sprinting == sprinting) { if (this.sprinting == sprinting) {
return return
} }
session.network.send(EntityActionC2SP(player, session, sprinting.decide(EntityActionC2SP.EntityActions.START_SPRINTING, EntityActionC2SP.EntityActions.STOP_SPRINTING))) session.connection.send(EntityActionC2SP(player, session, sprinting.decide(EntityActionC2SP.EntityActions.START_SPRINTING, EntityActionC2SP.EntityActions.STOP_SPRINTING)))
this.sprinting = sprinting this.sprinting = sprinting
} }
@ -58,7 +58,7 @@ class MovementPacketSender(
if (this.sneaking == sneaking) { if (this.sneaking == sneaking) {
return return
} }
session.network.send(EntityActionC2SP(player, session, sneaking.decide(EntityActionC2SP.EntityActions.START_SNEAKING, EntityActionC2SP.EntityActions.STOP_SNEAKING))) session.connection.send(EntityActionC2SP(player, session, sneaking.decide(EntityActionC2SP.EntityActions.START_SNEAKING, EntityActionC2SP.EntityActions.STOP_SNEAKING)))
this.sneaking = sneaking this.sneaking = sneaking
} }
@ -70,7 +70,7 @@ class MovementPacketSender(
return return
} }
this.flying = flying this.flying = flying
session.network.send(ToggleFlyC2SP(abilities)) session.connection.send(ToggleFlyC2SP(abilities))
} }
private fun sendMovement(position: Vec3d, rotation: EntityRotation, onGround: Boolean) { private fun sendMovement(position: Vec3d, rotation: EntityRotation, onGround: Boolean) {
@ -87,7 +87,7 @@ class MovementPacketSender(
onGround != this.onGround -> GroundChangeC2SP(onGround) onGround != this.onGround -> GroundChangeC2SP(onGround)
else -> null else -> null
} }
packet?.let { session.network.send(it) } packet?.let { session.connection.send(it) }
if (sendPosition) { if (sendPosition) {
this.lastPacket = 0 this.lastPacket = 0
@ -111,17 +111,17 @@ class MovementPacketSender(
} }
private fun sendVehicle(vehicle: Entity) { private fun sendVehicle(vehicle: Entity) {
session.network.send(RotationC2SP(player.physics.rotation, player.physics.onGround)) session.connection.send(RotationC2SP(player.physics.rotation, player.physics.onGround))
session.network.send(VehicleInputC2SP(physics.input.sideways, physics.input.forwards, player.input.jump, player.input.sneak)) session.connection.send(VehicleInputC2SP(physics.input.sideways, physics.input.forwards, player.input.jump, player.input.sneak))
if (vehicle == player || !vehicle.clientControlled) { if (vehicle == player || !vehicle.clientControlled) {
return return
} }
session.network.send(MoveVehicleC2SP(vehicle.physics.position, vehicle.physics.rotation)) session.connection.send(MoveVehicleC2SP(vehicle.physics.position, vehicle.physics.rotation))
sendSprinting(player.isSprinting) sendSprinting(player.isSprinting)
} }
fun sendPositionRotation() { fun sendPositionRotation() {
session.network.send(PositionRotationC2SP(physics.position, physics.eyeY, physics.rotation, physics.onGround)) session.connection.send(PositionRotationC2SP(physics.position, physics.eyeY, physics.rotation, physics.onGround))
} }
override fun tick() { override fun tick() {

View File

@ -48,8 +48,8 @@ class SignatureKeyManagement(
private fun registerRefresh(millis: Int) { private fun registerRefresh(millis: Int) {
runLater(millis) { runLater(millis) {
val connected = session.connection.nullCast<NetworkConnection>()?.state != null val connection = session.connection.nullCast<NetworkConnection>() ?: return@runLater
if (session.error != null || (session.established && !connected) || (connected && !session.network.encrypted)) { if (session.error != null || (session.established && !connection.active) || (connection.active && !connection.client!!.encrypted)) {
// session is dead // session is dead
return@runLater return@runLater
} }
@ -89,16 +89,13 @@ class SignatureKeyManagement(
fun sendSession() { fun sendSession() {
val key = key?.playerKey ?: return val key = key?.playerKey ?: return
if (session.version.versionId < ProtocolVersions.V_22W43A) { if (session.version.versionId < ProtocolVersions.V_22W43A) return
if (session.connection !is NetworkConnection) return
if (session.connection.state != ProtocolStates.PLAY) return
if (!session.connection.client!!.encrypted) {
return return
} }
if (session.connection !is NetworkConnection || session.connection.state != ProtocolStates.PLAY) { session.connection.send(SessionDataC2SP(session.sessionId, key))
return
}
if (!session.network.encrypted) {
return
}
session.network.send(SessionDataC2SP(session.sessionId, key))
} }
companion object { companion object {

View File

@ -26,7 +26,7 @@ object WinGameHandler : GameEventHandler {
val credits = data.toInt() == 0x01 val credits = data.toInt() == 0x01
session.events.fire(WinGameEvent(session, credits)) session.events.fire(WinGameEvent(session, credits))
if (!credits) { if (!credits) {
session.network.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN)) session.connection.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN))
} }
} }
} }

View File

@ -126,6 +126,6 @@ class RenderLoop(
context.window.destroy() context.window.destroy()
Log.log(LogMessageType.RENDERING) { "Render window destroyed!" } Log.log(LogMessageType.RENDERING) { "Render window destroyed!" }
// disconnect // disconnect
context.session.network.disconnect() context.session.terminate()
} }
} }

View File

@ -110,7 +110,7 @@ class ErosCrashReport : JavaFXWindowController() {
}) })
catchAll(executor = { catchAll(executor = {
for (session in PlaySession.ACTIVE_CONNECTIONS.toSynchronizedSet()) { for (session in PlaySession.ACTIVE_CONNECTIONS.toSynchronizedSet()) {
session.network.disconnect() session.terminate()
} }
}) })

View File

@ -66,7 +66,7 @@ class ConnectingDialog(
@FXML @FXML
fun cancel() { fun cancel() {
session.network.disconnect() session.terminate()
close() close()
} }

View File

@ -13,6 +13,7 @@
package de.bixilon.minosoft.gui.eros.main.play.server package de.bixilon.minosoft.gui.eros.main.play.server
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedSet import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedSet
import de.bixilon.kutil.concurrent.pool.DefaultThreadPool.async import de.bixilon.kutil.concurrent.pool.DefaultThreadPool.async
import de.bixilon.kutil.latch.CallbackLatch import de.bixilon.kutil.latch.CallbackLatch
@ -174,7 +175,7 @@ class ServerListController : EmbeddedJavaFXController<Pane>(), Refreshable {
} }
session.events.register(JavaFXEventListener.of<KickEvent> { event -> session.events.register(JavaFXEventListener.of<KickEvent> { event ->
(if (session.network.state == ProtocolStates.LOGIN) KickDialog( val dialog = if (session.connection.unsafeCast<NetworkConnection>().state == ProtocolStates.LOGIN) KickDialog(
title = "minosoft:session.login_kick.title".toResourceLocation(), title = "minosoft:session.login_kick.title".toResourceLocation(),
header = "minosoft:session.login_kick.header".toResourceLocation(), header = "minosoft:session.login_kick.header".toResourceLocation(),
description = TranslatableComponents.CONNECTION_LOGIN_KICK_DESCRIPTION(server, account), description = TranslatableComponents.CONNECTION_LOGIN_KICK_DESCRIPTION(server, account),
@ -184,7 +185,8 @@ class ServerListController : EmbeddedJavaFXController<Pane>(), Refreshable {
header = "minosoft:session.kick.header".toResourceLocation(), header = "minosoft:session.kick.header".toResourceLocation(),
description = TranslatableComponents.CONNECTION_KICK_DESCRIPTION(server, account), description = TranslatableComponents.CONNECTION_KICK_DESCRIPTION(server, account),
reason = event.reason, reason = event.reason,
)).show() )
dialog.show()
}) })
val latch = CallbackLatch(1) val latch = CallbackLatch(1)
val assetsDialog = VerifyAssetsDialog(latch = latch).apply { show() } val assetsDialog = VerifyAssetsDialog(latch = latch).apply { show() }

View File

@ -57,7 +57,7 @@ class Rendering(private val session: PlaySession) {
audioPlayer.exit() audioPlayer.exit()
} catch (ignored: Throwable) { } catch (ignored: Throwable) {
} }
session.network.disconnect() session.terminate()
session.error = exception session.error = exception
latch.minus(audioLatch.count) latch.minus(audioLatch.count)
} }
@ -85,7 +85,7 @@ class Rendering(private val session: PlaySession) {
session.events.fire(WindowCloseEvent(context, window = context.window)) session.events.fire(WindowCloseEvent(context, window = context.window))
} catch (ignored: Throwable) { } catch (ignored: Throwable) {
} }
session.network.disconnect() session.terminate()
session.error = exception session.error = exception
} }
} }

View File

@ -47,7 +47,7 @@ class CreditsScreen(
override fun onClose() { override fun onClose() {
super.onClose() super.onClose()
guiRenderer.session.network.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN)) guiRenderer.session.connection.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN))
} }
companion object { companion object {

View File

@ -126,7 +126,7 @@ class SignEditorScreen(
override fun onClose() { override fun onClose() {
super.onClose() super.onClose()
val text = getText() val text = getText()
guiRenderer.session.network.send(SignTextC2SP(blockPosition, this.side, text)) guiRenderer.session.connection.send(SignTextC2SP(blockPosition, this.side, text))
} }
override fun forceSilentApply() { override fun forceSilentApply() {

View File

@ -40,11 +40,11 @@ class PauseMenu(guiRenderer: GUIRenderer) : Menu(guiRenderer) {
this += ButtonElement(guiRenderer, "menu.pause.back_to_game".i18n()) { guiRenderer.gui.popOrPause() } this += ButtonElement(guiRenderer, "menu.pause.back_to_game".i18n()) { guiRenderer.gui.popOrPause() }
this += ButtonElement(guiRenderer, "menu.pause.options.debug".i18n()) { guiRenderer.gui.push(DebugMenu) } this += ButtonElement(guiRenderer, "menu.pause.options.debug".i18n()) { guiRenderer.gui.push(DebugMenu) }
this += NeutralizedButtonElement(guiRenderer, "menu.pause.disconnect".i18n(), "menu.pause.disconnect.confirm".i18n()) { guiRenderer.session.network.disconnect() } this += NeutralizedButtonElement(guiRenderer, "menu.pause.disconnect".i18n(), "menu.pause.disconnect.confirm".i18n()) { guiRenderer.session.terminate() }
if (ErosProfileManager.selected.general.hideErosOnceConnected) { if (ErosProfileManager.selected.general.hideErosOnceConnected) {
add(ButtonElement(guiRenderer, "menu.pause.show_eros".i18n()) { JavaFXUtil.runLater { Eros.setVisibility(true) } }) add(ButtonElement(guiRenderer, "menu.pause.show_eros".i18n()) { JavaFXUtil.runLater { Eros.setVisibility(true) } })
} }
this += NeutralizedButtonElement(guiRenderer, "menu.pause.exit".i18n(), "menu.pause.exit.confirm".i18n()) { guiRenderer.session.network.disconnect(); ShutdownManager.shutdown() } this += NeutralizedButtonElement(guiRenderer, "menu.pause.exit".i18n(), "menu.pause.exit.confirm".i18n()) { guiRenderer.session.terminate(); ShutdownManager.shutdown() }
} }
companion object : GUIBuilder<LayoutedGUIElement<PauseMenu>> { companion object : GUIBuilder<LayoutedGUIElement<PauseMenu>> {

View File

@ -14,6 +14,7 @@
package de.bixilon.minosoft.gui.rendering.gui.hud.elements.tab package de.bixilon.minosoft.gui.rendering.gui.hud.elements.tab
import de.bixilon.kotlinglm.vec2.Vec2 import de.bixilon.kotlinglm.vec2.Vec2
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.concurrent.pool.DefaultThreadPool import de.bixilon.kutil.concurrent.pool.DefaultThreadPool
import de.bixilon.minosoft.data.abilities.Gamemodes import de.bixilon.minosoft.data.abilities.Gamemodes
import de.bixilon.minosoft.data.entities.entities.player.additional.PlayerAdditional import de.bixilon.minosoft.data.entities.entities.player.additional.PlayerAdditional
@ -32,6 +33,7 @@ import de.bixilon.minosoft.gui.rendering.gui.elements.text.TextElement
import de.bixilon.minosoft.gui.rendering.gui.mesh.GUIVertexConsumer import de.bixilon.minosoft.gui.rendering.gui.mesh.GUIVertexConsumer
import de.bixilon.minosoft.gui.rendering.gui.mesh.GUIVertexOptions import de.bixilon.minosoft.gui.rendering.gui.mesh.GUIVertexOptions
import de.bixilon.minosoft.gui.rendering.util.vec.vec2.Vec2Util.EMPTY import de.bixilon.minosoft.gui.rendering.util.vec.vec2.Vec2Util.EMPTY
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.util.KUtil.nullCompare import de.bixilon.minosoft.util.KUtil.nullCompare
import java.util.* import java.util.*
@ -80,7 +82,7 @@ class TabListEntryElement(
init { init {
background = ColorElement(guiRenderer, size, RGBColor(120, 120, 120, 130)) background = ColorElement(guiRenderer, size, RGBColor(120, 120, 120, 130))
DefaultThreadPool += { skinElement.texture = context.textures.skins.getSkin(uuid, item.properties, fetch = guiRenderer.session.network.encrypted, async = false)?.texture } DefaultThreadPool += { skinElement.texture = context.textures.skins.getSkin(uuid, item.properties, fetch = guiRenderer.session.connection.nullCast<NetworkConnection>()?.client?.encrypted == true, async = false)?.texture }
forceSilentApply() forceSilentApply()
} }

View File

@ -13,6 +13,7 @@
package de.bixilon.minosoft.gui.rendering.input.key package de.bixilon.minosoft.gui.rendering.input.key
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.primitive.BooleanUtil.decide import de.bixilon.kutil.primitive.BooleanUtil.decide
import de.bixilon.minosoft.config.StaticConfiguration import de.bixilon.minosoft.config.StaticConfiguration
import de.bixilon.minosoft.config.key.KeyActions import de.bixilon.minosoft.config.key.KeyActions
@ -23,6 +24,7 @@ import de.bixilon.minosoft.gui.rendering.RenderContext
import de.bixilon.minosoft.gui.rendering.input.key.manager.binding.BindingsManager import de.bixilon.minosoft.gui.rendering.input.key.manager.binding.BindingsManager
import de.bixilon.minosoft.gui.rendering.system.base.PolygonModes import de.bixilon.minosoft.gui.rendering.system.base.PolygonModes
import de.bixilon.minosoft.gui.rendering.system.window.CursorModes import de.bixilon.minosoft.gui.rendering.system.window.CursorModes
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.util.KUtil.format import de.bixilon.minosoft.util.KUtil.format
@ -46,8 +48,9 @@ object DebugKeyBindings {
KeyActions.STICKY to setOf(KeyCodes.KEY_I), KeyActions.STICKY to setOf(KeyCodes.KEY_I),
ignoreConsumer = true, ignoreConsumer = true,
)) { )) {
val connection = session.connection.nullCast<NetworkConnection>() ?: return@register
session.util.sendDebugMessage("Pausing incoming packets: ${it.format()}") session.util.sendDebugMessage("Pausing incoming packets: ${it.format()}")
session.network.receiver.paused = it connection.client!!.receiver.paused = it
} }
register(PAUSE_OUTGOING, KeyBinding( register(PAUSE_OUTGOING, KeyBinding(
@ -55,8 +58,9 @@ object DebugKeyBindings {
KeyActions.STICKY to setOf(KeyCodes.KEY_O), KeyActions.STICKY to setOf(KeyCodes.KEY_O),
ignoreConsumer = true, ignoreConsumer = true,
)) { )) {
val connection = session.connection.nullCast<NetworkConnection>() ?: return@register
session.util.sendDebugMessage("Pausing outgoing packets: ${it.format()}") session.util.sendDebugMessage("Pausing outgoing packets: ${it.format()}")
session.network.sender.paused = it connection.client!!.sender.paused = it
} }
} }

View File

@ -64,7 +64,7 @@ class AttackHandler(
return return
} }
interactions.session.network.send(EntityAttackC2SP(target.entity.id ?: return, player.isSneaking)) interactions.session.connection.send(EntityAttackC2SP(target.entity.id ?: return, player.isSneaking))
if (player.gamemode == Gamemodes.SPECTATOR) { if (player.gamemode == Gamemodes.SPECTATOR) {
return return
} }

View File

@ -30,7 +30,7 @@ class DropHandler(
session.player.items.inventory.getHotbarSlot()?.item?.decreaseCount() session.player.items.inventory.getHotbarSlot()?.item?.decreaseCount()
PlayerActionC2SP.Actions.DROP_ITEM PlayerActionC2SP.Actions.DROP_ITEM
} }
rateLimiter += { session.network.send(PlayerActionC2SP(type)) } rateLimiter += { session.connection.send(PlayerActionC2SP(type)) }
} }
fun draw() { fun draw() {

View File

@ -35,7 +35,7 @@ class HotbarHandler(
return return
} }
session.player.items.hotbar = slot session.player.items.hotbar = slot
slotLimiter += { session.network.send(HotbarSlotC2SP(slot)) } slotLimiter += { session.connection.send(HotbarSlotC2SP(slot)) }
} }
private fun canSwap(): Boolean { private fun canSwap(): Boolean {
@ -53,7 +53,7 @@ class HotbarHandler(
val main = inventory[EquipmentSlots.MAIN_HAND] val main = inventory[EquipmentSlots.MAIN_HAND]
val off = inventory[EquipmentSlots.OFF_HAND] val off = inventory[EquipmentSlots.OFF_HAND]
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.SWAP_ITEMS_IN_HAND)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.SWAP_ITEMS_IN_HAND))
if (main == null && off == null) { if (main == null && off == null) {
// both are air, we can't swap // both are air, we can't swap

View File

@ -73,7 +73,7 @@ class InteractionManager(val camera: SessionCamera) : Tickable {
fun swingHand(hand: Hands) { fun swingHand(hand: Hands) {
swingArmRateLimiter += { swingArmRateLimiter += {
session.network.send(SwingArmC2SP(hand)) session.connection.send(SwingArmC2SP(hand))
session.player.swingHand(hand) session.player.swingHand(hand)
} }
} }

View File

@ -88,7 +88,7 @@ class ItemPickHandler(
interactions.hotbar.selectSlot(slot) interactions.hotbar.selectSlot(slot)
val selectedSlot = session.player.items.hotbar + PlayerInventory.HOTBAR_OFFSET val selectedSlot = session.player.items.hotbar + PlayerInventory.HOTBAR_OFFSET
rateLimiter += { session.network.send(ItemStackCreateC2SP(selectedSlot, stack)) } rateLimiter += { session.connection.send(ItemStackCreateC2SP(selectedSlot, stack)) }
session.player.items.inventory[selectedSlot] = stack session.player.items.inventory[selectedSlot] = stack
// ToDo: Use ItemPickC2SP // ToDo: Use ItemPickC2SP

View File

@ -29,7 +29,7 @@ class CreativeBreaker(
val sequence = breaking.executor.start(target.blockPosition, target.state) val sequence = breaking.executor.start(target.blockPosition, target.state)
breaking.executor.finish() breaking.executor.finish()
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.START_DIGGING, target.blockPosition, target.direction, sequence)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.START_DIGGING, target.blockPosition, target.direction, sequence))
breaking.interactions.swingHand(Hands.MAIN) breaking.interactions.swingHand(Hands.MAIN)
return true return true
} }

View File

@ -42,7 +42,7 @@ class SurvivalDigger(
private fun cancel(status: BlockDigStatus) { private fun cancel(status: BlockDigStatus) {
breaking.executor.cancel() breaking.executor.cancel()
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.CANCELLED_DIGGING, status.position, sequence = 0)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.CANCELLED_DIGGING, status.position, sequence = 0))
this.status = null this.status = null
} }
@ -50,7 +50,7 @@ class SurvivalDigger(
val sequence = breaking.executor.finish() val sequence = breaking.executor.finish()
this.status = null this.status = null
if (!instant) { if (!instant) {
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.FINISHED_DIGGING, status.position, status.direction, sequence)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.FINISHED_DIGGING, status.position, status.direction, sequence))
breaking.addCooldown() breaking.addCooldown()
} }
breaking.interactions.swingHand(Hands.MAIN) breaking.interactions.swingHand(Hands.MAIN)
@ -118,7 +118,7 @@ class SurvivalDigger(
} else { } else {
nextStatus = BlockDigStatus(target.blockPosition, target.state, slot, productivity, target.direction) nextStatus = BlockDigStatus(target.blockPosition, target.state, slot, productivity, target.direction)
val sequence = breaking.executor.start(target.blockPosition, target.state) val sequence = breaking.executor.start(target.blockPosition, target.state)
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.START_DIGGING, target.blockPosition, target.direction, sequence)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.START_DIGGING, target.blockPosition, target.direction, sequence))
} }
if (instant || nextStatus.progress >= 1.0f) { if (instant || nextStatus.progress >= 1.0f) {

View File

@ -51,7 +51,7 @@ class LongUseHandler(
stack.item.item.finishUse(session.player, using.hand, stack, using.tick) stack.item.item.finishUse(session.player, using.hand, stack, using.tick)
} }
if (!force) { if (!force) {
session.network.send(PlayerActionC2SP(PlayerActionC2SP.Actions.RELEASE_ITEM)) session.connection.send(PlayerActionC2SP(PlayerActionC2SP.Actions.RELEASE_ITEM))
} }
clearUsing() clearUsing()
} }

View File

@ -81,7 +81,7 @@ class ShortUseHandler(
if (result == InteractionResults.INVALID) { if (result == InteractionResults.INVALID) {
return true return true
} }
session.network.send(BlockInteractC2SP( session.connection.send(BlockInteractC2SP(
position = target.blockPosition, position = target.blockPosition,
direction = target.direction, direction = target.direction,
cursorPosition = Vec3(target.cursor), cursorPosition = Vec3(target.cursor),
@ -105,7 +105,7 @@ class ShortUseHandler(
val entityId = session.world.entities.getId(target.entity) ?: return InteractionResults.IGNORED val entityId = session.world.entities.getId(target.entity) ?: return InteractionResults.IGNORED
// used in armor stands // used in armor stands
val player = session.player val player = session.player
session.network.send(EntityInteractPositionC2SP(entityId, Vec3(target.position), hand, player.isSneaking)) session.connection.send(EntityInteractPositionC2SP(entityId, Vec3(target.position), hand, player.isSneaking))
if (player.gamemode == Gamemodes.SPECTATOR) { if (player.gamemode == Gamemodes.SPECTATOR) {
return InteractionResults.IGNORED return InteractionResults.IGNORED
@ -125,7 +125,7 @@ class ShortUseHandler(
// ToDo: return hit.entity.interact(hand) (e.g. equipping saddle) // ToDo: return hit.entity.interact(hand) (e.g. equipping saddle)
return InteractionResults.IGNORED return InteractionResults.IGNORED
} finally { } finally {
session.world.entities.getId(target.entity)?.let { session.network.send(EntityEmptyInteractC2SP(it, hand, player.isSneaking)) } session.world.entities.getId(target.entity)?.let { session.connection.send(EntityEmptyInteractC2SP(it, hand, player.isSneaking)) }
} }
} }

View File

@ -137,9 +137,9 @@ class UseHandler(
fun sendItemUse(hand: Hands, stack: ItemStack) { fun sendItemUse(hand: Hands, stack: ItemStack) {
if (session.version < V_15W31A) { if (session.version < V_15W31A) {
session.network.send(BlockInteractC2SP(null, null, null, stack, hand, false, 1)) session.connection.send(BlockInteractC2SP(null, null, null, stack, hand, false, 1))
} }
session.network.send(UseItemC2SP(hand, interactions.session.sequence.getAndIncrement())) session.connection.send(UseItemC2SP(hand, interactions.session.sequence.getAndIncrement()))
} }
private companion object { private companion object {

View File

@ -35,7 +35,7 @@ object ElytraPhysics {
private fun LocalPlayerPhysics.startElytraFalling() { private fun LocalPlayerPhysics.startElytraFalling() {
entity.isFlyingWithElytra = true entity.isFlyingWithElytra = true
val id = entity.session.world.entities.getId(entity) ?: return val id = entity.session.world.entities.getId(entity) ?: return
entity.session.network.send(EntityActionC2SP(id, EntityActionC2SP.EntityActions.START_ELYTRA_FLYING)) entity.session.connection.send(EntityActionC2SP(id, EntityActionC2SP.EntityActions.START_ELYTRA_FLYING))
} }
private fun LocalPlayerPhysics.canStartElytraFlight(): Boolean { private fun LocalPlayerPhysics.canStartElytraFlight(): Boolean {

View File

@ -54,6 +54,10 @@ class NetworkConnection(
client?.disconnect() client?.disconnect()
} }
override fun detach() {
client?.detach()
}
override fun send(packet: C2SPacket) { override fun send(packet: C2SPacket) {
client?.send(packet) client?.send(packet)
} }

View File

@ -23,6 +23,7 @@ interface ServerConnection {
fun connect(session: Session) fun connect(session: Session)
fun disconnect() fun disconnect()
fun detach()
fun send(packet: C2SPacket) fun send(packet: C2SPacket)
} }

View File

@ -15,7 +15,6 @@ package de.bixilon.minosoft.protocol.network.network.client.netty
import de.bixilon.kutil.cast.CastUtil.nullCast import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.exception.ExceptionUtil.catchAll import de.bixilon.kutil.exception.ExceptionUtil.catchAll
import de.bixilon.kutil.observer.DataObserver.Companion.observe
import de.bixilon.minosoft.config.profile.profiles.other.OtherProfileManager import de.bixilon.minosoft.config.profile.profiles.other.OtherProfileManager
import de.bixilon.minosoft.protocol.connection.NetworkConnection import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.network.client.ClientNetwork import de.bixilon.minosoft.protocol.network.network.client.ClientNetwork
@ -54,8 +53,6 @@ class NettyClient(
override val connection: NetworkConnection, override val connection: NetworkConnection,
val session: Session, val session: Session,
) : SimpleChannelInboundHandler<Any>(), ClientNetwork { ) : SimpleChannelInboundHandler<Any>(), ClientNetwork {
@Deprecated("unused")
var state = ProtocolStates.HANDSHAKE // TODO
override val sender = PacketSender(this) override val sender = PacketSender(this)
override val receiver = PacketReceiver(this, session) override val receiver = PacketReceiver(this, session)
override var compressionThreshold = -1 override var compressionThreshold = -1
@ -65,10 +62,6 @@ class NettyClient(
override var detached = false override var detached = false
private set private set
init {
connection::state.observe(this) { this.state = it ?: ProtocolStates.HANDSHAKE }
}
override fun connect() { override fun connect() {
val natives = if (connection.native) TransportNatives.get() else NioNatives val natives = if (connection.native) TransportNatives.get() else NioNatives
val bootstrap = Bootstrap() val bootstrap = Bootstrap()

View File

@ -55,7 +55,6 @@ import de.bixilon.minosoft.modding.event.master.GlobalEventMaster
import de.bixilon.minosoft.modding.loader.phase.DefaultModPhases import de.bixilon.minosoft.modding.loader.phase.DefaultModPhases
import de.bixilon.minosoft.protocol.connection.NetworkConnection import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.connection.ServerConnection import de.bixilon.minosoft.protocol.connection.ServerConnection
import de.bixilon.minosoft.protocol.network.network.client.netty.NettyClient
import de.bixilon.minosoft.protocol.network.session.Session import de.bixilon.minosoft.protocol.network.session.Session
import de.bixilon.minosoft.protocol.network.session.play.channel.DefaultChannelHandlers import de.bixilon.minosoft.protocol.network.session.play.channel.DefaultChannelHandlers
import de.bixilon.minosoft.protocol.network.session.play.channel.SessionChannelHandler import de.bixilon.minosoft.protocol.network.session.play.channel.SessionChannelHandler
@ -83,8 +82,6 @@ class PlaySession(
override val version: Version, override val version: Version,
val profiles: SelectedProfiles = SelectedProfiles(), val profiles: SelectedProfiles = SelectedProfiles(),
) : Session() { ) : Session() {
@Deprecated("connection")
val network = NettyClient(connection.unsafeCast(), this)
val sessionId = KUtil.secureRandomUUID() val sessionId = KUtil.secureRandomUUID()
val settingsManager = ClientSettingsManager(this) val settingsManager = ClientSettingsManager(this)
val registries = Registries().apply { updateFlattened(version.flattened) } val registries = Registries().apply { updateFlattened(version.flattened) }
@ -132,16 +129,18 @@ class PlaySession(
RegistriesFixer.register(this) RegistriesFixer.register(this)
DefaultChannelHandlers.register(this) DefaultChannelHandlers.register(this)
connection.unsafeCast<NetworkConnection>()::state.observe(this) { connection::active.observe(this) {
if (it != null) { if (it) {
ACTIVE_CONNECTIONS += this ACTIVE_CONNECTIONS += this
ERRORED_CONNECTIONS -= this ERRORED_CONNECTIONS -= this
state = PlaySessionStates.HANDSHAKING if (connection is NetworkConnection) {
val address = connection.unsafeCast<NetworkConnection>().address state = PlaySessionStates.HANDSHAKING
network.send(HandshakeC2SP(address.hostname, address.port, HandshakeC2SP.Actions.PLAY, version.protocolId)) val address = connection.unsafeCast<NetworkConnection>().address
// after sending it, switch to next state connection.send(HandshakeC2SP(address.hostname, address.port, HandshakeC2SP.Actions.PLAY, version.protocolId))
network.connection.state = ProtocolStates.LOGIN // after sending it, switch to next state
connection.state = ProtocolStates.LOGIN
}
} else { } else {
established = true established = true
assetsManager.unload() assetsManager.unload()
@ -152,38 +151,40 @@ class PlaySession(
} }
} }
} }
connection.unsafeCast<NetworkConnection>()::state.observe(this) { state -> if (connection is NetworkConnection) {
when (state) { connection::state.observe(this) { state ->
ProtocolStates.HANDSHAKE, ProtocolStates.STATUS -> Broken("Invalid state!") when (state) {
ProtocolStates.LOGIN -> { ProtocolStates.STATUS -> Broken("Invalid state!")
this.state = PlaySessionStates.LOGGING_IN ProtocolStates.LOGIN -> {
world.biomes.init() this.state = PlaySessionStates.LOGGING_IN
this.network.send(StartC2SP(this.player, this.sessionId)) world.biomes.init()
} connection.send(StartC2SP(this.player, this.sessionId))
ProtocolStates.PLAY -> {
this.state = PlaySessionStates.JOINING
if (CLI.session == null) {
CLI.session = this
} }
events.listen<ChatMessageEvent> { ProtocolStates.PLAY -> {
val additionalPrefix = when (it.message.type.position) { this.state = PlaySessionStates.JOINING
ChatTextPositions.SYSTEM -> "[SYSTEM] "
ChatTextPositions.HOTBAR -> "[HOTBAR] " if (CLI.session == null) {
else -> "" CLI.session = this
} }
Log.log(LogMessageType.CHAT_IN, level = if (it.message.type.position == ChatTextPositions.HOTBAR) LogLevels.VERBOSE else LogLevels.INFO, prefix = ChatComponent.of(additionalPrefix)) { it.message.text }
} }
}
else -> Unit else -> Unit
}
} }
} }
ticker.init() ticker.init()
GlobalEventMaster.fire(PlaySessionCreateEvent(this)) GlobalEventMaster.fire(PlaySessionCreateEvent(this))
events.listen<ChatMessageEvent> {
val additionalPrefix = when (it.message.type.position) {
ChatTextPositions.SYSTEM -> "[SYSTEM] "
ChatTextPositions.HOTBAR -> "[HOTBAR] "
else -> ""
}
Log.log(LogMessageType.CHAT_IN, level = if (it.message.type.position == ChatTextPositions.HOTBAR) LogLevels.VERBOSE else LogLevels.INFO, prefix = ChatComponent.of(additionalPrefix)) { it.message.text }
}
} }
@ -248,7 +249,7 @@ class PlaySession(
private fun establish(latch: AbstractLatch?) { private fun establish(latch: AbstractLatch?) {
latch?.dec() // remove initial value latch?.dec() // remove initial value
network.connect() connection.connect(this)
state = PlaySessionStates.ESTABLISHING state = PlaySessionStates.ESTABLISHING
} }
@ -265,7 +266,7 @@ class PlaySession(
} }
override fun terminate() { override fun terminate() {
network.disconnect() connection.disconnect()
state = PlaySessionStates.DISCONNECTED state = PlaySessionStates.DISCONNECTED
} }

View File

@ -13,8 +13,10 @@
package de.bixilon.minosoft.protocol.network.session.play.channel.login package de.bixilon.minosoft.protocol.network.session.play.channel.login
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedList import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedList
import de.bixilon.minosoft.data.registries.identified.ResourceLocation import de.bixilon.minosoft.data.registries.identified.ResourceLocation
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.network.session.play.channel.ChannelManager import de.bixilon.minosoft.protocol.network.session.play.channel.ChannelManager
import de.bixilon.minosoft.protocol.packets.c2s.login.ChannelC2SP import de.bixilon.minosoft.protocol.packets.c2s.login.ChannelC2SP
@ -54,9 +56,9 @@ class LoginChannelManager(
} }
fun send(messageId: Int, data: ByteArray?) { fun send(messageId: Int, data: ByteArray?) {
if (session.network.state != ProtocolStates.LOGIN) { if (session.connection.nullCast<NetworkConnection>()?.state != ProtocolStates.LOGIN) {
throw IllegalStateException("Not in login!") throw IllegalStateException("Not in login!")
} }
session.network.send(ChannelC2SP(messageId, data)) session.connection.send(ChannelC2SP(messageId, data))
} }
} }

View File

@ -13,8 +13,10 @@
package de.bixilon.minosoft.protocol.network.session.play.channel.play package de.bixilon.minosoft.protocol.network.session.play.channel.play
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedList import de.bixilon.kutil.collections.CollectionUtil.toSynchronizedList
import de.bixilon.minosoft.data.registries.identified.ResourceLocation import de.bixilon.minosoft.data.registries.identified.ResourceLocation
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.network.session.play.channel.ChannelManager import de.bixilon.minosoft.protocol.network.session.play.channel.ChannelManager
import de.bixilon.minosoft.protocol.packets.c2s.common.ChannelC2SP import de.bixilon.minosoft.protocol.packets.c2s.common.ChannelC2SP
@ -45,9 +47,10 @@ class PlayChannelManager(
} }
fun send(channel: ResourceLocation, data: ByteArray) { fun send(channel: ResourceLocation, data: ByteArray) {
if (session.network.state != ProtocolStates.LOGIN) { // TODO: Play == ready? what if offline? should not crash
throw IllegalStateException("Not in login!") if (session.connection.nullCast<NetworkConnection>()?.state != ProtocolStates.PLAY) {
throw IllegalStateException("Not in play!")
} }
session.network.send(ChannelC2SP(channel, data)) session.connection.send(ChannelC2SP(channel, data))
} }
} }

View File

@ -38,7 +38,7 @@ object BrandHandler {
private fun PlaySession.sendBrand(channel: ResourceLocation, brand: String) { private fun PlaySession.sendBrand(channel: ResourceLocation, brand: String) {
val buffer = PlayOutByteBuffer(this) val buffer = PlayOutByteBuffer(this)
buffer.writeBareByteArray(brand.encodeNetwork()) buffer.writeBareByteArray(brand.encodeNetwork())
network.send(ChannelC2SP(channel, buffer)) connection.send(ChannelC2SP(channel, buffer))
} }
fun PlaySession.sendBrand() { fun PlaySession.sendBrand() {

View File

@ -13,9 +13,11 @@
package de.bixilon.minosoft.protocol.network.session.play.settings package de.bixilon.minosoft.protocol.network.session.play.settings
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.kutil.observer.DataObserver.Companion.observe import de.bixilon.kutil.observer.DataObserver.Companion.observe
import de.bixilon.kutil.observer.set.SetObserver.Companion.observeSet import de.bixilon.kutil.observer.set.SetObserver.Companion.observeSet
import de.bixilon.minosoft.data.language.LanguageUtil import de.bixilon.minosoft.data.language.LanguageUtil
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.c2s.common.SettingsC2SP import de.bixilon.minosoft.protocol.packets.c2s.common.SettingsC2SP
import de.bixilon.minosoft.protocol.protocol.ProtocolStates import de.bixilon.minosoft.protocol.protocol.ProtocolStates
@ -66,15 +68,16 @@ class ClientSettingsManager(
} }
private fun canSendSettings(): Boolean { private fun canSendSettings(): Boolean {
if (session.network.state == ProtocolStates.PLAY) return true // TODO: what if not a NetworkConnection
if (session.version > V_1_20_2_PRE1 && session.network.state == ProtocolStates.CONFIGURATION) return true if (session.connection.nullCast<NetworkConnection>()?.state == ProtocolStates.PLAY) return true
if (session.version > V_1_20_2_PRE1 && session.connection.nullCast<NetworkConnection>()?.state == ProtocolStates.CONFIGURATION) return true
return false return false
} }
fun sendClientSettings() { fun sendClientSettings() {
if (!canSendSettings()) return if (!canSendSettings()) return
session.network.send(SettingsC2SP( session.connection.send(SettingsC2SP(
locale = language, locale = language,
chatColors = session.profiles.gui.chat.chatColors, chatColors = session.profiles.gui.chat.chatColors,
viewDistance = session.profiles.block.viewDistance, viewDistance = session.profiles.block.viewDistance,

View File

@ -53,7 +53,7 @@ class ChunkReceiver(
val end = nanos() val end = nanos()
val delta = end - start val delta = end - start
session.network.send(NextChunkBatchC2SP(100.0f)) // TODO: calculate size session.connection.send(NextChunkBatchC2SP(100.0f)) // TODO: calculate size
reset() reset()
} }
} }

View File

@ -13,6 +13,7 @@
package de.bixilon.minosoft.protocol.network.session.play.util package de.bixilon.minosoft.protocol.network.session.play.util
import de.bixilon.kutil.cast.CastUtil.nullCast
import de.bixilon.minosoft.commands.nodes.ChatNode import de.bixilon.minosoft.commands.nodes.ChatNode
import de.bixilon.minosoft.commands.nodes.SessionNode.Companion.COMMAND_PREFIX import de.bixilon.minosoft.commands.nodes.SessionNode.Companion.COMMAND_PREFIX
import de.bixilon.minosoft.commands.stack.CommandStack import de.bixilon.minosoft.commands.stack.CommandStack
@ -30,6 +31,7 @@ import de.bixilon.minosoft.modding.event.events.chat.ChatMessageEvent
import de.bixilon.minosoft.modding.event.events.chat.ChatMessageSendEvent import de.bixilon.minosoft.modding.event.events.chat.ChatMessageSendEvent
import de.bixilon.minosoft.modding.event.events.container.ContainerCloseEvent import de.bixilon.minosoft.modding.event.events.container.ContainerCloseEvent
import de.bixilon.minosoft.protocol.ProtocolUtil.encodeNetwork import de.bixilon.minosoft.protocol.ProtocolUtil.encodeNetwork
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.c2s.play.chat.ChatMessageC2SP import de.bixilon.minosoft.protocol.packets.c2s.play.chat.ChatMessageC2SP
import de.bixilon.minosoft.protocol.packets.c2s.play.chat.CommandC2SP import de.bixilon.minosoft.protocol.packets.c2s.play.chat.CommandC2SP
@ -70,7 +72,7 @@ class SessionUtil(
} }
Log.log(LogMessageType.CHAT_OUT) { trimmed } Log.log(LogMessageType.CHAT_OUT) { trimmed }
if (!session.version.requiresSignedChat) { if (!session.version.requiresSignedChat) {
return session.network.send(ChatMessageC2SP(trimmed)) return session.connection.send(ChatMessageC2SP(trimmed))
} }
val keyManagement = session.player.keyManagement val keyManagement = session.player.keyManagement
@ -78,7 +80,7 @@ class SessionUtil(
try { try {
val key = keyManagement.key val key = keyManagement.key
if (key == null) { if (key == null) {
session.network.send(SignedChatMessageC2SP(message.encodeNetwork(), time = Instant.now(), salt = 0, signature = null, false, Acknowledgement.EMPTY)) session.connection.send(SignedChatMessageC2SP(message.encodeNetwork(), time = Instant.now(), salt = 0, signature = null, false, Acknowledgement.EMPTY))
return return
} }
sendSignedMessage(key, trimmed) sendSignedMessage(key, trimmed)
@ -95,13 +97,13 @@ class SessionUtil(
val acknowledgement = Acknowledgement.EMPTY val acknowledgement = Acknowledgement.EMPTY
val signature: ByteArray? = if (session.network.encrypted) { val signature: ByteArray? = if (session.connection.nullCast<NetworkConnection>()?.client?.encrypted == true) {
signer.signMessage(privateKey.private, message, null, salt, uuid, time, acknowledgement.lastSeen) signer.signMessage(privateKey.private, message, null, salt, uuid, time, acknowledgement.lastSeen)
} else { } else {
null null
} }
session.network.send(SignedChatMessageC2SP(message.encodeNetwork(), time = time, salt = salt, signature = signature, false, acknowledgement)) session.connection.send(SignedChatMessageC2SP(message.encodeNetwork(), time = time, salt = salt, signature = signature, false, acknowledgement))
} }
fun sendCommand(command: String, stack: CommandStack) { fun sendCommand(command: String, stack: CommandStack) {
@ -112,7 +114,7 @@ class SessionUtil(
ChatUtil.validateChatMessage(session, trimmed) ChatUtil.validateChatMessage(session, trimmed)
val time = Instant.now() val time = Instant.now()
if (stack.size == 0) { if (stack.size == 0) {
session.network.send(CommandC2SP(trimmed, time, 0L, emptyMap(), false, Acknowledgement.EMPTY)) // TODO: remove session.connection.send(CommandC2SP(trimmed, time, 0L, emptyMap(), false, Acknowledgement.EMPTY)) // TODO: remove
Log.log(LogMessageType.OTHER, LogLevels.WARN) { "Command $trimmed failed to parse!" } Log.log(LogMessageType.OTHER, LogLevels.WARN) { "Command $trimmed failed to parse!" }
throw IllegalArgumentException("Empty command stack! Did the command fail to parse?") throw IllegalArgumentException("Empty command stack! Did the command fail to parse?")
} }
@ -126,11 +128,11 @@ class SessionUtil(
try { try {
val privateKey = keyManagement.key val privateKey = keyManagement.key
privateKey?.let { SignatureKeyManagement.verify(privateKey, time) } privateKey?.let { SignatureKeyManagement.verify(privateKey, time) }
if (privateKey != null && session.network.encrypted && session.profiles.session.signature.signCommands) { if (privateKey != null && (session.connection is NetworkConnection && session.connection.client!!.encrypted) && session.profiles.session.signature.signCommands) {
signature = stack.sign(signer, privateKey.private, salt, time) signature = stack.sign(signer, privateKey.private, salt, time)
} }
session.network.send(CommandC2SP(trimmed, time, salt, signature, false, acknowledgement)) session.connection.send(CommandC2SP(trimmed, time, salt, signature, false, acknowledgement))
} finally { } finally {
keyManagement.release() keyManagement.release()
} }
@ -155,6 +157,6 @@ class SessionUtil(
} }
fun respawn() { fun respawn() {
session.network.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN)) session.connection.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN))
} }
} }

View File

@ -12,6 +12,8 @@
*/ */
package de.bixilon.minosoft.protocol.packets.s2c.common package de.bixilon.minosoft.protocol.packets.s2c.common
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket
import de.bixilon.minosoft.protocol.protocol.buffers.play.PlayInByteBuffer import de.bixilon.minosoft.protocol.protocol.buffers.play.PlayInByteBuffer
@ -24,7 +26,7 @@ class CompressionS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
session.network.setupCompression(threshold) session.connection.unsafeCast<NetworkConnection>().client!!.setupCompression(threshold)
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -34,7 +34,7 @@ class HeartbeatS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
} }
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
session.network.send(HeartbeatC2SP(id)) session.connection.send(HeartbeatC2SP(id))
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -12,8 +12,10 @@
*/ */
package de.bixilon.minosoft.protocol.packets.s2c.common package de.bixilon.minosoft.protocol.packets.s2c.common
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.data.text.ChatComponent import de.bixilon.minosoft.data.text.ChatComponent
import de.bixilon.minosoft.modding.event.events.KickEvent import de.bixilon.minosoft.modding.event.events.KickEvent
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.network.session.play.PlaySessionStates import de.bixilon.minosoft.protocol.network.session.play.PlaySessionStates
import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket
@ -25,7 +27,7 @@ import de.bixilon.minosoft.util.logging.LogLevels
import de.bixilon.minosoft.util.logging.LogMessageType import de.bixilon.minosoft.util.logging.LogMessageType
class KickS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket { class KickS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
val reason: ChatComponent = if (buffer.session.network.state == ProtocolStates.LOGIN && buffer.versionId >= V_23W42A) buffer.readChatComponent() else buffer.readNbtChatComponent() val reason: ChatComponent = if (buffer.session.connection.unsafeCast<NetworkConnection>().state == ProtocolStates.LOGIN && buffer.versionId >= V_23W42A) buffer.readChatComponent() else buffer.readNbtChatComponent()
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
if (!session.connection.active) { if (!session.connection.active) {
@ -34,7 +36,7 @@ class KickS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
session.events.fire(KickEvent(session, reason)) session.events.fire(KickEvent(session, reason))
// got kicked // got kicked
session.terminate() session.terminate()
if (session.network.state == ProtocolStates.LOGIN) { if (session.connection.unsafeCast<NetworkConnection>().state == ProtocolStates.LOGIN) {
session.state = PlaySessionStates.ERROR session.state = PlaySessionStates.ERROR
} else { } else {
session.state = PlaySessionStates.KICKED session.state = PlaySessionStates.KICKED

View File

@ -25,7 +25,7 @@ class PingS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
val payload = buffer.readInt() val payload = buffer.readInt()
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
session.network.send(PongC2SP(payload)) session.connection.send(PongC2SP(payload))
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -50,7 +50,7 @@ class ResourcepackS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
if (session.events.fire(event)) { if (session.events.fire(event)) {
return return
} }
session.network.send(ResourcepackC2SP(uuid, hash, ResourcepackC2SP.ResourcePackStates.SUCCESSFULLY)) // ToDo: This fakes it, to not get kicked on most servers session.connection.send(ResourcepackC2SP(uuid, hash, ResourcepackC2SP.ResourcePackStates.SUCCESSFULLY)) // ToDo: This fakes it, to not get kicked on most servers
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -12,6 +12,8 @@
*/ */
package de.bixilon.minosoft.protocol.packets.s2c.configuration package de.bixilon.minosoft.protocol.packets.s2c.configuration
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.c2s.configuration.ReadyC2SP import de.bixilon.minosoft.protocol.packets.c2s.configuration.ReadyC2SP
import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket
@ -26,8 +28,8 @@ class ReadyS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
session.util.prepareSpawn() session.util.prepareSpawn()
session.network.send(ReadyC2SP()) session.connection.send(ReadyC2SP())
session.network.state = ProtocolStates.PLAY session.connection.unsafeCast<NetworkConnection>().state = ProtocolStates.PLAY
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -14,6 +14,8 @@ package de.bixilon.minosoft.protocol.packets.s2c.login
import com.google.common.primitives.Longs import com.google.common.primitives.Longs
import de.bixilon.kutil.base64.Base64Util.toBase64 import de.bixilon.kutil.base64.Base64Util.toBase64
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.c2s.login.EncryptionC2SP import de.bixilon.minosoft.protocol.packets.c2s.login.EncryptionC2SP
import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket
@ -56,12 +58,12 @@ class EncryptionS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
signature.update(Longs.toByteArray(salt)) signature.update(Longs.toByteArray(salt))
val signed = signature.sign() val signed = signature.sign()
session.network.send(EncryptionC2SP(encryptedSecretKey, EncryptionSignatureData(salt, signed))) session.connection.send(EncryptionC2SP(encryptedSecretKey, EncryptionSignatureData(salt, signed)))
} else { } else {
session.network.send(EncryptionC2SP(encryptedSecretKey, CryptManager.encryptData(publicKey, nonce))) session.connection.send(EncryptionC2SP(encryptedSecretKey, CryptManager.encryptData(publicKey, nonce)))
} }
session.network.setupEncryption(encryptCipher, decryptCipher) session.connection.unsafeCast<NetworkConnection>().client!!.setupEncryption(encryptCipher, decryptCipher)
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -12,9 +12,10 @@
*/ */
package de.bixilon.minosoft.protocol.packets.s2c.login package de.bixilon.minosoft.protocol.packets.s2c.login
import de.bixilon.kutil.primitive.BooleanUtil.decide import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.data.entities.entities.player.properties.PlayerProperties import de.bixilon.minosoft.data.entities.entities.player.properties.PlayerProperties
import de.bixilon.minosoft.data.text.ChatComponent import de.bixilon.minosoft.data.text.ChatComponent
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.network.session.play.channel.vanila.BrandHandler.sendBrand import de.bixilon.minosoft.protocol.network.session.play.channel.vanila.BrandHandler.sendBrand
import de.bixilon.minosoft.protocol.packets.c2s.login.ConfigureC2SP import de.bixilon.minosoft.protocol.packets.c2s.login.ConfigureC2SP
@ -28,18 +29,18 @@ import de.bixilon.minosoft.util.logging.LogMessageType
import java.util.* import java.util.*
class SuccessS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket { class SuccessS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
val uuid: UUID = (buffer.versionId < ProtocolVersions.V_20W12A).decide({ buffer.readUUIDString() }, { buffer.readUUID() }) val uuid: UUID = if (buffer.versionId < ProtocolVersions.V_20W12A) buffer.readUUIDString() else buffer.readUUID()
val name: String = buffer.readString() val name: String = buffer.readString()
val properties: PlayerProperties? = if (buffer.versionId >= ProtocolVersions.V_22W17A) buffer.readPlayerProperties() else null val properties: PlayerProperties? = if (buffer.versionId >= ProtocolVersions.V_22W17A) buffer.readPlayerProperties() else null
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
if (session.version.hasConfigurationState) { if (session.version.hasConfigurationState) {
session.network.send(ConfigureC2SP()) session.connection.send(ConfigureC2SP())
session.network.state = ProtocolStates.CONFIGURATION session.connection.unsafeCast<NetworkConnection>().state = ProtocolStates.CONFIGURATION
session.sendBrand() session.sendBrand()
session.settingsManager.sendClientSettings() session.settingsManager.sendClientSettings()
} else { } else {
session.network.state = ProtocolStates.PLAY session.connection.unsafeCast<NetworkConnection>().state = ProtocolStates.PLAY
} }
val playerEntity = session.player val playerEntity = session.player

View File

@ -12,6 +12,8 @@
*/ */
package de.bixilon.minosoft.protocol.packets.s2c.play package de.bixilon.minosoft.protocol.packets.s2c.play
import de.bixilon.kutil.cast.CastUtil.unsafeCast
import de.bixilon.minosoft.protocol.connection.NetworkConnection
import de.bixilon.minosoft.protocol.network.session.play.PlaySession import de.bixilon.minosoft.protocol.network.session.play.PlaySession
import de.bixilon.minosoft.protocol.packets.c2s.play.ReconfigureC2SP import de.bixilon.minosoft.protocol.packets.c2s.play.ReconfigureC2SP
import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket import de.bixilon.minosoft.protocol.packets.s2c.PlayS2CPacket
@ -26,8 +28,8 @@ class ReconfigureS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
override fun handle(session: PlaySession) { override fun handle(session: PlaySession) {
session.util.resetWorld() session.util.resetWorld()
session.network.send(ReconfigureC2SP()) session.connection.send(ReconfigureC2SP())
session.network.state = ProtocolStates.CONFIGURATION session.connection.unsafeCast<NetworkConnection>().state = ProtocolStates.CONFIGURATION
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -35,7 +35,7 @@ class MoveVehicleS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
} }
vehicle.forceTeleport(position) vehicle.forceTeleport(position)
vehicle.forceRotate(EntityRotation(yaw, pitch)) vehicle.forceRotate(EntityRotation(yaw, pitch))
session.network.send(MoveVehicleC2SP(vehicle.physics.position, vehicle.physics.rotation)) session.connection.send(MoveVehicleC2SP(vehicle.physics.position, vehicle.physics.rotation))
} }
override fun log(reducedLog: Boolean) { override fun log(reducedLog: Boolean) {

View File

@ -86,9 +86,9 @@ class PositionRotationS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
entity.forceRotate(EntityRotation(yaw, pitch)) entity.forceRotate(EntityRotation(yaw, pitch))
if (session.version.versionId >= ProtocolVersions.V_15W42A) { if (session.version.versionId >= ProtocolVersions.V_15W42A) {
session.network.send(ConfirmTeleportC2SP(teleportId)) session.connection.send(ConfirmTeleportC2SP(teleportId))
} }
session.network.send(PositionRotationC2SP(position, position.y + entity.physics.eyeHeight, rotation, onGround)) session.connection.send(PositionRotationC2SP(position, position.y + entity.physics.eyeHeight, rotation, onGround))
if (session.state == PlaySessionStates.SPAWNING) { if (session.state == PlaySessionStates.SPAWNING) {
session.state = PlaySessionStates.PLAYING session.state = PlaySessionStates.PLAYING

View File

@ -47,7 +47,7 @@ class HealthS2CP(buffer: PlayInByteBuffer) : PlayS2CPacket {
} }
if (session.profiles.session.autoRespawn) { if (session.profiles.session.autoRespawn) {
session.network.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN)) session.connection.send(ClientActionC2SP(ClientActionC2SP.ClientActions.PERFORM_RESPAWN))
} }
} }
} }

View File

@ -44,7 +44,7 @@ object SessionManageCommand : Command {
LiteralNode("select").apply { LiteralNode("select").apply {
addFilter(false) { stack, sessions -> addFilter(false) { stack, sessions ->
val session = sessions.first() val session = sessions.first()
if (session.network.connection.state == null) { if (!session.connection.active) {
throw CommandException("Session $session not established anymore!") throw CommandException("Session $session not established anymore!")
} }
CLI.session = session CLI.session = session

View File

@ -25,7 +25,7 @@ object DebugCommand : SessionCommand {
override var node = LiteralNode("debug") override var node = LiteralNode("debug")
.addChild(LiteralNode("allowFly", executor = { it.fly() }, allowArguments = true).addChild(ArgumentNode("value", BooleanParser, executable = true))) .addChild(LiteralNode("allowFly", executor = { it.fly() }, allowArguments = true).addChild(ArgumentNode("value", BooleanParser, executable = true)))
.addChild(LiteralNode("network").addChild( .addChild(LiteralNode("network").addChild(
LiteralNode("detach", executor = { it.session.network.detach(); it.print.sendDebugMessage("Now you are alone on the wire...") }), LiteralNode("detach", executor = { it.session.connection.detach(); it.print.sendDebugMessage("Now you are alone on the wire...") }),
)) ))
.addChild(LiteralNode("cache").addChild(LiteralNode("biome", executor = { it.session.world.biomes.resetCache(); it.print.sendDebugMessage("Biome cache cleared!") }))) .addChild(LiteralNode("cache").addChild(LiteralNode("biome", executor = { it.session.world.biomes.resetCache(); it.print.sendDebugMessage("Biome cache cleared!") })))

View File

@ -294,7 +294,7 @@ object KUtil {
URLProtocolStreamHandlers.register("resource", ResourceURLHandler) URLProtocolStreamHandlers.register("resource", ResourceURLHandler)
ShutdownManager += { ShutdownManager += {
for (session in PlaySession.ACTIVE_CONNECTIONS.toSynchronizedSet()) { for (session in PlaySession.ACTIVE_CONNECTIONS.toSynchronizedSet()) {
session.network.disconnect() session.terminate()
} }
} }
ShutdownManager += { ShutdownManager += {