diff --git a/common/src/main/scala/net/psforever/objects/GlobalDefinitions.scala b/common/src/main/scala/net/psforever/objects/GlobalDefinitions.scala index 6d961e8fc..917fc4522 100644 --- a/common/src/main/scala/net/psforever/objects/GlobalDefinitions.scala +++ b/common/src/main/scala/net/psforever/objects/GlobalDefinitions.scala @@ -1228,17 +1228,86 @@ object GlobalDefinitions { fury_weapon_systema.FireModes.head.AmmoSlotIndex = 0 fury_weapon_systema.FireModes.head.Magazine = 2 + val + quadassault_weapon_system = ToolDefinition(ObjectClass.quadassault_weapon_system) + quadassault_weapon_system.Size = EquipmentSize.VehicleWeapon + quadassault_weapon_system.AmmoTypes += Ammo.bullet_12mm + quadassault_weapon_system.FireModes += new FireModeDefinition + quadassault_weapon_system.FireModes.head.AmmoTypeIndices += 0 + quadassault_weapon_system.FireModes.head.AmmoSlotIndex = 0 + quadassault_weapon_system.FireModes.head.Magazine = 100 + + val + chaingun_p = ToolDefinition(ObjectClass.chaingun_p) + chaingun_p.Size = EquipmentSize.VehicleWeapon + chaingun_p.AmmoTypes += Ammo.bullet_12mm + chaingun_p.FireModes += new FireModeDefinition + chaingun_p.FireModes.head.AmmoTypeIndices += 0 + chaingun_p.FireModes.head.AmmoSlotIndex = 0 + chaingun_p.FireModes.head.Magazine = 150 + val fury = VehicleDefinition(ObjectClass.fury) fury.Seats += 0 -> new SeatDefinition() fury.Seats(0).Bailable = true - fury.Seats(0).ControlledWeapon = Some(1) + fury.Seats(0).ControlledWeapon = 1 fury.MountPoints += 0 -> 0 fury.MountPoints += 2 -> 0 fury.Weapons += 1 -> fury_weapon_systema fury.TrunkSize = InventoryTile(11, 11) fury.TrunkOffset = 30 + val + quadassault = VehicleDefinition(ObjectClass.quadassault) + quadassault.Seats += 0 -> new SeatDefinition() + quadassault.Seats(0).Bailable = true + quadassault.Seats(0).ControlledWeapon = 1 + quadassault.MountPoints += 0 -> 0 + quadassault.MountPoints += 2 -> 0 + quadassault.Weapons += 1 -> quadassault_weapon_system + quadassault.TrunkSize = InventoryTile(11, 11) + quadassault.TrunkOffset = 30 + + val + quadstealth = VehicleDefinition(ObjectClass.quadstealth) + quadstealth.CanCloak = true + quadstealth.Seats += 0 -> new SeatDefinition() + quadstealth.Seats(0).Bailable = true + quadstealth.MountPoints += 0 -> 0 + quadstealth.MountPoints += 2 -> 0 + quadstealth.CanCloak = true + quadstealth.TrunkSize = InventoryTile(11, 11) + quadstealth.TrunkOffset = 30 + + val + two_man_assault_buggy = VehicleDefinition(ObjectClass.two_man_assault_buggy) + two_man_assault_buggy.Seats += 0 -> new SeatDefinition() + two_man_assault_buggy.Seats(0).Bailable = true + two_man_assault_buggy.Seats += 1 -> new SeatDefinition() + two_man_assault_buggy.Seats(1).Bailable = true + two_man_assault_buggy.Seats(1).ControlledWeapon = 2 + two_man_assault_buggy.MountPoints += 1 -> 0 + two_man_assault_buggy.MountPoints += 2 -> 1 + two_man_assault_buggy.Weapons += 2 -> chaingun_p + two_man_assault_buggy.TrunkSize = InventoryTile(11, 11) + two_man_assault_buggy.TrunkOffset = 30 + + val + phantasm = VehicleDefinition(ObjectClass.phantasm) + phantasm.CanCloak = true + phantasm.Seats += 0 -> new SeatDefinition() + phantasm.Seats += 1 -> new SeatDefinition() + phantasm.Seats(1).Bailable = true + phantasm.Seats += 2 -> new SeatDefinition() + phantasm.Seats(2).Bailable = true + phantasm.Seats += 3 -> new SeatDefinition() + phantasm.Seats(3).Bailable = true + phantasm.Seats += 4 -> new SeatDefinition() + phantasm.Seats(4).Bailable = true + phantasm.MountPoints += 1 -> 0 //TODO add and check all + phantasm.TrunkSize = InventoryTile(11, 8) + phantasm.TrunkOffset = 30 //TODO check + val order_terminal = new OrderTerminalDefinition val diff --git a/common/src/main/scala/net/psforever/objects/Vehicle.scala b/common/src/main/scala/net/psforever/objects/Vehicle.scala index 206fc78ff..ab1608b20 100644 --- a/common/src/main/scala/net/psforever/objects/Vehicle.scala +++ b/common/src/main/scala/net/psforever/objects/Vehicle.scala @@ -4,11 +4,13 @@ package net.psforever.objects import net.psforever.objects.definition.VehicleDefinition import net.psforever.objects.equipment.{Equipment, EquipmentSize} import net.psforever.objects.inventory.GridInventory -import net.psforever.objects.vehicles.{Seat, Utility, VehicleLockState} +import net.psforever.objects.serverobject.PlanetSideServerObject +import net.psforever.objects.vehicles.{AccessPermissionGroup, Seat, Utility, VehicleLockState} import net.psforever.packet.game.PlanetSideGUID import net.psforever.packet.game.objectcreate.DriveState import net.psforever.types.PlanetSideEmpire +import scala.annotation.tailrec import scala.collection.mutable /** @@ -17,29 +19,31 @@ import scala.collection.mutable * All infantry seating, all mounted weapons, and the trunk space are considered part of the same index hierarchy. * Generally, all seating is declared first - the driver and passengers and and gunners. * Following that are the mounted weapons and other utilities. - * Trunk space starts being indexed afterwards. - * The first seat is always the op;erator (driver/pilot). - * "Passengers" are seats that are not the operator and are not in control of a mounted weapon. - * "Gunners" are seats that are not the operator and ARE in control of a mounted weapon. - * (The operator can be in control of a weapon - that is the whole point of a turret.)
+ * Trunk space starts being indexed afterwards.
*
- * Having said all that, to keep it simple, infantry seating, mounted weapons, and utilities are stored in separate `Map`s. - * @param vehicleDef the vehicle's definition entry' + * To keep it simple, infantry seating, mounted weapons, and utilities are stored separately. + * @param vehicleDef the vehicle's definition entry'; * stores and unloads pertinent information about the `Vehicle`'s configuration; * used in the initialization process (`loadVehicleDefinition`) */ -class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGameObject { +class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideServerObject { private var faction : PlanetSideEmpire.Value = PlanetSideEmpire.TR private var owner : Option[PlanetSideGUID] = None private var health : Int = 1 private var shields : Int = 0 private var deployed : DriveState.Value = DriveState.Mobile private var decal : Int = 0 - private var trunkLockState : VehicleLockState.Value = VehicleLockState.Locked private var trunkAccess : Option[PlanetSideGUID] = None + private var jammered : Boolean = false + private var cloaked : Boolean = false - private val seats : mutable.HashMap[Int, Seat] = mutable.HashMap() - private val weapons : mutable.HashMap[Int, EquipmentSlot] = mutable.HashMap() + /** + * Permissions control who gets to access different parts of the vehicle; + * the groups are Driver (seat), Gunner (seats), Passenger (seats), and the Trunk + */ + private val groupPermissions : Array[VehicleLockState.Value] = Array(VehicleLockState.Locked, VehicleLockState.Empire, VehicleLockState.Empire, VehicleLockState.Locked) + private var seats : Map[Int, Seat] = Map.empty + private var weapons : Map[Int, EquipmentSlot] = Map.empty private val utilities : mutable.ArrayBuffer[Utility] = mutable.ArrayBuffer() private val trunk : GridInventory = GridInventory() @@ -68,8 +72,15 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame } def Owner_=(owner : Option[PlanetSideGUID]) : Option[PlanetSideGUID] = { - this.owner = owner - owner + owner match { + case Some(_) => + if(Definition.CanBeOwned) { + this.owner = owner + } + case None => + this.owner = None + } + Owner } def Health : Int = { @@ -98,15 +109,15 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame vehicleDef.MaxShields } - def Configuration : DriveState.Value = { + def Drive : DriveState.Value = { this.deployed } - def Configuration_=(deploy : DriveState.Value) : DriveState.Value = { + def Drive_=(deploy : DriveState.Value) : DriveState.Value = { if(vehicleDef.Deployment) { this.deployed = deploy } - Configuration + Drive } def Decal : Int = { @@ -118,6 +129,20 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame decal } + def Jammered : Boolean = jammered + + def Jammered_=(jamState : Boolean) : Boolean = { + jammered = jamState + Jammered + } + + def Cloaked : Boolean = cloaked + + def Cloaked_=(isCloaked : Boolean) : Boolean = { + cloaked = isCloaked + Cloaked + } + /** * Given the index of an entry mounting point, return the infantry-accessible `Seat` associated with it. * @param mountPoint an index representing the seat position / mounting point @@ -127,6 +152,60 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame vehicleDef.MountPoints.get(mountPoint) } + /** + * What are the access permissions for a position on this vehicle, seats or trunk? + * @param group the group index + * @return what sort of access permission exist for this group + */ + def PermissionGroup(group : Int) : Option[VehicleLockState.Value] = { + reindexPermissionsGroup(group) match { + case Some(index) => + Some(groupPermissions(index)) + case None => + None + } + } + + /** + * Change the access permissions for a position on this vehicle, seats or trunk. + * @param group the group index + * @param level the new permission for this group + * @return the new access permission for this group; + * `None`, if the group does not exist or the level of permission was not changed + */ + def PermissionGroup(group : Int, level : Long) : Option[VehicleLockState.Value] = { + reindexPermissionsGroup(group) match { + case Some(index) => + val current = groupPermissions(index) + val next = try { VehicleLockState(level.toInt) } catch { case _ : Exception => groupPermissions(index) } + if(current != next) { + groupPermissions(index) = next + PermissionGroup(index) + } + else { + None + } + case None => + None + } + } + + /** + * When the access permission group is communicated via `PlanetsideAttributeMessage`, the index is between 10 and 13. + * Internally, permission groups are stored as an `Array`, so the respective re-indexing plots 10 -> 0 and 13 -> 3. + * @param group the group index + * @return the modified group index + */ + private def reindexPermissionsGroup(group : Int) : Option[Int] = if(group > 9 && group < 14) { + Some(group - 10) + } + else if(group > -1 && group < 4) { + Some(group) + } + else { + None + } + /** * Get the seat at the index. * The specified "seat" can only accommodate a player as opposed to weapon mounts which share the same indexing system. @@ -146,7 +225,26 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame seats.values.toList } - def Weapons : mutable.HashMap[Int, EquipmentSlot] = weapons + def SeatPermissionGroup(seatNumber : Int) : Option[AccessPermissionGroup.Value] = { + if(seatNumber == 0) { + Some(AccessPermissionGroup.Driver) + } + else { + Seat(seatNumber) match { + case Some(seat) => + seat.ControlledWeapon match { + case Some(_) => + Some(AccessPermissionGroup.Gunner) + case None => + Some(AccessPermissionGroup.Passenger) + } + case None => + None + } + } + } + + def Weapons : Map[Int, EquipmentSlot] = weapons /** * Get the weapon at the index. @@ -164,20 +262,25 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame } /** - * Given a player who may be a passenger, retrieve an index where this player is seated. + * Given a player who may be an occupant, retrieve an number of the seat where this player is sat. * @param player the player - * @return a seat by index, or `None` if the `player` is not actually seated in this `Vehicle` + * @return a seat number, or `None` if the `player` is not actually seated in this vehicle */ - def PassengerInSeat(player : Player) : Option[Int] = { - var outSeat : Option[Int] = None - val GUID = player.GUID - for((seatNumber, seat) <- this.seats) { - val occupant : Option[PlanetSideGUID] = seat.Occupant - if(occupant.isDefined && occupant.get == GUID) { - outSeat = Some(seatNumber) + def PassengerInSeat(player : Player) : Option[Int] = recursivePassengerInSeat(seats.iterator, player) + + @tailrec private def recursivePassengerInSeat(iter : Iterator[(Int, Seat)], player : Player) : Option[Int] = { + if(!iter.hasNext) { + None + } + else { + val (seatNumber, seat) = iter.next + if(seat.Occupant.contains(player)) { + Some(seatNumber) + } + else { + recursivePassengerInSeat(iter, player) } } - outSeat } /** @@ -267,7 +370,7 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame */ def CanAccessTrunk(player : Player) : Boolean = { if(trunkAccess.isEmpty || trunkAccess.contains(player.GUID)) { - trunkLockState match { + groupPermissions(3) match { case VehicleLockState.Locked => //only the owner owner.isEmpty || (owner.isDefined && player.GUID == owner.get) case VehicleLockState.Group => //anyone in the owner's squad or platoon @@ -285,19 +388,7 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame * Check access to the `Trunk`. * @return the current access value for the `Vehicle` `Trunk` */ - def TrunkLockState : VehicleLockState.Value = { - this.trunkLockState - } - - /** - * Change the access value for the trunk. - * @param lockState the new access value for the `Vehicle` `Trunk` - * @return the current access value for the `Vehicle` `Trunk` after the change - */ - def TrunkLockState_=(lockState : VehicleLockState.Value) : VehicleLockState.Value = { - this.trunkLockState = lockState - lockState - } + def TrunkLockState : VehicleLockState.Value = groupPermissions(3) /** * This is the definition entry that is used to store and unload pertinent information about the `Vehicle`. @@ -316,22 +407,52 @@ class Vehicle(private val vehicleDef : VehicleDefinition) extends PlanetSideGame object Vehicle { /** - * Overloaded constructor. - * @param vehicleDef the vehicle's definition entry - * @return a `Vwehicle` object + * A basic `Trait` connecting all of the actionable `Vehicle` response messages. */ - def apply(vehicleDef : VehicleDefinition) : Vehicle = { - new Vehicle(vehicleDef) - } + sealed trait Exchange + + /** + * Message that carries the result of the processed request message back to the original user (`player`). + * @param player the player who sent this request message + * @param response the result of the processed request + */ + final case class VehicleMessages(player : Player, response : Exchange) + + /** + * The `Vehicle` will become unresponsive to player activity. + * Usually, it does this to await deconstruction and clean-up + * @see `VehicleControl` + */ + final case class PrepareForDeletion() + + /** + * This player wants to sit down in an available(?) seat. + * @param seat_num the seat where the player is trying to occupy; + * this is NOT the entry mount point index; + * make certain to convert! + * @param player the `Player` object + */ + final case class TrySeatPlayer(seat_num : Int, player : Player) + /** + * The recipient player of this packet is being allowed to sit in the assigned seat. + * @param vehicle the `Vehicle` object that generated this message + * @param seat_num the seat that the player will occupy + */ + final case class CanSeatPlayer(vehicle : Vehicle, seat_num : Int) extends Exchange + /** + * The recipient player of this packet is not allowed to sit in the requested seat. + * @param vehicle the `Vehicle` object that generated this message + * @param seat_num the seat that the player can not occupy + */ + final case class CannotSeatPlayer(vehicle : Vehicle, seat_num : Int) extends Exchange + /** * Overloaded constructor. * @param vehicleDef the vehicle's definition entry - * @return a `Vwehicle` object + * @return a `Vehicle` object */ - def apply(guid : PlanetSideGUID, vehicleDef : VehicleDefinition) : Vehicle = { - val obj = new Vehicle(vehicleDef) - obj.GUID = guid - obj + def apply(vehicleDef : VehicleDefinition) : Vehicle = { + new Vehicle(vehicleDef) } /** @@ -344,16 +465,13 @@ object Vehicle { //general stuff vehicle.Health = vdef.MaxHealth //create weapons - for((num, definition) <- vdef.Weapons) { + vehicle.weapons = vdef.Weapons.map({case (num, definition) => val slot = EquipmentSlot(EquipmentSize.VehicleWeapon) slot.Equipment = Tool(definition) - vehicle.weapons += num -> slot - vehicle - } + num -> slot + }).toMap //create seats - for((num, seatDef) <- vdef.Seats) { - vehicle.seats += num -> Seat(seatDef, vehicle) - } + vehicle.seats = vdef.Seats.map({ case(num, definition) => num -> Seat(definition)}).toMap for(i <- vdef.Utilities) { //TODO utilies must be loaded and wired on a case-by-case basis? vehicle.Utilities += Utility.Select(i, vehicle) diff --git a/common/src/main/scala/net/psforever/objects/definition/SeatDefinition.scala b/common/src/main/scala/net/psforever/objects/definition/SeatDefinition.scala index 5535274e2..f1b12915c 100644 --- a/common/src/main/scala/net/psforever/objects/definition/SeatDefinition.scala +++ b/common/src/main/scala/net/psforever/objects/definition/SeatDefinition.scala @@ -37,8 +37,12 @@ class SeatDefinition extends BasicDefinition { this.weaponMount } - def ControlledWeapon_=(seat : Option[Int]) : Option[Int] = { - this.weaponMount = seat + def ControlledWeapon_=(wep : Int) : Option[Int] = { + ControlledWeapon_=(Some(wep)) + } + + def ControlledWeapon_=(wep : Option[Int]) : Option[Int] = { + this.weaponMount = wep ControlledWeapon } } diff --git a/common/src/main/scala/net/psforever/objects/definition/VehicleDefinition.scala b/common/src/main/scala/net/psforever/objects/definition/VehicleDefinition.scala index d7c67fe6c..708741ef7 100644 --- a/common/src/main/scala/net/psforever/objects/definition/VehicleDefinition.scala +++ b/common/src/main/scala/net/psforever/objects/definition/VehicleDefinition.scala @@ -22,7 +22,9 @@ class VehicleDefinition(objectId : Int) extends ObjectDefinition(objectId) { private var deployment : Boolean = false private val utilities : mutable.ArrayBuffer[Int] = mutable.ArrayBuffer[Int]() private var trunkSize : InventoryTile = InventoryTile.None - private var trunkOffset: Int = 0 + private var trunkOffset : Int = 0 + private var canCloak : Boolean = false + private var canBeOwned : Boolean = true Name = "vehicle" Packet = new VehicleConverter @@ -44,6 +46,20 @@ class VehicleDefinition(objectId : Int) extends ObjectDefinition(objectId) { def MountPoints : mutable.HashMap[Int, Int] = mountPoints + def CanBeOwned : Boolean = canBeOwned + + def CanBeOwned_=(ownable : Boolean) : Boolean = { + canBeOwned = ownable + CanBeOwned + } + + def CanCloak : Boolean = canCloak + + def CanCloak_=(cloakable : Boolean) : Boolean = { + canCloak = cloakable + CanCloak + } + def Weapons : mutable.HashMap[Int, ToolDefinition] = weapons def Deployment : Boolean = deployment diff --git a/common/src/main/scala/net/psforever/objects/definition/converter/VehicleConverter.scala b/common/src/main/scala/net/psforever/objects/definition/converter/VehicleConverter.scala index 064093674..2517e8c8c 100644 --- a/common/src/main/scala/net/psforever/objects/definition/converter/VehicleConverter.scala +++ b/common/src/main/scala/net/psforever/objects/definition/converter/VehicleConverter.scala @@ -2,11 +2,10 @@ package net.psforever.objects.definition.converter import net.psforever.objects.equipment.Equipment -import net.psforever.objects.{EquipmentSlot, Vehicle} +import net.psforever.objects.Vehicle import net.psforever.packet.game.PlanetSideGUID import net.psforever.packet.game.objectcreate.{InventoryItemData, _} -import scala.annotation.tailrec import scala.util.{Failure, Success, Try} class VehicleConverter extends ObjectCreateConverter[Vehicle]() { @@ -19,47 +18,66 @@ class VehicleConverter extends ObjectCreateConverter[Vehicle]() { PlacementData(obj.Position, obj.Orientation, obj.Velocity), obj.Faction, 0, - if(obj.Owner.isDefined) { obj.Owner.get } else { PlanetSideGUID(0) } //this is the owner field, right? + PlanetSideGUID(0) //if(obj.Owner.isDefined) { obj.Owner.get } else { PlanetSideGUID(0) } //TODO is this really Owner? ), 0, obj.Health / obj.MaxHealth * 255, //TODO not precise false, false, - DriveState.Mobile, - false, + obj.Drive, false, false, + obj.Cloaked, SpecificFormatData(obj), - Some(InventoryData(MakeMountings(obj).sortBy(_.parentSlot))) + Some(InventoryData((MakeMountings(obj) ++ MakeTrunk(obj)).sortBy(_.parentSlot))) )(SpecificFormatModifier) ) } /** - * For an object with a list of weapon mountings, convert those weapons into data as if found in an `0x17` packet. - * @param obj the Vehicle game object - * @return the converted data + * na + * @param obj the `Player` game object + * @return a list of all tools that were in the mounted weapon slots in decoded packet form */ - private def MakeMountings(obj : Vehicle) : List[InventoryItemData.InventoryItem] = recursiveMakeMountings(obj.Weapons.iterator) - - @tailrec private def recursiveMakeMountings(iter : Iterator[(Int,EquipmentSlot)], list : List[InventoryItemData.InventoryItem] = Nil) : List[InventoryItemData.InventoryItem] = { - if(!iter.hasNext) { - list - } - else { - val (index, slot) = iter.next - if(slot.Equipment.isDefined) { + private def MakeMountings(obj : Vehicle) : List[InventoryItemData.InventoryItem] = { + obj.Weapons.map({ + case((index, slot)) => val equip : Equipment = slot.Equipment.get - recursiveMakeMountings( - iter, - list :+ InventoryItemData(equip.Definition.ObjectId, equip.GUID, index, equip.Definition.Packet.ConstructorData(equip).get) - ) - } - else { - recursiveMakeMountings(iter, list) - } - } + InventoryItemData(equip.Definition.ObjectId, equip.GUID, index, equip.Definition.Packet.ConstructorData(equip).get) + }).toList } + /** + * na + * @param obj the `Player` game object + * @return a list of all items that were in the inventory in decoded packet form + */ + private def MakeTrunk(obj : Vehicle) : List[InternalSlot] = { + obj.Trunk.Items.map({ + case(_, item) => + val equip : Equipment = item.obj + InventoryItemData(equip.Definition.ObjectId, equip.GUID, item.start, equip.Definition.Packet.ConstructorData(equip).get) + }).toList + } + +// @tailrec private def recursiveMakeSeats(iter : Iterator[(Int, Seat)], list : List[InventoryItemData.InventoryItem] = Nil) : List[InventoryItemData.InventoryItem] = { +// if(!iter.hasNext) { +// list +// } +// else { +// val (index, seat) = iter.next +// seat.Occupant match { +// case Some(avatar) => +// val definition = avatar.Definition +// recursiveMakeSeats( +// iter, +// list :+ InventoryItemData(definition.ObjectId, avatar.GUID, index, definition.Packet.ConstructorData(avatar).get) +// ) +// case None => +// recursiveMakeSeats(iter, list) +// } +// } +// } + protected def SpecificFormatModifier : VehicleFormat.Value = VehicleFormat.Normal protected def SpecificFormatData(obj : Vehicle) : Option[SpecificVehicleData] = None diff --git a/common/src/main/scala/net/psforever/objects/equipment/EquipmentSize.scala b/common/src/main/scala/net/psforever/objects/equipment/EquipmentSize.scala index 484d91609..16ffebb99 100644 --- a/common/src/main/scala/net/psforever/objects/equipment/EquipmentSize.scala +++ b/common/src/main/scala/net/psforever/objects/equipment/EquipmentSize.scala @@ -9,6 +9,8 @@ object EquipmentSize extends Enumeration { Rifle, //6x3 and 9x3 Max, //max weapon only VehicleWeapon, //vehicle-mounted weapons + BFRArmWeapon, //duel arm weapons for bfr + BFRGunnerWeapon, //gunner seat for bfr Inventory, //reserved Any = Value diff --git a/common/src/main/scala/net/psforever/objects/inventory/AccessibleInventory.scala b/common/src/main/scala/net/psforever/objects/inventory/AccessibleInventory.scala new file mode 100644 index 000000000..d0d5e15ef --- /dev/null +++ b/common/src/main/scala/net/psforever/objects/inventory/AccessibleInventory.scala @@ -0,0 +1,13 @@ +// Copyright (c) 2017 PSForever +package net.psforever.objects.inventory + +import net.psforever.objects.Player +import net.psforever.packet.game.PlanetSideGUID + +trait AccessibleInventory { + def Inventory : GridInventory + + def CanAccess(who : Player) : Boolean + def Access(who : PlanetSideGUID) : Boolean + def Unaccess : Boolean +} \ No newline at end of file diff --git a/common/src/main/scala/net/psforever/objects/serverobject/terminals/CertTerminalDefinition.scala b/common/src/main/scala/net/psforever/objects/serverobject/terminals/CertTerminalDefinition.scala index dbab72d77..8f990196e 100644 --- a/common/src/main/scala/net/psforever/objects/serverobject/terminals/CertTerminalDefinition.scala +++ b/common/src/main/scala/net/psforever/objects/serverobject/terminals/CertTerminalDefinition.scala @@ -18,7 +18,7 @@ class CertTerminalDefinition extends TerminalDefinition(171) { */ private val certificationList : Map[String, (CertificationType.Value, Int)] = Map( "medium_assault" -> (CertificationType.MediumAssault, 2), - "reinforced_armo" -> (CertificationType.ReinforcedExoSuit, 3), + "reinforced_armor" -> (CertificationType.ReinforcedExoSuit, 3), "quad_all" -> (CertificationType.ATV, 1), "switchblade" -> (CertificationType.Switchblade, 1), "harasser" -> (CertificationType.Harasser, 1), diff --git a/common/src/main/scala/net/psforever/objects/vehicles/AccessPermissionGroup.scala b/common/src/main/scala/net/psforever/objects/vehicles/AccessPermissionGroup.scala new file mode 100644 index 000000000..5a99956e5 --- /dev/null +++ b/common/src/main/scala/net/psforever/objects/vehicles/AccessPermissionGroup.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2017 PSForever +package net.psforever.objects.vehicles + +/** + * An `Enumeration` of various permission groups that control access to aspects of a vehicle.
+ * - `Driver` is a seat that is always seat number 0.
+ * - `Gunner` is a seat that is not the `Driver` and controls a mounted weapon.
+ * - `Passenger` is a seat that is not the `Driver` and does not have control of a mounted weapon.
+ * - `Trunk` represnts access to the vehicle's internal storage space.
+ * Organized to replicate the `PlanetsideAttributeMessage` value used for that given access level. + * In their respective `PlanetsideAttributeMessage` packet, the groups are indexed in the same order as 10 through 13. + */ +object AccessPermissionGroup extends Enumeration { + type Type = Value + + val + Driver, + Gunner, + Passenger, + Trunk + = Value +} \ No newline at end of file diff --git a/common/src/main/scala/net/psforever/objects/vehicles/Seat.scala b/common/src/main/scala/net/psforever/objects/vehicles/Seat.scala index 263fa2e22..f69f927df 100644 --- a/common/src/main/scala/net/psforever/objects/vehicles/Seat.scala +++ b/common/src/main/scala/net/psforever/objects/vehicles/Seat.scala @@ -2,33 +2,22 @@ package net.psforever.objects.vehicles import net.psforever.objects.definition.SeatDefinition -import net.psforever.objects.{Player, Vehicle} -import net.psforever.packet.game.PlanetSideGUID -import net.psforever.types.PlanetSideEmpire +import net.psforever.objects.Player /** * Server-side support for a slot that infantry players can occupy, ostensibly called a "seat" and treated like a "seat." * (Players can sit in it.) - * @param seatDef the Definition that constructs this item and maintains some of its immutable fields - * @param vehicle the vehicle where this seat is installed + * @param seatDef the Definition that constructs this item and maintains some of its unchanging fields */ -class Seat(private val seatDef : SeatDefinition, private val vehicle : Vehicle) { - private var occupant : Option[PlanetSideGUID] = None - private var lockState : VehicleLockState.Value = VehicleLockState.Empire - - /** - * The faction association of this `Seat` is tied directly to the connected `Vehicle`. - * @return the faction association - */ - def Faction : PlanetSideEmpire.Value = { - vehicle.Faction - } +class Seat(private val seatDef : SeatDefinition) { + private var occupant : Option[Player] = None +// private var lockState : VehicleLockState.Value = VehicleLockState.Empire /** * Is this seat occupied? * @return the GUID of the player sitting in this seat, or `None` if it is left vacant */ - def Occupant : Option[PlanetSideGUID] = { + def Occupant : Option[Player] = { this.occupant } @@ -38,10 +27,12 @@ class Seat(private val seatDef : SeatDefinition, private val vehicle : Vehicle) * @param player the player who wants to sit, or `None` if the occupant is getting up * @return the GUID of the player sitting in this seat, or `None` if it is left vacant */ - def Occupant_=(player : Option[Player]) : Option[PlanetSideGUID] = { + def Occupant_=(player : Player) : Option[Player] = Occupant_=(Some(player)) + + def Occupant_=(player : Option[Player]) : Option[Player] = { if(player.isDefined) { if(this.occupant.isEmpty) { - this.occupant = Some(player.get.GUID) + this.occupant = player } } else { @@ -58,14 +49,14 @@ class Seat(private val seatDef : SeatDefinition, private val vehicle : Vehicle) this.occupant.isDefined } - def SeatLockState : VehicleLockState.Value = { - this.lockState - } - - def SeatLockState_=(lockState : VehicleLockState.Value) : VehicleLockState.Value = { - this.lockState = lockState - SeatLockState - } +// def SeatLockState : VehicleLockState.Value = { +// this.lockState +// } +// +// def SeatLockState_=(lockState : VehicleLockState.Value) : VehicleLockState.Value = { +// this.lockState = lockState +// SeatLockState +// } def ArmorRestriction : SeatArmorRestriction.Value = { seatDef.ArmorRestriction @@ -79,25 +70,6 @@ class Seat(private val seatDef : SeatDefinition, private val vehicle : Vehicle) seatDef.ControlledWeapon } - /** - * Given a player, can they access this `Seat` under its current restrictions and permissions. - * @param player the player who wants to sit - * @return `true` if the player can sit down in this `Seat`; `false`, otherwise - */ - def CanUseSeat(player : Player) : Boolean = { - var access : Boolean = false - val owner : Option[PlanetSideGUID] = vehicle.Owner - lockState match { - case VehicleLockState.Locked => - access = owner.isEmpty || (owner.isDefined && player.GUID == owner.get) - case VehicleLockState.Group => - access = Faction == player.Faction //TODO this is not correct - case VehicleLockState.Empire => - access = Faction == player.Faction - } - access - } - /** * Override the string representation to provide additional information. * @return the string output @@ -110,11 +82,10 @@ class Seat(private val seatDef : SeatDefinition, private val vehicle : Vehicle) object Seat { /** * Overloaded constructor. - * @param vehicle the vehicle where this seat is installed * @return a `Seat` object */ - def apply(seatDef : SeatDefinition, vehicle : Vehicle) : Seat = { - new Seat(seatDef, vehicle) + def apply(seatDef : SeatDefinition) : Seat = { + new Seat(seatDef) } /** @@ -122,13 +93,12 @@ object Seat { * @return the string output */ def toString(obj : Seat) : String = { - val weaponStr = if(obj.ControlledWeapon.isDefined) { " (gunner)" } else { "" } val seatStr = if(obj.isOccupied) { - "occupied by %d".format(obj.Occupant.get.guid) + s", occupied by player ${obj.Occupant.get.GUID}" } else { - "unoccupied" + "" } - s"{Seat$weaponStr: $seatStr}" + s"seat$seatStr" } } diff --git a/common/src/main/scala/net/psforever/objects/vehicles/SeatArmorRestriction.scala b/common/src/main/scala/net/psforever/objects/vehicles/SeatArmorRestriction.scala index 391b3d86e..8558b3866 100644 --- a/common/src/main/scala/net/psforever/objects/vehicles/SeatArmorRestriction.scala +++ b/common/src/main/scala/net/psforever/objects/vehicles/SeatArmorRestriction.scala @@ -11,7 +11,8 @@ package net.psforever.objects.vehicles object SeatArmorRestriction extends Enumeration { type Type = Value - val MaxOnly, + val + MaxOnly, NoMax, NoReinforcedOrMax = Value diff --git a/common/src/main/scala/net/psforever/objects/vehicles/VehicleControl.scala b/common/src/main/scala/net/psforever/objects/vehicles/VehicleControl.scala new file mode 100644 index 000000000..5f6be0e3a --- /dev/null +++ b/common/src/main/scala/net/psforever/objects/vehicles/VehicleControl.scala @@ -0,0 +1,37 @@ +// Copyright (c) 2017 PSForever +package net.psforever.objects.vehicles + +import akka.actor.Actor +import net.psforever.objects.Vehicle + +/** + * An `Actor` that handles messages being dispatched to a specific `Vehicle`.
+ *
+ * Vehicle-controlling actors have two behavioral states - responsive and "`Disabled`." + * The latter is applicable only when the specific vehicle is being deconstructed. + * @param vehicle the `Vehicle` object being governed + */ +class VehicleControl(private val vehicle : Vehicle) extends Actor { + def receive : Receive = { + case Vehicle.PrepareForDeletion => + context.become(Disabled) + + case Vehicle.TrySeatPlayer(seat_num, player) => + vehicle.Seat(seat_num) match { + case Some(seat) => + if((seat.Occupant = player).contains(player)) { + sender ! Vehicle.VehicleMessages(player, Vehicle.CanSeatPlayer(vehicle, seat_num)) + } + else { + sender ! Vehicle.VehicleMessages(player, Vehicle.CannotSeatPlayer(vehicle, seat_num)) + } + case None => + sender ! Vehicle.VehicleMessages(player, Vehicle.CannotSeatPlayer(vehicle, seat_num)) + } + case _ => ; + } + + def Disabled : Receive = { + case _ => ; + } +} diff --git a/common/src/main/scala/net/psforever/objects/vehicles/VehicleLockState.scala b/common/src/main/scala/net/psforever/objects/vehicles/VehicleLockState.scala index 661567019..748f370cc 100644 --- a/common/src/main/scala/net/psforever/objects/vehicles/VehicleLockState.scala +++ b/common/src/main/scala/net/psforever/objects/vehicles/VehicleLockState.scala @@ -3,12 +3,12 @@ package net.psforever.objects.vehicles /** * An `Enumeration` of various access states for vehicle components, such as the seats and the trunk. + * Organized to replicate the `PlanetsideAttributeMessage` value used for that given access level. */ object VehicleLockState extends Enumeration { type Type = Value - val Empire, //owner's whole faction - Group, //owner's squad/platoon only - Locked //owner only - = Value + val Locked = Value(0) //owner only + val Group = Value(1) //owner's squad/platoon only + val Empire = Value(3) //owner's whole faction } diff --git a/common/src/main/scala/net/psforever/objects/zones/Zone.scala b/common/src/main/scala/net/psforever/objects/zones/Zone.scala index 94c30d493..7bf7d22c5 100644 --- a/common/src/main/scala/net/psforever/objects/zones/Zone.scala +++ b/common/src/main/scala/net/psforever/objects/zones/Zone.scala @@ -4,7 +4,7 @@ package net.psforever.objects.zones import akka.actor.{ActorContext, ActorRef, Props} import akka.routing.RandomPool import net.psforever.objects.serverobject.doors.Base -import net.psforever.objects.{PlanetSideGameObject, Player} +import net.psforever.objects.{PlanetSideGameObject, Player, Vehicle} import net.psforever.objects.equipment.Equipment import net.psforever.objects.guid.NumberPoolHub import net.psforever.objects.guid.actor.UniqueNumberSystem @@ -14,6 +14,7 @@ import net.psforever.packet.GamePacket import net.psforever.packet.game.PlanetSideGUID import net.psforever.types.Vector3 +import scala.annotation.tailrec import scala.collection.mutable.ListBuffer /** @@ -49,6 +50,10 @@ class Zone(private val zoneId : String, zoneMap : ZoneMap, zoneNumber : Int) { private val equipmentOnGround : ListBuffer[Equipment] = ListBuffer[Equipment]() /** Used by the `Zone` to coordinate `Equipment` dropping and collection requests. */ private var ground : ActorRef = ActorRef.noSender + /** */ + private var vehicles : List[Vehicle] = List[Vehicle]() + /** */ + private var transport : ActorRef = ActorRef.noSender private var bases : List[Base] = List() @@ -69,6 +74,7 @@ class Zone(private val zoneId : String, zoneMap : ZoneMap, zoneNumber : Int) { implicit val guid : NumberPoolHub = this.guid //passed into builderObject.Build implicitly accessor = context.actorOf(RandomPool(25).props(Props(classOf[UniqueNumberSystem], guid, UniqueNumberSystem.AllocateNumberPoolActors(guid))), s"$Id-uns") ground = context.actorOf(Props(classOf[ZoneGroundActor], equipmentOnGround), s"$Id-ground") + transport = context.actorOf(Props(classOf[ZoneVehicleActor], this), s"$Id-vehicles") Map.LocalObjects.foreach({ builderObject => builderObject.Build @@ -165,6 +171,37 @@ class Zone(private val zoneId : String, zoneMap : ZoneMap, zoneNumber : Int) { */ def EquipmentOnGround : List[Equipment] = equipmentOnGround.toList + def Vehicles : List[Vehicle] = vehicles + + def AddVehicle(vehicle : Vehicle) : List[Vehicle] = { + vehicles = vehicles :+ vehicle + Vehicles + } + + def RemoveVehicle(vehicle : Vehicle) : List[Vehicle] = { + vehicles = recursiveFindVehicle(vehicles.iterator, vehicle) match { + case Some(index) => + vehicles.take(index) ++ vehicles.drop(index + 1) + case None => ; + vehicles + } + Vehicles + } + + @tailrec private def recursiveFindVehicle(iter : Iterator[Vehicle], target : Vehicle, index : Int = 0) : Option[Int] = { + if(!iter.hasNext) { + None + } + else { + if(iter.next.equals(target)) { + Some(index) + } + else { + recursiveFindVehicle(iter, target, index + 1) + } + } + } + /** * Coordinate `Equipment` that has been dropped on the ground or to-be-dropped on the ground. * @return synchronized reference to the ground @@ -175,6 +212,8 @@ class Zone(private val zoneId : String, zoneMap : ZoneMap, zoneNumber : Int) { */ def Ground : ActorRef = ground + def Transport : ActorRef = transport + def MakeBases(num : Int) : List[Base] = { bases = (0 to num).map(id => new Base(id)).toList bases @@ -250,6 +289,10 @@ object Zone { */ final case class ItemFromGround(player : Player, item : Equipment) + final case class SpawnVehicle(vehicle : Vehicle) + + final case class DespawnVehicle(vehicle : Vehicle) + /** * Message to report the packet messages that initialize the client. * @param list a `List` of `GamePacket` messages diff --git a/common/src/main/scala/net/psforever/objects/zones/ZoneVehicleActor.scala b/common/src/main/scala/net/psforever/objects/zones/ZoneVehicleActor.scala new file mode 100644 index 000000000..b7d3c6a5a --- /dev/null +++ b/common/src/main/scala/net/psforever/objects/zones/ZoneVehicleActor.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2017 PSForever +package net.psforever.objects.zones + +import akka.actor.Actor + +/** + * Synchronize management of the list of `Vehicles` maintained by some `Zone`. + * @param zone the `Zone` object + */ +class ZoneVehicleActor(zone : Zone) extends Actor { + //private[this] val log = org.log4s.getLogger + + def receive : Receive = { + case Zone.SpawnVehicle(vehicle) => + zone.AddVehicle(vehicle) + + case Zone.DespawnVehicle(vehicle) => + zone.RemoveVehicle(vehicle) + + case _ => ; + } +} diff --git a/common/src/main/scala/net/psforever/packet/game/PlanetsideAttributeMessage.scala b/common/src/main/scala/net/psforever/packet/game/PlanetsideAttributeMessage.scala index 0b640c685..c61b03e7a 100644 --- a/common/src/main/scala/net/psforever/packet/game/PlanetsideAttributeMessage.scala +++ b/common/src/main/scala/net/psforever/packet/game/PlanetsideAttributeMessage.scala @@ -6,7 +6,7 @@ import scodec.Codec import scodec.codecs._ /** - * Attribute Type:
+ * Players/General:
* Server to client :
* `0 - health`
* `1 - healthMax`
@@ -86,7 +86,19 @@ import scodec.codecs._ * `78 - Cavern Kills. Value is the number of kills`
* `106 - Custom Head` * Client to Server :
- * `106 - Custom Head` + * `106 - Custom Head`
+ *
+ * Vehicles:
+ * 0 - Vehicle health
+ * 10 - Driver seat permissions (0 = Locked, 1 = Group, 3 = Empire)
+ * 11 - Gunner seat(s) permissions (same)
+ * 12 - Passenger seat(s) permissions (same)
+ * 13 - Trunk permissions (same)
+ * 21 - Asserts first time event eligibility / makes owner if no owner is assigned
+ * 22 - Toggles gunner and passenger mount points (1 = hides, 0 = reveals; this also locks their permissions)
+ * 68 - ???
+ * 80 - Damage vehicle (unknown value)
+ * 113 - ??? * @param player_guid the player * @param attribute_type na * @param attribute_value na diff --git a/common/src/main/scala/net/psforever/packet/game/objectcreate/ObjectClass.scala b/common/src/main/scala/net/psforever/packet/game/objectcreate/ObjectClass.scala index f396aba12..37b85c5a6 100644 --- a/common/src/main/scala/net/psforever/packet/game/objectcreate/ObjectClass.scala +++ b/common/src/main/scala/net/psforever/packet/game/objectcreate/ObjectClass.scala @@ -803,6 +803,7 @@ object ObjectClass { case ObjectClass.battlewagon_weapon_systemd => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.bolt_driver => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chainblade => ConstructorData.genericCodec(WeaponData.codec, "weapon") + case ObjectClass.chaingun_p => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.colossus_burster => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.colossus_burster_left => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.colossus_burster_right => ConstructorData.genericCodec(WeaponData.codec, "weapon") @@ -918,7 +919,6 @@ object ObjectClass { case ObjectClass.cannon_dropship_20mm => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chaingun_12mm => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chaingun_15mm => ConstructorData.genericCodec(WeaponData.codec, "weapon") - case ObjectClass.chaingun_p => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v2 => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v3 => ConstructorData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v4 => ConstructorData.genericCodec(WeaponData.codec, "weapon") @@ -1080,6 +1080,7 @@ object ObjectClass { // case ObjectClass.aphelion_starfire_right => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.bolt_driver => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chainblade => DroppedItemData.genericCodec(WeaponData.codec, "weapon") +// case ObjectClass.chaingun_p => DroppedItemData.genericCodec(WeaponData.codec, "weapon") // case ObjectClass.colossus_burster => DroppedItemData.genericCodec(WeaponData.codec, "weapon") // case ObjectClass.colossus_burster_left => DroppedItemData.genericCodec(WeaponData.codec, "weapon") // case ObjectClass.colossus_burster_right => DroppedItemData.genericCodec(WeaponData.codec, "weapon") @@ -1144,7 +1145,6 @@ object ObjectClass { case ObjectClass.advanced_missile_launcher_t => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chaingun_12mm => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.chaingun_15mm => DroppedItemData.genericCodec(WeaponData.codec, "weapon") - case ObjectClass.chaingun_p => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v2 => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v3 => DroppedItemData.genericCodec(WeaponData.codec, "weapon") case ObjectClass.cycler_v4 => DroppedItemData.genericCodec(WeaponData.codec, "weapon") diff --git a/common/src/test/scala/objects/ConverterTest.scala b/common/src/test/scala/objects/ConverterTest.scala index 9f53443c1..3b946fba6 100644 --- a/common/src/test/scala/objects/ConverterTest.scala +++ b/common/src/test/scala/objects/ConverterTest.scala @@ -281,7 +281,8 @@ class ConverterTest extends Specification { val hellfire_ammo_box = AmmoBox(PlanetSideGUID(432), hellfire_ammo) - val fury = Vehicle(PlanetSideGUID(413), fury_def) + val fury = Vehicle(fury_def) + fury.GUID = PlanetSideGUID(413) fury.Faction = PlanetSideEmpire.VS fury.Position = Vector3(3674.8438f, 2732f, 91.15625f) fury.Orientation = Vector3(0.0f, 0.0f, 90.0f) diff --git a/common/src/test/scala/objects/VehicleTest.scala b/common/src/test/scala/objects/VehicleTest.scala new file mode 100644 index 000000000..11b1d65ab --- /dev/null +++ b/common/src/test/scala/objects/VehicleTest.scala @@ -0,0 +1,103 @@ +// Copyright (c) 2017 PSForever +package objects + +import net.psforever.objects.{GlobalDefinitions, Vehicle} +import net.psforever.objects.definition.SeatDefinition +import net.psforever.objects.vehicles.{Seat, SeatArmorRestriction, VehicleLockState} +import org.specs2.mutable._ + +class VehicleTest extends Specification { + + "SeatDefinition" should { + val seat = new SeatDefinition + seat.ArmorRestriction = SeatArmorRestriction.MaxOnly + seat.Bailable = true + seat.ControlledWeapon = 5 + + "define (default)" in { + val t_seat = new SeatDefinition + t_seat.ArmorRestriction mustEqual SeatArmorRestriction.NoMax + t_seat.Bailable mustEqual false + t_seat.ControlledWeapon mustEqual None + } + + "define (custom)" in { + seat.ArmorRestriction mustEqual SeatArmorRestriction.MaxOnly + seat.Bailable mustEqual true + seat.ControlledWeapon mustEqual Some(5) + } + } + + "VehicleDefinition" should { + "define" in { + val fury = GlobalDefinitions.fury + fury.CanBeOwned mustEqual true + fury.CanCloak mustEqual false + fury.Seats.size mustEqual 1 + fury.Seats(0).Bailable mustEqual true + fury.Seats(0).ControlledWeapon mustEqual Some(1) + fury.MountPoints.size mustEqual 2 + fury.MountPoints.get(0) mustEqual Some(0) + fury.MountPoints.get(1) mustEqual None + fury.MountPoints.get(2) mustEqual Some(0) + fury.Weapons.size mustEqual 1 + fury.Weapons.get(0) mustEqual None + fury.Weapons.get(1) mustEqual Some(GlobalDefinitions.fury_weapon_systema) + fury.TrunkSize.width mustEqual 11 + fury.TrunkSize.height mustEqual 11 + fury.TrunkOffset mustEqual 30 + } + } + + "Seat" should { + val seat_def = new SeatDefinition + seat_def.ArmorRestriction = SeatArmorRestriction.MaxOnly + seat_def.Bailable = true + seat_def.ControlledWeapon = 5 + + "construct" in { + val seat = new Seat(seat_def) + seat.ArmorRestriction mustEqual SeatArmorRestriction.MaxOnly + seat.Bailable mustEqual true + seat.ControlledWeapon mustEqual Some(5) + seat.isOccupied mustEqual false + seat.Occupant mustEqual None + } + } + + "Vehicle" should { + "construct" in { + Vehicle(GlobalDefinitions.fury) + ok + } + + "construct (detailed)" in { + val fury_vehicle = Vehicle(GlobalDefinitions.fury) + fury_vehicle.Owner mustEqual None + fury_vehicle.Seats.size mustEqual 1 + fury_vehicle.Seats.head.ArmorRestriction mustEqual SeatArmorRestriction.NoMax + fury_vehicle.Seats.head.isOccupied mustEqual false + fury_vehicle.Seats.head.Occupant mustEqual None + fury_vehicle.Seats.head.Bailable mustEqual true + fury_vehicle.Seats.head.ControlledWeapon mustEqual Some(1) + fury_vehicle.PermissionGroup(0) mustEqual Some(VehicleLockState.Locked) //driver + fury_vehicle.PermissionGroup(1) mustEqual Some(VehicleLockState.Empire) //gunner + fury_vehicle.PermissionGroup(2) mustEqual Some(VehicleLockState.Empire) //passenger + fury_vehicle.PermissionGroup(3) mustEqual Some(VehicleLockState.Locked) //trunk + fury_vehicle.Weapons.size mustEqual 1 + fury_vehicle.Weapons.get(0) mustEqual None + fury_vehicle.Weapons.get(1).isDefined mustEqual true + fury_vehicle.Weapons(1).Equipment.isDefined mustEqual true + fury_vehicle.Weapons(1).Equipment.get.Definition mustEqual GlobalDefinitions.fury.Weapons(1) + fury_vehicle.WeaponControlledFromSeat(0) mustEqual fury_vehicle.Weapons(1).Equipment + fury_vehicle.Trunk.Width mustEqual 11 + fury_vehicle.Trunk.Height mustEqual 11 + fury_vehicle.Trunk.Offset mustEqual 30 + fury_vehicle.GetSeatFromMountPoint(0) mustEqual Some(0) + fury_vehicle.GetSeatFromMountPoint(1) mustEqual None + fury_vehicle.GetSeatFromMountPoint(2) mustEqual Some(0) + fury_vehicle.Decal mustEqual 0 + fury_vehicle.Health mustEqual fury_vehicle.Definition.MaxHealth + } + } +} diff --git a/pslogin/src/main/scala/PsLogin.scala b/pslogin/src/main/scala/PsLogin.scala index e3e4bc1b4..870f402ee 100644 --- a/pslogin/src/main/scala/PsLogin.scala +++ b/pslogin/src/main/scala/PsLogin.scala @@ -18,8 +18,10 @@ import net.psforever.objects.serverobject.builders.{DoorObjectBuilder, IFFLockOb import org.slf4j import org.fusesource.jansi.Ansi._ import org.fusesource.jansi.Ansi.Color._ +import services.ServiceManager import services.avatar._ import services.local._ +import services.vehicle.VehicleService import scala.collection.JavaConverters._ import scala.concurrent.Await @@ -206,6 +208,7 @@ object PsLogin { serviceManager ! ServiceManager.Register(RandomPool(50).props(Props[TaskResolver]), "taskResolver") serviceManager ! ServiceManager.Register(Props[AvatarService], "avatar") serviceManager ! ServiceManager.Register(Props[LocalService], "local") + serviceManager ! ServiceManager.Register(Props[VehicleService], "vehicle") serviceManager ! ServiceManager.Register(Props(classOf[InterstellarCluster], createContinents()), "galaxy") /** Create two actors for handling the login and world server endpoints */ diff --git a/pslogin/src/main/scala/WorldSessionActor.scala b/pslogin/src/main/scala/WorldSessionActor.scala index 2d9dfadb8..9948e6d72 100644 --- a/pslogin/src/main/scala/WorldSessionActor.scala +++ b/pslogin/src/main/scala/WorldSessionActor.scala @@ -9,23 +9,24 @@ import scodec.Attempt.{Failure, Successful} import scodec.bits._ import org.log4s.MDC import MDCContextAware.Implicits._ -import ServiceManager.Lookup +import services.ServiceManager.Lookup import net.psforever.objects._ -import net.psforever.objects.serverobject.doors.Door -import net.psforever.objects.zones.{InterstellarCluster, Zone} -import net.psforever.objects.entity.IdentifiableEntity import net.psforever.objects.equipment._ import net.psforever.objects.guid.{Task, TaskResolver} -import net.psforever.objects.guid.actor.{Register, Unregister} import net.psforever.objects.inventory.{GridInventory, InventoryItem} import net.psforever.objects.serverobject.{CommonMessages, PlanetSideServerObject} +import net.psforever.objects.serverobject.doors.Door import net.psforever.objects.serverobject.locks.IFFLock import net.psforever.objects.serverobject.terminals.Terminal +import net.psforever.objects.vehicles.{AccessPermissionGroup, Seat, VehicleLockState} +import net.psforever.objects.zones.{InterstellarCluster, Zone} import net.psforever.packet.game.objectcreate._ import net.psforever.types._ +import scripts.GUIDTask import services._ import services.avatar._ import services.local._ +import services.vehicle.{VehicleAction, VehicleResponse, VehicleServiceMessage, VehicleServiceResponse} import scala.annotation.tailrec import scala.util.Success @@ -39,6 +40,7 @@ class WorldSessionActor extends Actor with MDCContextAware { var rightRef : ActorRef = ActorRef.noSender var avatarService : ActorRef = ActorRef.noSender var localService : ActorRef = ActorRef.noSender + var vehicleService : ActorRef = ActorRef.noSender var taskResolver : ActorRef = Actor.noSender var galaxy : ActorRef = Actor.noSender var continent : Zone = null @@ -53,12 +55,13 @@ class WorldSessionActor extends Actor with MDCContextAware { avatarService ! Service.Leave() localService ! Service.Leave() + vehicleService ! Service.Leave() LivePlayerList.Remove(sessionId) match { case Some(tplayer) => if(tplayer.HasGUID) { val guid = tplayer.GUID avatarService ! AvatarServiceMessage(tplayer.Continent, AvatarAction.ObjectDelete(guid, guid)) - taskResolver ! UnregisterAvatar(tplayer) + taskResolver ! GUIDTask.UnregisterAvatar(tplayer)(continent.GUID) //TODO normally, the actual player avatar persists a minute or so after the user disconnects } case None => ; @@ -81,6 +84,7 @@ class WorldSessionActor extends Actor with MDCContextAware { context.become(Started) ServiceManager.serviceManager ! Lookup("avatar") ServiceManager.serviceManager ! Lookup("local") + ServiceManager.serviceManager ! Lookup("vehicle") ServiceManager.serviceManager ! Lookup("taskResolver") ServiceManager.serviceManager ! Lookup("galaxy") @@ -96,6 +100,9 @@ class WorldSessionActor extends Actor with MDCContextAware { case ServiceManager.LookupResult("local", endpoint) => localService = endpoint log.info("ID: " + sessionId + " Got local service " + endpoint) + case ServiceManager.LookupResult("vehicle", endpoint) => + vehicleService = endpoint + log.info("ID: " + sessionId + " Got vehicle service " + endpoint) case ServiceManager.LookupResult("taskResolver", endpoint) => taskResolver = endpoint log.info("ID: " + sessionId + " Got task resolver service " + endpoint) @@ -113,12 +120,12 @@ class WorldSessionActor extends Actor with MDCContextAware { case AvatarServiceResponse(_, guid, reply) => reply match { - case AvatarServiceResponse.ArmorChanged(suit, subtype) => + case AvatarResponse.ArmorChanged(suit, subtype) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, ArmorChangedMessage(guid, suit, subtype))) } - case AvatarServiceResponse.EquipmentInHand(slot, item) => + case AvatarResponse.EquipmentInHand(slot, item) => if(player.GUID != guid) { val definition = item.Definition sendResponse( @@ -133,7 +140,7 @@ class WorldSessionActor extends Actor with MDCContextAware { ) } - case AvatarServiceResponse.EquipmentOnGround(pos, orient, item) => + case AvatarResponse.EquipmentOnGround(pos, orient, item) => if(player.GUID != guid) { val definition = item.Definition sendResponse( @@ -147,7 +154,7 @@ class WorldSessionActor extends Actor with MDCContextAware { ) } - case AvatarServiceResponse.LoadPlayer(pdata) => + case AvatarResponse.LoadPlayer(pdata) => if(player.GUID != guid) { sendResponse( PacketCoding.CreateGamePacket( @@ -157,22 +164,22 @@ class WorldSessionActor extends Actor with MDCContextAware { ) } - case AvatarServiceResponse.ObjectDelete(item_guid, unk) => + case AvatarResponse.ObjectDelete(item_guid, unk) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(item_guid, unk))) } - case AvatarServiceResponse.ObjectHeld(slot) => + case AvatarResponse.ObjectHeld(slot) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, ObjectHeldMessage(guid, slot, true))) } - case AvatarServiceResponse.PlanetSideAttribute(attribute_type, attribute_value) => + case AvatarResponse.PlanetSideAttribute(attribute_type, attribute_value) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, PlanetsideAttributeMessage(guid, attribute_type, attribute_value))) } - case AvatarServiceResponse.PlayerState(msg, spectating, weaponInHand) => + case AvatarResponse.PlayerState(msg, spectating, weaponInHand) => if(player.GUID != guid) { val now = System.currentTimeMillis() val (location, time, distanceSq) : (Vector3, Long, Float) = if(spectating) { @@ -213,7 +220,7 @@ class WorldSessionActor extends Actor with MDCContextAware { } } - case AvatarServiceResponse.Reload(mag) => + case AvatarResponse.Reload(mag) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, ReloadMessage(guid, mag, 0))) } @@ -223,24 +230,76 @@ class WorldSessionActor extends Actor with MDCContextAware { case LocalServiceResponse(_, guid, reply) => reply match { - case LocalServiceResponse.DoorOpens(door_guid) => + case LocalResponse.DoorOpens(door_guid) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, GenericObjectStateMsg(door_guid, 16))) } - case LocalServiceResponse.DoorCloses(door_guid) => //door closes for everyone + case LocalResponse.DoorCloses(door_guid) => //door closes for everyone sendResponse(PacketCoding.CreateGamePacket(0, GenericObjectStateMsg(door_guid, 17))) - case LocalServiceResponse.HackClear(target_guid, unk1, unk2) => + case LocalResponse.HackClear(target_guid, unk1, unk2) => sendResponse(PacketCoding.CreateGamePacket(0, HackMessage(0, target_guid, guid, 0, unk1, HackState.HackCleared, unk2))) - case LocalServiceResponse.HackObject(target_guid, unk1, unk2) => + case LocalResponse.HackObject(target_guid, unk1, unk2) => if(player.GUID != guid) { sendResponse(PacketCoding.CreateGamePacket(0, HackMessage(0, target_guid, guid, 100, unk1, HackState.Hacked, unk2))) } - case LocalServiceResponse.TriggerSound(sound, pos, unk, volume) => + case LocalResponse.TriggerSound(sound, pos, unk, volume) => sendResponse(PacketCoding.CreateGamePacket(0, TriggerSoundMessage(sound, pos, unk, volume))) + + case _ => ; + } + + case VehicleServiceResponse(_, guid, reply) => + reply match { + case VehicleResponse.Awareness(vehicle_guid) => + //resets exclamation point fte marker (once) + sendResponse(PacketCoding.CreateGamePacket(0, PlanetsideAttributeMessage(guid, 21, vehicle_guid.guid.toLong))) + + case VehicleResponse.ChildObjectState(object_guid, pitch, yaw) => + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, ChildObjectStateMessage(object_guid, pitch, yaw))) + } + + case VehicleResponse.DismountVehicle(unk1, unk2) => + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, DismountVehicleMsg(guid, unk1, unk2))) + } + + case VehicleResponse.KickPassenger(unk1, unk2) => + sendResponse(PacketCoding.CreateGamePacket(0, DismountVehicleMsg(guid, unk1, unk2))) + + case VehicleResponse.LoadVehicle(vehicle, vtype, vguid, vdata) => + //this is not be suitable for vehicles with people who are seated in it before it spawns (if that is possible) + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, ObjectCreateMessage(vtype, vguid, vdata))) + ReloadVehicleAccessPermissions(vehicle) + } + + case VehicleResponse.MountVehicle(vehicle_guid, seat) => + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, ObjectAttachMessage(vehicle_guid, guid, seat))) + if(player.VehicleOwned.contains(vehicle_guid)) { //simplistic vehicle ownership management + player.VehicleOwned = None + } + } + + case VehicleResponse.SeatPermissions(vehicle_guid, seat_group, permission) => + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, PlanetsideAttributeMessage(vehicle_guid, seat_group, permission))) + } + + case VehicleResponse.UnloadVehicle(vehicle_guid) => + sendResponse(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(vehicle_guid, 0))) + + case VehicleResponse.VehicleState(vehicle_guid, unk1, pos, ang, vel, unk2, unk3, unk4, wheel_direction, unk5, unk6) => + if(player.GUID != guid) { + sendResponse(PacketCoding.CreateGamePacket(0, VehicleStateMessage(vehicle_guid, unk1, pos, ang, vel, unk2, unk3, unk4, wheel_direction, unk5, unk6))) + } + + case _ => ; } case Door.DoorMessage(tplayer, msg, order) => @@ -375,7 +434,7 @@ class WorldSessionActor extends Actor with MDCContextAware { tplayer.Fit(item) match { case Some(index) => sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage (msg.terminal_guid, TransactionType.Buy, true))) - PutEquipmentInSlot(tplayer, item, index) + taskResolver ! PutEquipmentInSlot(tplayer, item, index) case None => sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage (msg.terminal_guid, TransactionType.Buy, false))) } @@ -385,7 +444,7 @@ class WorldSessionActor extends Actor with MDCContextAware { case Some(item) => if(item.GUID == msg.item_guid) { sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage (msg.terminal_guid, TransactionType.Sell, true))) - RemoveEquipmentFromSlot(tplayer, item, Player.FreeHandSlot) + taskResolver ! RemoveEquipmentFromSlot(tplayer, item, Player.FreeHandSlot) } case None => sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage (msg.terminal_guid, TransactionType.Sell, false))) @@ -407,7 +466,7 @@ class WorldSessionActor extends Actor with MDCContextAware { }) (beforeHolsters ++ beforeInventory).foreach({ elem => sendResponse(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(elem.obj.GUID, 0))) - taskResolver ! UnregisterEquipment(elem.obj) + taskResolver ! GUIDTask.UnregisterEquipment(elem.obj)(continent.GUID) }) //report change sendResponse(PacketCoding.CreateGamePacket(0, ArmorChangedMessage(tplayer.GUID, exosuit, 0))) @@ -433,11 +492,11 @@ class WorldSessionActor extends Actor with MDCContextAware { } //draw holsters holsters.foreach(entry => { - PutEquipmentInSlot(tplayer, entry.obj, entry.start) + taskResolver ! PutEquipmentInSlot(tplayer, entry.obj, entry.start) }) //put items into inventory inventory.foreach(entry => { - PutEquipmentInSlot(tplayer, entry.obj, entry.start) + taskResolver ! PutEquipmentInSlot(tplayer, entry.obj, entry.start) }) //TODO drop items on ground sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage (msg.terminal_guid, TransactionType.InfantryLoadout, true))) @@ -471,6 +530,41 @@ class WorldSessionActor extends Actor with MDCContextAware { sendResponse(PacketCoding.CreateGamePacket(0, ItemTransactionResultMessage(msg.terminal_guid, msg.transaction_type, false))) } + case Vehicle.VehicleMessages(tplayer, reply) => + reply match { + case Vehicle.CanSeatPlayer(vehicle, seat_num) => + log.info(s"MountVehicleMsg: ${player.GUID} mounts ${vehicle.GUID} @ $seat_num") + val vehicle_guid : PlanetSideGUID = vehicle.GUID + tplayer.VehicleSeated = Some(vehicle_guid) + if(seat_num == 0) { //simplistic vehicle ownership management + player.VehicleOwned = Some(vehicle_guid) + vehicle.Owner = Some(player.GUID) + } + vehicle.WeaponControlledFromSeat(seat_num) match { + case Some(weapon : Tool) => + //update mounted weapon belonging to seat + val magazine = weapon.AmmoSlots(weapon.FireModeIndex).Box //update the magazine in the weapon, specifically + sendResponse(PacketCoding.CreateGamePacket(0, InventoryStateMessage(magazine.GUID, 0, weapon.GUID, weapon.Magazine.toLong))) + //update all related ammunition objects in trunk + vehicle.Trunk.Items + .filter({ case ((_, item)) => item.obj.isInstanceOf[AmmoBox] && item.obj.asInstanceOf[AmmoBox].AmmoType == weapon.AmmoType }) + .foreach({ case ((_, item)) => + val box = item.obj.asInstanceOf[AmmoBox] + sendResponse(PacketCoding.CreateGamePacket(0, InventoryStateMessage(box.GUID, 0, vehicle_guid, box.Capacity.toLong))) + }) + case None => ; //no weapons to update + } + val player_guid : PlanetSideGUID = tplayer.GUID + sendResponse(PacketCoding.CreateGamePacket(0, ObjectAttachMessage(vehicle_guid, player_guid, seat_num))) + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.MountVehicle(player_guid, vehicle_guid, seat_num)) + + case Vehicle.CannotSeatPlayer(vehicle, seat_num) => + val seat : Seat = vehicle.Seat(seat_num).get + log.warn(s"MountVehicleMsg: player $tplayer attempted to board vehicle ${vehicle.GUID}'s seat $seat_num, but was not allowed") + + case _ => ; + } + case ListAccountCharacters => import net.psforever.objects.definition.converter.CharacterSelectConverter val gen : AtomicInteger = new AtomicInteger(1) @@ -512,6 +606,16 @@ class WorldSessionActor extends Actor with MDCContextAware { failWithError(s"$tplayer failed to load anywhere") } + case VehicleLoaded(vehicle) => + val definition = vehicle.Definition + val objedtId = definition.ObjectId + val vehicle_guid = vehicle.GUID + val vdata = definition.Packet.ConstructorData(vehicle).get + sendResponse(PacketCoding.CreateGamePacket(0, ObjectCreateMessage(objedtId, vehicle_guid, vdata))) + ReloadVehicleAccessPermissions(vehicle) + continent.Transport ! Zone.SpawnVehicle(vehicle) + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.LoadVehicle(player.GUID, vehicle, objedtId, vehicle_guid, vdata)) + case Zone.ClientInitialization(/*initList*/_) => //TODO iterate over initList; for now, just do this sendResponse( @@ -691,53 +795,46 @@ class WorldSessionActor extends Actor with MDCContextAware { } } - import net.psforever.objects.GlobalDefinitions._ - //this part is created by WSA based on the database query (should be in case of ConnectToWorldRequestMessage, maybe) - val energy_cell_box1 = AmmoBox(energy_cell) - val energy_cell_box2 = AmmoBox(energy_cell, 16) - val bullet_9mm_box1 = AmmoBox(bullet_9mm) - val bullet_9mm_box2 = AmmoBox(bullet_9mm) - val bullet_9mm_box3 = AmmoBox(bullet_9mm) - val bullet_9mm_box4 = AmmoBox(bullet_9mm, 25) - val bullet_9mm_AP_box = AmmoBox(bullet_9mm_AP) - val melee_ammo_box = AmmoBox(melee_ammo) - val - beamer1 = Tool(beamer) - beamer1.AmmoSlots.head.Box = energy_cell_box2 - val - suppressor1 = Tool(suppressor) - suppressor1.AmmoSlots.head.Box = bullet_9mm_box4 - val - forceblade1 = Tool(forceblade) - forceblade1.AmmoSlots.head.Box = melee_ammo_box - val rek = SimpleItem(remote_electronics_kit) - val extra_rek = SimpleItem(remote_electronics_kit) - val - player = Player("IlllIIIlllIlIllIlllIllI", PlanetSideEmpire.VS, CharacterGender.Female, 41, 1) - player.Position = Vector3(3674.8438f, 2726.789f, 91.15625f) - player.Orientation = Vector3(0f, 0f, 90f) - player.Certifications += CertificationType.StandardAssault - player.Certifications += CertificationType.MediumAssault - player.Certifications += CertificationType.StandardExoSuit - player.Certifications += CertificationType.AgileExoSuit - player.Certifications += CertificationType.ReinforcedExoSuit - player.Certifications += CertificationType.ATV - player.Certifications += CertificationType.Harasser - player.Slot(0).Equipment = beamer1 - player.Slot(2).Equipment = suppressor1 - player.Slot(4).Equipment = forceblade1 - player.Slot(6).Equipment = bullet_9mm_box1 - player.Slot(9).Equipment = bullet_9mm_box2 - player.Slot(12).Equipment = bullet_9mm_box3 - player.Slot(33).Equipment = bullet_9mm_AP_box - player.Slot(36).Equipment = energy_cell_box1 - player.Slot(39).Equipment = rek - player.Slot(5).Equipment.get.asInstanceOf[LockerContainer].Inventory += 0 -> extra_rek + var player : Player = null + var harasser : Vehicle = null //TODO used in testing def handleGamePkt(pkt : PlanetSideGamePacket) = pkt match { case ConnectToWorldRequestMessage(server, token, majorVersion, minorVersion, revision, buildDate, unk) => val clientVersion = s"Client Version: $majorVersion.$minorVersion.$revision, $buildDate" log.info(s"New world login to $server with Token:$token. $clientVersion") + //TODO begin temp player character auto-loading; remove later + import net.psforever.objects.GlobalDefinitions._ + val + beamer1 = Tool(beamer) + beamer1.AmmoSlots.head.Box = AmmoBox(energy_cell, 16) + val + suppressor1 = Tool(suppressor) + suppressor1.AmmoSlots.head.Box = AmmoBox(bullet_9mm, 25) + val + forceblade1 = Tool(forceblade) + forceblade1.AmmoSlots.head.Box = AmmoBox(melee_ammo) + + player = Player("TestCharacter"+sessionId.toString, PlanetSideEmpire.VS, CharacterGender.Female, 41, 1) + player.Position = Vector3(3674.8438f, 2726.789f, 91.15625f) + player.Orientation = Vector3(0f, 0f, 90f) + player.Certifications += CertificationType.StandardAssault + player.Certifications += CertificationType.MediumAssault + player.Certifications += CertificationType.StandardExoSuit + player.Certifications += CertificationType.AgileExoSuit + player.Certifications += CertificationType.ReinforcedExoSuit + player.Certifications += CertificationType.ATV + player.Certifications += CertificationType.Harasser + player.Slot(0).Equipment = beamer1 + player.Slot(2).Equipment = suppressor1 + player.Slot(4).Equipment = forceblade1 + player.Slot(6).Equipment = AmmoBox(bullet_9mm) + player.Slot(9).Equipment = AmmoBox(bullet_9mm) + player.Slot(12).Equipment = AmmoBox(bullet_9mm) + player.Slot(33).Equipment = AmmoBox(bullet_9mm_AP) + player.Slot(36).Equipment = AmmoBox(energy_cell) + player.Slot(39).Equipment = SimpleItem(remote_electronics_kit) + player.Slot(5).Equipment.get.asInstanceOf[LockerContainer].Inventory += 0 -> SimpleItem(remote_electronics_kit) + //TODO end temp player character auto-loading self ! ListAccountCharacters import scala.concurrent.duration._ @@ -778,14 +875,6 @@ class WorldSessionActor extends Actor with MDCContextAware { sendResponse(PacketCoding.CreateGamePacket(0, TimeOfDayMessage(1191182336))) sendResponse(PacketCoding.CreateGamePacket(0, ReplicationStreamMessage(5, Some(6), Vector(SquadListing())))) //clear squad list - //load active players in zone - LivePlayerList.ZonePopulation(continent.Number, _ => true).foreach(char => { - sendResponse( - PacketCoding.CreateGamePacket(0, - ObjectCreateMessage(ObjectClass.avatar, char.GUID, char.Definition.Packet.ConstructorData(char).get) - ) - ) - }) //render Equipment that was dropped into zone before the player arrived continent.EquipmentOnGround.foreach(item => { val definition = item.Definition @@ -799,8 +888,54 @@ class WorldSessionActor extends Actor with MDCContextAware { ) ) }) + //load active players in zone + LivePlayerList.ZonePopulation(continent.Number, _ => true).foreach(char => { + sendResponse( + PacketCoding.CreateGamePacket(0, + ObjectCreateMessage(ObjectClass.avatar, char.GUID, char.Definition.Packet.ConstructorData(char).get) + ) + ) + }) + //load active vehicles in zone + continent.Vehicles.foreach(vehicle => { + val definition = vehicle.Definition + sendResponse( + PacketCoding.CreateGamePacket(0, + ObjectCreateMessage( + definition.ObjectId, + vehicle.GUID, + definition.Packet.ConstructorData(vehicle).get + ) + ) + ) + //seat vehicle occupants + vehicle.Definition.MountPoints.values.foreach(seat_num => { + vehicle.Seat(seat_num).get.Occupant match { + case Some(tplayer) => + sendResponse(PacketCoding.CreateGamePacket(0, ObjectAttachMessage(vehicle.GUID, tplayer.GUID, seat_num))) + case None => ; + } + }) + ReloadVehicleAccessPermissions(vehicle) + }) + //TODO begin temp vehicle auto-loading + import net.psforever.objects.GlobalDefinitions._ + if(continent.Vehicles.isEmpty) { + harasser = Vehicle(two_man_assault_buggy) + harasser.Position = Vector3(3674.8438f, 2730.789f, 91.15625f) + harasser.Faction = PlanetSideEmpire.VS + harasser.Orientation = Vector3(0f, 0f, 90f) + harasser.Weapons(2).Equipment.get.asInstanceOf[Tool].AmmoSlots.head.Box = AmmoBox(bullet_12mm, 150) + harasser.Trunk += 30 -> AmmoBox(bullet_12mm, 100) + taskResolver ! RegisterNewVehicle(harasser) + } + else { + harasser = continent.Vehicles.head //subsequent players after first + } + //TODO end temp vehicle auto-loading avatarService ! Service.Join(player.Continent) localService ! Service.Join(player.Continent) + vehicleService ! Service.Join(player.Continent) self ! SetCurrentAvatar(player) case msg @ PlayerStateMessageUpstream(avatar_guid, pos, vel, yaw, pitch, yaw_upper, seq_time, unk3, is_crouching, is_jumping, unk4, is_cloaking, unk5, unk6) => @@ -812,16 +947,53 @@ class WorldSessionActor extends Actor with MDCContextAware { player.Jumping = is_jumping val wepInHand : Boolean = player.Slot(player.DrawnSlot).Equipment match { - case Some(item) => item.Definition == bolt_driver + case Some(item) => item.Definition == GlobalDefinitions.bolt_driver case None => false } - avatarService ! AvatarServiceMessage(player.Continent, AvatarAction.PlayerState(avatar_guid, msg, player.Spectator, wepInHand)) - //log.info("PlayerState: " + msg) + avatarService ! AvatarServiceMessage(continent.Id, AvatarAction.PlayerState(avatar_guid, msg, player.Spectator, wepInHand)) case msg @ ChildObjectStateMessage(object_guid, pitch, yaw) => + //the majority of the following check retrieves information to determine if we are in control of the child + player.VehicleSeated match { + case Some(vehicle_guid) => + continent.GUID(vehicle_guid) match { + case Some(obj : Vehicle) => + obj.PassengerInSeat(player) match { + case Some(seat_num) => + obj.WeaponControlledFromSeat(seat_num) match { + case Some(tool) => + if(tool.GUID == object_guid) { + //TODO set tool orientation? + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.ChildObjectState(player.GUID, object_guid, pitch, yaw)) + } + case None => + log.warn(s"ChildObjectState: player $player is not using stated controllable agent") + } + case None => + log.warn(s"ChildObjectState: player ${player.GUID} is not in a position to use controllable agent") + } + case _ => + log.warn(s"ChildObjectState: player $player's controllable agent not available in scope") + } + case None => + //TODO status condition of "playing getting out of vehicle to allow for late packets without warning + //log.warn(s"ChildObjectState: player $player not related to anything with a controllable agent") + } //log.info("ChildObjectState: " + msg) case msg @ VehicleStateMessage(vehicle_guid, unk1, pos, ang, vel, unk5, unk6, unk7, wheels, unk9, unkA) => + continent.GUID(vehicle_guid) match { + case Some(obj : Vehicle) => + if(obj.Seat(0).get.Occupant.contains(player)) { //we're driving the vehicle + obj.Position = pos + obj.Orientation = ang + obj.Velocity = vel + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.VehicleState(player.GUID, vehicle_guid, unk1, pos, ang, vel, unk5, unk6, unk7, wheels, unk9, unkA)) + } + //TODO placing a "not driving" warning here may trigger as we are disembarking the vehicle + case _ => + log.warn(s"VehicleState: no vehicle $vehicle_guid found in zone") + } //log.info("VehicleState: " + msg) case msg @ ProjectileStateMessage(projectile_guid, shot_pos, shot_vector, unk1, unk2, unk3, unk4, time_alive) => @@ -892,19 +1064,34 @@ class WorldSessionActor extends Actor with MDCContextAware { case msg @ ReloadMessage(item_guid, ammo_clip, unk1) => log.info("Reload: " + msg) - val reloadValue = player.Slot(player.DrawnSlot).Equipment match { - case Some(item) => - item match { - case tool : Tool => - tool.FireMode.Magazine - case _ => + val reloadValue : Int = player.VehicleSeated match { + case Some(vehicle_guid) => //weapon is vehicle turret? + continent.GUID(vehicle_guid) match { + case Some(vehicle : Vehicle) => + vehicle.PassengerInSeat(player) match { + case Some(seat_num) => + vehicle.WeaponControlledFromSeat(seat_num) match { + case Some(item : Tool) => + item.FireMode.Magazine + case _ => ; + 0 + } + case None => ; + 0 + } + case _ => ; + 0 + } + case None => //not in vehicle; weapon in hand? + player.Slot(player.DrawnSlot).Equipment match { //TODO check that item in hand is item_guid? + case Some(item : Tool) => + item.FireMode.Magazine + case Some(_) | None => ; 0 } - case None => - 0 } - //TODO hunt for ammunition in inventory if(reloadValue > 0) { + //TODO hunt for ammunition in backpack/trunk sendResponse(PacketCoding.CreateGamePacket(0, ReloadMessage(item_guid, reloadValue, unk1))) } @@ -939,14 +1126,32 @@ class WorldSessionActor extends Actor with MDCContextAware { } case msg @ RequestDestroyMessage(object_guid) => - // TODO: Make sure this is the correct response in all cases - player.Find(object_guid) match { - case Some(slot) => - taskResolver ! RemoveEquipmentFromSlot(player, player.Slot(slot).Equipment.get, slot) - log.info("RequestDestroy: " + msg) + // TODO: Make sure this is the correct response for all cases + continent.GUID(object_guid) match { + case Some(vehicle : Vehicle) => + if(player.VehicleOwned.contains(object_guid) && vehicle.Owner.contains(player.GUID)) { + vehicleService ! VehicleServiceMessage.RequestDeleteVehicle(vehicle, continent) + log.info(s"RequestDestroy: vehicle $object_guid") + } + else { + log.info(s"RequestDestroy: must own vehicle $object_guid in order to deconstruct it") + } + + case Some(obj : Equipment) => + player.Find(object_guid) match { //player should be holding it + case Some(slot) => + taskResolver ! RemoveEquipmentFromSlot(player, player.Slot(slot).Equipment.get, slot) + log.info(s"RequestDestroy: equipment $object_guid") + case None => + sendResponse(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(object_guid, 0))) + log.warn(s"RequestDestroy: object $object_guid not found in player hands") + } + case None => - sendResponse(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(object_guid, 0))) log.warn(s"RequestDestroy: object $object_guid not found") + + case _ => + log.warn(s"RequestDestroy: not allowed to delete object $object_guid") } case msg @ ObjectDeleteMessage(object_guid, unk1) => @@ -1068,6 +1273,19 @@ class WorldSessionActor extends Actor with MDCContextAware { case _ => ; } + case Some(obj : Vehicle) => + if(obj.Faction == player.Faction) { + player.Slot(player.DrawnSlot).Equipment match { + case Some(tool : Tool) => + if(tool.Definition == GlobalDefinitions.nano_dispenser) { + //TODO repairing behavior + } + case Some(_) | None => + //TODO trunk access + sendResponse(PacketCoding.CreateGamePacket(0, UseItemMessage(avatar_guid, unk1, object_guid, unk2, unk3, unk4, unk5, unk6, unk7, unk8, itemType))) + } + } + case Some(obj : PlanetSideGameObject) => if(itemType != 121) { sendResponse(PacketCoding.CreateGamePacket(0, UseItemMessage(avatar_guid, unk1, object_guid, unk2, unk3, unk4, unk5, unk6, unk7, unk8, itemType))) @@ -1080,7 +1298,7 @@ class WorldSessionActor extends Actor with MDCContextAware { case None => ; } - + case msg @ UnuseItemMessage(player_guid, item) => log.info("UnuseItem: " + msg) @@ -1136,12 +1354,79 @@ class WorldSessionActor extends Actor with MDCContextAware { log.info("WarpgateRequest: " + msg) case msg @ MountVehicleMsg(player_guid, vehicle_guid, unk) => - sendResponse(PacketCoding.CreateGamePacket(0, ObjectAttachMessage(vehicle_guid,player_guid,0))) - log.info("MounVehicleMsg: "+msg) + //log.info("MountVehicleMsg: "+msg) + continent.GUID(vehicle_guid) match { + case Some(obj : Vehicle) => + obj.GetSeatFromMountPoint(unk) match { + case Some(seat_num) => + obj.Actor ! Vehicle.TrySeatPlayer(seat_num, player) + case None => + log.warn(s"MountVehicleMsg: attempted to board vehicle $vehicle_guid's seat $unk, but no seat exists there") + } + case None | Some(_) => + log.warn(s"MountVehicleMsg: not a vehicle") + } case msg @ DismountVehicleMsg(player_guid, unk1, unk2) => - sendResponse(PacketCoding.CreateGamePacket(0, msg)) //should be safe; replace with ObjectDetachMessage later - log.info("DismountVehicleMsg: " + msg) + //TODO optimize this later + log.info(s"DismountVehicleMsg: $msg") + if(player.GUID == player_guid) { + //normally disembarking from a seat + player.VehicleSeated match { + case Some(vehicle_guid) => + continent.GUID(vehicle_guid) match { + case Some(obj : Vehicle) => + obj.Seats.find(seat => seat.Occupant.contains(player)) match { + case Some(seat) => + val vel = obj.Velocity.getOrElse(new Vector3(0f, 0f, 0f)) + val total_vel : Int = math.abs(vel.x * vel.y * vel.z).toInt + if(seat.Bailable || obj.Velocity.isEmpty || total_vel == 0) { + seat.Occupant = None + player.VehicleSeated = None + sendResponse(PacketCoding.CreateGamePacket(0, DismountVehicleMsg(player_guid, unk1, unk2))) //should be safe; replace with ObjectDetachMessage later + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.DismountVehicle(player_guid, unk1, unk2)) + } + case None => + log.warn(s"DismountVehicleMsg: can not find where player $player_guid is seated in vehicle $vehicle_guid") + } + case _ => + log.warn(s"DismountVehicleMsg: can not find vehicle $vehicle_guid") + } + case None => + log.warn(s"DismountVehicleMsg: player $player_guid not considered seated in a vehicle") + } + } + else { + //kicking someone else out of a seat; need to own that seat + player.VehicleOwned match { + case Some(vehicle_guid) => + continent.GUID(player_guid) match { + case Some(tplayer : Player) => + if(tplayer.VehicleSeated.contains(vehicle_guid)) { + continent.GUID(vehicle_guid) match { + case Some(obj : Vehicle) => + obj.Seats.find(seat => seat.Occupant.contains(tplayer)) match { + case Some(seat) => + seat.Occupant = None + tplayer.VehicleSeated = None + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.KickPassenger(player_guid, unk1, unk2)) + case None => + log.warn(s"DismountVehicleMsg: can not find where player $player_guid is seated in vehicle $vehicle_guid") + } + case _ => + log.warn(s"DismountVehicleMsg: can not find vehicle $vehicle_guid") + } + } + else { + log.warn(s"DismountVehicleMsg: non-owner player $player trying to kick player $tplayer out of his seat") + } + case _ => + log.warn(s"DismountVehicleMsg: player $player_guid could not be found to kick") + } + case None => + log.warn(s"DismountVehicleMsg: $player does not own a vehicle") + } + } case msg @ DeployRequestMessage(player_guid, entity, unk1, unk2, unk3, pos) => //if you try to deploy, can not undeploy @@ -1162,9 +1447,46 @@ class WorldSessionActor extends Actor with MDCContextAware { case msg @ BindPlayerMessage(action, bindDesc, unk1, logging, unk2, unk3, unk4, pos) => log.info("BindPlayerMessage: " + msg) - case msg @ PlanetsideAttributeMessage(avatar_guid, attribute_type, attribute_value) => + case msg @ PlanetsideAttributeMessage(object_guid, attribute_type, attribute_value) => log.info("PlanetsideAttributeMessage: "+msg) - sendResponse(PacketCoding.CreateGamePacket(0,PlanetsideAttributeMessage(avatar_guid, attribute_type, attribute_value))) + continent.GUID(object_guid) match { + case Some(vehicle : Vehicle) => + if(player.VehicleOwned.contains(vehicle.GUID)) { + if(9 < attribute_type && attribute_type < 14) { + vehicle.PermissionGroup(attribute_type, attribute_value) match { + case Some(allow) => + val group = AccessPermissionGroup(attribute_type - 10) + log.info(s"Vehicle attributes: vehicle ${vehicle.GUID} access permission $group changed to $allow") + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.SeatPermissions(player.GUID, vehicle.GUID, attribute_type, attribute_value)) + //kick players who should not be seated in the vehicle due to permission changes + if(allow == VehicleLockState.Locked) { //TODO only important permission atm + vehicle.Definition.MountPoints.values.foreach(seat_num => { + val seat = vehicle.Seat(seat_num).get + seat.Occupant match { + case Some(tplayer) => + if(vehicle.SeatPermissionGroup(seat_num).contains(group) && tplayer != player) { + seat.Occupant = None + tplayer.VehicleSeated = None + vehicleService ! VehicleServiceMessage(continent.Id, VehicleAction.KickPassenger(tplayer.GUID, 4, false)) + } + case None => ; + } + }) + } + case None => ; + } + } + else { + log.warn(s"Vehicle attributes: unsupported change on vehicle $object_guid - $attribute_type") + } + } + else { + log.warn(s"Vehicle attributes: $player does not own vehicle ${vehicle.GUID} and can not change it") + } + case _ => + log.warn(s"echo unknown attributes behavior") + sendResponse(PacketCoding.CreateGamePacket(0,PlanetsideAttributeMessage(object_guid, attribute_type, attribute_value))) + } case msg @ BattleplanMessage(char_id, player_name, zonr_id, diagrams) => log.info("Battleplan: "+msg) @@ -1244,28 +1566,6 @@ class WorldSessionActor extends Actor with MDCContextAware { } } - /** - * Iterate over a group of `EquipmentSlot`s, some of which may be occupied with an item. - * Use `func` on any discovered `Equipment` to transform items into tasking, and add the tasking to a `List`. - * @param iter the `Iterator` of `EquipmentSlot`s - * @param func the function used to build tasking from any discovered `Equipment` - * @param list a persistent `List` of `Equipment` tasking - * @return a `List` of `Equipment` tasking - */ - @tailrec private def recursiveHolsterTaskBuilding(iter : Iterator[EquipmentSlot], func : ((Equipment)=>TaskResolver.GiveTask), list : List[TaskResolver.GiveTask] = Nil) : List[TaskResolver.GiveTask] = { - if(!iter.hasNext) { - list - } - else { - iter.next.Equipment match { - case Some(item) => - recursiveHolsterTaskBuilding(iter, func, list :+ func(item)) - case None => - recursiveHolsterTaskBuilding(iter, func, list) - } - } - } - /** * Construct tasking that coordinates the following:
* 1) Accept a new piece of `Equipment` and register it with a globally unique identifier.
@@ -1273,17 +1573,18 @@ class WorldSessionActor extends Actor with MDCContextAware { * @param target what object will accept the new `Equipment` * @param obj the new `Equipment` * @param index the slot where the new `Equipment` will be placed - * @see `RegisterEquipment` + * @see `GUIDTask.RegisterEquipment` * @see `PutInSlot` + * @return a `TaskResolver.GiveTask` message */ - private def PutEquipmentInSlot(target : Player, obj : Equipment, index : Int) : Unit = { - val regTask = RegisterEquipment(obj) + private def PutEquipmentInSlot(target : Player, obj : Equipment, index : Int) : TaskResolver.GiveTask = { + val regTask = GUIDTask.RegisterEquipment(obj)(continent.GUID) obj match { case tool : Tool => val linearToolTask = TaskResolver.GiveTask(regTask.task) +: regTask.subs - taskResolver ! TaskResolver.GiveTask(PutInSlot(target, tool, index).task, linearToolTask) + TaskResolver.GiveTask(PutInSlot(target, tool, index).task, linearToolTask) case _ => - taskResolver ! TaskResolver.GiveTask(PutInSlot(target, obj, index).task, List(regTask)) + TaskResolver.GiveTask(PutInSlot(target, obj, index).task, List(regTask)) } } @@ -1294,72 +1595,18 @@ class WorldSessionActor extends Actor with MDCContextAware { * @param target the object that currently possesses the `Equipment` * @param obj the `Equipment` * @param index the slot from where the `Equipment` will be removed - * @see `UnregisterEquipment` + * @see `GUIDTask.UnregisterEquipment` * @see `RemoveFromSlot` + * @return a `TaskResolver.GiveTask` message */ - private def RemoveEquipmentFromSlot(target : Player, obj : Equipment, index : Int) : Unit = { - val regTask = UnregisterEquipment(obj) + private def RemoveEquipmentFromSlot(target : Player, obj : Equipment, index : Int) : TaskResolver.GiveTask = { + val regTask = GUIDTask.UnregisterEquipment(obj)(continent.GUID) //to avoid an error from a GUID-less object from being searchable, it is removed from the inventory first obj match { case _ : Tool => - taskResolver ! TaskResolver.GiveTask(regTask.task, RemoveFromSlot(target, obj, index) +: regTask.subs) + TaskResolver.GiveTask(regTask.task, RemoveFromSlot(target, obj, index) +: regTask.subs) case _ => - taskResolver ! TaskResolver.GiveTask(regTask.task, RemoveFromSlot(target, obj, index) :: Nil) - } - } - - /** - * Construct tasking that registers an object with the a globally unique identifier selected from a pool of numbers. - * The object in question is not considered to have any form of internal complexity. - * @param obj the object being registered - * @return a `TaskResolver.GiveTask` message - */ - private def RegisterObjectTask(obj : IdentifiableEntity) : TaskResolver.GiveTask = { - TaskResolver.GiveTask( - new Task() { - private val localObject = obj - private val localAccessor = continent.GUID - - override def isComplete : Task.Resolution.Value = { - try { - localObject.GUID - Task.Resolution.Success - } - catch { - case _ : Exception => - Task.Resolution.Incomplete - } - } - - def Execute(resolver : ActorRef) : Unit = { - localAccessor ! Register(localObject, "dynamic", resolver) - } - }) - } - - /** - * Construct tasking that registers an object that is an object of type `Tool`. - * `Tool` objects have internal structures called "ammo slots;" - * each ammo slot contains a register-able `AmmoBox` object. - * @param obj the object being registered - * @return a `TaskResolver.GiveTask` message - */ - private def RegisterTool(obj : Tool) : TaskResolver.GiveTask = { - val ammoTasks : List[TaskResolver.GiveTask] = (0 until obj.MaxAmmoSlot).map(ammoIndex => RegisterObjectTask(obj.AmmoSlots(ammoIndex).Box)).toList - TaskResolver.GiveTask(RegisterObjectTask(obj).task, ammoTasks) - } - - /** - * Construct tasking that registers an object, determining whether it is a complex object of type `Tool` or a more simple object type. - * @param obj the object being registered - * @return a `TaskResolver.GiveTask` message - */ - private def RegisterEquipment(obj : Equipment) : TaskResolver.GiveTask = { - obj match { - case tool : Tool => - RegisterTool(tool) - case _ => - RegisterObjectTask(obj) + TaskResolver.GiveTask(regTask.task, List(RemoveFromSlot(target, obj, index))) } } @@ -1377,6 +1624,7 @@ class WorldSessionActor extends Actor with MDCContextAware { private val localIndex = index private val localObject = obj private val localAnnounce = self + private val localService = avatarService override def isComplete : Task.Resolution.Value = { if(localTarget.Slot(localIndex).Equipment.contains(localObject)) { @@ -1405,7 +1653,7 @@ class WorldSessionActor extends Actor with MDCContextAware { ) ) if(0 <= localIndex && localIndex < 5) { - avatarService ! AvatarServiceMessage(localTarget.Continent, AvatarAction.EquipmentInHand(localTarget.GUID, localIndex, localObject)) + localService ! AvatarServiceMessage(localTarget.Continent, AvatarAction.EquipmentInHand(localTarget.GUID, localIndex, localObject)) } } }) @@ -1418,14 +1666,6 @@ class WorldSessionActor extends Actor with MDCContextAware { * @return a `TaskResolver.GiveTask` message */ private def RegisterAvatar(tplayer : Player) : TaskResolver.GiveTask = { - val holsterTasks = recursiveHolsterTaskBuilding(tplayer.Holsters().iterator, RegisterEquipment) - val fifthHolsterTask = tplayer.Slot(5).Equipment match { - case Some(locker) => - RegisterObjectTask(locker) :: locker.asInstanceOf[LockerContainer].Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => RegisterEquipment(entry.obj)}).toList - case None => - List.empty[TaskResolver.GiveTask]; - } - val inventoryTasks = tplayer.Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => RegisterEquipment(entry.obj)}) TaskResolver.GiveTask( new Task() { private val localPlayer = tplayer @@ -1449,64 +1689,55 @@ class WorldSessionActor extends Actor with MDCContextAware { override def onFailure(ex : Throwable) : Unit = { localAnnounce ! PlayerFailedToLoad(localPlayer) //alerts WSA } - }, RegisterObjectTask(tplayer) +: (holsterTasks ++ fifthHolsterTask ++ inventoryTasks) + }, List(GUIDTask.RegisterAvatar(tplayer)(continent.GUID)) ) } - /** - * Construct tasking that un-registers an object. - * The object in question is not considered to have any form of internal complexity. - * @param obj the object being un-registered - * @return a `TaskResolver.GiveTask` message - */ - private def UnregisterObjectTask(obj : IdentifiableEntity) : TaskResolver.GiveTask = { + def RegisterVehicle(vehicle : Vehicle) : TaskResolver.GiveTask = { TaskResolver.GiveTask( new Task() { - private val localObject = obj - private val localAccessor = continent.GUID + private val localVehicle = vehicle + private val localAnnounce = self override def isComplete : Task.Resolution.Value = { - try { - localObject.GUID - Task.Resolution.Incomplete + if(localVehicle.HasGUID) { + Task.Resolution.Success } - catch { - case _ : Exception => - Task.Resolution.Success + else { + Task.Resolution.Incomplete } } def Execute(resolver : ActorRef) : Unit = { - localAccessor ! Unregister(localObject, resolver) + log.info(s"Vehicle $localVehicle is registered") + resolver ! scala.util.Success(this) + localAnnounce ! VehicleLoaded(localVehicle) //alerts WSA } - } + }, List(GUIDTask.RegisterVehicle(vehicle)(continent.GUID)) ) } - /** - * Construct tasking that un-registers an object that is an object of type `Tool`. - * `Tool` objects have internal structures called "ammo slots;" - * each ammo slot contains a register-able `AmmoBox` object. - * @param obj the object being un-registered - * @return a `TaskResolver.GiveTask` message - */ - private def UnregisterTool(obj : Tool) : TaskResolver.GiveTask = { - val ammoTasks : List[TaskResolver.GiveTask] = (0 until obj.MaxAmmoSlot).map(ammoIndex => UnregisterObjectTask(obj.AmmoSlots(ammoIndex).Box)).toList - TaskResolver.GiveTask(UnregisterObjectTask(obj).task, ammoTasks) - } + def RegisterNewVehicle(obj : Vehicle) : TaskResolver.GiveTask = { + TaskResolver.GiveTask( + new Task() { + private val localVehicle = obj + private val localAnnounce = vehicleService + private val localSession : String = sessionId.toString - /** - * Construct tasking that un-registers an object, determining whether it is a complex object of type `Tool` or a more simple object type. - * @param obj the object being registered - * @return a `TaskResolver.GiveTask` message - */ - private def UnregisterEquipment(obj : Equipment) : TaskResolver.GiveTask = { - obj match { - case tool : Tool => - UnregisterTool(tool) - case _ => - UnregisterObjectTask(obj) - } + override def isComplete : Task.Resolution.Value = { + if(localVehicle.Actor != ActorRef.noSender) { + Task.Resolution.Success + } + else { + Task.Resolution.Incomplete + } + } + + def Execute(resolver : ActorRef) : Unit = { + localAnnounce ! VehicleServiceMessage.GiveActorControl(obj, localSession) + resolver ! scala.util.Success(this) + } + }, List(RegisterVehicle(obj))) } /** @@ -1524,6 +1755,7 @@ class WorldSessionActor extends Actor with MDCContextAware { private val localObject = obj private val localObjectGUID = obj.GUID private val localAnnounce = self //self may not be the same when it executes + private val localService = avatarService override def isComplete : Task.Resolution.Value = { if(localTarget.Slot(localIndex).Equipment.contains(localObject)) { @@ -1542,28 +1774,11 @@ class WorldSessionActor extends Actor with MDCContextAware { override def onSuccess() : Unit = { localAnnounce ! ResponseToSelf(PacketCoding.CreateGamePacket(0, ObjectDeleteMessage(localObjectGUID, 0))) if(0 <= localIndex && localIndex < 5) { - avatarService ! AvatarServiceMessage(localTarget.Continent, AvatarAction.ObjectDelete(localTarget.GUID, localObjectGUID)) + localService ! AvatarServiceMessage(localTarget.Continent, AvatarAction.ObjectDelete(localTarget.GUID, localObjectGUID)) } } - }) - } - - /** - * Construct tasking that un-registers all aspects of a `Player` avatar. - * `Players` are complex objects that contain a variety of other register-able objects and each of these objects much be handled. - * @param tplayer the avatar `Player` - * @return a `TaskResolver.GiveTask` message - */ - private def UnregisterAvatar(tplayer : Player) : TaskResolver.GiveTask = { - val holsterTasks = recursiveHolsterTaskBuilding(tplayer.Holsters().iterator, UnregisterEquipment) - val inventoryTasks = tplayer.Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => UnregisterEquipment(entry.obj)}) - val fifthHolsterTask = tplayer.Slot(5).Equipment match { - case Some(locker) => - UnregisterObjectTask(locker) :: locker.asInstanceOf[LockerContainer].Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => UnregisterEquipment(entry.obj)}).toList - case None => - List.empty[TaskResolver.GiveTask]; - } - TaskResolver.GiveTask(UnregisterObjectTask(tplayer).task, holsterTasks ++ fifthHolsterTask ++ inventoryTasks) + } + ) } /** @@ -1645,6 +1860,26 @@ class WorldSessionActor extends Actor with MDCContextAware { localService ! LocalServiceMessage(continent.Id, LocalAction.HackTemporarily(player.GUID, continent, target, unk)) } + /** + * Temporary function that iterates over vehicle permissions and turns them into `PlanetsideAttributeMessage` packets.
+ *
+ * 2 November 2017 + * Unexpected behavior causes seat mount points to become blocked when a new driver claims the vehicle. + * For the purposes of ensuring that other players are always aware of the proper permission state of the trunk and seats, + * packets are intentionally dispatched to the current client to update the states. + * Perform this action just after any instance where the client would initially gain awareness of the vehicle. + * The most important examples include either the player or the vehicle itself spawning in for the first time. + * @param vehicle the `Vehicle` + */ + def ReloadVehicleAccessPermissions(vehicle : Vehicle) : Unit = { + val vehicle_guid = vehicle.GUID + (0 to 3).foreach(group => { + sendResponse(PacketCoding.CreateGamePacket(0, + PlanetsideAttributeMessage(vehicle_guid, group + 10, vehicle.PermissionGroup(group).get.id.toLong) + )) + }) + } + def failWithError(error : String) = { log.error(error) sendResponse(PacketCoding.CreateControlPacket(ConnectionClose())) @@ -1675,6 +1910,7 @@ object WorldSessionActor { private final case class PlayerFailedToLoad(tplayer : Player) private final case class ListAccountCharacters() private final case class SetCurrentAvatar(tplayer : Player) + private final case class VehicleLoaded(vehicle : Vehicle) /** * A message that indicates the user is using a remote electronics kit to hack some server object. diff --git a/pslogin/src/main/scala/scripts/GUIDTask.scala b/pslogin/src/main/scala/scripts/GUIDTask.scala new file mode 100644 index 000000000..0d04585b7 --- /dev/null +++ b/pslogin/src/main/scala/scripts/GUIDTask.scala @@ -0,0 +1,282 @@ +// Copyright (c) 2017 PSForever +package scripts + +/** + * The basic compiled tasks for assigning (registering) and revoking (unregistering) globally unique identifiers.
+ *
+ * Almost all of these functions will be invoked from `WorldSessionActor`. + * Some of the "unregistering" functions will invoke on delayed `Service` operations, + * indicating behavior that is not user/observer dependent. + * The object's (current) `Zone` must also be knowable since the GUID systems are tied to individual zones. + * For simplicity, all functions have the same format where the hook into the GUID system is an `implicit` parameter. + * It will get passed from the more complicated functions down into the less complicated functions, + * until it has found the basic number assignment functionality.
+ *
+ * All functions produce a `TaskResolver.GiveTask` container object that is expected to be used by a `TaskResolver`. + * These "task containers" can also be unpackaged into their tasks, sorted into other containers, + * and combined with other "task containers" to enact more complicated sequences of operations. + */ +object GUIDTask { + import akka.actor.ActorRef + import net.psforever.objects.entity.IdentifiableEntity + import net.psforever.objects.equipment.Equipment + import net.psforever.objects.guid.{Task, TaskResolver} + import net.psforever.objects.{EquipmentSlot, Player, Tool, Vehicle} + + import scala.annotation.tailrec + /** + * Construct tasking that registers an object with a globally unique identifier selected from a pool of numbers.
+ *
+ * Regardless of the complexity of the object provided to this function, only the current depth will be assigned a GUID. + * This is the most basic operation that all objects that can be assigned a GUID must perform. + * @param obj the object being registered + * @param guid implicit reference to a unique number system + * @return a `TaskResolver.GiveTask` message + */ + def RegisterObjectTask(obj : IdentifiableEntity)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + TaskResolver.GiveTask( + new Task() { + private val localObject = obj + private val localAccessor = guid + + override def isComplete : Task.Resolution.Value = if(localObject.HasGUID) { + Task.Resolution.Success + } + else { + Task.Resolution.Incomplete + } + + def Execute(resolver : ActorRef) : Unit = { + import net.psforever.objects.guid.actor.Register + localAccessor ! Register(localObject, "dynamic", resolver) //TODO pool should not be hardcoded + } + }) + } + + /** + * Construct tasking that registers an object with a globally unique identifier selected from a pool of numbers, as a `Tool`.
+ *
+ * `Tool` objects are complicated by an internal structure informally called a "magazine feed." + * The objects in the magazine feed are called `AmmoBox` objects. + * Each `AmmoBox` object can be registered to a unique number system much like the `Tool` itself; and, + * each must be registered properly for the whole of the `Tool` to be communicated from the server to the client. + * While the matter has been abstracted for convenience, most `Tool` objects will have only one `AmmoBox` at a time + * and the common outlier will only be two.
+ *
+ * Do not invoke this function unless certain the object will be of type `Tool`, + * else use a more general function to differentiate between simple and complex objects. + * @param obj the `Tool` object being registered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterEquipment` + * @return a `TaskResolver.GiveTask` message + */ + def RegisterTool(obj : Tool)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + val ammoTasks : List[TaskResolver.GiveTask] = (0 until obj.MaxAmmoSlot).map(ammoIndex => RegisterObjectTask(obj.AmmoSlots(ammoIndex).Box)).toList + TaskResolver.GiveTask(RegisterObjectTask(obj).task, ammoTasks) + } + + /** + * Construct tasking that registers an object with a globally unique identifier selected from a pool of numbers, + * after determining whether the object is complex (`Tool`) or simple.
+ *
+ * The objects in this case are specifically `Equipment`, a subclass of the basic register-able `IdentifiableEntity`. + * About five subclasses of `Equipment` exist, but they decompose into two groups - "complex objects" and "simple objects." + * "Simple objects" are most groups of `Equipment` and just their own GUID to be registered. + * "Complex objects" are just the `Tool` category of `Equipment`. + * They have internal objects that must also have their GUID's registered to function.
+ *
+ * Using this function when passing unknown `Equipment` is recommended. + * The type will be sorted and the object will be handled according to its complexity level. + * @param obj the `Equipment` object being registered + * @param guid implicit reference to a unique number system + * @return a `TaskResolver.GiveTask` message + */ + def RegisterEquipment(obj : Equipment)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + obj match { + case tool : Tool => + RegisterTool(tool) + case _ => + RegisterObjectTask(obj) + } + } + + /** + * Construct tasking that registers an object with a globally unique identifier selected from a pool of numbers, as a `Player`.
+ *
+ * `Player` objects are far more complicated than `Tools` (but they are not `Equipment`). + * A player has an inventory in which it can hold a countable number of `Equipment`; and, + * this inventory holds a sub-inventory with its own countable number of `Equipment`. + * Although a process of completing and inserting `Equipment` into the inventories that looks orderly can be written, + * this function assumes that the player is already fully composed. + * Use this function for an sudden introduction of the player into his environment + * (as defined by the scope of the unique number system). + * For working with processes concerning these "orderly insertions," + * a task built of lesser registration tasks and supporting tasks should be written instead. + * @param tplayer the `Player` object being registered + * @param guid implicit reference to a unique number system + * @return a `TaskResolver.GiveTask` message + */ + def RegisterAvatar(tplayer : Player)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + import net.psforever.objects.LockerContainer + import net.psforever.objects.inventory.InventoryItem + val holsterTasks = recursiveHolsterTaskBuilding(tplayer.Holsters().iterator, RegisterEquipment) + val fifthHolsterTask = tplayer.Slot(5).Equipment match { + case Some(locker) => + RegisterObjectTask(locker) :: locker.asInstanceOf[LockerContainer].Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => RegisterEquipment(entry.obj)}).toList + case None => + List.empty[TaskResolver.GiveTask]; + } + val inventoryTasks = tplayer.Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => RegisterEquipment(entry.obj)}) + TaskResolver.GiveTask(RegisterObjectTask(tplayer).task, holsterTasks ++ fifthHolsterTask ++ inventoryTasks) + } + + /** + * Construct tasking that registers an object with a globally unique identifier selected from a pool of numbers, as a `Vehicle`.
+ *
+ * `Vehicle` objects are far more complicated than `Tools` (but they are not `Equipment`). + * A vehicle has an inventory in which it can hold a countable number of `Equipment`; and, + * it may possess weapons (`Tools`, usually) that are firmly mounted on its outside. + * (This is similar to the holsters on a `Player` object but they can not be swapped out for other `Equipment` or for nothing.) + * Although a process of completing and inserting `Equipment` into the inventories that looks orderly can be written, + * this function assumes that the vehicle is already fully composed. + * Use this function for an sudden introduction of the vehicle into its environment + * (as defined by the scope of the unique number system). + * For working with processes concerning these "orderly insertions," + * a task built of lesser registration tasks and supporting tasks should be written instead. + * @param vehicle the `Vehicle` object being registered + * @param guid implicit reference to a unique number system + * @return a `TaskResolver.GiveTask` message + */ + def RegisterVehicle(vehicle : Vehicle)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + import net.psforever.objects.inventory.InventoryItem + val weaponTasks = vehicle.Weapons.map({ case(_ : Int, entry : EquipmentSlot) => RegisterEquipment(entry.Equipment.get)}).toList + val inventoryTasks = vehicle.Trunk.Items.map({ case((_ : Int, entry : InventoryItem)) => RegisterEquipment(entry.obj)}) + TaskResolver.GiveTask(RegisterObjectTask(vehicle).task, weaponTasks ++ inventoryTasks) + } + + /** + * Construct tasking that unregisters an object from a globally unique identifier system.
+ *
+ * This task performs an operation that reverses the effect of `RegisterObjectTask`. + * It is the most basic operation that all objects that can have their GUIDs revoked must perform. + * @param obj the object being unregistered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterObjectTask` + * @return a `TaskResolver.GiveTask` message + */ + def UnregisterObjectTask(obj : IdentifiableEntity)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + TaskResolver.GiveTask( + new Task() { + private val localObject = obj + private val localAccessor = guid + + override def isComplete : Task.Resolution.Value = if(!localObject.HasGUID) { + Task.Resolution.Success + } + else { + Task.Resolution.Incomplete + } + + def Execute(resolver : ActorRef) : Unit = { + import net.psforever.objects.guid.actor.Unregister + localAccessor ! Unregister(localObject, resolver) + } + } + ) + } + + /** + * Construct tasking that unregisters a `Tool` object from a globally unique identifier system.
+ *
+ * This task performs an operation that reverses the effect of `RegisterTool`. + * @param obj the `Tool` object being unregistered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterTool` + * @return a `TaskResolver.GiveTask` message + */ + def UnregisterTool(obj : Tool)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + val ammoTasks : List[TaskResolver.GiveTask] = (0 until obj.MaxAmmoSlot).map(ammoIndex => UnregisterObjectTask(obj.AmmoSlots(ammoIndex).Box)).toList + TaskResolver.GiveTask(UnregisterObjectTask(obj).task, ammoTasks) + } + + /** + * Construct tasking that unregisters an object from a globally unique identifier system + * after determining whether the object is complex (`Tool`) or simple.
+ *
+ * This task performs an operation that reverses the effect of `RegisterEquipment`. + * @param obj the `Equipment` object being unregistered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterEquipment` + * @return a `TaskResolver.GiveTask` message + */ + def UnregisterEquipment(obj : Equipment)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + obj match { + case tool : Tool => + UnregisterTool(tool) + case _ => + UnregisterObjectTask(obj) + } + } + + /** + * Construct tasking that unregisters a `Player` object from a globally unique identifier system.
+ *
+ * This task performs an operation that reverses the effect of `RegisterAvatar`. + * @param tplayer the `Player` object being unregistered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterAvatar` + * @return a `TaskResolver.GiveTask` message + */ + def UnregisterAvatar(tplayer : Player)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + import net.psforever.objects.LockerContainer + import net.psforever.objects.inventory.InventoryItem + val holsterTasks = recursiveHolsterTaskBuilding(tplayer.Holsters().iterator, UnregisterEquipment) + val inventoryTasks = tplayer.Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => UnregisterEquipment(entry.obj)}) + val fifthHolsterTask = tplayer.Slot(5).Equipment match { + case Some(locker) => + UnregisterObjectTask(locker) :: locker.asInstanceOf[LockerContainer].Inventory.Items.map({ case((_ : Int, entry : InventoryItem)) => UnregisterEquipment(entry.obj)}).toList + case None => + List.empty[TaskResolver.GiveTask]; + } + TaskResolver.GiveTask(UnregisterObjectTask(tplayer).task, holsterTasks ++ fifthHolsterTask ++ inventoryTasks) + } + +/** + * Construct tasking that unregisters a `Vehicle` object from a globally unique identifier system.
+ *
+ * This task performs an operation that reverses the effect of `RegisterVehicle`. + * @param vehicle the `Vehicle` object being unregistered + * @param guid implicit reference to a unique number system + * @see `GUIDTask.RegisterVehicle` + * @return a `TaskResolver.GiveTask` message + */ + def UnregisterVehicle(vehicle : Vehicle)(implicit guid : ActorRef) : TaskResolver.GiveTask = { + import net.psforever.objects.inventory.InventoryItem + val weaponTasks = vehicle.Weapons.map({ case(_ : Int, entry : EquipmentSlot) => UnregisterTool(entry.Equipment.get.asInstanceOf[Tool]) }).toList + val inventoryTasks = vehicle.Trunk.Items.map({ case((_ : Int, entry : InventoryItem)) => UnregisterEquipment(entry.obj)}) + TaskResolver.GiveTask(UnregisterObjectTask(vehicle).task, weaponTasks ++ inventoryTasks) + } + + /** + * Iterate over a group of `EquipmentSlot`s, some of which may be occupied with an item. + * Use `func` on any discovered `Equipment` to transform items into tasking, and add the tasking to a `List`. + * @param iter the `Iterator` of `EquipmentSlot`s + * @param func the function used to build tasking from any discovered `Equipment`; + * strictly either `RegisterEquipment` or `UnregisterEquipment` + * @param list a persistent `List` of `Equipment` tasking + * @return a `List` of `Equipment` tasking + */ + @tailrec private def recursiveHolsterTaskBuilding(iter : Iterator[EquipmentSlot], func : ((Equipment)=>TaskResolver.GiveTask), list : List[TaskResolver.GiveTask] = Nil)(implicit guid : ActorRef) : List[TaskResolver.GiveTask] = { + if(!iter.hasNext) { + list + } + else { + iter.next.Equipment match { + case Some(item) => + recursiveHolsterTaskBuilding(iter, func, list :+ func(item)) + case None => + recursiveHolsterTaskBuilding(iter, func, list) + } + } + } +} \ No newline at end of file diff --git a/pslogin/src/main/scala/ServiceManager.scala b/pslogin/src/main/scala/services/ServiceManager.scala similarity index 99% rename from pslogin/src/main/scala/ServiceManager.scala rename to pslogin/src/main/scala/services/ServiceManager.scala index 40f2c4c0f..91dcb4497 100644 --- a/pslogin/src/main/scala/ServiceManager.scala +++ b/pslogin/src/main/scala/services/ServiceManager.scala @@ -1,3 +1,5 @@ +package services + // Copyright (c) 2017 PSForever import akka.actor.{Actor, ActorIdentity, ActorRef, ActorSystem, Identify, Props} diff --git a/pslogin/src/main/scala/services/avatar/AvatarResponse.scala b/pslogin/src/main/scala/services/avatar/AvatarResponse.scala new file mode 100644 index 000000000..87f37e841 --- /dev/null +++ b/pslogin/src/main/scala/services/avatar/AvatarResponse.scala @@ -0,0 +1,28 @@ +// Copyright (c) 2017 PSForever +package services.avatar + +import net.psforever.objects.equipment.Equipment +import net.psforever.packet.game.{PlanetSideGUID, PlayerStateMessageUpstream} +import net.psforever.packet.game.objectcreate.ConstructorData +import net.psforever.types.{ExoSuitType, Vector3} + +object AvatarResponse { + trait Response + + final case class ArmorChanged(suit : ExoSuitType.Value, subtype : Int) extends Response + //final case class DropItem(pos : Vector3, orient : Vector3, item : PlanetSideGUID) extends Response + final case class EquipmentInHand(slot : Int, item : Equipment) extends Response + final case class EquipmentOnGround(pos : Vector3, orient : Vector3, item : Equipment) extends Response + final case class LoadPlayer(pdata : ConstructorData) extends Response + // final case class unLoadMap() extends Response + // final case class LoadMap() extends Response + final case class ObjectDelete(item_guid : PlanetSideGUID, unk : Int) extends Response + final case class ObjectHeld(slot : Int) extends Response + final case class PlanetSideAttribute(attribute_type : Int, attribute_value : Long) extends Response + final case class PlayerState(msg : PlayerStateMessageUpstream, spectator : Boolean, weaponInHand : Boolean) extends Response + final case class Reload(mag : Int) extends Response + // final case class PlayerStateShift(itemID : PlanetSideGUID) extends Response + // final case class DestroyDisplay(itemID : PlanetSideGUID) extends Response + // final case class HitHintReturn(itemID : PlanetSideGUID) extends Response + // final case class ChangeWeapon(facingYaw : Int) extends Response +} diff --git a/pslogin/src/main/scala/services/avatar/AvatarService.scala b/pslogin/src/main/scala/services/avatar/AvatarService.scala index 5b656c23c..0e3c6f16f 100644 --- a/pslogin/src/main/scala/services/avatar/AvatarService.scala +++ b/pslogin/src/main/scala/services/avatar/AvatarService.scala @@ -31,39 +31,39 @@ class AvatarService extends Actor { action match { case AvatarAction.ArmorChanged(player_guid, suit, subtype) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.ArmorChanged(suit, subtype)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.ArmorChanged(suit, subtype)) ) case AvatarAction.EquipmentInHand(player_guid, slot, obj) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.EquipmentInHand(slot, obj)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.EquipmentInHand(slot, obj)) ) case AvatarAction.EquipmentOnGround(player_guid, pos, orient, obj) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.EquipmentOnGround(pos, orient, obj)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.EquipmentOnGround(pos, orient, obj)) ) case AvatarAction.LoadPlayer(player_guid, pdata) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.LoadPlayer(pdata)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.LoadPlayer(pdata)) ) case AvatarAction.ObjectDelete(player_guid, item_guid, unk) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.ObjectDelete(item_guid, unk)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.ObjectDelete(item_guid, unk)) ) case AvatarAction.ObjectHeld(player_guid, slot) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.ObjectHeld(slot)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.ObjectHeld(slot)) ) case AvatarAction.PlanetsideAttribute(guid, attribute_type, attribute_value) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", guid, AvatarServiceResponse.PlanetSideAttribute(attribute_type, attribute_value)) + AvatarServiceResponse(s"/$forChannel/Avatar", guid, AvatarResponse.PlanetSideAttribute(attribute_type, attribute_value)) ) case AvatarAction.PlayerState(guid, msg, spectator, weapon) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", guid, AvatarServiceResponse.PlayerState(msg, spectator, weapon)) + AvatarServiceResponse(s"/$forChannel/Avatar", guid, AvatarResponse.PlayerState(msg, spectator, weapon)) ) case AvatarAction.Reload(player_guid, mag) => AvatarEvents.publish( - AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarServiceResponse.Reload(mag)) + AvatarServiceResponse(s"/$forChannel/Avatar", player_guid, AvatarResponse.Reload(mag)) ) case _ => ; } diff --git a/pslogin/src/main/scala/services/avatar/AvatarServiceResponse.scala b/pslogin/src/main/scala/services/avatar/AvatarServiceResponse.scala index 29e05ed62..0d31425eb 100644 --- a/pslogin/src/main/scala/services/avatar/AvatarServiceResponse.scala +++ b/pslogin/src/main/scala/services/avatar/AvatarServiceResponse.scala @@ -1,34 +1,10 @@ // Copyright (c) 2017 PSForever package services.avatar -import net.psforever.objects.equipment.Equipment -import net.psforever.packet.game.{PlanetSideGUID, PlayerStateMessageUpstream} -import net.psforever.packet.game.objectcreate.ConstructorData -import net.psforever.types.{ExoSuitType, Vector3} +import net.psforever.packet.game.PlanetSideGUID import services.GenericEventBusMsg final case class AvatarServiceResponse(toChannel : String, avatar_guid : PlanetSideGUID, - replyMessage : AvatarServiceResponse.Response + replyMessage : AvatarResponse.Response ) extends GenericEventBusMsg - -object AvatarServiceResponse { - trait Response - - final case class ArmorChanged(suit : ExoSuitType.Value, subtype : Int) extends Response - //final case class DropItem(pos : Vector3, orient : Vector3, item : PlanetSideGUID) extends Response - final case class EquipmentInHand(slot : Int, item : Equipment) extends Response - final case class EquipmentOnGround(pos : Vector3, orient : Vector3, item : Equipment) extends Response - final case class LoadPlayer(pdata : ConstructorData) extends Response -// final case class unLoadMap() extends Response -// final case class LoadMap() extends Response - final case class ObjectDelete(item_guid : PlanetSideGUID, unk : Int) extends Response - final case class ObjectHeld(slot : Int) extends Response - final case class PlanetSideAttribute(attribute_type : Int, attribute_value : Long) extends Response - final case class PlayerState(msg : PlayerStateMessageUpstream, spectator : Boolean, weaponInHand : Boolean) extends Response - final case class Reload(mag : Int) extends Response -// final case class PlayerStateShift(itemID : PlanetSideGUID) extends Response -// final case class DestroyDisplay(itemID : PlanetSideGUID) extends Response -// final case class HitHintReturn(itemID : PlanetSideGUID) extends Response -// final case class ChangeWeapon(facingYaw : Int) extends Response -} diff --git a/pslogin/src/main/scala/services/local/LocalResponse.scala b/pslogin/src/main/scala/services/local/LocalResponse.scala new file mode 100644 index 000000000..72bd523f7 --- /dev/null +++ b/pslogin/src/main/scala/services/local/LocalResponse.scala @@ -0,0 +1,15 @@ +// Copyright (c) 2017 PSForever +package services.local + +import net.psforever.packet.game.{PlanetSideGUID, TriggeredSound} +import net.psforever.types.Vector3 + +object LocalResponse { + trait Response + + final case class DoorOpens(door_guid : PlanetSideGUID) extends Response + final case class DoorCloses(door_guid : PlanetSideGUID) extends Response + final case class HackClear(target_guid : PlanetSideGUID, unk1 : Long, unk2 : Long) extends Response + final case class HackObject(target_guid : PlanetSideGUID, unk1 : Long, unk2 : Long) extends Response + final case class TriggerSound(sound : TriggeredSound.Value, pos : Vector3, unk : Int, volume : Float) extends Response +} diff --git a/pslogin/src/main/scala/services/local/LocalService.scala b/pslogin/src/main/scala/services/local/LocalService.scala index 56acf25d8..bf5b109aa 100644 --- a/pslogin/src/main/scala/services/local/LocalService.scala +++ b/pslogin/src/main/scala/services/local/LocalService.scala @@ -6,7 +6,6 @@ import services.local.support.{DoorCloseActor, HackClearActor} import services.{GenericEventBus, Service} class LocalService extends Actor { - //import LocalService._ private val doorCloser = context.actorOf(Props[DoorCloseActor], "local-door-closer") private val hackClearer = context.actorOf(Props[HackClearActor], "local-hack-clearer") private [this] val log = org.log4s.getLogger @@ -19,7 +18,7 @@ class LocalService extends Actor { def receive = { case Service.Join(channel) => - val path = s"/$channel/LocalEnvironment" + val path = s"/$channel/Local" val who = sender() log.info(s"$who has joined $path") LocalEvents.subscribe(who, path) @@ -33,24 +32,24 @@ class LocalService extends Actor { case LocalAction.DoorOpens(player_guid, zone, door) => doorCloser ! DoorCloseActor.DoorIsOpen(door, zone) LocalEvents.publish( - LocalServiceResponse(s"/$forChannel/LocalEnvironment", player_guid, LocalServiceResponse.DoorOpens(door.GUID)) + LocalServiceResponse(s"/$forChannel/Local", player_guid, LocalResponse.DoorOpens(door.GUID)) ) case LocalAction.DoorCloses(player_guid, door_guid) => LocalEvents.publish( - LocalServiceResponse(s"/$forChannel/LocalEnvironment", player_guid, LocalServiceResponse.DoorCloses(door_guid)) + LocalServiceResponse(s"/$forChannel/Local", player_guid, LocalResponse.DoorCloses(door_guid)) ) case LocalAction.HackClear(player_guid, target, unk1, unk2) => LocalEvents.publish( - LocalServiceResponse(s"/$forChannel/LocalEnvironment", player_guid, LocalServiceResponse.HackClear(target.GUID, unk1, unk2)) + LocalServiceResponse(s"/$forChannel/Local", player_guid, LocalResponse.HackClear(target.GUID, unk1, unk2)) ) case LocalAction.HackTemporarily(player_guid, zone, target, unk1, unk2) => hackClearer ! HackClearActor.ObjectIsHacked(target, zone, unk1, unk2) LocalEvents.publish( - LocalServiceResponse(s"/$forChannel/LocalEnvironment", player_guid, LocalServiceResponse.HackObject(target.GUID, unk1, unk2)) + LocalServiceResponse(s"/$forChannel/Local", player_guid, LocalResponse.HackObject(target.GUID, unk1, unk2)) ) case LocalAction.TriggerSound(player_guid, sound, pos, unk, volume) => LocalEvents.publish( - LocalServiceResponse(s"/$forChannel/LocalEnvironment", player_guid, LocalServiceResponse.TriggerSound(sound, pos, unk, volume)) + LocalServiceResponse(s"/$forChannel/Local", player_guid, LocalResponse.TriggerSound(sound, pos, unk, volume)) ) case _ => ; } @@ -58,13 +57,13 @@ class LocalService extends Actor { //response from DoorCloseActor case DoorCloseActor.CloseTheDoor(door_guid, zone_id) => LocalEvents.publish( - LocalServiceResponse(s"/$zone_id/LocalEnvironment", Service.defaultPlayerGUID, LocalServiceResponse.DoorCloses(door_guid)) + LocalServiceResponse(s"/$zone_id/Local", Service.defaultPlayerGUID, LocalResponse.DoorCloses(door_guid)) ) //response from HackClearActor case HackClearActor.ClearTheHack(target_guid, zone_id, unk1, unk2) => LocalEvents.publish( - LocalServiceResponse(s"/$zone_id/LocalEnvironment", Service.defaultPlayerGUID, LocalServiceResponse.HackClear(target_guid, unk1, unk2)) + LocalServiceResponse(s"/$zone_id/Local", Service.defaultPlayerGUID, LocalResponse.HackClear(target_guid, unk1, unk2)) ) case msg => diff --git a/pslogin/src/main/scala/services/local/LocalServiceResponse.scala b/pslogin/src/main/scala/services/local/LocalServiceResponse.scala index 736732bc0..4708feb50 100644 --- a/pslogin/src/main/scala/services/local/LocalServiceResponse.scala +++ b/pslogin/src/main/scala/services/local/LocalServiceResponse.scala @@ -1,21 +1,10 @@ // Copyright (c) 2017 PSForever package services.local -import net.psforever.packet.game.{PlanetSideGUID, TriggeredSound} -import net.psforever.types.Vector3 +import net.psforever.packet.game.PlanetSideGUID import services.GenericEventBusMsg final case class LocalServiceResponse(toChannel : String, avatar_guid : PlanetSideGUID, - replyMessage : LocalServiceResponse.Response + replyMessage : LocalResponse.Response ) extends GenericEventBusMsg - -object LocalServiceResponse { - trait Response - - final case class DoorOpens(door_guid : PlanetSideGUID) extends Response - final case class DoorCloses(door_guid : PlanetSideGUID) extends Response - final case class HackClear(target_guid : PlanetSideGUID, unk1 : Long, unk2 : Long) extends Response - final case class HackObject(target_guid : PlanetSideGUID, unk1 : Long, unk2 : Long) extends Response - final case class TriggerSound(sound : TriggeredSound.Value, pos : Vector3, unk : Int, volume : Float) extends Response -} diff --git a/pslogin/src/main/scala/services/vehicle/VehicleAction.scala b/pslogin/src/main/scala/services/vehicle/VehicleAction.scala new file mode 100644 index 000000000..03d700f43 --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/VehicleAction.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2017 PSForever +package services.vehicle + +import net.psforever.objects.Vehicle +import net.psforever.objects.zones.Zone +import net.psforever.packet.game.PlanetSideGUID +import net.psforever.packet.game.objectcreate.ConstructorData +import net.psforever.types.Vector3 + +object VehicleAction { + trait Action + + final case class Awareness(player_guid : PlanetSideGUID, vehicle_guid : PlanetSideGUID) extends Action + final case class ChildObjectState(player_guid : PlanetSideGUID, object_guid : PlanetSideGUID, pitch : Float, yaw : Float) extends Action + final case class DismountVehicle(player_guid : PlanetSideGUID, unk1 : Int, unk2 : Boolean) extends Action + final case class KickPassenger(player_guid : PlanetSideGUID, unk1 : Int, unk2 : Boolean) extends Action + final case class LoadVehicle(player_guid : PlanetSideGUID, vehicle : Vehicle, vtype : Int, vguid : PlanetSideGUID, vdata : ConstructorData) extends Action + final case class MountVehicle(player_guid : PlanetSideGUID, object_guid : PlanetSideGUID, seat : Int) extends Action + final case class SeatPermissions(player_guid : PlanetSideGUID, vehicle_guid : PlanetSideGUID, seat_group : Int, permission : Long) extends Action + final case class UnloadVehicle(player_guid : PlanetSideGUID, continent : Zone, vehicle : Vehicle) extends Action + final case class VehicleState(player_guid : PlanetSideGUID, vehicle_guid : PlanetSideGUID, unk1 : Int, pos : Vector3, ang : Vector3, vel : Option[Vector3], unk2 : Option[Int], unk3 : Int, unk4 : Int, wheel_direction : Int, unk5 : Boolean, unk6 : Boolean) extends Action +} diff --git a/pslogin/src/main/scala/services/vehicle/VehicleResponse.scala b/pslogin/src/main/scala/services/vehicle/VehicleResponse.scala new file mode 100644 index 000000000..8806e1920 --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/VehicleResponse.scala @@ -0,0 +1,21 @@ +// Copyright (c) 2017 PSForever +package services.vehicle + +import net.psforever.objects.Vehicle +import net.psforever.packet.game.PlanetSideGUID +import net.psforever.packet.game.objectcreate.ConstructorData +import net.psforever.types.Vector3 + +object VehicleResponse { + trait Response + + final case class Awareness(vehicle_guid : PlanetSideGUID) extends Response + final case class ChildObjectState(object_guid : PlanetSideGUID, pitch : Float, yaw : Float) extends Response + final case class DismountVehicle(unk1 : Int, unk2 : Boolean) extends Response + final case class KickPassenger(unk1 : Int, unk2 : Boolean) extends Response + final case class LoadVehicle(vehicle : Vehicle, vtype : Int, vguid : PlanetSideGUID, vdata : ConstructorData) extends Response + final case class MountVehicle(object_guid : PlanetSideGUID, seat : Int) extends Response + final case class SeatPermissions(vehicle_guid : PlanetSideGUID, seat_group : Int, permission : Long) extends Response + final case class UnloadVehicle(vehicle_guid : PlanetSideGUID) extends Response + final case class VehicleState(vehicle_guid : PlanetSideGUID, unk1 : Int, pos : Vector3, ang : Vector3, vel : Option[Vector3], unk2 : Option[Int], unk3 : Int, unk4 : Int, wheel_direction : Int, unk5 : Boolean, unk6 : Boolean) extends Response +} diff --git a/pslogin/src/main/scala/services/vehicle/VehicleService.scala b/pslogin/src/main/scala/services/vehicle/VehicleService.scala new file mode 100644 index 000000000..12842a95b --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/VehicleService.scala @@ -0,0 +1,91 @@ +// Copyright (c) 2017 PSForever +package services.vehicle + +import akka.actor.{Actor, ActorRef, Props} +import services.vehicle.support.{DeconstructionActor, VehicleContextActor} +import services.{GenericEventBus, Service} + +class VehicleService extends Actor { + private val vehicleContext : ActorRef = context.actorOf(Props[VehicleContextActor], "vehicle-context-root") + private val vehicleDecon : ActorRef = context.actorOf(Props[DeconstructionActor], "vehicle-decon-agent") + vehicleDecon ! DeconstructionActor.RequestTaskResolver + private [this] val log = org.log4s.getLogger + + override def preStart = { + log.info("Starting...") + } + + val VehicleEvents = new GenericEventBus[VehicleServiceResponse] + + def receive = { + case Service.Join(channel) => + val path = s"/$channel/Vehicle" + val who = sender() + + log.info(s"$who has joined $path") + + VehicleEvents.subscribe(who, path) + case Service.Leave() => + VehicleEvents.unsubscribe(sender()) + case Service.LeaveAll() => + VehicleEvents.unsubscribe(sender()) + + case VehicleServiceMessage(forChannel, action) => + action match { + case VehicleAction.Awareness(player_guid, vehicle_guid) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.Awareness(vehicle_guid)) + ) + case VehicleAction.ChildObjectState(player_guid, object_guid, pitch, yaw) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.ChildObjectState(object_guid, pitch, yaw)) + ) + case VehicleAction.DismountVehicle(player_guid, unk1, unk2) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.DismountVehicle(unk1, unk2)) + ) + case VehicleAction.KickPassenger(player_guid, unk1, unk2) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.KickPassenger(unk1, unk2)) + ) + case VehicleAction.LoadVehicle(player_guid, vehicle, vtype, vguid, vdata) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.LoadVehicle(vehicle, vtype, vguid, vdata)) + ) + case VehicleAction.MountVehicle(player_guid, vehicle_guid, seat) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.MountVehicle(vehicle_guid, seat)) + ) + case VehicleAction.SeatPermissions(player_guid, vehicle_guid, seat_group, permission) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.SeatPermissions(vehicle_guid, seat_group, permission)) + ) + case VehicleAction.VehicleState(player_guid, vehicle_guid, unk1, pos, ang, vel, unk2, unk3, unk4, wheel_direction, unk5, unk6) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$forChannel/Vehicle", player_guid, VehicleResponse.VehicleState(vehicle_guid, unk1, pos, ang, vel, unk2, unk3, unk4, wheel_direction, unk5, unk6)) + ) + case _ => ; + } + + //message to VehicleContext + case VehicleServiceMessage.GiveActorControl(vehicle, actorName) => + vehicleContext ! VehicleServiceMessage.GiveActorControl(vehicle, actorName) + + //message to VehicleContext + case VehicleServiceMessage.RevokeActorControl(vehicle) => + vehicleContext ! VehicleServiceMessage.RevokeActorControl(vehicle) + + //message to DeconstructionActor + case VehicleServiceMessage.RequestDeleteVehicle(vehicle, continent) => + vehicleDecon ! DeconstructionActor.RequestDeleteVehicle(vehicle, continent) + + //response from DeconstructionActor + case DeconstructionActor.DeleteVehicle(vehicle_guid, zone_id) => + VehicleEvents.publish( + VehicleServiceResponse(s"/$zone_id/Vehicle", Service.defaultPlayerGUID, VehicleResponse.UnloadVehicle(vehicle_guid)) + ) + + case msg => + log.info(s"Unhandled message $msg from $sender") + } +} diff --git a/pslogin/src/main/scala/services/vehicle/VehicleServiceMessage.scala b/pslogin/src/main/scala/services/vehicle/VehicleServiceMessage.scala new file mode 100644 index 000000000..c3e1c4804 --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/VehicleServiceMessage.scala @@ -0,0 +1,13 @@ +// Copyright (c) 2017 PSForever +package services.vehicle + +import net.psforever.objects.Vehicle +import net.psforever.objects.zones.Zone + +final case class VehicleServiceMessage(forChannel : String, actionMessage : VehicleAction.Action) + +object VehicleServiceMessage { + final case class GiveActorControl(vehicle : Vehicle, actorName : String) + final case class RevokeActorControl(vehicle : Vehicle) + final case class RequestDeleteVehicle(vehicle : Vehicle, continent : Zone) +} diff --git a/pslogin/src/main/scala/services/vehicle/VehicleServiceResponse.scala b/pslogin/src/main/scala/services/vehicle/VehicleServiceResponse.scala new file mode 100644 index 000000000..c80128734 --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/VehicleServiceResponse.scala @@ -0,0 +1,11 @@ +// Copyright (c) 2017 PSForever +package services.vehicle + +import net.psforever.packet.game.PlanetSideGUID +import services.GenericEventBusMsg + +final case class VehicleServiceResponse(toChannel : String, + avatar_guid : PlanetSideGUID, + replyMessage : VehicleResponse.Response + ) extends GenericEventBusMsg + diff --git a/pslogin/src/main/scala/services/vehicle/support/DeconstructionActor.scala b/pslogin/src/main/scala/services/vehicle/support/DeconstructionActor.scala new file mode 100644 index 000000000..6ad68310a --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/support/DeconstructionActor.scala @@ -0,0 +1,181 @@ +// Copyright (c) 2017 PSForever +package services.vehicle.support + +import akka.actor.{Actor, ActorRef, Cancellable} +import net.psforever.objects.Vehicle +import net.psforever.objects.vehicles.Seat +import net.psforever.objects.zones.Zone +import net.psforever.packet.game.PlanetSideGUID +import scripts.GUIDTask +import services.ServiceManager +import services.ServiceManager.Lookup +import services.vehicle.{VehicleAction, VehicleServiceMessage} + +import scala.annotation.tailrec +import scala.concurrent.duration._ + +/** + * Manage a previously-functioning vehicle as it is being deconstructed.
+ *
+ * A reference to a vehicle should be passed to this object as soon as it is going to be cleaned-up from the game world. + * Once accepted, only a few seconds will remain before the vehicle is deleted. + * To ensure that no players are lost in the deletion, all occupants of the vehicle are kicked out. + * Furthermore, the vehicle is rendered "dead" and inaccessible right up to the point where it is removed. + */ +class DeconstructionActor extends Actor { + /** The periodic `Executor` that scraps the next vehicle on the list */ + private var scrappingProcess : Cancellable = DeconstructionActor.DefaultProcess + /** A `List` of currently doomed vehicles */ + private var vehicles : List[DeconstructionActor.VehicleEntry] = Nil + /** The manager that helps unregister the vehicle from its current GUID scope */ + private var taskResolver : ActorRef = Actor.noSender + //private[this] val log = org.log4s.getLogger + + + def receive : Receive = { + /* + ask for a resolver to deal with the GUID system + when the TaskResolver is finally delivered, switch over to a behavior that actually deals with submitted vehicles + */ + case DeconstructionActor.RequestTaskResolver => + ServiceManager.serviceManager ! Lookup("taskResolver") + + case ServiceManager.LookupResult("taskResolver", endpoint) => + taskResolver = endpoint + context.become(Processing) + + case _ => ; + } + + def Processing : Receive = { + case DeconstructionActor.RequestDeleteVehicle(vehicle, zone, time) => + vehicles = vehicles :+ DeconstructionActor.VehicleEntry(vehicle, zone, time) + vehicle.Actor ! Vehicle.PrepareForDeletion + //kick everyone out + vehicle.Definition.MountPoints.values.foreach(seat_num => { + val zone_id : String = zone.Id + val seat : Seat = vehicle.Seat(seat_num).get + seat.Occupant match { + case Some(tplayer) => + seat.Occupant = None + tplayer.VehicleSeated = None + context.parent ! VehicleServiceMessage(zone_id, VehicleAction.KickPassenger(tplayer.GUID, 4, false)) + case None => ; + } + }) + if(vehicles.size == 1) { //we were the only entry so the event must be started from scratch + import scala.concurrent.ExecutionContext.Implicits.global + scrappingProcess = context.system.scheduler.scheduleOnce(DeconstructionActor.timeout, self, DeconstructionActor.TryDeleteVehicle()) + } + + case DeconstructionActor.TryDeleteVehicle() => + scrappingProcess.cancel + val now : Long = System.nanoTime + val (vehiclesToScrap, vehiclesRemain) = PartitionEntries(vehicles, now) + vehicles = vehiclesRemain + vehiclesToScrap.foreach(entry => { + val vehicle = entry.vehicle + val zone = entry.zone + entry.zone.Transport ! Zone.DespawnVehicle(vehicle) + context.parent ! DeconstructionActor.DeleteVehicle(vehicle.GUID, zone.Id) //call up to the main event system + context.parent ! VehicleServiceMessage.RevokeActorControl(vehicle) //call up to a sibling manager + taskResolver ! GUIDTask.UnregisterVehicle(vehicle)(zone.GUID) + }) + + if(vehiclesRemain.nonEmpty) { + val short_timeout : FiniteDuration = math.max(1, DeconstructionActor.timeout_time - (now - vehiclesRemain.head.time)) nanoseconds + import scala.concurrent.ExecutionContext.Implicits.global + scrappingProcess = context.system.scheduler.scheduleOnce(short_timeout, self, DeconstructionActor.TryDeleteVehicle()) + } + + case _ => ; + } + + /** + * Iterate over entries in a `List` until an entry that does not exceed the time limit is discovered. + * Separate the original `List` into two: + * a `List` of elements that have exceeded the time limit, + * and a `List` of elements that still satisfy the time limit. + * As newer entries to the `List` will always resolve later than old ones, + * and newer entries are always added to the end of the main `List`, + * processing in order is always correct. + * @param list the `List` of entries to divide + * @param now the time right now (in nanoseconds) + * @see `List.partition` + * @return a `Tuple` of two `Lists`, whose qualifications are explained above + */ + private def PartitionEntries(list : List[DeconstructionActor.VehicleEntry], now : Long) : (List[DeconstructionActor.VehicleEntry], List[DeconstructionActor.VehicleEntry]) = { + val n : Int = recursivePartitionEntries(list.iterator, now) + (list.take(n), list.drop(n)) //take and drop so to always return new lists + } + + /** + * Mark the index where the `List` of elements can be divided into two: + * a `List` of elements that have exceeded the time limit, + * and a `List` of elements that still satisfy the time limit. + * @param iter the `Iterator` of entries to divide + * @param now the time right now (in nanoseconds) + * @param index a persistent record of the index where list division should occur; + * defaults to 0 + * @return the index where division will occur + */ + @tailrec private def recursivePartitionEntries(iter : Iterator[DeconstructionActor.VehicleEntry], now : Long, index : Int = 0) : Int = { + if(!iter.hasNext) { + index + } + else { + val entry = iter.next() + if(now - entry.time >= DeconstructionActor.timeout_time) { + recursivePartitionEntries(iter, now, index + 1) + } + else { + index + } + } + } +} + +object DeconstructionActor { + /** The wait before completely deleting a vehicle; as a Long for calculation simplicity */ + private final val timeout_time : Long = 5000000000L //nanoseconds (5s) + /** The wait before completely deleting a vehicle; as a `FiniteDuration` for `Executor` simplicity */ + private final val timeout : FiniteDuration = timeout_time nanoseconds + + private final val DefaultProcess : Cancellable = new Cancellable() { + override def cancel : Boolean = true + override def isCancelled : Boolean = true + } + + final case class RequestTaskResolver() + + /** + * Message that carries information about a vehicle to be deconstructed. + * @param vehicle the `Vehicle` object + * @param zone the `Zone` in which the vehicle resides + * @param time when the vehicle was doomed + * @see `VehicleEntry` + */ + final case class RequestDeleteVehicle(vehicle : Vehicle, zone : Zone, time : Long = System.nanoTime()) + /** + * Message that carries information about a vehicle to be deconstructed. + * Prompting, as compared to `RequestDeleteVehicle` which is reactionary. + * @param vehicle_guid the vehicle + * @param zone_id the `Zone` in which the vehicle resides + */ + final case class DeleteVehicle(vehicle_guid : PlanetSideGUID, zone_id : String) + /** + * Internal message used to signal a test of the queued vehicle information. + */ + private final case class TryDeleteVehicle() + + /** + * Entry of vehicle information. + * The `zone` is maintained separately as a necessity, required to complete the deletion of the vehicle + * via unregistering of the vehicle and all related, registered objects. + * @param vehicle the `Vehicle` object + * @param zone the `Zone` in which the vehicle resides + * @param time when the vehicle was doomed + * @see `RequestDeleteVehicle` + */ + private final case class VehicleEntry(vehicle : Vehicle, zone : Zone, time : Long) +} diff --git a/pslogin/src/main/scala/services/vehicle/support/VehicleContextActor.scala b/pslogin/src/main/scala/services/vehicle/support/VehicleContextActor.scala new file mode 100644 index 000000000..756a31a34 --- /dev/null +++ b/pslogin/src/main/scala/services/vehicle/support/VehicleContextActor.scala @@ -0,0 +1,30 @@ +// Copyright (c) 2017 PSForever +package services.vehicle.support + +import akka.actor.{Actor, Props} +import net.psforever.objects.vehicles.VehicleControl +import services.vehicle.VehicleServiceMessage + +/** + * Provide a context for a `Vehicle` `Actor` - the `VehicleControl`.
+ *
+ * A vehicle can be passed between different zones and, therefore, does not belong to the zone. + * A vehicle cna be given to different players and can persist and change though players have gone. + * Therefore, also does not belong to `WorldSessionActor`. + * A vehicle must anchored to something that exists outside of the `InterstellarCluster` and its agents.
+ *
+ * The only purpose of this `Actor` is to allow vehicles to borrow a context for the purpose of `Actor` creation. + * It is also be allowed to be responsible for cleaning up that context. + * (In reality, it can be cleaned up anywhere a `PoisonPill` can be sent.) + */ +class VehicleContextActor() extends Actor { + def receive : Receive = { + case VehicleServiceMessage.GiveActorControl(vehicle, actorName) => + vehicle.Actor = context.actorOf(Props(classOf[VehicleControl], vehicle), s"${vehicle.Definition.Name}_$actorName") + + case VehicleServiceMessage.RevokeActorControl(vehicle) => + vehicle.Actor ! akka.actor.PoisonPill + + case _ => ; + } +}