Merge branch 'main' into mpgem_editor

This commit is contained in:
puvvadar
2021-04-28 15:51:53 -07:00
4762 changed files with 75455 additions and 116479 deletions
+27 -15
View File
@@ -15,6 +15,7 @@
#include <AzCore/RTTI/RTTI.h>
#include <AzNetworking/ConnectionLayer/IConnection.h>
#include <AzNetworking/DataStructures/ByteBuffer.h>
#include <Include/MultiplayerStats.h>
namespace AzNetworking
{
@@ -23,21 +24,6 @@ namespace AzNetworking
namespace Multiplayer
{
struct MultiplayerStats
{
uint64_t m_entityCount = 0;
uint64_t m_clientConnectionCount = 0;
uint64_t m_serverConnectionCount = 0;
uint64_t m_propertyUpdatesSent = 0;
uint64_t m_propertyUpdatesSentBytes = 0;
uint64_t m_propertyUpdatesRecv = 0;
uint64_t m_propertyUpdatesRecvBytes = 0;
uint64_t m_rpcsSent = 0;
uint64_t m_rpcsSentBytes = 0;
uint64_t m_rpcsRecv = 0;
uint64_t m_rpcsRecvBytes = 0;
};
//! Collection of types of Multiplayer Connections
enum class MultiplayerAgentType
{
@@ -88,6 +74,32 @@ namespace Multiplayer
//! @param handler The SessionShutdownEvent handler to add
virtual void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) = 0;
//! Sends a packet telling if entity update messages can be sent
//! @param readyForEntityUpdates Ready for entity updates or not
virtual void SendReadyForEntityUpdates(bool readyForEntityUpdates) = 0;
//! Returns the gem name associated with the provided component index.
//! @param netComponentId the componentId to return the gem name of
//! @return the name of the gem that contains the requested component
virtual const char* GetComponentGemName(NetComponentId netComponentId) const = 0;
//! Returns the component name associated with the provided component index.
//! @param netComponentId the componentId to return the component name of
//! @return the name of the component
virtual const char* GetComponentName(NetComponentId netComponentId) const = 0;
//! Returns the property name associated with the provided component index and property index.
//! @param netComponentId the component index to return the property name of
//! @param propertyIndex the index of the network property to return the property name of
//! @return the name of the network property
virtual const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const = 0;
//! Returns the Rpc name associated with the provided component index and rpc index.
//! @param netComponentId the componentId to return the property name of
//! @param rpcIndex the index of the rpc to return the rpc name of
//! @return the name of the requested rpc
virtual const char* GetComponentRpcName(NetComponentId netComponentId, RpcIndex rpcIndex) const = 0;
//! Retrieve the stats object bound to this multiplayer instance.
//! @return the stats object bound to this multiplayer instance
MultiplayerStats& GetStats() { return m_stats; }
@@ -0,0 +1,164 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <Include/MultiplayerStats.h>
namespace Multiplayer
{
void MultiplayerStats::ReserveComponentStats(NetComponentId netComponentId, uint16_t propertyCount, uint16_t rpcCount)
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
if (m_componentStats.size() <= netComponentIndex)
{
m_componentStats.resize(netComponentIndex + 1);
}
m_componentStats[netComponentIndex].m_propertyUpdatesSent.resize(propertyCount);
m_componentStats[netComponentIndex].m_propertyUpdatesRecv.resize(propertyCount);
m_componentStats[netComponentIndex].m_rpcsSent.resize(rpcCount);
m_componentStats[netComponentIndex].m_rpcsRecv.resize(rpcCount);
}
void MultiplayerStats::RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes)
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
const uint16_t propertyIndex = aznumeric_cast<uint16_t>(propertyId);
m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_totalCalls++;
m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_totalBytes += totalBytes;
m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_callHistory[m_recordMetricIndex]++;
m_componentStats[netComponentIndex].m_propertyUpdatesSent[propertyIndex].m_byteHistory[m_recordMetricIndex] += totalBytes;
}
void MultiplayerStats::RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes)
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
const uint16_t propertyIndex = aznumeric_cast<uint16_t>(propertyId);
m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_totalCalls++;
m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_totalBytes += totalBytes;
m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_callHistory[m_recordMetricIndex]++;
m_componentStats[netComponentIndex].m_propertyUpdatesRecv[propertyIndex].m_byteHistory[m_recordMetricIndex] += totalBytes;
}
void MultiplayerStats::RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes)
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
const uint16_t rpcIndex = aznumeric_cast<uint16_t>(rpcId);
m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_totalCalls++;
m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_totalBytes += totalBytes;
m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_callHistory[m_recordMetricIndex]++;
m_componentStats[netComponentIndex].m_rpcsSent[rpcIndex].m_byteHistory[m_recordMetricIndex] += totalBytes;
}
void MultiplayerStats::RecordRpcReceived(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes)
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
const uint16_t rpcIndex = aznumeric_cast<uint16_t>(rpcId);
m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_totalCalls++;
m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_totalBytes += totalBytes;
m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_callHistory[m_recordMetricIndex]++;
m_componentStats[netComponentIndex].m_rpcsRecv[rpcIndex].m_byteHistory[m_recordMetricIndex] += totalBytes;
}
void MultiplayerStats::TickStats(AZ::TimeMs metricFrameTimeMs)
{
m_totalHistoryTimeMs = metricFrameTimeMs * static_cast<AZ::TimeMs>(RingbufferSamples);
m_recordMetricIndex = ++m_recordMetricIndex % RingbufferSamples;
}
static void CombineMetrics(MultiplayerStats::Metric& outArg1, const MultiplayerStats::Metric& arg2)
{
outArg1.m_totalCalls += arg2.m_totalCalls;
outArg1.m_totalBytes += arg2.m_totalBytes;
for (uint32_t index = 0; index < MultiplayerStats::RingbufferSamples; ++index)
{
outArg1.m_callHistory[index] += arg2.m_callHistory[index];
outArg1.m_byteHistory[index] += arg2.m_byteHistory[index];
}
}
static MultiplayerStats::Metric SumMetricVector(const AZStd::vector<MultiplayerStats::Metric>& metricVector)
{
MultiplayerStats::Metric result;
for (AZStd::size_t index = 0; index < metricVector.size(); ++index)
{
CombineMetrics(result, metricVector[index]);
}
return result;
}
MultiplayerStats::Metric MultiplayerStats::CalculateComponentPropertyUpdateSentMetrics(NetComponentId netComponentId) const
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
return SumMetricVector(m_componentStats[netComponentIndex].m_propertyUpdatesSent);
}
MultiplayerStats::Metric MultiplayerStats::CalculateComponentPropertyUpdateRecvMetrics(NetComponentId netComponentId) const
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
return SumMetricVector(m_componentStats[netComponentIndex].m_propertyUpdatesRecv);
}
MultiplayerStats::Metric MultiplayerStats::CalculateComponentRpcsSentMetrics(NetComponentId netComponentId) const
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
return SumMetricVector(m_componentStats[netComponentIndex].m_rpcsSent);
}
MultiplayerStats::Metric MultiplayerStats::CalculateComponentRpcsRecvMetrics(NetComponentId netComponentId) const
{
const uint16_t netComponentIndex = aznumeric_cast<uint16_t>(netComponentId);
return SumMetricVector(m_componentStats[netComponentIndex].m_rpcsRecv);
}
MultiplayerStats::Metric MultiplayerStats::CalculateTotalPropertyUpdateSentMetrics() const
{
Metric result;
for (AZStd::size_t index = 0; index < m_componentStats.size(); ++index)
{
const NetComponentId netComponentId = aznumeric_cast<NetComponentId>(index);
CombineMetrics(result, CalculateComponentPropertyUpdateSentMetrics(netComponentId));
}
return result;
}
MultiplayerStats::Metric MultiplayerStats::CalculateTotalPropertyUpdateRecvMetrics() const
{
Metric result;
for (AZStd::size_t index = 0; index < m_componentStats.size(); ++index)
{
const NetComponentId netComponentId = aznumeric_cast<NetComponentId>(index);
CombineMetrics(result, CalculateComponentPropertyUpdateRecvMetrics(netComponentId));
}
return result;
}
MultiplayerStats::Metric MultiplayerStats::CalculateTotalRpcsSentMetrics() const
{
Metric result;
for (AZStd::size_t index = 0; index < m_componentStats.size(); ++index)
{
const NetComponentId netComponentId = aznumeric_cast<NetComponentId>(index);
CombineMetrics(result, CalculateComponentRpcsSentMetrics(netComponentId));
}
return result;
}
MultiplayerStats::Metric MultiplayerStats::CalculateTotalRpcsRecvMetrics() const
{
Metric result;
for (AZStd::size_t index = 0; index < m_componentStats.size(); ++index)
{
const NetComponentId netComponentId = aznumeric_cast<NetComponentId>(index);
CombineMetrics(result, CalculateComponentRpcsRecvMetrics(netComponentId));
}
return result;
}
}
@@ -0,0 +1,71 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Time/ITime.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/containers/array.h>
#include <Include/MultiplayerTypes.h>
namespace AzNetworking
{
class INetworkInterface;
}
namespace Multiplayer
{
struct MultiplayerStats
{
uint64_t m_entityCount = 0;
uint64_t m_clientConnectionCount = 0;
uint64_t m_serverConnectionCount = 0;
uint64_t m_recordMetricIndex = 0;
AZ::TimeMs m_totalHistoryTimeMs = AZ::TimeMs{ 0 };
static const uint32_t RingbufferSamples = 32;
using MetricRingbuffer = AZStd::array<uint64_t, RingbufferSamples>;
struct Metric
{
uint64_t m_totalCalls = 0;
uint64_t m_totalBytes = 0;
MetricRingbuffer m_callHistory;
MetricRingbuffer m_byteHistory;
};
struct ComponentStats
{
AZStd::vector<Metric> m_propertyUpdatesSent;
AZStd::vector<Metric> m_propertyUpdatesRecv;
AZStd::vector<Metric> m_rpcsSent;
AZStd::vector<Metric> m_rpcsRecv;
};
AZStd::vector<ComponentStats> m_componentStats;
void ReserveComponentStats(NetComponentId netComponentId, uint16_t propertyCount, uint16_t rpcCount);
void RecordPropertySent(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes);
void RecordPropertyReceived(NetComponentId netComponentId, PropertyIndex propertyId, uint32_t totalBytes);
void RecordRpcSent(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes);
void RecordRpcReceived(NetComponentId netComponentId, RpcIndex rpcId, uint32_t totalBytes);
void TickStats(AZ::TimeMs metricFrameTimeMs);
Metric CalculateComponentPropertyUpdateSentMetrics(NetComponentId netComponentId) const;
Metric CalculateComponentPropertyUpdateRecvMetrics(NetComponentId netComponentId) const;
Metric CalculateComponentRpcsSentMetrics(NetComponentId netComponentId) const;
Metric CalculateComponentRpcsRecvMetrics(NetComponentId netComponentId) const;
Metric CalculateTotalPropertyUpdateSentMetrics() const;
Metric CalculateTotalPropertyUpdateRecvMetrics() const;
Metric CalculateTotalRpcsSentMetrics() const;
Metric CalculateTotalRpcsRecvMetrics() const;
};
}
@@ -0,0 +1,124 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/EBus/Event.h>
#include <AzCore/Name/Name.h>
#include <AzCore/RTTI/TypeSafeIntegral.h>
#include <AzCore/std/string/fixed_string.h>
#include <AzNetworking/Serialization/ISerializer.h>
#include <AzNetworking/ConnectionLayer/ConnectionEnums.h>
namespace Multiplayer
{
//! The default number of rewindable samples for us to store.
static constexpr uint32_t RewindHistorySize = 128;
AZ_TYPE_SAFE_INTEGRAL(HostId, uint32_t);
static constexpr HostId InvalidHostId = static_cast<HostId>(-1);
AZ_TYPE_SAFE_INTEGRAL(NetEntityId, uint32_t);
static constexpr NetEntityId InvalidNetEntityId = static_cast<NetEntityId>(-1);
AZ_TYPE_SAFE_INTEGRAL(NetComponentId, uint16_t);
static constexpr NetComponentId InvalidNetComponentId = static_cast<NetComponentId>(-1);
AZ_TYPE_SAFE_INTEGRAL(PropertyIndex, uint16_t);
AZ_TYPE_SAFE_INTEGRAL(RpcIndex, uint16_t);
using LongNetworkString = AZ::CVarFixedString;
using ReliabilityType = AzNetworking::ReliabilityType;
class NetworkEntityRpcMessage;
using RpcSendEvent = AZ::Event<NetworkEntityRpcMessage&>;
// Note that we explicitly set storage classes so that sizeof() is accurate for serialized size
enum class RpcDeliveryType : uint8_t
{
None,
AuthorityToClient, // Invoked from Authority, handled on Client
AuthorityToAutonomous, // Invoked from Authority, handled on Autonomous
AutonomousToAuthority, // Invoked from Autonomous, handled on Authority
ServerToAuthority // Invoked from Server, handled on Authority
};
enum class NetEntityRole : uint8_t
{
InvalidRole, // No role
Client, // A simulated proxy on a client
Autonomous, // An autonomous proxy on a client (can execute local prediction)
Server, // A simulated proxy on a server
Authority // An authoritative proxy on a server (full authority)
};
enum class ComponentSerializationType : uint8_t
{
Properties,
Correction
};
enum class EntityIsMigrating : uint8_t
{
False,
True
};
enum class AutoActivate : uint8_t
{
DoNotActivate,
Activate
};
// This is just a placeholder
// The level/prefab cooking will devise the actual solution for identifying a dynamically spawnable entity within a prefab
struct PrefabEntityId
{
AZ_TYPE_INFO(PrefabEntityId, "{EFD37465-CCAC-4E87-A825-41B4010A2C75}");
static constexpr uint32_t AllIndices = AZStd::numeric_limits<uint32_t>::max();
AZ::Name m_prefabName;
uint32_t m_entityOffset = AllIndices;
PrefabEntityId() = default;
explicit PrefabEntityId(AZ::Name name, uint32_t entityOffset = AllIndices)
: m_prefabName(name)
, m_entityOffset(entityOffset)
{
}
bool operator==(const PrefabEntityId& rhs) const
{
return m_prefabName == rhs.m_prefabName && m_entityOffset == rhs.m_entityOffset;
}
bool operator!=(const PrefabEntityId& rhs) const
{
return !(*this == rhs);
}
bool Serialize(AzNetworking::ISerializer& serializer)
{
serializer.Serialize(m_prefabName, "prefabName");
serializer.Serialize(m_entityOffset, "entityOffset");
return serializer.IsValid();
}
};
}
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::HostId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetEntityId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetComponentId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::PropertyIndex);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::RpcIndex);
@@ -1,7 +1,7 @@
#pragma once
#include <AzCore/std/containers/list.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
namespace AZ
{
@@ -12,15 +12,8 @@ namespace AZ
{% set Namespace = dataFiles[0].attrib['Namespace'] %}
namespace {{ Namespace }}
{
enum class ComponentTypes
{
{% for Component in dataFiles %}
{% set ComponentName = Component.attrib['Name'] %}
{{ ComponentName }},
{% endfor %}
Count
};
static_assert(ComponentTypes::Count < static_cast<ComponentTypes>(Multiplayer::InvalidNetComponentId), "ComponentId overflow");
//! Registers all multiplayer components contained within this gem with the MultiplayerComponentRegistry.
void RegisterMultiplayerComponents();
//! For reflecting multiplayer components into the serialize, edit, and behaviour contexts.
void CreateComponentDescriptors(AZStd::list<AZ::ComponentDescriptor*>& descriptors);
@@ -1,4 +1,6 @@
#include <AzCore/Component/Component.h>
#include <Source/Components/MultiplayerComponentRegistry.h>
#include <Source/NetworkEntity/INetworkEntityManager.h>
{% for Component in dataFiles %}
{% set ComponentDerived = Component.attrib['OverrideComponent']|booleanTrue %}
{% set ControllerDerived = Component.attrib['OverrideController']|booleanTrue %}
@@ -10,8 +12,38 @@
{% endfor %}
{% set Namespace = dataFiles[0].attrib['Namespace'] %}
{% for Component in dataFiles %}
{% if Component.attrib['Namespace'] != Namespace %}
#error "mismatched component namespaces detected in declared multiplayer components, expected {{ Namespace }} but found {{ Component.attrib['Namespace'] }}"
{% endif %}
{% endfor %}
namespace {{ Namespace }}
{
void RegisterMultiplayerComponents()
{
Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry();
Multiplayer::MultiplayerStats& stats = AZ::Interface<Multiplayer::IMultiplayer>::Get()->GetStats();
{% for Component in dataFiles %}
{% set ComponentName = Component.attrib['Name'] %}
{% set ComponentBaseName = ComponentName %}
{% if Component.attrib['OverrideComponent']|booleanTrue %}
{% set ComponentBaseName = ComponentName + "Base" %}
{% endif %}
{% set NetworkInputCount = Component.findall('NetworkInput') | len %}
{% set NetworkPropertyCount = Component.findall('NetworkProperty') | len %}
{% set RpcCount = Component.findall('RemoteProcedure') | len %}
{
Multiplayer::MultiplayerComponentRegistry::ComponentData componentData;
componentData.m_gemName = AZ::Name("{{ Namespace }}");
componentData.m_componentName = AZ::Name("{{ Component.attrib['Name'] }}");
componentData.m_componentPropertyNameLookupFunction = {{ ComponentBaseName }}::GetNetworkPropertyName;
componentData.m_componentRpcNameLookupFunction = {{ ComponentBaseName }}::GetRpcName;
{{ ComponentBaseName }}::s_netComponentId = multiplayerComponentRegistry->RegisterMultiplayerComponent(componentData);
stats.ReserveComponentStats({{ ComponentBaseName }}::s_netComponentId, static_cast<uint16_t>({{ NetworkPropertyCount }}), static_cast<uint16_t>({{ RpcCount }}));
}
{% endfor %}
}
void CreateComponentDescriptors(AZStd::list<AZ::ComponentDescriptor*>& descriptors)
{
descriptors.insert(descriptors.end(), {
@@ -227,7 +227,7 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] }
#include <Source/Components/MultiplayerController.h>
#include <Source/NetworkInput/IMultiplayerComponentInput.h>
#include <Source/NetworkTime/RewindableObject.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
{% call(Include) AutoComponentMacros.ParseIncludes(Component) %}
#include <{{ Include.attrib['File'] }}>
{% endcall %}
@@ -251,9 +251,6 @@ namespace {{ Component.attrib['Namespace'] }}
class {{ ComponentName }};
class {{ ControllerName }};
//! Returns a human readable name for the provided remoteProcedureId.
const char* GetRemoteProcedureName(uint16_t remoteProcedureId);
{% set RecordName = ComponentName + "Record" %}
//! @class {{RecordName }}
//! @brief A record of the changed bits in the NetworkProperties for component {{ ComponentName }}.
@@ -329,7 +326,6 @@ namespace {{ Component.attrib['Namespace'] }}
: public Multiplayer::IMultiplayerComponentInput
{
public:
static const Multiplayer::NetComponentId s_componentId = static_cast<Multiplayer::NetComponentId>({{ Component.attrib['Namespace'] }}::ComponentTypes::{{ Component.attrib['Name'] }});
Multiplayer::NetComponentId GetComponentId() const override;
INetworkInput& operator=(const INetworkInput& rhs) override;
bool Serialize(AzNetworking::ISerializer& serializer);
@@ -412,8 +408,6 @@ namespace {{ Component.attrib['Namespace'] }}
AZ_MULTIPLAYER_COMPONENT({{ Component.attrib['Namespace'] }}::{{ ComponentBaseName }}, s_{{ LowerFirst(ComponentName) }}ConcreteUuid, Multiplayer::MultiplayerComponent);
{% endif %}
static const Multiplayer::NetComponentId s_componentId = static_cast<Multiplayer::NetComponentId>({{ Component.attrib['Namespace'] }}::ComponentTypes::{{ Component.attrib['Name'] }});
static void Reflect(AZ::ReflectContext* context);
static void ReflectToEditContext(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
@@ -489,6 +483,10 @@ namespace {{ Component.attrib['Namespace'] }}
bool SerializeAutonomousToAuthorityProperties({{ RecordName }}& replicationRecord, AzNetworking::ISerializer& serializer);
void NotifyChangesAutonomousToAuthorityProperties(const {{ RecordName }}& replicationRecord) const;
//! Debug name helpers
static const char* GetNetworkPropertyName(PropertyIndex propertyIndex);
static const char* GetRpcName(RpcIndex rpcIndex);
AZStd::unique_ptr<{{ RecordName }}> m_currentRecord;
AZStd::unique_ptr<{{ ControllerName }}> m_controller;
@@ -518,6 +516,9 @@ namespace {{ Component.attrib['Namespace'] }}
{% call(Type, Name) AutoComponentMacros.ParseComponentServiceTypeAndName(Component) %}
{{ Type }}* {{ Name }} = nullptr;
{% endcall %}
static NetComponentId s_netComponentId;
friend void RegisterMultiplayerComponents();
};
}
{% endfor %}
@@ -285,15 +285,15 @@ void {{ ClassName }}::Set{{ UpperFirst(Property.attrib['Name']) }}(const {{ Prop
{{ AutoComponentMacros.ParseRpcParams(Property, paramNames, paramTypes, paramDefines) }}
void {{ ClassName }}::{{ UpperFirst(Property.attrib['Name']) }}({{ ', '.join(paramDefines) }})
{
constexpr uint8_t rpcId = static_cast<uint8_t>({{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ UpperFirst(Property.attrib['Name']) }});
constexpr Multiplayer::NetComponentId componentId = static_cast<Multiplayer::NetComponentId>({{ Component.attrib['Namespace'] }}::ComponentTypes::{{ Component.attrib['Name'] }});
constexpr RpcIndex rpcId = static_cast<RpcIndex>({{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ UpperFirst(Property.attrib['Name']) }});
{% if Property.attrib['IsReliable']|booleanTrue %}
constexpr AzNetworking::ReliabilityType isReliable = Multiplayer::ReliabilityType::Reliable;
{% else %}
constexpr AzNetworking::ReliabilityType isReliable = Multiplayer::ReliabilityType::Unreliable;
{% endif %}
Multiplayer::NetworkEntityRpcMessage rpcMessage(Multiplayer::RpcDeliveryType::{{ InvokeFrom }}To{{ HandleOn }}, GetNetEntityId(), componentId, rpcId, isReliable);
const Multiplayer::NetComponentId netComponentId = GetParent().GetNetComponentId();
Multiplayer::NetworkEntityRpcMessage rpcMessage(Multiplayer::RpcDeliveryType::{{ InvokeFrom }}To{{ HandleOn }}, GetNetEntityId(), netComponentId, rpcId, isReliable);
{% if paramNames|count > 0 %}
{{ UpperFirst(Component.attrib['Name']) }}Internal::{{ UpperFirst(Property.attrib['Name']) }}RpcStruct rpcStruct({{ ', '.join(paramNames) }});
{% else %}
@@ -509,6 +509,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re
m_{{ LowerFirst(Property.attrib['Name']) }},
"{{ Property.attrib['Name'] }}",
GetNetComponentId(),
static_cast<PropertyIndex>({{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties::{{ UpperFirst(Property.attrib['Name']) }}),
stats
);
{% endif %}
@@ -646,6 +647,16 @@ enum class RemoteProcedure
MAX
};
{% endmacro %}
{% macro DeclareNetworkPropertyEnumerations(Component) %}
enum class NetworkProperties
{
{% for NetworkProperty in Component.iter('NetworkProperty') %}
{{ UpperFirst(NetworkProperty.attrib['Name']) }},
{% endfor %}
MAX
};
{% endmacro %}
{#
@@ -881,6 +892,9 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N
{% else %}
{% set ControllerBaseName = ControllerName %}
{% endif %}
{% set NetworkInputCount = Component.findall('NetworkInput') | len %}
{% set NetworkPropertyCount = Component.findall('NetworkProperty') | len %}
{% set RpcCount = Component.findall('RemoteProcedure') | len %}
#include "{{ includeFile }}"
#include <AzCore/Console/IConsole.h>
#include <AzCore/Console/ILogger.h>
@@ -901,9 +915,12 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N
namespace {{ Component.attrib['Namespace'] }}
{
NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = InvalidNetComponentId;
namespace {{ UpperFirst(Component.attrib['Name']) }}Internal
{
{{ DeclareRemoteProcedureEnumerations(Component)|indent(8) }}
{{ DeclareNetworkPropertyEnumerations(Component)|indent(8) }}
{{ DefineNetworkPropertyDirtyEnumeration(Component, ClassType, 'Authority', 'Authority')|indent(8) }}
{{ DefineNetworkPropertyDirtyEnumeration(Component, ClassType, 'Authority', 'Client')|indent(8) }}
{{ DefineNetworkPropertyDirtyEnumeration(Component, ClassType, 'Authority', 'Server')|indent(8) }}
@@ -1229,14 +1246,14 @@ namespace {{ Component.attrib['Namespace'] }}
Multiplayer::NetComponentId {{ ComponentBaseName }}::GetNetComponentId() const
{
return s_componentId;
return s_netComponentId;
}
#pragma warning(push)
#pragma warning(disable: 4065) // switch statement contains 'default' but no 'case' labels
bool {{ ComponentBaseName }}::HandleRpcMessage([[maybe_unused]] Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& message)
{
const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcType = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(message.GetRpcMessageType());
const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcType = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(message.GetRpcIndex());
switch (rpcType)
{
{{ DeclareRpcHandleCases(Component, ComponentDerived, 'Server', 'Authority', "(remoteRole == Multiplayer::NetEntityRole::Authority || remoteRole == Multiplayer::NetEntityRole::Server)" )|indent(8) }}
@@ -1379,6 +1396,35 @@ namespace {{ Component.attrib['Namespace'] }}
}
{% endif %}
const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] PropertyIndex propertyIndex)
{
{% if NetworkPropertyCount > 0 %}
const {{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties propertyId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties>(propertyIndex);
switch (propertyId)
{
{% for NetworkProperty in Component.iter('NetworkProperty') %}
case {{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties::{{ UpperFirst(NetworkProperty.attrib['Name']) }}:
return "{{ UpperFirst(NetworkProperty.attrib['Name']) }}";
{% endfor %}
}
{% endif %}
return "Unknown network property";
}
const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] RpcIndex rpcIndex)
{
{% if RpcCount > 0 %}
const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(rpcIndex);
switch (rpcId)
{
{% for RemoteProcedure in Component.iter('RemoteProcedure') %}
case {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure::{{ RemoteProcedure.attrib['Name'] }}:
return "{{ RemoteProcedure.attrib['Name'] }}";
{% endfor %}
}
{% endif %}
return "Unknown Rpc";
}
{% endfor %}
}
{% endfor %}
@@ -10,7 +10,7 @@
<ComponentRelation Constraint="Weak" HasController="true" Name="NetworkTransformComponent" Namespace="Multiplayer" Include="Source/Components/NetworkTransformComponent.h" />
<Include File="Source/MultiplayerTypes.h"/>
<Include File="Include/MultiplayerTypes.h"/>
<Include File="Source/NetworkInput/NetworkInput.h"/>
<Include File="Source/NetworkInput/NetworkInputHistory.h"/>
<Include File="Source/NetworkInput/NetworkInputVector.h"/>
@@ -2,7 +2,7 @@
<PacketGroup Name="MultiplayerPackets" PacketStart="CorePackets::PacketType::MAX">
<Include File="AzNetworking/AutoGen/CorePackets.AutoPackets.h" />
<Include File="Source/MultiplayerTypes.h" />
<Include File="Include/MultiplayerTypes.h" />
<Include File="Source/NetworkEntity/NetworkEntityRpcMessage.h" />
<Include File="Source/NetworkEntity/NetworkEntityUpdateMessage.h" />
@@ -14,6 +14,10 @@
<Member Type="Multiplayer::HostId" Name="hostId" Init="Multiplayer::InvalidHostId" />
<Member Type="Multiplayer::LongNetworkString" Name="map" />
</Packet>
<Packet Name="ReadyForEntityUpdates" Desc="Client confirming it is ready to receive entity updates">
<Member Type="bool" Name="readyForEntityUpdates" />
</Packet>
<Packet Name="SyncConsole" Desc="Packet for synchornizing cvars between hosts">
<Member Type="Multiplayer::LongNetworkString" Name="commandSet" Container="Vector" Count="32" />
@@ -10,7 +10,7 @@
<ComponentRelation Constraint="Weak" HasController="false" Name="TransformComponent" Namespace="AzFramework" Include="AzFramework/Components/TransformComponent.h" />
<Include File="Source/MultiplayerTypes.h"/>
<Include File="Include/MultiplayerTypes.h"/>
<NetworkProperty Type="AZ::Quaternion" Name="rotation" Init="AZ::Quaternion::CreateIdentity()" ReplicateFrom="Authority" ReplicateTo="Client" IsRewindable="true" IsPredictable="true" IsPublic="true" Container="Object" ExposeToEditor="false" GenerateEventBindings="true" />
<NetworkProperty Type="AZ::Vector3" Name="translation" Init="AZ::Vector3::CreateZero()" ReplicateFrom="Authority" ReplicateTo="Client" IsRewindable="true" IsPredictable="true" IsPublic="true" Container="Object" ExposeToEditor="false" GenerateEventBindings="true" />
@@ -16,7 +16,7 @@
#include <AzNetworking/Serialization/ISerializer.h>
#include <AzNetworking/DataStructures/FixedSizeBitsetView.h>
#include <Source/NetworkEntity/NetworkEntityHandle.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <Include/IMultiplayer.h>
//! Macro to declare bindings for a multiplayer component inheriting from MultiplayerComponent
@@ -104,13 +104,14 @@ namespace Multiplayer
template <typename TYPE>
inline void SerializeNetworkPropertyHelper
(
AzNetworking::ISerializer& serializer,
bool modifyRecord,
AzNetworking::FixedSizeBitsetView& bitset,
int32_t bitIndex,
TYPE& value,
const char* name,
[[maybe_unused]] NetComponentId componentId,
AzNetworking::ISerializer& serializer,
bool modifyRecord,
AzNetworking::FixedSizeBitsetView& bitset,
int32_t bitIndex,
TYPE& value,
const char* name,
NetComponentId componentId,
PropertyIndex propertyIndex,
MultiplayerStats& stats
)
{
@@ -131,13 +132,11 @@ namespace Multiplayer
{
if (modifyRecord)
{
stats.m_propertyUpdatesRecv++;
stats.m_propertyUpdatesRecvBytes += updateSize;
stats.RecordPropertyReceived(componentId, propertyIndex, updateSize);
}
else
{
stats.m_propertyUpdatesSent++;
stats.m_propertyUpdatesSentBytes += updateSize;
stats.RecordPropertySent(componentId, propertyIndex, updateSize);
}
}
}
@@ -0,0 +1,58 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <Source/Components/MultiplayerComponentRegistry.h>
namespace Multiplayer
{
NetComponentId MultiplayerComponentRegistry::RegisterMultiplayerComponent(const ComponentData& componentData)
{
NetComponentId netComponentId = m_nextNetComponentId++;
m_componentData[netComponentId] = componentData;
return netComponentId;
}
const char* MultiplayerComponentRegistry::GetComponentGemName(NetComponentId netComponentId) const
{
const ComponentData& componentData = GetMultiplayerComponentData(netComponentId);
return componentData.m_gemName.GetCStr();
}
const char* MultiplayerComponentRegistry::GetComponentName(NetComponentId netComponentId) const
{
const ComponentData& componentData = GetMultiplayerComponentData(netComponentId);
return componentData.m_componentName.GetCStr();
}
const char* MultiplayerComponentRegistry::GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const
{
const ComponentData& componentData = GetMultiplayerComponentData(netComponentId);
return componentData.m_componentPropertyNameLookupFunction(propertyIndex);
}
const char* MultiplayerComponentRegistry::GetComponentRpcName(NetComponentId netComponentId, RpcIndex rpcIndex) const
{
const ComponentData& componentData = GetMultiplayerComponentData(netComponentId);
return componentData.m_componentRpcNameLookupFunction(rpcIndex);
}
const MultiplayerComponentRegistry::ComponentData& MultiplayerComponentRegistry::GetMultiplayerComponentData(NetComponentId netComponentId) const
{
static ComponentData nullComponentData;
auto it = m_componentData.find(netComponentId);
if (it != m_componentData.end())
{
return it->second;
}
return nullComponentData;
}
}
@@ -0,0 +1,70 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/Name/Name.h>
#include <AzCore/std/containers/unordered_map.h>
#include <Source/Components/MultiplayerComponent.h>
namespace Multiplayer
{
class MultiplayerComponentRegistry
{
public:
using PropertyNameLookupFunction = AZStd::function<const char*(PropertyIndex index)>;
using RpcNameLookupFunction = AZStd::function<const char* (RpcIndex index)>;
struct ComponentData
{
AZ::Name m_gemName;
AZ::Name m_componentName;
PropertyNameLookupFunction m_componentPropertyNameLookupFunction;
RpcNameLookupFunction m_componentRpcNameLookupFunction;
};
//! Registers a multiplayer component with the multiplayer system.
//! @param componentData the data associated with the component being registered
//! @return the NetComponentId assigned to this particular component
NetComponentId RegisterMultiplayerComponent(const ComponentData& componentData);
//! Returns the gem name associated with the provided NetComponentId.
//! @param netComponentId the NetComponentId to return the gem name of
//! @return the name of the gem that contains the requested component
const char* GetComponentGemName(NetComponentId netComponentId) const;
//! Returns the component name associated with the provided NetComponentId.
//! @param netComponentId the NetComponentId to return the component name of
//! @return the name of the component
const char* GetComponentName(NetComponentId netComponentId) const;
//! Returns the property name associated with the provided NetComponentId and propertyIndex.
//! @param netComponentId the NetComponentId to return the property name of
//! @param propertyIndex the index off the network property to return the property name of
//! @return the name of the network property
const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const;
//! Returns the Rpc name associated with the provided NetComponentId and rpcId.
//! @param netComponentId the NetComponentId to return the property name of
//! @param rpcIndex the index of the rpc to return the rpc name of
//! @return the name of the requested rpc
const char* GetComponentRpcName(NetComponentId netComponentId, RpcIndex rpcIndex) const;
//! Retrieves the stored component data for a given NetComponentId.
//! @param netComponentId the NetComponentId to return component data for
//! @return reference to the requested component data, an empty container will be returned if the NetComponentId does not exist
const ComponentData& GetMultiplayerComponentData(NetComponentId netComponentId) const;
private:
NetComponentId m_nextNetComponentId = NetComponentId{ 0 };
AZStd::unordered_map<NetComponentId, ComponentData> m_componentData;
};
}
@@ -23,7 +23,7 @@
#include <Source/NetworkEntity/EntityReplication/ReplicationRecord.h>
#include <Source/NetworkEntity/NetworkEntityHandle.h>
#include <Source/NetworkInput/IMultiplayerComponentInput.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <AzCore/EBus/Event.h>
namespace Multiplayer
@@ -14,10 +14,8 @@
namespace Multiplayer
{
static constexpr uint32_t Uint32Max = AZStd::numeric_limits<uint32_t>::max();
// This can be used to help mitigate client side performance when large numbers of entities are created off the network
AZ_CVAR(uint32_t, cl_ClientMaxRemoteEntitiesPendingCreationCount, Uint32Max, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we have sent to the client, but have not had a confirmation back from the client");
AZ_CVAR(uint32_t, cl_ClientMaxRemoteEntitiesPendingCreationCount, AZStd::numeric_limits<uint32_t>::max(), nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we have sent to the client, but have not had a confirmation back from the client");
AZ_CVAR(AZ::TimeMs, cl_ClientEntityReplicatorPendingRemovalTimeMs, AZ::TimeMs{ 10000 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "How long should wait prior to removing an entity for the client through a change in the replication window, entity deletes are still immediate");
ClientToServerConnectionData::ClientToServerConnectionData
@@ -33,10 +33,10 @@ namespace Multiplayer
AzNetworking::IConnection* GetConnection() const override;
EntityReplicationManager& GetReplicationManager() override;
void Update(AZ::TimeMs serverGameTimeMs) override;
bool CanSendUpdates() const override;
void SetCanSendUpdates(bool canSendUpdates) override;
//! @}
bool CanSendUpdates();
private:
EntityReplicationManager m_entityReplicationManager;
AzNetworking::IConnection* m_connection = nullptr;
@@ -12,8 +12,13 @@
namespace Multiplayer
{
inline bool ClientToServerConnectionData::CanSendUpdates()
inline bool ClientToServerConnectionData::CanSendUpdates() const
{
return m_canSendUpdates;
}
inline void ClientToServerConnectionData::SetCanSendUpdates(bool canSendUpdates)
{
m_canSendUpdates = canSendUpdates;
}
}
@@ -44,5 +44,13 @@ namespace Multiplayer
//! Creates and manages sending updates to the remote endpoint.
//! @param serverGameTimeMs current server game time in milliseconds
virtual void Update(AZ::TimeMs serverGameTimeMs) = 0;
//! Returns whether update messages can be sent to the connection.
//! @return true if update messages can be sent
virtual bool CanSendUpdates() const = 0;
//! Sets the state of connection whether update messages can be sent or not.
//! @param canSendUpdates the state value
virtual void SetCanSendUpdates(bool canSendUpdates) = 0;
};
}
@@ -14,11 +14,9 @@
namespace Multiplayer
{
static constexpr uint32_t Uint32Max = AZStd::numeric_limits<uint32_t>::max();
// This can be used to help mitigate client side performance when large numbers of entities are created off the network
AZ_CVAR(uint32_t, sv_ClientMaxRemoteEntitiesPendingCreationCount, Uint32Max, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we have sent to the client, but have not had a confirmation back from the client");
AZ_CVAR(uint32_t, sv_ClientMaxRemoteEntitiesPendingCreationCountPostInit, Uint32Max, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we will send to clients after gameplay has begun");
AZ_CVAR(uint32_t, sv_ClientMaxRemoteEntitiesPendingCreationCount, AZStd::numeric_limits<uint32_t>::max(), nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we have sent to the client, but have not had a confirmation back from the client");
AZ_CVAR(uint32_t, sv_ClientMaxRemoteEntitiesPendingCreationCountPostInit, AZStd::numeric_limits<uint32_t>::max(), nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we will send to clients after gameplay has begun");
AZ_CVAR(AZ::TimeMs, sv_ClientEntityReplicatorPendingRemovalTimeMs, AZ::TimeMs{ 10000 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "How long should wait prior to removing an entity for the client through a change in the replication window, entity deletes are still immediate");
ServerToClientConnectionData::ServerToClientConnectionData
@@ -34,10 +34,10 @@ namespace Multiplayer
AzNetworking::IConnection* GetConnection() const override;
EntityReplicationManager& GetReplicationManager() override;
void Update(AZ::TimeMs serverGameTimeMs) override;
bool CanSendUpdates() const override;
void SetCanSendUpdates(bool canSendUpdates) override;
//! @}
bool CanSendUpdates();
NetworkEntityHandle GetPrimaryPlayerEntity();
const NetworkEntityHandle& GetPrimaryPlayerEntity() const;
@@ -51,7 +51,7 @@ namespace Multiplayer
EntityStopEvent::Handler m_controlledEntityRemovedHandler;
EntityMigrationEvent::Handler m_controlledEntityMigrationHandler;
AzNetworking::IConnection* m_connection = nullptr;
bool m_canSendUpdates = true;
bool m_canSendUpdates = false;
};
}
@@ -12,11 +12,17 @@
namespace Multiplayer
{
inline bool ServerToClientConnectionData::CanSendUpdates()
inline bool ServerToClientConnectionData::CanSendUpdates() const
{
return m_canSendUpdates;
}
inline void ServerToClientConnectionData::SetCanSendUpdates(bool canSendUpdates)
{
m_canSendUpdates = canSendUpdates;
}
inline NetworkEntityHandle ServerToClientConnectionData::GetPrimaryPlayerEntity()
{
return m_controlledEntity;
@@ -60,63 +60,227 @@ namespace Multiplayer
{
if (ImGui::BeginMenu("Multiplayer"))
{
//{
// static int lossPercent{ 0 };
// lossPercent = static_cast<int>(net_UdpDebugLossPercent);
// if (ImGui::SliderInt("UDP Loss Percent", &lossPercent, 0, 100))
// {
// net_UdpDebugLossPercent = lossPercent;
// m_ClientAgent.UpdateConnectionCvars(net_UdpDebugLossPercent);
// }
//}
//
//{
// static int latency{ 0 };
// latency = static_cast<int>(net_UdpDebugLatencyMs);
// if (ImGui::SliderInt("UDP Latency Ms", &latency, 0, 3000))
// {
// net_UdpDebugLatencyMs = latency;
// m_ClientAgent.UpdateConnectionCvars(net_UdpDebugLatencyMs);
// }
//}
//
//{
// static int variance{ 0 };
// variance = static_cast<int>(net_UdpDebugVarianceMs);
// if (ImGui::SliderInt("UDP Variance Ms", &variance, 0, 1000))
// {
// net_UdpDebugVarianceMs = variance;
// m_ClientAgent.UpdateConnectionCvars(net_UdpDebugVarianceMs);
// }
//}
ImGui::Checkbox("Multiplayer Stats", &m_displayStats);
ImGui::Checkbox("Networking Stats", &m_displayNetworkingStats);
ImGui::Checkbox("Multiplayer Stats", &m_displayMultiplayerStats);
ImGui::EndMenu();
}
}
void AccumulatePerSecondValues(const MultiplayerStats& stats, const MultiplayerStats::Metric& metric, float& outCallsPerSecond, float& outBytesPerSecond)
{
uint64_t summedCalls = 0;
uint64_t summedBytes = 0;
for (uint32_t index = 0; index < MultiplayerStats::RingbufferSamples; ++index)
{
summedCalls += metric.m_callHistory[index];
summedBytes += metric.m_byteHistory[index];
}
const float totalTimeSeconds = static_cast<float>(stats.m_totalHistoryTimeMs) / 1000.0f;
outCallsPerSecond += (summedCalls > 0 && totalTimeSeconds > 0.0f) ? static_cast<float>(summedCalls) / totalTimeSeconds : 0.0f;
outBytesPerSecond += (summedBytes > 0 && totalTimeSeconds > 0.0f) ? static_cast<float>(summedBytes) / totalTimeSeconds : 0.0f;
}
bool DrawMetricsRow(const char* name, bool expandable, uint64_t totalCalls, uint64_t totalBytes, float callsPerSecond, float bytesPerSecond)
{
const ImGuiTreeNodeFlags flags = expandable ? ImGuiTreeNodeFlags_SpanFullWidth
: (ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::TableNextRow();
ImGui::TableNextColumn();
const bool open = ImGui::TreeNodeEx(name, flags);
ImGui::TableNextColumn();
ImGui::Text("%11llu", aznumeric_cast<AZ::u64>(totalCalls));
ImGui::TableNextColumn();
ImGui::Text("%11llu", aznumeric_cast<AZ::u64>(totalBytes));
ImGui::TableNextColumn();
ImGui::Text("%11.2f", callsPerSecond);
ImGui::TableNextColumn();
ImGui::Text("%11.2f", bytesPerSecond);
return open;
}
bool DrawSummaryRow(const char* name, const MultiplayerStats& stats)
{
const MultiplayerStats::Metric propertyUpdatesSent = stats.CalculateTotalPropertyUpdateSentMetrics();
const MultiplayerStats::Metric propertyUpdatesRecv = stats.CalculateTotalPropertyUpdateRecvMetrics();
const MultiplayerStats::Metric rpcsSent = stats.CalculateTotalRpcsSentMetrics();
const MultiplayerStats::Metric rpcsRecv = stats.CalculateTotalRpcsRecvMetrics();
const uint64_t totalCalls = propertyUpdatesSent.m_totalCalls + propertyUpdatesRecv.m_totalCalls + rpcsSent.m_totalCalls + rpcsRecv.m_totalCalls;
const uint64_t totalBytes = propertyUpdatesSent.m_totalBytes + propertyUpdatesRecv.m_totalBytes + rpcsSent.m_totalBytes + rpcsRecv.m_totalBytes;
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, propertyUpdatesSent, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, propertyUpdatesRecv, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, rpcsSent, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, rpcsRecv, callsPerSecond, bytesPerSecond);
return DrawMetricsRow(name, true, totalCalls, totalBytes, callsPerSecond, bytesPerSecond);
}
bool DrawComponentRow(const char* name, const MultiplayerStats& stats, NetComponentId netComponentId)
{
const MultiplayerStats::Metric propertyUpdatesSent = stats.CalculateComponentPropertyUpdateSentMetrics(netComponentId);
const MultiplayerStats::Metric propertyUpdatesRecv = stats.CalculateComponentPropertyUpdateRecvMetrics(netComponentId);
const MultiplayerStats::Metric rpcsSent = stats.CalculateComponentRpcsSentMetrics(netComponentId);
const MultiplayerStats::Metric rpcsRecv = stats.CalculateComponentRpcsRecvMetrics(netComponentId);
const uint64_t totalCalls = propertyUpdatesSent.m_totalCalls + propertyUpdatesRecv.m_totalCalls + rpcsSent.m_totalCalls + rpcsRecv.m_totalCalls;
const uint64_t totalBytes = propertyUpdatesSent.m_totalBytes + propertyUpdatesRecv.m_totalBytes + rpcsSent.m_totalBytes + rpcsRecv.m_totalBytes;
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, propertyUpdatesSent, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, propertyUpdatesRecv, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, rpcsSent, callsPerSecond, bytesPerSecond);
AccumulatePerSecondValues(stats, rpcsRecv, callsPerSecond, bytesPerSecond);
return DrawMetricsRow(name, true, totalCalls, totalBytes, callsPerSecond, bytesPerSecond);
}
void DrawComponentDetails(const MultiplayerStats& stats, NetComponentId netComponentId)
{
IMultiplayer* multiplayer = AZ::Interface<IMultiplayer>::Get();
{
const MultiplayerStats::Metric metric = stats.CalculateComponentPropertyUpdateSentMetrics(netComponentId);
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, metric, callsPerSecond, bytesPerSecond);
if (DrawMetricsRow("PropertyUpdates Sent", true, metric.m_totalCalls, metric.m_totalBytes, callsPerSecond, bytesPerSecond))
{
const MultiplayerStats::ComponentStats& componentStats = stats.m_componentStats[aznumeric_cast<AZStd::size_t>(netComponentId)];
for (AZStd::size_t index = 0; index < componentStats.m_propertyUpdatesSent.size(); ++index)
{
const PropertyIndex propertyIndex = aznumeric_cast<PropertyIndex>(index);
const char* propertyName = multiplayer->GetComponentPropertyName(netComponentId, propertyIndex);
const MultiplayerStats::Metric& subMetric = componentStats.m_propertyUpdatesSent[index];
callsPerSecond = 0.0f;
bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, subMetric, callsPerSecond, bytesPerSecond);
DrawMetricsRow(propertyName, false, subMetric.m_totalCalls, subMetric.m_totalBytes, callsPerSecond, bytesPerSecond);
}
ImGui::TreePop();
}
}
{
const MultiplayerStats::Metric metric = stats.CalculateComponentPropertyUpdateRecvMetrics(netComponentId);
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, metric, callsPerSecond, bytesPerSecond);
if (DrawMetricsRow("PropertyUpdates Recv", true, metric.m_totalCalls, metric.m_totalBytes, callsPerSecond, bytesPerSecond))
{
const MultiplayerStats::ComponentStats& componentStats = stats.m_componentStats[aznumeric_cast<AZStd::size_t>(netComponentId)];
for (AZStd::size_t index = 0; index < componentStats.m_propertyUpdatesRecv.size(); ++index)
{
const PropertyIndex propertyIndex = aznumeric_cast<PropertyIndex>(index);
const char* propertyName = multiplayer->GetComponentPropertyName(netComponentId, propertyIndex);
const MultiplayerStats::Metric& subMetric = componentStats.m_propertyUpdatesRecv[index];
callsPerSecond = 0.0f;
bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, subMetric, callsPerSecond, bytesPerSecond);
DrawMetricsRow(propertyName, false, subMetric.m_totalCalls, subMetric.m_totalBytes, callsPerSecond, bytesPerSecond);
}
ImGui::TreePop();
}
}
{
const MultiplayerStats::Metric metric = stats.CalculateComponentRpcsSentMetrics(netComponentId);
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, metric, callsPerSecond, bytesPerSecond);
if (DrawMetricsRow("RemoteProcedures Sent", true, metric.m_totalCalls, metric.m_totalBytes, callsPerSecond, bytesPerSecond))
{
const MultiplayerStats::ComponentStats& componentStats = stats.m_componentStats[aznumeric_cast<AZStd::size_t>(netComponentId)];
for (AZStd::size_t index = 0; index < componentStats.m_rpcsSent.size(); ++index)
{
const RpcIndex rpcIndex = aznumeric_cast<RpcIndex>(index);
const char* rpcName = multiplayer->GetComponentRpcName(netComponentId, rpcIndex);
const MultiplayerStats::Metric& subMetric = componentStats.m_rpcsSent[index];
callsPerSecond = 0.0f;
bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, subMetric, callsPerSecond, bytesPerSecond);
DrawMetricsRow(rpcName, false, subMetric.m_totalCalls, subMetric.m_totalBytes, callsPerSecond, bytesPerSecond);
}
ImGui::TreePop();
}
}
{
const MultiplayerStats::Metric metric = stats.CalculateComponentRpcsRecvMetrics(netComponentId);
float callsPerSecond = 0.0f;
float bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, metric, callsPerSecond, bytesPerSecond);
if (DrawMetricsRow("RemoteProcedures Recv", true, metric.m_totalCalls, metric.m_totalBytes, callsPerSecond, bytesPerSecond))
{
const MultiplayerStats::ComponentStats& componentStats = stats.m_componentStats[aznumeric_cast<AZStd::size_t>(netComponentId)];
for (AZStd::size_t index = 0; index < componentStats.m_rpcsRecv.size(); ++index)
{
const RpcIndex rpcIndex = aznumeric_cast<RpcIndex>(index);
const char* rpcName = multiplayer->GetComponentRpcName(netComponentId, rpcIndex);
const MultiplayerStats::Metric& subMetric = componentStats.m_rpcsRecv[index];
callsPerSecond = 0.0f;
bytesPerSecond = 0.0f;
AccumulatePerSecondValues(stats, subMetric, callsPerSecond, bytesPerSecond);
DrawMetricsRow(rpcName, false, subMetric.m_totalCalls, subMetric.m_totalBytes, callsPerSecond, bytesPerSecond);
}
ImGui::TreePop();
}
}
}
void MultiplayerDebugSystemComponent::OnImGuiUpdate()
{
if (m_displayStats)
const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x;
const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing();
if (m_displayMultiplayerStats)
{
if (ImGui::Begin("Multiplayer Stats", &m_displayStats, ImGuiWindowFlags_HorizontalScrollbar))
if (ImGui::Begin("Multiplayer Stats", &m_displayMultiplayerStats, ImGuiWindowFlags_HorizontalScrollbar))
{
IMultiplayer* multiplayer = AZ::Interface<IMultiplayer>::Get();
Multiplayer::MultiplayerStats& stats = multiplayer->GetStats();
const Multiplayer::MultiplayerStats& stats = multiplayer->GetStats();
ImGui::Text("Multiplayer operating in %s mode", GetEnumString(multiplayer->GetAgentType()));
ImGui::Text("Total networked entities: %llu", aznumeric_cast<AZ::u64>(stats.m_entityCount));
ImGui::Text("Total client connections: %llu", aznumeric_cast<AZ::u64>(stats.m_clientConnectionCount));
ImGui::Text("Total server connections: %llu", aznumeric_cast<AZ::u64>(stats.m_serverConnectionCount));
ImGui::Text("Total property updates sent: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesSent));
ImGui::Text("Total property updates sent bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesSentBytes));
ImGui::Text("Total property updates received: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesRecv));
ImGui::Text("Total property updates received bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesRecvBytes));
ImGui::Text("Total RPCs sent: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsSent));
ImGui::Text("Total RPCs sent bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsSentBytes));
ImGui::Text("Total RPCs received: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsRecv));
ImGui::Text("Total RPCs received bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsRecvBytes));
ImGui::NewLine();
static ImGuiTableFlags flags = ImGuiTableFlags_BordersV
| ImGuiTableFlags_BordersOuterH
| ImGuiTableFlags_Resizable
| ImGuiTableFlags_RowBg
| ImGuiTableFlags_NoBordersInBody;
if (ImGui::BeginTable("", 5, flags))
{
// The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On
ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide, TEXT_BASE_WIDTH * 36.0f);
ImGui::TableSetupColumn("Total Calls", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
ImGui::TableSetupColumn("Total Bytes", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
ImGui::TableSetupColumn("Calls/Sec", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
ImGui::TableSetupColumn("Bytes/Sec", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
ImGui::TableHeadersRow();
if (DrawSummaryRow("Totals", stats))
{
for (AZStd::size_t index = 0; index < stats.m_componentStats.size(); ++index)
{
const NetComponentId netComponentId = aznumeric_cast<NetComponentId>(index);
using StringLabel = AZStd::fixed_string<128>;
const StringLabel gemName = multiplayer->GetComponentGemName(netComponentId);
const StringLabel componentName = multiplayer->GetComponentName(netComponentId);
const StringLabel label = gemName + "::" + componentName;
if (DrawComponentRow(label.c_str(), stats, netComponentId))
{
DrawComponentDetails(stats, netComponentId);
ImGui::TreePop();
}
}
}
ImGui::EndTable();
}
ImGui::End();
}
ImGui::End();
}
}
#endif
@@ -51,6 +51,7 @@ namespace Multiplayer
//! @}
#endif
private:
bool m_displayStats = false;
bool m_displayNetworkingStats = false;
bool m_displayMultiplayerStats = false;
};
}
@@ -114,6 +114,9 @@ namespace Multiplayer
m_networkInterface = AZ::Interface<INetworking>::Get()->CreateNetworkInterface(AZ::Name(s_networkInterfaceName), sv_protocol, TrustZone::ExternalClientToServer, *this);
m_consoleCommandHandler.Connect(AZ::Interface<AZ::IConsole>::Get()->GetConsoleCommandInvokedEvent());
AZ::Interface<IMultiplayer>::Register(this);
//! Register our gems multiplayer components to assign NetComponentIds
RegisterMultiplayerComponents();
}
void MultiplayerSystemComponent::Deactivate()
@@ -381,6 +384,19 @@ namespace Multiplayer
return false;
}
bool MultiplayerSystemComponent::HandleRequest( AzNetworking::IConnection* connection,
[[maybe_unused]] const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::ReadyForEntityUpdates& packet)
{
IConnectionData* connectionData = reinterpret_cast<IConnectionData*>(connection->GetUserData());
if (connectionData)
{
connectionData->SetCanSendUpdates(packet.GetReadyForEntityUpdates());
return true;
}
return false;
}
ConnectResult MultiplayerSystemComponent::ValidateConnect
(
[[maybe_unused]] const IpAddress& remoteAddress,
@@ -503,6 +519,35 @@ namespace Multiplayer
handler.Connect(m_shutdownEvent);
}
void MultiplayerSystemComponent::SendReadyForEntityUpdates(bool readyForEntityUpdates)
{
IConnectionSet& connectionSet = m_networkInterface->GetConnectionSet();
connectionSet.VisitConnections([readyForEntityUpdates](IConnection& connection)
{
connection.SendReliablePacket(MultiplayerPackets::ReadyForEntityUpdates(readyForEntityUpdates));
});
}
const char* MultiplayerSystemComponent::GetComponentGemName(NetComponentId netComponentId) const
{
return GetMultiplayerComponentRegistry()->GetComponentGemName(netComponentId);
}
const char* MultiplayerSystemComponent::GetComponentName(NetComponentId netComponentId) const
{
return GetMultiplayerComponentRegistry()->GetComponentName(netComponentId);
}
const char* MultiplayerSystemComponent::GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const
{
return GetMultiplayerComponentRegistry()->GetComponentPropertyName(netComponentId, propertyIndex);
}
const char* MultiplayerSystemComponent::GetComponentRpcName(NetComponentId netComponentId, RpcIndex rpcIndex) const
{
return GetMultiplayerComponentRegistry()->GetComponentRpcName(netComponentId, rpcIndex);
}
void MultiplayerSystemComponent::DumpStats([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments)
{
const MultiplayerStats& stats = GetStats();
@@ -510,14 +555,20 @@ namespace Multiplayer
AZLOG_INFO("Total networked entities: %llu", aznumeric_cast<AZ::u64>(stats.m_entityCount));
AZLOG_INFO("Total client connections: %llu", aznumeric_cast<AZ::u64>(stats.m_clientConnectionCount));
AZLOG_INFO("Total server connections: %llu", aznumeric_cast<AZ::u64>(stats.m_serverConnectionCount));
AZLOG_INFO("Total property updates sent: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesSent));
AZLOG_INFO("Total property updates sent bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesSentBytes));
AZLOG_INFO("Total property updates received: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesRecv));
AZLOG_INFO("Total property updates received bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_propertyUpdatesRecvBytes));
AZLOG_INFO("Total RPCs sent: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsSent));
AZLOG_INFO("Total RPCs sent bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsSentBytes));
AZLOG_INFO("Total RPCs received: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsRecv));
AZLOG_INFO("Total RPCs received bytes: %llu", aznumeric_cast<AZ::u64>(stats.m_rpcsRecvBytes));
const MultiplayerStats::Metric propertyUpdatesSent = stats.CalculateTotalPropertyUpdateSentMetrics();
const MultiplayerStats::Metric propertyUpdatesRecv = stats.CalculateTotalPropertyUpdateRecvMetrics();
const MultiplayerStats::Metric rpcsSent = stats.CalculateTotalRpcsSentMetrics();
const MultiplayerStats::Metric rpcsRecv = stats.CalculateTotalRpcsRecvMetrics();
AZLOG_INFO("Total property updates sent: %llu", aznumeric_cast<AZ::u64>(propertyUpdatesSent.m_totalCalls));
AZLOG_INFO("Total property updates sent bytes: %llu", aznumeric_cast<AZ::u64>(propertyUpdatesSent.m_totalBytes));
AZLOG_INFO("Total property updates received: %llu", aznumeric_cast<AZ::u64>(propertyUpdatesRecv.m_totalCalls));
AZLOG_INFO("Total property updates received bytes: %llu", aznumeric_cast<AZ::u64>(propertyUpdatesRecv.m_totalBytes));
AZLOG_INFO("Total RPCs sent: %llu", aznumeric_cast<AZ::u64>(rpcsSent.m_totalCalls));
AZLOG_INFO("Total RPCs sent bytes: %llu", aznumeric_cast<AZ::u64>(rpcsSent.m_totalBytes));
AZLOG_INFO("Total RPCs received: %llu", aznumeric_cast<AZ::u64>(rpcsRecv.m_totalCalls));
AZLOG_INFO("Total RPCs received bytes: %llu", aznumeric_cast<AZ::u64>(rpcsRecv.m_totalBytes));
}
void MultiplayerSystemComponent::OnConsoleCommandInvoked
@@ -71,6 +71,7 @@ namespace Multiplayer
bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::ClientMigration& packet);
bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::NotifyClientMigration& packet);
bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::EntityMigration& packet);
bool HandleRequest(AzNetworking::IConnection* connection, const AzNetworking::IPacketHeader& packetHeader, MultiplayerPackets::ReadyForEntityUpdates& packet);
//! IConnectionListener interface
//! @{
@@ -88,6 +89,11 @@ namespace Multiplayer
void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) override;
void AddSessionInitHandler(SessionInitEvent::Handler& handler) override;
void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) override;
void SendReadyForEntityUpdates(bool readyForEntityUpdates) override;
const char* GetComponentGemName(NetComponentId netComponentId) const override;
const char* GetComponentName(NetComponentId netComponentId) const override;
const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const override;
const char* GetComponentRpcName(NetComponentId netComponentId, RpcIndex rpcIndex) const override;
//! @}
//! Console commands.
@@ -33,6 +33,9 @@ namespace Multiplayer
AZ_TYPE_SAFE_INTEGRAL(NetComponentId, uint16_t);
static constexpr NetComponentId InvalidNetComponentId = static_cast<NetComponentId>(-1);
AZ_TYPE_SAFE_INTEGRAL(PropertyIndex, uint16_t);
AZ_TYPE_SAFE_INTEGRAL(RpcIndex, uint16_t);
using LongNetworkString = AZ::CVarFixedString;
using ReliabilityType = AzNetworking::ReliabilityType;
@@ -70,6 +73,12 @@ namespace Multiplayer
True
};
enum class AutoActivate : uint8_t
{
DoNotActivate,
Activate
};
// This is just a placeholder
// The level/prefab cooking will devise the actual solution for identifying a dynamically spawnable entity within a prefab
struct PrefabEntityId
@@ -111,3 +120,5 @@ namespace Multiplayer
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::HostId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetEntityId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::NetComponentId);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::PropertyIndex);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(Multiplayer::RpcIndex);
@@ -21,6 +21,7 @@
#include <Source/NetworkEntity/INetworkEntityManager.h>
#include <Source/Components/NetBindComponent.h>
#include <Source/AutoGen/Multiplayer.AutoPackets.h>
#include <Include/IMultiplayer.h>
#include <AzNetworking/ConnectionLayer/IConnection.h>
#include <AzNetworking/ConnectionLayer/IConnectionListener.h>
#include <AzNetworking/PacketLayer/IPacketHeader.h>
@@ -542,11 +543,8 @@ namespace Multiplayer
// Create an entity if we don't have one
if (createEntity)
{
// @pereslav
//replicatorEntity = GetNetworkEntityManager()->CreateSingleEntityImmediateInternal(prefabEntityId, EntitySpawnType::Replicate, AutoActivate::DoNotActivate, netEntityId, localNetworkRole, AZ::Transform::Identity());
INetworkEntityManager::EntityList entityList = GetNetworkEntityManager()->CreateEntitiesImmediate(
prefabEntityId, netEntityId, localNetworkRole,
AZ::Transform::Identity());
prefabEntityId, netEntityId, localNetworkRole, AutoActivate::DoNotActivate, AZ::Transform::Identity());
if (entityList.size() == 1)
{
@@ -825,11 +823,12 @@ namespace Multiplayer
{
if (entityReplicator == nullptr)
{
IMultiplayer* multiplayer = AZ::Interface<IMultiplayer>::Get();
AZLOG_INFO
(
"EntityReplicationManager: Dropping remote RPC message for component %u of rpc type %d, entityId %u has already been deleted",
aznumeric_cast<uint32_t>(message.GetComponentId()),
message.GetRpcMessageType(),
"EntityReplicationManager: Dropping remote RPC message for component %s of rpc index %s, entityId %u has already been deleted",
multiplayer->GetComponentName(message.GetComponentId()),
multiplayer->GetComponentRpcName(message.GetComponentId(), message.GetRpcIndex()),
message.GetEntityId()
);
return false;
@@ -449,8 +449,7 @@ namespace Multiplayer
{
// Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics
MultiplayerStats& stats = AZ::Interface<IMultiplayer>::Get()->GetStats();
stats.m_rpcsSent++;
stats.m_rpcsSentBytes += entityRpcMessage.GetEstimatedSerializeSize();
stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize());
m_replicationManager.AddDeferredRpcMessage(entityRpcMessage);
}
@@ -604,7 +603,7 @@ namespace Multiplayer
aznumeric_cast<uint32_t>(GetRemoteNetworkRole()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcDeliveryType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetComponentId()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcMessageType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcIndex()),
entityRpcMessage.GetReliability() == ReliabilityType::Reliable ? "true" : "false",
IsMarkedForRemoval() ? "true" : "false"
);
@@ -621,7 +620,7 @@ namespace Multiplayer
aznumeric_cast<uint32_t>(GetRemoteNetworkRole()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcDeliveryType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetComponentId()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcMessageType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcIndex()),
entityRpcMessage.GetReliability() == ReliabilityType::Reliable ? "true" : "false",
IsMarkedForRemoval() ? "true" : "false"
);
@@ -633,8 +632,7 @@ namespace Multiplayer
{
// Received rpc metrics, log rpc received, time spent, number of bytes, and the componentId/rpcId for bandwidth metrics
MultiplayerStats& stats = AZ::Interface<IMultiplayer>::Get()->GetStats();
stats.m_rpcsRecv++;
stats.m_rpcsRecvBytes += entityRpcMessage.GetEstimatedSerializeSize();
stats.RecordRpcReceived(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize());
if (!m_netBindComponent)
{
@@ -646,7 +644,7 @@ namespace Multiplayer
aznumeric_cast<uint32_t>(GetRemoteNetworkRole()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcDeliveryType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetComponentId()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcMessageType()),
aznumeric_cast<uint32_t>(entityRpcMessage.GetRpcIndex()),
entityRpcMessage.GetReliability() == ReliabilityType::Reliable ? "true" : "false",
IsMarkedForRemoval() ? "true" : "false"
);
@@ -15,7 +15,7 @@
#include <AzNetworking/DataStructures/FixedSizeVectorBitset.h>
#include <AzNetworking/Serialization/ISerializer.h>
#include <AzNetworking/Utilities/NetworkCommon.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
namespace Multiplayer
{
@@ -12,7 +12,7 @@
#pragma once
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <Source/NetworkEntity/NetworkEntityHandle.h>
#include <AzCore/Component/Entity.h>
#include <AzCore/EBus/Event.h>
@@ -23,6 +23,7 @@ namespace Multiplayer
class NetworkEntityTracker;
class NetworkEntityAuthorityTracker;
class NetworkEntityRpcMessage;
class MultiplayerComponentRegistry;
using EntityExitDomainEvent = AZ::Event<const ConstNetworkEntityHandle&>;
using ControllersActivatedEvent = AZ::Event<const ConstNetworkEntityHandle&, EntityIsMigrating>;
@@ -48,6 +49,10 @@ namespace Multiplayer
//! @return the NetworkEntityAuthorityTracker for this INetworkEntityManager instance
virtual NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() = 0;
//! Returns the MultiplayerComponentRegistry for this INetworkEntityManager instance.
//! @return the MultiplayerComponentRegistry for this INetworkEntityManager instance
virtual MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() = 0;
//! Returns the HostId for this INetworkEntityManager instance.
//! @return the HostId for this INetworkEntityManager instance
virtual HostId GetHostId() const = 0;
@@ -55,7 +60,8 @@ namespace Multiplayer
//! Creates new entities of the given archetype
//! @param prefabEntryId the name of the spawnable to spawn
virtual EntityList CreateEntitiesImmediate(
const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, const AZ::Transform& transform) = 0;
const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, AutoActivate autoActivate,
const AZ::Transform& transform) = 0;
//! Returns an ConstEntityPtr for the provided entityId.
//! @param netEntityId the netEntityId to get an ConstEntityPtr for
@@ -144,4 +150,9 @@ namespace Multiplayer
{
return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker();
}
inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry()
{
return GetNetworkEntityManager()->GetMultiplayerComponentRegistry();
}
}
@@ -13,7 +13,7 @@
#pragma once
#include <AzCore/Component/Entity.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
namespace Multiplayer
{
@@ -11,19 +11,19 @@
*/
#include <Source/NetworkEntity/NetworkEntityManager.h>
#include <Source/Components/NetBindComponent.h>
#include <Include/IMultiplayer.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Asset/AssetManager.h>
#include <AzCore/Console/IConsole.h>
#include <AzCore/Console/ILogger.h>
#include <AzCore/Interface/Interface.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Slice/SliceMetadataInfoComponent.h>
#include <AzFramework/Components/TransformComponent.h>
#include <AzFramework/Entity/EntityContextBus.h>
#include <AzFramework/Entity/GameEntityContextBus.h>
#include <AzFramework/Components/TransformComponent.h>
#include <Include/IMultiplayer.h>
#include <Pipeline/NetworkSpawnableHolderComponent.h>
#include <AzCore/Asset/AssetManager.h>
#include <Source/Components/NetBindComponent.h>
namespace Multiplayer
{
@@ -62,6 +62,11 @@ namespace Multiplayer
return &m_networkEntityAuthorityTracker;
}
MultiplayerComponentRegistry* NetworkEntityManager::GetMultiplayerComponentRegistry()
{
return &m_multiplayerComponentRegistry;
}
HostId NetworkEntityManager::GetHostId() const
{
return m_hostId;
@@ -356,7 +361,7 @@ namespace Multiplayer
INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate(
const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole,
const AZ::Transform& transform)
AutoActivate autoActivate, const AZ::Transform& transform)
{
INetworkEntityManager::EntityList returnList;
@@ -402,6 +407,11 @@ namespace Multiplayer
transformComponent->SetWorldTM(transform);
}
if (autoActivate == AutoActivate::DoNotActivate)
{
clone->SetRuntimeActiveByDefault(false);
}
AzFramework::GameEntityContextRequestBus::Broadcast(
&AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone);
@@ -457,7 +467,9 @@ namespace Multiplayer
m_rootSpawnableAsset = netSpawnableAsset;
const auto agentType = AZ::Interface<IMultiplayer>::Get()->GetAgentType();
auto* multiplayer = AZ::Interface<IMultiplayer>::Get();
const auto agentType = multiplayer->GetAgentType();
const bool spawnImmediately =
(agentType == MultiplayerAgentType::ClientServer || agentType == MultiplayerAgentType::DedicatedServer);
@@ -465,6 +477,12 @@ namespace Multiplayer
{
CreateEntitiesImmediate(*netSpawnable, NetEntityRole::Authority);
}
else
{
// If we don't spawn net entities immediately (i.e. it is a client),
// tell the server/host it can start sending updates that will instantiate entities.
multiplayer->SendReadyForEntityUpdates(true);
}
}
void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation)
@@ -21,7 +21,7 @@
#include <Source/NetworkEntity/NetworkEntityRpcMessage.h>
#include <Source/EntityDomains/IEntityDomain.h>
#include <Source/NetworkEntity/NetworkSpawnableLibrary.h>
#include <Source/Components/MultiplayerComponentRegistry.h>
namespace Multiplayer
{
@@ -42,6 +42,7 @@ namespace Multiplayer
//! @{
NetworkEntityTracker* GetNetworkEntityTracker() override;
NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() override;
MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() override;
HostId GetHostId() const override;
ConstNetworkEntityHandle GetEntity(NetEntityId netEntityId) const override;
@@ -49,7 +50,7 @@ namespace Multiplayer
EntityList CreateEntitiesImmediate(
const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole,
const AZ::Transform& transform) override;
AutoActivate autoActivate, const AZ::Transform& transform) override;
uint32_t GetEntityCount() const override;
NetworkEntityHandle AddEntityToEntityMap(NetEntityId netEntityId, AZ::Entity* entity) override;
@@ -85,6 +86,8 @@ namespace Multiplayer
NetworkEntityTracker m_networkEntityTracker;
NetworkEntityAuthorityTracker m_networkEntityAuthorityTracker;
MultiplayerComponentRegistry m_multiplayerComponentRegistry;
AZ::ScheduledEvent m_removeEntitiesEvent;
AZStd::vector<NetEntityId> m_removeList;
AZStd::unique_ptr<IEntityDomain> m_entityDomain;
@@ -21,7 +21,7 @@ namespace Multiplayer
: m_rpcDeliveryType(rhs.m_rpcDeliveryType)
, m_entityId(rhs.m_entityId)
, m_componentId(rhs.m_componentId)
, m_rpcMessageType(rhs.m_rpcMessageType)
, m_rpcIndex(rhs.m_rpcIndex)
, m_data(AZStd::move(rhs.m_data))
, m_isReliable(rhs.m_isReliable)
{
@@ -32,7 +32,7 @@ namespace Multiplayer
: m_rpcDeliveryType(rhs.m_rpcDeliveryType)
, m_entityId(rhs.m_entityId)
, m_componentId(rhs.m_componentId)
, m_rpcMessageType(rhs.m_rpcMessageType)
, m_rpcIndex(rhs.m_rpcIndex)
, m_isReliable(rhs.m_isReliable)
{
if (rhs.m_data != nullptr)
@@ -42,11 +42,11 @@ namespace Multiplayer
}
}
NetworkEntityRpcMessage::NetworkEntityRpcMessage(RpcDeliveryType rpcDeliveryType, NetEntityId entityId, NetComponentId componentId, uint8_t rpcMessageType, ReliabilityType isReliable)
NetworkEntityRpcMessage::NetworkEntityRpcMessage(RpcDeliveryType rpcDeliveryType, NetEntityId entityId, NetComponentId componentId, RpcIndex rpcIndex, ReliabilityType isReliable)
: m_rpcDeliveryType(rpcDeliveryType)
, m_entityId(entityId)
, m_componentId(componentId)
, m_rpcMessageType(rpcMessageType)
, m_rpcIndex(rpcIndex)
, m_isReliable(isReliable)
{
;
@@ -57,7 +57,7 @@ namespace Multiplayer
m_rpcDeliveryType = rhs.m_rpcDeliveryType;
m_entityId = rhs.m_entityId;
m_componentId = rhs.m_componentId;
m_rpcMessageType = rhs.m_rpcMessageType;
m_rpcIndex = rhs.m_rpcIndex;
m_isReliable = rhs.m_isReliable;
m_data = AZStd::move(rhs.m_data);
return *this;
@@ -68,7 +68,7 @@ namespace Multiplayer
m_rpcDeliveryType = rhs.m_rpcDeliveryType;
m_entityId = rhs.m_entityId;
m_componentId = rhs.m_componentId;
m_rpcMessageType = rhs.m_rpcMessageType;
m_rpcIndex = rhs.m_rpcIndex;
m_isReliable = rhs.m_isReliable;
if (rhs.m_data != nullptr)
{
@@ -85,7 +85,7 @@ namespace Multiplayer
return ((m_rpcDeliveryType == rhs.m_rpcDeliveryType)
&& (m_entityId == rhs.m_entityId)
&& (m_componentId == rhs.m_componentId)
&& (m_rpcMessageType == rhs.m_rpcMessageType));
&& (m_rpcIndex == rhs.m_rpcIndex));
}
bool NetworkEntityRpcMessage::operator !=(const NetworkEntityRpcMessage& rhs) const
@@ -98,7 +98,7 @@ namespace Multiplayer
static constexpr uint32_t sizeOfFields = sizeof(RpcDeliveryType)
+ sizeof(NetEntityId)
+ sizeof(NetComponentId)
+ sizeof(uint8_t);
+ sizeof(RpcIndex);
// 2-byte size header + the actual blob payload itself
const uint32_t sizeOfBlob = (m_data != nullptr) ? sizeof(uint16_t) + m_data->GetSize() : 0;
@@ -127,9 +127,9 @@ namespace Multiplayer
return m_componentId;
}
uint8_t NetworkEntityRpcMessage::GetRpcMessageType() const
RpcIndex NetworkEntityRpcMessage::GetRpcIndex() const
{
return m_rpcMessageType;
return m_rpcIndex;
}
bool NetworkEntityRpcMessage::SetRpcParams(IRpcParamStruct& params)
@@ -167,7 +167,7 @@ namespace Multiplayer
serializer.Serialize(m_rpcDeliveryType, "RpcDeliveryType");
serializer.Serialize(m_entityId, "EntityId");
serializer.Serialize(m_componentId, "ComponentId");
serializer.Serialize(m_rpcMessageType, "RpcMessageType");
serializer.Serialize(m_rpcIndex, "RpcIndex");
// m_data should never be nullptr, it contains serialized data for our Rpc params struct
if (m_data == nullptr)
@@ -14,7 +14,7 @@
#include <AzNetworking/Serialization/ISerializer.h>
#include <AzNetworking/DataStructures/ByteBuffer.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
namespace Multiplayer
{
@@ -35,12 +35,12 @@ namespace Multiplayer
NetworkEntityRpcMessage(const NetworkEntityRpcMessage& rhs);
//! Fill explicit constructor.
//! @param rpcDeliveryType the delivery type (origin and target) for this RPC
//! @param entityId the networked entityId of the entity handling this RPC
//! @param componentType the networked componentId of the component handling this RPC
//! @param rpcMessageType the component defined RPC type, so the component knows which RPC this message corresponds to
//! @param isReliable whether or not this RPC should be sent reliably
explicit NetworkEntityRpcMessage(RpcDeliveryType rpcDeliveryType, NetEntityId entityId, NetComponentId componentId, uint8_t rpcMessageType, ReliabilityType isReliable);
//! @param rpcDeliveryType the delivery type (origin and target) for this rpc
//! @param entityId the networked entityId of the entity handling this rpc
//! @param componentType the networked componentId of the component handling this rpc
//! @param rpcIndex the component defined rpc index, so the component knows which rpc this message corresponds to
//! @param isReliable whether or not this rpc should be sent reliably
explicit NetworkEntityRpcMessage(RpcDeliveryType rpcDeliveryType, NetEntityId entityId, NetComponentId componentId, RpcIndex rpcIndex, ReliabilityType isReliable);
NetworkEntityRpcMessage& operator =(NetworkEntityRpcMessage&& rhs);
NetworkEntityRpcMessage& operator =(const NetworkEntityRpcMessage& rhs);
@@ -67,9 +67,9 @@ namespace Multiplayer
//! @return the current value of EntityComponentType
NetComponentId GetComponentId() const;
//! Gets the current value of RpcMessageType.
//! @return the current value of RpcMessageType
uint8_t GetRpcMessageType() const;
//! Gets the current value of RpcIndex.
//! @return the current value of RpcIndex
RpcIndex GetRpcIndex() const;
//! Writes the data contained inside a_Params to this NetworkEntityRpcMessage's blob buffer.
//! @param params the parameters to save inside this NetworkEntityRpcMessage instance
@@ -98,7 +98,7 @@ namespace Multiplayer
RpcDeliveryType m_rpcDeliveryType = RpcDeliveryType::None;
NetEntityId m_entityId = InvalidNetEntityId;
NetComponentId m_componentId = InvalidNetComponentId;
uint8_t m_rpcMessageType = 0;
RpcIndex m_rpcIndex = RpcIndex{ 0 };
// Only allocated if we actually have data
// This is to prevent blowing out stack memory if we declare an array of these EntityUpdateMessages
@@ -12,7 +12,7 @@
#pragma once
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <Source/NetworkEntity/NetworkEntityHandle.h>
#include <AzCore/std/containers/unordered_map.h>
#include <AzCore/Component/Entity.h>
@@ -131,7 +131,7 @@ namespace Multiplayer
}
// 2-byte size header + the actual blob payload itself
const uint32_t sizeOfBlob = (m_data != nullptr) ? sizeof(uint16_t) + m_data->GetSize() : 0;
const uint32_t sizeOfBlob = (m_data != nullptr) ? sizeof(PropertyIndex) + m_data->GetSize() : 0;
if (m_hasValidPrefabId)
{
@@ -15,7 +15,7 @@
#include <AzNetworking/Serialization/ISerializer.h>
#include <AzNetworking/DataStructures/ByteBuffer.h>
#include <AzCore/Name/Name.h>
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
namespace Multiplayer
{
@@ -46,6 +46,7 @@ namespace Multiplayer
const AZ::Name name = AZ::Name(relativePath);
m_spawnables[name] = id;
m_spawnablesReverseLookup[id] = name;
}
void NetworkSpawnableLibrary::OnCatalogLoaded([[maybe_unused]] const char* catalogFile)
@@ -12,7 +12,7 @@
#pragma once
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <AzNetworking/DataStructures/FixedSizeBitset.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
@@ -12,7 +12,7 @@
#pragma once
#include <Source/MultiplayerTypes.h>
#include <Include/MultiplayerTypes.h>
#include <Source/NetworkEntity/NetworkEntityHandle.h>
#include <AzCore/std/containers/unordered_map.h>
@@ -11,11 +11,13 @@
set(FILES
Include/IMultiplayer.h
Include/MultiplayerStats.cpp
Include/MultiplayerStats.h
Include/MultiplayerTypes.h
Source/Multiplayer_precompiled.cpp
Source/Multiplayer_precompiled.h
Source/MultiplayerSystemComponent.cpp
Source/MultiplayerSystemComponent.h
Source/MultiplayerTypes.h
Source/AutoGen/AutoComponent_Header.jinja
Source/AutoGen/AutoComponent_Source.jinja
Source/AutoGen/AutoComponent_Common.jinja
@@ -26,6 +28,8 @@ set(FILES
Source/AutoGen/NetworkTransformComponent.AutoComponent.xml
Source/Components/LocalPredictionPlayerInputComponent.cpp
Source/Components/LocalPredictionPlayerInputComponent.h
Source/Components/MultiplayerComponentRegistry.cpp
Source/Components/MultiplayerComponentRegistry.h
Source/Components/MultiplayerComponent.cpp
Source/Components/MultiplayerComponent.h
Source/Components/MultiplayerController.cpp