Merging from development

Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
This commit is contained in:
Esteban Papp
2021-12-07 12:35:41 -08:00
parent b1eeebb6b6
commit cd5306febf
334 changed files with 9946 additions and 3757 deletions
@@ -0,0 +1,43 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
#include <AzCore/DOM/DomBackend.h>
#include <AzCore/IO/ByteContainerStream.h>
namespace AZ::Dom
{
//! A DOM backend for serializing and deserializing JSON <=> UTF-8 text
//! \param ParseFlags Controls how deserialized JSON is parsed.
//! \param WriteFormat Controls how serialized JSON is formatted.
template<
Json::ParseFlags ParseFlags = Json::ParseFlags::ParseComments,
Json::OutputFormatting WriteFormat = Json::OutputFormatting::PrettyPrintedJson>
class JsonBackend final : public Backend
{
public:
Visitor::Result ReadFromBuffer(const char* buffer, size_t size, AZ::Dom::Lifetime lifetime, Visitor& visitor) override
{
return Json::VisitSerializedJson<ParseFlags>({ buffer, size }, lifetime, visitor);
}
Visitor::Result ReadFromBufferInPlace(char* buffer, [[maybe_unused]] AZStd::optional<size_t> size, Visitor& visitor) override
{
return Json::VisitSerializedJsonInPlace<ParseFlags>(buffer, visitor);
}
Visitor::Result WriteToBuffer(AZStd::string& buffer, WriteCallback callback)
{
AZ::IO::ByteContainerStream<AZStd::string> stream{ &buffer };
AZStd::unique_ptr<Visitor> visitor = Json::CreateJsonStreamWriter(stream, WriteFormat);
return callback(*visitor);
}
};
} // namespace AZ::Dom
@@ -0,0 +1,582 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
#include <AzCore/IO/ByteContainerStream.h>
#include <AzCore/IO/TextStreamWriters.h>
#include <AzCore/JSON/filewritestream.h>
#include <AzCore/JSON/memorystream.h>
#include <AzCore/JSON/prettywriter.h>
#include <AzCore/JSON/rapidjson.h>
#include <AzCore/JSON/reader.h>
#include <AzCore/JSON/writer.h>
#include <AzCore/std/containers/stack.h>
#include <AzCore/std/containers/variant.h>
#include <AzCore/std/optional.h>
namespace AZ::Dom::Json
{
//
// class RapidJsonValueWriter
//
RapidJsonValueWriter::RapidJsonValueWriter(rapidjson::Value& outputValue, rapidjson::Value::AllocatorType& allocator)
: m_result(outputValue)
, m_allocator(allocator)
{
}
VisitorFlags RapidJsonValueWriter::GetVisitorFlags() const
{
return VisitorFlags::SupportsRawKeys | VisitorFlags::SupportsArrays | VisitorFlags::SupportsObjects;
}
Visitor::Result RapidJsonValueWriter::Null()
{
CurrentValue().SetNull();
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::Bool(bool value)
{
CurrentValue().SetBool(value);
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::Int64(AZ::s64 value)
{
CurrentValue().SetInt64(value);
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::Uint64(AZ::u64 value)
{
CurrentValue().SetUint64(value);
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::Double(double value)
{
CurrentValue().SetDouble(value);
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::String(AZStd::string_view value, Lifetime lifetime)
{
if (lifetime == Lifetime::Temporary)
{
CurrentValue().SetString(value.data(), aznumeric_cast<rapidjson::SizeType>(value.length()), m_allocator);
}
else
{
CurrentValue().SetString(value.data(), aznumeric_cast<rapidjson::SizeType>(value.length()));
}
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::StartObject()
{
CurrentValue().SetObject();
const bool isObject = true;
m_entryStack.emplace_front(isObject, CurrentValue());
return VisitorSuccess();
}
Visitor::Result RapidJsonValueWriter::EndObject(AZ::u64 attributeCount)
{
if (m_entryStack.empty())
{
return VisitorFailure(VisitorErrorCode::InternalError, "EndObject called without a matching BeginObject call");
}
const ValueInfo& frontEntry = m_entryStack.front();
if (!frontEntry.m_isObject)
{
return VisitorFailure(VisitorErrorCode::InternalError, "Expected EndArray and received EndObject instead");
}
if (frontEntry.m_entryCount != attributeCount)
{
return VisitorFailure(
VisitorErrorCode::InternalError,
AZStd::string::format(
"EndObject: Expected %llu attributes but received %llu attributes instead", attributeCount,
frontEntry.m_entryCount));
}
m_entryStack.pop_front();
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::Key(AZ::Name key)
{
return RawKey(key.GetStringView(), Lifetime::Persistent);
}
Visitor::Result RapidJsonValueWriter::RawKey(AZStd::string_view key, Lifetime lifetime)
{
AZ_Assert(!m_entryStack.empty(), "Attempmted to push a key with no object");
AZ_Assert(m_entryStack.front().m_isObject, "Attempted to push a key to an array");
if (lifetime == Lifetime::Persistent)
{
m_entryStack.front().m_key.SetString(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()));
}
else
{
m_entryStack.front().m_key.SetString(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()), m_allocator);
}
return VisitorSuccess();
}
Visitor::Result RapidJsonValueWriter::StartArray()
{
CurrentValue().SetArray();
const bool isObject = false;
m_entryStack.emplace_front(isObject, CurrentValue());
return VisitorSuccess();
}
Visitor::Result RapidJsonValueWriter::EndArray(AZ::u64 elementCount)
{
if (m_entryStack.empty())
{
return VisitorFailure(VisitorErrorCode::InternalError, "EndArray called without a matching BeginArray call");
}
const ValueInfo& frontEntry = m_entryStack.front();
if (frontEntry.m_isObject)
{
return VisitorFailure(VisitorErrorCode::InternalError, "Expected EndObject and received EndArray instead");
}
if (frontEntry.m_entryCount != elementCount)
{
return VisitorFailure(
VisitorErrorCode::InternalError,
AZStd::string::format(
"EndArray: Expected %llu elements but received %llu elements instead", elementCount, frontEntry.m_entryCount));
}
m_entryStack.pop_front();
return FinishWrite();
}
Visitor::Result RapidJsonValueWriter::FinishWrite()
{
if (m_entryStack.empty())
{
return VisitorSuccess();
}
// Retrieve the top value of the stack and replace it with a null value
rapidjson::Value value;
m_entryStack.front().m_value.Swap(value);
ValueInfo& newEntry = m_entryStack.front();
++newEntry.m_entryCount;
if (newEntry.m_key.IsString())
{
newEntry.m_container.AddMember(m_entryStack.front().m_key.Move(), AZStd::move(value), m_allocator);
newEntry.m_key.SetNull();
}
else
{
newEntry.m_container.PushBack(AZStd::move(value), m_allocator);
}
return VisitorSuccess();
}
rapidjson::Value& RapidJsonValueWriter::CurrentValue()
{
if (m_entryStack.empty())
{
return m_result;
}
return m_entryStack.front().m_value;
}
RapidJsonValueWriter::ValueInfo::ValueInfo(bool isObject, rapidjson::Value& container)
: m_isObject(isObject)
, m_container(container)
{
}
//
// class StreamWriter
//
// Visitor that writes to a rapidjson::Writer
template<class Writer>
class StreamWriter : public Visitor
{
public:
StreamWriter(AZ::IO::GenericStream* stream)
: m_streamWriter(stream)
, m_writer(Writer(m_streamWriter))
{
}
VisitorFlags GetVisitorFlags() const override
{
return VisitorFlags::SupportsRawKeys | VisitorFlags::SupportsArrays | VisitorFlags::SupportsObjects;
}
Result Null() override
{
return CheckWrite(m_writer.Null());
}
Result Bool(bool value) override
{
return CheckWrite(m_writer.Bool(value));
}
Result Int64(AZ::s64 value) override
{
return CheckWrite(m_writer.Int64(value));
}
Result Uint64(AZ::u64 value) override
{
return CheckWrite(m_writer.Uint64(value));
}
Result Double(double value) override
{
return CheckWrite(m_writer.Double(value));
}
Result String(AZStd::string_view value, Lifetime lifetime) override
{
const bool shouldCopy = lifetime == Lifetime::Temporary;
return CheckWrite(m_writer.String(value.data(), aznumeric_cast<rapidjson::SizeType>(value.size()), shouldCopy));
}
Result StartObject() override
{
return CheckWrite(m_writer.StartObject());
}
Result EndObject(AZ::u64 attributeCount) override
{
return CheckWrite(m_writer.EndObject(aznumeric_cast<rapidjson::SizeType>(attributeCount)));
}
Result Key(AZ::Name key) override
{
return RawKey(key.GetStringView(), Lifetime::Persistent);
}
Result RawKey(AZStd::string_view key, Lifetime lifetime) override
{
const bool shouldCopy = lifetime == Lifetime::Temporary;
return CheckWrite(m_writer.Key(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()), shouldCopy));
}
Result StartArray() override
{
return CheckWrite(m_writer.StartArray());
}
Result EndArray(AZ::u64 elementCount) override
{
return CheckWrite(m_writer.EndArray(aznumeric_cast<rapidjson::SizeType>(elementCount)));
}
private:
Result CheckWrite(bool writeSucceeded)
{
if (writeSucceeded)
{
return VisitorSuccess();
}
else
{
return VisitorFailure(VisitorErrorCode::InternalError, "Failed to write JSON");
}
}
AZ::IO::RapidJSONStreamWriter m_streamWriter;
Writer m_writer;
};
//
// struct JsonReadHandler
//
RapidJsonReadHandler::RapidJsonReadHandler(Visitor* visitor, Lifetime stringLifetime)
: m_visitor(visitor)
, m_stringLifetime(stringLifetime)
, m_outcome(AZ::Success())
{
}
bool RapidJsonReadHandler::Null()
{
return CheckResult(m_visitor->Null());
}
bool RapidJsonReadHandler::Bool(bool b)
{
return CheckResult(m_visitor->Bool(b));
}
bool RapidJsonReadHandler::Int(int i)
{
return CheckResult(m_visitor->Int64(aznumeric_cast<AZ::s64>(i)));
}
bool RapidJsonReadHandler::Uint(unsigned i)
{
return CheckResult(m_visitor->Uint64(aznumeric_cast<AZ::u64>(i)));
}
bool RapidJsonReadHandler::Int64(int64_t i)
{
return CheckResult(m_visitor->Int64(i));
}
bool RapidJsonReadHandler::Uint64(uint64_t i)
{
return CheckResult(m_visitor->Uint64(i));
}
bool RapidJsonReadHandler::Double(double d)
{
return CheckResult(m_visitor->Double(d));
}
bool RapidJsonReadHandler::RawNumber(
[[maybe_unused]] const char* str, [[maybe_unused]] rapidjson::SizeType length, [[maybe_unused]] bool copy)
{
AZ_Assert(false, "Raw numbers are unsupported in the rapidjson DOM backend");
return false;
}
bool RapidJsonReadHandler::String(const char* str, rapidjson::SizeType length, bool copy)
{
const Lifetime lifetime = copy ? m_stringLifetime : Lifetime::Temporary;
return CheckResult(m_visitor->String(AZStd::string_view(str, length), lifetime));
}
bool RapidJsonReadHandler::StartObject()
{
return CheckResult(m_visitor->StartObject());
}
bool RapidJsonReadHandler::Key(const char* str, rapidjson::SizeType length, [[maybe_unused]] bool copy)
{
AZStd::string_view key = AZStd::string_view(str, length);
if (!m_visitor->SupportsRawKeys())
{
m_visitor->Key(AZ::Name(key));
}
const Lifetime lifetime = copy ? m_stringLifetime : Lifetime::Temporary;
return CheckResult(m_visitor->RawKey(key, lifetime));
}
bool RapidJsonReadHandler::EndObject([[maybe_unused]] rapidjson::SizeType memberCount)
{
return CheckResult(m_visitor->EndObject(memberCount));
}
bool RapidJsonReadHandler::StartArray()
{
return CheckResult(m_visitor->StartArray());
}
bool RapidJsonReadHandler::EndArray([[maybe_unused]] rapidjson::SizeType elementCount)
{
return CheckResult(m_visitor->EndArray(elementCount));
}
Visitor::Result&& RapidJsonReadHandler::TakeOutcome()
{
return AZStd::move(m_outcome);
}
bool RapidJsonReadHandler::CheckResult(Visitor::Result result)
{
if (result.IsSuccess())
{
return true;
}
else
{
m_outcome = AZStd::move(result);
return false;
}
}
//
// Serialized JSON util functions
//
AZStd::unique_ptr<Visitor> CreateJsonStreamWriter(AZ::IO::GenericStream& stream, OutputFormatting format)
{
if (format == OutputFormatting::MinifiedJson)
{
using WriterType = rapidjson::Writer<AZ::IO::RapidJSONStreamWriter>;
return AZStd::make_unique<StreamWriter<WriterType>>(&stream);
}
else
{
using WriterType = rapidjson::PrettyWriter<AZ::IO::RapidJSONStreamWriter>;
return AZStd::make_unique<StreamWriter<WriterType>>(&stream);
}
}
//
// In-memory rapidjson util functions
//
AZ::Outcome<rapidjson::Document, AZStd::string> WriteToRapidJsonDocument(Backend::WriteCallback writeCallback)
{
rapidjson::Document document;
RapidJsonValueWriter writer(document, document.GetAllocator());
auto result = writeCallback(writer);
if (!result.IsSuccess())
{
return AZ::Failure(result.TakeError().FormatVisitorErrorMessage());
}
return AZ::Success(AZStd::move(document));
}
Visitor::Result WriteToRapidJsonValue(
rapidjson::Value& value, rapidjson::Value::AllocatorType& allocator, Backend::WriteCallback writeCallback)
{
RapidJsonValueWriter writer(value, allocator);
return writeCallback(writer);
}
Visitor::Result VisitRapidJsonValue(const rapidjson::Value& value, Visitor& visitor, Lifetime lifetime)
{
struct EndArrayMarker
{
};
struct EndObjectMarker
{
};
// Processing stack consists of values comprised of one of a:
// - rapidjson::Value to process
// - EndArrayMarker or EndObjectMarker denoting the end of an array or object
// - string denoting a key at the beginning of a key/value pair
using Entry = AZStd::variant<const rapidjson::Value*, EndArrayMarker, EndObjectMarker, AZStd::string_view>;
AZStd::stack<Entry> entryStack;
AZStd::stack<u64> entryCountStack;
entryStack.push(&value);
while (!entryStack.empty())
{
const Entry currentEntry = entryStack.top();
entryStack.pop();
Visitor::Result result = AZ::Success();
AZStd::visit(
[&visitor, &entryStack, &entryCountStack, &result, lifetime](auto&& arg)
{
using Alternative = AZStd::decay_t<decltype(arg)>;
if constexpr (AZStd::is_same_v<Alternative, const rapidjson::Value*>)
{
const rapidjson::Value& currentValue = *arg;
if (!entryCountStack.empty())
{
++entryCountStack.top();
}
switch (currentValue.GetType())
{
case rapidjson::kNullType:
result = visitor.Null();
break;
case rapidjson::kFalseType:
result = visitor.Bool(false);
break;
case rapidjson::kTrueType:
result = visitor.Bool(true);
break;
case rapidjson::kObjectType:
entryStack.push(EndObjectMarker{});
entryCountStack.push(0);
result = visitor.StartObject();
for (auto it = currentValue.MemberEnd(); it != currentValue.MemberBegin(); --it)
{
auto entry = (it - 1);
const AZStd::string_view key(
entry->name.GetString(), aznumeric_cast<size_t>(entry->name.GetStringLength()));
entryStack.push(&entry->value);
entryStack.push(key);
}
break;
case rapidjson::kArrayType:
entryStack.push(EndArrayMarker{});
entryCountStack.push(0);
result = visitor.StartArray();
for (auto it = currentValue.End(); it != currentValue.Begin(); --it)
{
auto entry = (it - 1);
entryStack.push(entry);
}
break;
case rapidjson::kStringType:
result = visitor.String(
AZStd::string_view(currentValue.GetString(), aznumeric_cast<size_t>(currentValue.GetStringLength())),
lifetime);
break;
case rapidjson::kNumberType:
if (currentValue.IsFloat() || currentValue.IsDouble())
{
result = visitor.Double(currentValue.GetDouble());
}
else if (currentValue.IsInt64() || currentValue.IsInt())
{
result = visitor.Int64(currentValue.GetInt64());
}
else
{
result = visitor.Uint64(currentValue.GetUint64());
}
break;
default:
result = AZ::Failure(VisitorError(VisitorErrorCode::InvalidData, "Value with invalid type specified"));
}
}
else if constexpr (AZStd::is_same_v<Alternative, EndArrayMarker>)
{
result = visitor.EndArray(entryCountStack.top());
entryCountStack.pop();
}
else if constexpr (AZStd::is_same_v<Alternative, EndObjectMarker>)
{
result = visitor.EndObject(entryCountStack.top());
entryCountStack.pop();
}
else if constexpr (AZStd::is_same_v<Alternative, AZStd::string_view>)
{
if (visitor.SupportsRawKeys())
{
visitor.RawKey(arg, lifetime);
}
else
{
visitor.Key(AZ::Name(arg));
}
}
},
currentEntry);
if (!result.IsSuccess())
{
return result;
}
}
return AZ::Success();
}
} // namespace AZ::Dom::Json
@@ -0,0 +1,256 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/DOM/DomBackend.h>
#include <AzCore/DOM/DomVisitor.h>
#include <AzCore/IO/GenericStreams.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/JSON/document.h>
#include <AzCore/std/containers/deque.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
namespace AZ::Dom::Json
{
//! Specifies how JSON should be formatted when serialized.
enum class OutputFormatting
{
MinifiedJson, //!< Formats JSON in compact minified form, focusing on minimizing output size.
PrettyPrintedJson, //!< Formats JSON in a pretty printed form, focusing on legibility to readers.
};
//! Specifies parsing behavior when deserializing JSON.
enum class ParseFlags : int
{
Null = 0,
StopWhenDone = rapidjson::kParseStopWhenDoneFlag,
FullFloatingPointPrecision = rapidjson::kParseFullPrecisionFlag,
ParseComments = rapidjson::kParseCommentsFlag,
ParseNumbersAsStrings = rapidjson::kParseNumbersAsStringsFlag,
ParseTrailingCommas = rapidjson::kParseTrailingCommasFlag,
ParseNanAndInfinity = rapidjson::kParseNanAndInfFlag,
ParseEscapedApostrophies = rapidjson::kParseEscapedApostropheFlag,
};
AZ_DEFINE_ENUM_BITWISE_OPERATORS(ParseFlags);
//! Visitor that feeds into a rapidjson::Value
class RapidJsonValueWriter final : public Visitor
{
public:
RapidJsonValueWriter(rapidjson::Value& outputValue, rapidjson::Value::AllocatorType& allocator);
VisitorFlags GetVisitorFlags() const override;
Result Null() override;
Result Bool(bool value) override;
Result Int64(AZ::s64 value) override;
Result Uint64(AZ::u64 value) override;
Result Double(double value) override;
Result String(AZStd::string_view value, Lifetime lifetime) override;
Result StartObject() override;
Result EndObject(AZ::u64 attributeCount) override;
Result Key(AZ::Name key) override;
Result RawKey(AZStd::string_view key, Lifetime lifetime) override;
Result StartArray() override;
Result EndArray(AZ::u64 elementCount) override;
private:
Result FinishWrite();
rapidjson::Value& CurrentValue();
struct ValueInfo
{
ValueInfo(bool isObject, rapidjson::Value& container);
rapidjson::Value m_key;
rapidjson::Value m_value;
rapidjson::Value& m_container;
AZ::u64 m_entryCount = 0;
bool m_isObject;
};
rapidjson::Value& m_result;
rapidjson::Value::AllocatorType& m_allocator;
AZStd::deque<ValueInfo> m_entryStack;
};
//! Handler for a rapidjson::Reader that translates reads into an AZ::Dom::Visitor
struct RapidJsonReadHandler
{
public:
RapidJsonReadHandler(Visitor* visitor, Lifetime stringLifetime);
bool Null();
bool Bool(bool b);
bool Int(int i);
bool Uint(unsigned i);
bool Int64(int64_t i);
bool Uint64(uint64_t i);
bool Double(double d);
bool RawNumber(const char* str, rapidjson::SizeType length, bool copy);
bool String(const char* str, rapidjson::SizeType length, bool copy);
bool StartObject();
bool Key(const char* str, rapidjson::SizeType length, bool copy);
bool EndObject(rapidjson::SizeType memberCount);
bool StartArray();
bool EndArray(rapidjson::SizeType elementCount);
Visitor::Result&& TakeOutcome();
private:
bool CheckResult(Visitor::Result result);
Visitor::Result m_outcome;
Visitor* m_visitor;
Lifetime m_stringLifetime;
};
//! rapidjson stream wrapper for AZStd::string suitable for in-situ parsing
//! Faster than rapidjson::MemoryStream for reading from AZStd::string / AZStd::string_view (because it requires a null terminator)
//! \note This needs to be inlined for performance reasons.
struct NullDelimitedStringStream
{
using Ch = char; //<! Denotes the string character storage type for rapidjson
AZ_FORCE_INLINE NullDelimitedStringStream(char* buffer)
{
m_cursor = buffer;
m_begin = m_cursor;
}
AZ_FORCE_INLINE NullDelimitedStringStream(AZStd::string_view buffer)
{
// rapidjson won't actually call PutBegin or Put unless kParseInSituFlag is set, so this is safe
m_cursor = const_cast<char*>(buffer.data());
m_begin = m_cursor;
}
AZ_FORCE_INLINE char Peek() const
{
return *m_cursor;
}
AZ_FORCE_INLINE char Take()
{
return *m_cursor++;
}
AZ_FORCE_INLINE size_t Tell() const
{
return static_cast<size_t>(m_cursor - m_begin);
}
AZ_FORCE_INLINE char* PutBegin()
{
m_write = m_cursor;
return m_cursor;
}
AZ_FORCE_INLINE void Put(char c)
{
(*m_write++) = c;
}
AZ_FORCE_INLINE void Flush()
{
}
AZ_FORCE_INLINE size_t PutEnd(char* begin)
{
return m_write - begin;
}
AZ_FORCE_INLINE const char* Peek4() const
{
AZ_Assert(false, "Not implemented, encoding is hard-coded to UTF-8");
return m_cursor;
}
char* m_cursor; //!< Current read position.
char* m_write; //!< Current write position.
const char* m_begin; //!< Head of string.
};
//! Creates a Visitor that will write serialized JSON to the specified stream.
//! \param stream The stream the visitor will write to.
//! \param format The format to write in.
//! \return A Visitor that will write to stream when visited.
AZStd::unique_ptr<Visitor> CreateJsonStreamWriter(
AZ::IO::GenericStream& stream, OutputFormatting format = OutputFormatting::PrettyPrintedJson);
//! Reads serialized JSON from a string and applies it to a visitor.
//! \param buffer The UTF-8 serialized JSON to read.
//! \param lifetime Specifies the lifetime of the specified buffer. If the string specified by buffer might be deallocated,
//! ensure Lifetime::Temporary is specified.
//! \param visitor The visitor to visit with the JSON buffer's contents.
//! \param parseFlags (template) Settings for adjusting parser behavior.
//! \return The aggregate result specifying whether the visitor operations were successful.
template<ParseFlags parseFlags = ParseFlags::ParseComments>
Visitor::Result VisitSerializedJson(AZStd::string_view buffer, Lifetime lifetime, Visitor& visitor);
//! Reads serialized JSON from a string in-place and applies it to a visitor.
//! \param buffer The UTF-8 serialized JSON to read. This buffer will be modified as part of the deserialization process to
//! apply null terminators.
//! \param visitor The visitor to visit with the JSON buffer's contents. The strings provided to the visitor will only
//! be valid for the lifetime of buffer.
//! \param parseFlags (template) Settings for adjusting parser behavior.
//! \return The aggregate result specifying whether the visitor operations were successful.
template<ParseFlags parseFlags = ParseFlags::ParseComments>
Visitor::Result VisitSerializedJsonInPlace(char* buffer, Visitor& visitor);
//! Takes a visitor specified by a callback and produces a rapidjson::Document.
//! \param writeCallback A callback specifying a visitor to accept to build the resulting document.
//! \return An outcome with either the rapidjson::Document or an error message.
AZ::Outcome<rapidjson::Document, AZStd::string> WriteToRapidJsonDocument(Backend::WriteCallback writeCallback);
//! Takes a visitor specified by a callback and reads them into a rapidjson::Value.
//! \param value The value to read into, its contents will be overridden.
//! \param allocator The allocator to use when performing rapidjson allocations (generally provded by the rapidjson::Document).
//! \param writeCallback A callback specifying a visitor to accept to build the resulting document.
//! \return An outcome with either the rapidjson::Document or an error message.
Visitor::Result WriteToRapidJsonValue(
rapidjson::Value& value, rapidjson::Value::AllocatorType& allocator, Backend::WriteCallback writeCallback);
//! Accepts a visitor with the contents of a rapidjson::Value.
//! \param value The rapidjson::Value to apply to visitor.
//! \param visitor The visitor to receive the contents of value.
//! \param lifetime The lifetime to specify for visiting strings. If the rapidjson::Value might be destroyed or changed
//! before the visitor is finished using these values, Lifetime::Temporary should be specified.
//! \return The aggregate result specifying whether the visitor operations were successful.
Visitor::Result VisitRapidJsonValue(const rapidjson::Value& value, Visitor& visitor, Lifetime lifetime);
template<ParseFlags parseFlags>
Visitor::Result VisitSerializedJson(AZStd::string_view buffer, Lifetime lifetime, Visitor& visitor)
{
rapidjson::Reader reader;
RapidJsonReadHandler handler(&visitor, lifetime);
// If the string is null terminated, we can use the faster AzStringStream path - otherwise we fall back on rapidjson::MemoryStream
if (buffer.data()[buffer.size()] == '\0')
{
NullDelimitedStringStream stream(buffer);
reader.Parse<aznumeric_cast<unsigned>(parseFlags)>(stream, handler);
}
else
{
rapidjson::MemoryStream stream(buffer.data(), buffer.size());
reader.Parse<aznumeric_cast<unsigned>(parseFlags)>(stream, handler);
}
return handler.TakeOutcome();
}
template<ParseFlags parseFlags>
Visitor::Result VisitSerializedJsonInPlace(char* buffer, Visitor& visitor)
{
rapidjson::Reader reader;
NullDelimitedStringStream stream(buffer);
RapidJsonReadHandler handler(&visitor, Lifetime::Persistent);
reader.Parse<aznumeric_cast<unsigned>(parseFlags) | rapidjson::kParseInsituFlag>(stream, handler);
return handler.TakeOutcome();
}
} // namespace AZ::Dom::Json
@@ -0,0 +1,17 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/DOM/DomBackend.h>
namespace AZ::Dom
{
Visitor::Result Backend::ReadFromBufferInPlace(char* buffer, AZStd::optional<size_t> size, Visitor& visitor)
{
return ReadFromBuffer(buffer, size.value_or(strlen(buffer)), AZ::Dom::Lifetime::Persistent, visitor);
}
} // namespace AZ::Dom
@@ -0,0 +1,44 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/DOM/DomVisitor.h>
#include <AzCore/IO/GenericStreams.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/optional.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
namespace AZ::Dom
{
//! Backends are registered centrally and used to transition DOM formats to and from a textual format.
class Backend
{
public:
virtual ~Backend() = default;
//! Attempt to read this format from the given buffer into the target Visitor.
virtual Visitor::Result ReadFromBuffer(
const char* buffer, size_t size, AZ::Dom::Lifetime lifetime, Visitor& visitor) = 0;
//! Attempt to read this format from a mutable string into the target Visitor. This enables some backends to
//! parse without making additional string allocations.
//! This string must be null terminated.
//! This string may be modified and read in place without being copied, so when calling this please ensure that:
//! - The string won't be deallocated until the visitor no longer needs the values and
//! - The string is safe to modify in place.
//! The base implementation simply calls ReadFromBuffer.
virtual Visitor::Result ReadFromBufferInPlace(char* buffer, AZStd::optional<size_t> size, Visitor& visitor);
//! A callback that accepts a Visitor, making DOM calls to inform the serializer, and returns an
//! aggregate error code to indicate whether or not the operation succeeded.
using WriteCallback = AZStd::function<Visitor::Result(Visitor&)>;
//! Attempt to write a value to the specified string using a write callback.
virtual Visitor::Result WriteToBuffer(AZStd::string& buffer, WriteCallback callback) = 0;
};
} // namespace AZ::Dom
@@ -0,0 +1,24 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/DOM/DomUtils.h>
#include <AzCore/IO/ByteContainerStream.h>
namespace AZ::Dom::Utils
{
Visitor::Result ReadFromString(Backend& backend, AZStd::string_view string, AZ::Dom::Lifetime lifetime, Visitor& visitor)
{
return backend.ReadFromBuffer(string.data(), string.length(), lifetime, visitor);
}
Visitor::Result ReadFromStringInPlace(Backend& backend, AZStd::string& string, Visitor& visitor)
{
return backend.ReadFromBufferInPlace(string.data(), string.size(), visitor);
}
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/DOM/DomBackend.h>
namespace AZ::Dom::Utils
{
Visitor::Result ReadFromString(Backend& backend, AZStd::string_view string, AZ::Dom::Lifetime lifetime, Visitor& visitor);
Visitor::Result ReadFromStringInPlace(Backend& backend, AZStd::string& string, Visitor& visitor);
} // namespace AZ::Dom::Utils
@@ -8,7 +8,7 @@
#include <AzCore/DOM/DomVisitor.h>
namespace AZ::DOM
namespace AZ::Dom
{
const char* VisitorError::CodeToString(VisitorErrorCode code)
{
@@ -236,4 +236,4 @@ namespace AZ::DOM
{
return (GetVisitorFlags() & VisitorFlags::SupportsOpaqueValues) != VisitorFlags::Null;
}
} // namespace AZ::DOM
} // namespace AZ::Dom
+13 -12
View File
@@ -13,11 +13,11 @@
#include <AzCore/std/any.h>
#include <AzCore/std/string/string.h>
namespace AZ::DOM
namespace AZ::Dom
{
//
// Lifetime enum
//
//
//! Specifies the period in which a reference value will still be alive and safe to read.
enum class Lifetime
{
@@ -30,7 +30,7 @@ namespace AZ::DOM
//
// VisitorErrorCode enum
//
//
//! Error code specifying the reason a Visitor operation failed.
enum class VisitorErrorCode
{
@@ -75,7 +75,7 @@ namespace AZ::DOM
};
//! A type alias for opaque DOM types that aren't meant to be serializable.
//! /see VisitorInterface::OpaqueValue
//! \see VisitorInterface::OpaqueValue
using OpaqueType = AZStd::any;
//
@@ -116,7 +116,7 @@ namespace AZ::DOM
//! - \ref Double: 64 bit double precision float
//! - \ref Null: sentinel "empty" type with no value representation
//! - \ref String: UTF8 encoded string
//! - \ref Object: an ordered container of key/value pairs where keys are AZ::Names and values may be any DOM type
//! - \ref Object: an ordered container of key/value pairs where keys are \ref AZ::Name and values may be any DOM type
//! (including Object)
//! - \ref Array: an ordered container of values, in which values are any DOM value type (including Array)
//! - \ref Node: a container
@@ -144,17 +144,17 @@ namespace AZ::DOM
//! Raw (\see VisitorFlags::SupportsRawValues) and opaque values (\see VisitorFlags::SupportsOpaqueValues)
//! are disallowed by default, as their handling is intended to be implementation-specific.
virtual VisitorFlags GetVisitorFlags() const;
//! /see VisitorFlags::SupportsRawValues
//! \see VisitorFlags::SupportsRawValues
bool SupportsRawValues() const;
//! /see VisitorFlags::SupportsRawKeys
//! \see VisitorFlags::SupportsRawKeys
bool SupportsRawKeys() const;
//! /see VisitorFlags::SupportsObjects
//! \see VisitorFlags::SupportsObjects
bool SupportsObjects() const;
//! /see VisitorFlags::SupportsArrays
//! \see VisitorFlags::SupportsArrays
bool SupportsArrays() const;
//! /see VisitorFlags::SupportsNodes
//! \see VisitorFlags::SupportsNodes
bool SupportsNodes() const;
//! /see VisitorFlags::SupportsOpaqueValues
//! \see VisitorFlags::SupportsOpaqueValues
bool SupportsOpaqueValues() const;
//! Operates on an empty null value.
@@ -231,7 +231,8 @@ namespace AZ::DOM
static Result VisitorFailure(VisitorErrorCode code, AZStd::string additionalInfo);
//! Helper method, constructs a failure \ref Result with the specified error.
static Result VisitorFailure(VisitorError error);
//! Helper method, constructs a success \ref Result.
static Result VisitorSuccess();
};
} // namespace AZ::DOM
} // namespace AZ::Dom
@@ -5073,13 +5073,26 @@ LUA_API const Node* lua_getDummyNode()
// Check all constructors if they have use ScriptDataContext and if so choose this one
if (!customConstructorMethod)
{
int overrideIndex = -1;
AZ::AttributeReader(nullptr, FindAttribute
( Script::Attributes::DefaultConstructorOverrideIndex, behaviorClass->m_attributes)).Read<int>(overrideIndex);
int methodIndex = 0;
for (BehaviorMethod* method : behaviorClass->m_constructors)
{
if (methodIndex == overrideIndex)
{
customConstructorMethod = method;
break;
}
if (method->GetNumArguments() && method->GetArgument(method->GetNumArguments() - 1)->m_typeId == AZ::AzTypeInfo<ScriptDataContext>::Uuid())
{
customConstructorMethod = method;
break;
}
++methodIndex;
}
}
@@ -21,6 +21,7 @@ namespace AZ
static constexpr AZ::Crc32 ClassNameOverride = AZ_CRC_CE("ScriptClassNameOverride"); ///< Provide a custom name for script reflection, that doesn't match the behavior Context name
static constexpr AZ::Crc32 MethodOverride = AZ_CRC_CE("ScriptFunctionOverride"); ///< Use a custom function in the attribute instead of the function
static constexpr AZ::Crc32 ConstructorOverride = AZ_CRC_CE("ConstructorOverride"); ///< You can provide a custom constructor to be called when created from Lua script
static constexpr AZ::Crc32 DefaultConstructorOverrideIndex = AZ_CRC_CE("DefaultConstructorOverrideIndex"); ///< Use a different class constructor as the default constructor in Lua
static constexpr AZ::Crc32 EventHandlerCreationFunction = AZ_CRC_CE("EventHandlerCreationFunction"); ///< helps create a handler for any script target so that script functions can be used for AZ::Event signals
static constexpr AZ::Crc32 GenericConstructorOverride = AZ_CRC_CE("GenericConstructorOverride"); ///< You can provide a custom constructor to be called when creating a script
static constexpr AZ::Crc32 ReaderWriterOverride = AZ_CRC_CE("ReaderWriterOverride"); ///< paired with \ref ScriptContext::CustomReaderWriter allows you to customize read/write to Lua VM
@@ -133,6 +133,8 @@ namespace AZ
const static AZ::Crc32 AllowClearAsset = AZ_CRC("AllowClearAsset", 0x24827182);
// Show the name of the asset that was produced from the source asset
const static AZ::Crc32 ShowProductAssetFileName = AZ_CRC("ShowProductAssetFileName");
//! Regular expression pattern filter for source files
const static AZ::Crc32 SourceAssetFilterPattern = AZ_CRC_CE("SourceAssetFilterPattern");
//! Component icon attributes
const static AZ::Crc32 Icon = AZ_CRC("Icon", 0x659429db);
@@ -204,6 +204,22 @@ namespace AZ
// BaseJsonSerializer
//
JsonSerializationResult::Result BaseJsonSerializer::Load(void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue,
JsonDeserializerContext& context)
{
JsonSerializationResult::ResultCode result(JsonSerializationResult::Tasks::ReadField);
result.Combine(ContinueLoading(outputValue, outputValueTypeId, inputValue, context, ContinuationFlags::IgnoreTypeSerializer));
return context.Report(result, "Ignoring custom serialization during load");
}
JsonSerializationResult::Result BaseJsonSerializer::Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue,
const Uuid& valueTypeId, JsonSerializerContext& context)
{
JsonSerializationResult::ResultCode result(JsonSerializationResult::Tasks::WriteValue);
result.Combine(ContinueStoring(outputValue, inputValue, defaultValue, valueTypeId, context, ContinuationFlags::IgnoreTypeSerializer));
return context.Report(result, "Ignoring custom serialization during store");
}
BaseJsonSerializer::OperationFlags BaseJsonSerializer::GetOperationsFlags() const
{
return OperationFlags::None;
@@ -180,13 +180,16 @@ namespace AZ
//! Transforms the data from the rapidjson Value to outputValue, if the conversion is possible and supported.
//! The serializer is responsible for casting to the proper type and safely writing to the outputValue memory.
//! \note The default implementation is to load the object ignoring a custom serializers for the type, which allows for custom serializers
//! to modify the object after all default loading has occurred.
virtual JsonSerializationResult::Result Load(void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue,
JsonDeserializerContext& context) = 0;
JsonDeserializerContext& context);
//! Write the input value to a rapidjson value if the default value is not null and doesn't match the input value, otherwise
//! an error is returned and sets the rapidjson value to a null value.
//! \note The default implementation is to store the object ignoring custom serializers.
virtual JsonSerializationResult::Result Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue,
const Uuid& valueTypeId, JsonSerializerContext& context) = 0;
const Uuid& valueTypeId, JsonSerializerContext& context);
//! Returns the operation flags which tells the Json Serialization how this custom json serializer can be used.
virtual OperationFlags GetOperationsFlags() const;
+2 -3
View File
@@ -165,13 +165,12 @@ namespace AZ::Utils
}
Container fileContent;
fileContent.resize(length);
fileContent.resize_no_construct(length);
AZ::IO::SizeType bytesRead = file.Read(length, fileContent.data());
file.Close();
// Resize again just in case bytesRead is less than length for some reason
fileContent.resize(bytesRead);
fileContent.resize_no_construct(bytesRead);
return AZ::Success(AZStd::move(fileContent));
}
@@ -914,11 +914,11 @@ namespace UnitTest
m_testAssetManager->SetParallelDependentLoadingEnabled(true);
}
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
TEST_F(AssetJobsFloodTest, DISABLED_LoadTest_SameAsset_DifferentFilters)
#else
TEST_F(AssetJobsFloodTest, LoadTest_SameAsset_DifferentFilters)
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
{
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
@@ -1263,11 +1263,11 @@ namespace UnitTest
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
}
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadDependencies_NoLoadNotLoaded)
#else
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadDependencies_NoLoadNotLoaded)
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
{
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
// Setup has already created/destroyed assets
@@ -1304,11 +1304,11 @@ namespace UnitTest
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
}
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadContainerDependencies_LoadAllLoadsNoLoad)
#else
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadContainerDependencies_LoadAllLoadsNoLoad)
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
{
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
// Setup has already created/destroyed assets
@@ -1343,11 +1343,11 @@ namespace UnitTest
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
}
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadDependencies_BehaviorObeyed)
#else
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadDependencies_BehaviorObeyed)
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
{
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
// Setup has already created/destroyed assets
@@ -0,0 +1,185 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#if defined(HAVE_BENCHMARK)
#include <AzCore/DOM/DomUtils.h>
#include <AzCore/DOM/Backends/JSON/JsonBackend.h>
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
#include <AzCore/JSON/document.h>
#include <AzCore/Name/NameDictionary.h>
#include <AzCore/Serialization/Json/JsonUtils.h>
#include <AzCore/UnitTest/TestTypes.h>
namespace Benchmark
{
class DomJsonBenchmark : public UnitTest::AllocatorsBenchmarkFixture
{
public:
void SetUp(const ::benchmark::State& st) override
{
UnitTest::AllocatorsBenchmarkFixture::SetUp(st);
AZ::NameDictionary::Create();
}
void SetUp(::benchmark::State& st) override
{
UnitTest::AllocatorsBenchmarkFixture::SetUp(st);
AZ::NameDictionary::Create();
}
void TearDown(::benchmark::State& st) override
{
AZ::NameDictionary::Destroy();
UnitTest::AllocatorsBenchmarkFixture::TearDown(st);
}
void TearDown(const ::benchmark::State& st) override
{
AZ::NameDictionary::Destroy();
UnitTest::AllocatorsBenchmarkFixture::TearDown(st);
}
AZStd::string GenerateDomJsonBenchmarkPayload(int64_t entryCount, int64_t stringTemplateLength)
{
rapidjson::Document document;
document.SetObject();
AZStd::string entryTemplate;
while (entryTemplate.size() < static_cast<size_t>(stringTemplateLength))
{
entryTemplate += "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor ";
}
entryTemplate.resize(stringTemplateLength);
AZStd::string buffer;
auto createString = [&](int n) -> rapidjson::Value
{
buffer = AZStd::string::format("#%i %s", n, entryTemplate.c_str());
return rapidjson::Value(buffer.data(), static_cast<rapidjson::SizeType>(buffer.size()), document.GetAllocator());
};
auto createEntry = [&](int n) -> rapidjson::Value
{
rapidjson::Value entry(rapidjson::kObjectType);
entry.AddMember("string", createString(n), document.GetAllocator());
entry.AddMember("int", rapidjson::Value(n), document.GetAllocator());
entry.AddMember("double", rapidjson::Value(static_cast<double>(n) * 0.5), document.GetAllocator());
entry.AddMember("bool", rapidjson::Value(n % 2 == 0), document.GetAllocator());
entry.AddMember("null", rapidjson::Value(rapidjson::kNullType), document.GetAllocator());
return entry;
};
auto createArray = [&]() -> rapidjson::Value
{
rapidjson::Value array;
array.SetArray();
for (int i = 0; i < entryCount; ++i)
{
array.PushBack(createEntry(i), document.GetAllocator());
}
return array;
};
auto createObject = [&]() -> rapidjson::Value
{
rapidjson::Value object;
object.SetObject();
for (int i = 0; i < entryCount; ++i)
{
buffer = AZStd::string::format("Key%i", i);
rapidjson::Value key;
key.SetString(buffer.data(), static_cast<rapidjson::SizeType>(buffer.length()), document.GetAllocator());
object.AddMember(key.Move(), createArray(), document.GetAllocator());
}
return object;
};
document.SetObject();
document.AddMember("entries", createObject(), document.GetAllocator());
AZStd::string serializedJson;
auto result = AZ::JsonSerializationUtils::WriteJsonString(document, serializedJson);
AZ_Assert(result.IsSuccess(), "Failed to serialize generated JSON");
return serializedJson;
}
};
// Helper macro for registering JSON benchmarks
#define BENCHMARK_REGISTER_JSON(BaseClass, Method) \
BENCHMARK_REGISTER_F(BaseClass, Method) \
->Args({ 10, 5 }) \
->Args({ 10, 500 }) \
->Args({ 100, 5 }) \
->Args({ 100, 500 }) \
->Unit(benchmark::kMillisecond);
BENCHMARK_DEFINE_F(DomJsonBenchmark, DomDeserializeToDocumentInPlace)(benchmark::State& state)
{
AZ::Dom::JsonBackend backend;
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
for (auto _ : state)
{
state.PauseTiming();
AZStd::string payloadCopy = serializedPayload;
state.ResumeTiming();
auto result = AZ::Dom::Json::WriteToRapidJsonDocument(
[&](AZ::Dom::Visitor& visitor)
{
return AZ::Dom::Utils::ReadFromStringInPlace(backend, payloadCopy, visitor);
});
benchmark::DoNotOptimize(result.GetValue());
}
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
}
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, DomDeserializeToDocumentInPlace)
BENCHMARK_DEFINE_F(DomJsonBenchmark, DomDeserializeToDocument)(benchmark::State& state)
{
AZ::Dom::JsonBackend backend;
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
for (auto _ : state)
{
auto result = AZ::Dom::Json::WriteToRapidJsonDocument(
[&](AZ::Dom::Visitor& visitor)
{
return AZ::Dom::Utils::ReadFromString(backend, serializedPayload, AZ::Dom::Lifetime::Temporary, visitor);
});
benchmark::DoNotOptimize(result.GetValue());
}
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
}
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, DomDeserializeToDocument)
BENCHMARK_DEFINE_F(DomJsonBenchmark, JsonUtilsDeserializeToDocument)(benchmark::State& state)
{
AZ::Dom::JsonBackend backend;
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
for (auto _ : state)
{
auto result = AZ::JsonSerializationUtils::ReadJsonString(serializedPayload);
benchmark::DoNotOptimize(result.GetValue());
}
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
}
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, JsonUtilsDeserializeToDocument)
#undef BENCHMARK_REGISTER_JSON
} // namespace Benchmark
#endif // defined(HAVE_BENCHMARK)
@@ -0,0 +1,219 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/DOM/Backends/JSON/JsonBackend.h>
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
#include <AzCore/DOM/DomUtils.h>
#include <AzCore/Name/NameDictionary.h>
#include <AzCore/Serialization/Json/JsonSerialization.h>
#include <AzCore/Serialization/Json/JsonUtils.h>
#include <AzCore/UnitTest/TestTypes.h>
namespace AZ::Dom::Tests
{
class DomJsonTests : public UnitTest::AllocatorsFixture
{
public:
void SetUp() override
{
UnitTest::AllocatorsFixture::SetUp();
NameDictionary::Create();
m_document = AZStd::make_unique<rapidjson::Document>();
}
void TearDown() override
{
m_document.reset();
NameDictionary::Destroy();
UnitTest::AllocatorsFixture::TearDown();
}
rapidjson::Value CreateString(const AZStd::string& text)
{
rapidjson::Value key;
key.SetString(text.c_str(), static_cast<rapidjson::SizeType>(text.length()), m_document->GetAllocator());
return key;
}
template<class T>
void AddValue(const AZStd::string& key, T value)
{
m_document->AddMember(CreateString(key), rapidjson::Value(value), m_document->GetAllocator());
}
// Validate round-trip serialization to and from rapidjson::Document and a UTF-8 encoded string
void PerformSerializationChecks()
{
// Generate a canonical serializaed representation of this document using rapidjson
// This will be pretty-printed using the same rapidjson pretty printer we use, so should be binary identical
// to any output generated by the visitor API
AZStd::string canonicalSerializedDocument;
AZ::JsonSerializationUtils::WriteJsonString(*m_document, canonicalSerializedDocument);
auto visitDocumentFn = [this](AZ::Dom::Visitor& visitor)
{
return Json::VisitRapidJsonValue(*m_document, visitor, Lifetime::Temporary);
};
// Document -> Document
{
auto result = Json::WriteToRapidJsonDocument(visitDocumentFn);
EXPECT_TRUE(result.IsSuccess());
EXPECT_EQ(AZ::JsonSerialization::Compare(*m_document, result.GetValue()), AZ::JsonSerializerCompareResult::Equal);
}
// Document -> string
{
AZStd::string serializedDocument;
JsonBackend backend;
auto result = backend.WriteToBuffer(serializedDocument, visitDocumentFn);
EXPECT_TRUE(result.IsSuccess());
EXPECT_EQ(canonicalSerializedDocument, serializedDocument);
}
// string -> Document
{
auto result = Json::WriteToRapidJsonDocument(
[&canonicalSerializedDocument](AZ::Dom::Visitor& visitor)
{
JsonBackend backend;
return Dom::Utils::ReadFromString(backend, canonicalSerializedDocument, Lifetime::Temporary, visitor);
});
EXPECT_TRUE(result.IsSuccess());
EXPECT_EQ(AZ::JsonSerialization::Compare(*m_document, result.GetValue()), JsonSerializerCompareResult::Equal);
}
// string -> string
{
AZStd::string serializedDocument;
JsonBackend backend;
auto result = backend.WriteToBuffer(
serializedDocument,
[&backend, &canonicalSerializedDocument](AZ::Dom::Visitor& visitor)
{
return Dom::Utils::ReadFromString(backend, canonicalSerializedDocument, Lifetime::Temporary, visitor);
});
EXPECT_TRUE(result.IsSuccess());
EXPECT_EQ(canonicalSerializedDocument, serializedDocument);
}
}
AZStd::unique_ptr<rapidjson::Document> m_document;
};
TEST_F(DomJsonTests, EmptyArray)
{
m_document->SetArray();
PerformSerializationChecks();
}
TEST_F(DomJsonTests, SimpleArray)
{
m_document->SetArray();
for (int i = 0; i < 5; ++i)
{
m_document->PushBack(i, m_document->GetAllocator());
}
PerformSerializationChecks();
}
TEST_F(DomJsonTests, NestedArrays)
{
m_document->SetArray();
for (int j = 0; j < 7; ++j)
{
rapidjson::Value nestedArray(rapidjson::kArrayType);
for (int i = 0; i < 5; ++i)
{
nestedArray.PushBack(i, m_document->GetAllocator());
}
m_document->PushBack(nestedArray.Move(), m_document->GetAllocator());
}
PerformSerializationChecks();
}
TEST_F(DomJsonTests, EmptyObject)
{
m_document->SetObject();
PerformSerializationChecks();
}
TEST_F(DomJsonTests, SimpleObject)
{
m_document->SetObject();
for (int i = 0; i < 5; ++i)
{
m_document->AddMember(CreateString(AZStd::string::format("Key%i", i)), rapidjson::Value(i), m_document->GetAllocator());
}
PerformSerializationChecks();
}
TEST_F(DomJsonTests, NestedObjects)
{
m_document->SetObject();
for (int j = 0; j < 7; ++j)
{
rapidjson::Value nestedObject(rapidjson::kObjectType);
for (int i = 0; i < 5; ++i)
{
nestedObject.AddMember(CreateString(AZStd::string::format("Key%i", i)), rapidjson::Value(i), m_document->GetAllocator());
}
m_document->AddMember(CreateString(AZStd::string::format("Obj%i", j)), nestedObject.Move(), m_document->GetAllocator());
}
PerformSerializationChecks();
}
TEST_F(DomJsonTests, Int64)
{
m_document->SetObject();
AddValue("int64_min", AZStd::numeric_limits<int64_t>::min());
AddValue("int64_max", AZStd::numeric_limits<int64_t>::max());
PerformSerializationChecks();
}
TEST_F(DomJsonTests, Uint64)
{
m_document->SetObject();
AddValue("uint64_min", AZStd::numeric_limits<uint64_t>::min());
AddValue("uint64_max", AZStd::numeric_limits<uint64_t>::max());
PerformSerializationChecks();
}
TEST_F(DomJsonTests, Double)
{
m_document->SetObject();
AddValue("double_min", AZStd::numeric_limits<double>::min());
AddValue("double_max", AZStd::numeric_limits<double>::max());
PerformSerializationChecks();
}
TEST_F(DomJsonTests, Null)
{
m_document->SetObject();
m_document->AddMember(CreateString("null_value"), rapidjson::Value(rapidjson::kNullType), m_document->GetAllocator());
PerformSerializationChecks();
}
TEST_F(DomJsonTests, Bool)
{
m_document->SetObject();
AddValue("true_value", true);
AddValue("false_value", false);
PerformSerializationChecks();
}
TEST_F(DomJsonTests, String)
{
m_document->SetObject();
m_document->AddMember(CreateString("empty_string"), CreateString(""), m_document->GetAllocator());
m_document->AddMember(CreateString("short_string"), CreateString("test"), m_document->GetAllocator());
m_document->AddMember(
CreateString("long_string"), CreateString("abcdefghijklmnopqrstuvwxyz0123456789"), m_document->GetAllocator());
PerformSerializationChecks();
}
} // namespace AZ::Dom::Tests
@@ -13,6 +13,13 @@
namespace UnitTest
{
//! Null implementation of DebugDisplayRequests for dummy draw calls.
class NullDebugDisplayRequests : public AzFramework::DebugDisplayRequests
{
public:
virtual ~NullDebugDisplayRequests() = default;
};
//! Minimal implementation of DebugDisplayRequests to support testing shapes.
//! Stores a list of points based on received draw calls to delineate the exterior of the object requested to be drawn.
class TestDebugDisplayRequests : public AzFramework::DebugDisplayRequests
@@ -29,7 +29,8 @@ namespace UnitTest
void SetUpEditorFixtureImpl() override
{
ToolsApplicationFixtureT::SetUpEditorFixtureImpl();
m_viewportManipulatorInteraction = AZStd::make_unique<IndirectCallManipulatorViewportInteraction>();
m_viewportManipulatorInteraction =
AZStd::make_unique<IndirectCallManipulatorViewportInteraction>(ToolsApplicationFixtureT::CreateDebugDisplayRequests());
m_actionDispatcher = AZStd::make_unique<ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction);
m_cameraState =
AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
@@ -17,11 +17,10 @@ namespace AzManipulatorTestFramework
class ViewportInteraction;
//! Implementation of manipulator viewport interaction that manipulates the manager directly.
class DirectCallManipulatorViewportInteraction
: public ManipulatorViewportInteraction
class DirectCallManipulatorViewportInteraction : public ManipulatorViewportInteraction
{
public:
DirectCallManipulatorViewportInteraction();
explicit DirectCallManipulatorViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
~DirectCallManipulatorViewportInteraction();
// ManipulatorViewportInteractionInterface ...
@@ -21,7 +21,7 @@ namespace AzManipulatorTestFramework
class IndirectCallManipulatorViewportInteraction : public ManipulatorViewportInteraction
{
public:
IndirectCallManipulatorViewportInteraction();
explicit IndirectCallManipulatorViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
~IndirectCallManipulatorViewportInteraction();
// ManipulatorViewportInteractionInterface ...
@@ -11,10 +11,13 @@
#include <AzFramework/Visibility/EntityVisibilityQuery.h>
#include <AzManipulatorTestFramework/AzManipulatorTestFramework.h>
namespace AzFramework
{
class DebugDisplayRequests;
}
namespace AzManipulatorTestFramework
{
class NullDebugDisplayRequests;
//! Implementation of the viewport interaction model to handle viewport interaction requests.
class ViewportInteraction
: public ViewportInteractionInterface
@@ -23,7 +26,7 @@ namespace AzManipulatorTestFramework
, private AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler
{
public:
ViewportInteraction();
explicit ViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
~ViewportInteraction();
// ViewportInteractionInterface overrides ...
@@ -63,7 +66,7 @@ namespace AzManipulatorTestFramework
static constexpr AzFramework::ViewportId m_viewportId = 1234; //!< Arbitrary viewport id for manipulator tests.
AzFramework::EntityVisibilityQuery m_entityVisibilityQuery;
AZStd::unique_ptr<NullDebugDisplayRequests> m_nullDebugDisplayRequests;
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> m_debugDisplayRequests;
AzFramework::CameraState m_cameraState;
bool m_gridSnapping = false;
bool m_angularSnapping = false;
@@ -118,10 +118,11 @@ namespace AzManipulatorTestFramework
return m_manipulatorManager->Interacting();
}
DirectCallManipulatorViewportInteraction::DirectCallManipulatorViewportInteraction()
DirectCallManipulatorViewportInteraction::DirectCallManipulatorViewportInteraction(
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
: m_customManager(
AZStd::make_unique<CustomManipulatorManager>(AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId"))))
, m_viewportInteraction(AZStd::make_unique<ViewportInteraction>())
, m_viewportInteraction(AZStd::make_unique<ViewportInteraction>(AZStd::move(debugDisplayRequests)))
, m_manipulatorManager(AZStd::make_unique<DirectCallManipulatorManager>(m_viewportInteraction.get(), m_customManager))
{
}
@@ -76,8 +76,9 @@ namespace AzManipulatorTestFramework
return manipulatorInteracting;
}
IndirectCallManipulatorViewportInteraction::IndirectCallManipulatorViewportInteraction()
: m_viewportInteraction(AZStd::make_unique<ViewportInteraction>())
IndirectCallManipulatorViewportInteraction::IndirectCallManipulatorViewportInteraction(
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
: m_viewportInteraction(AZStd::make_unique<ViewportInteraction>(AZStd::move(debugDisplayRequests)))
, m_manipulatorManager(AZStd::make_unique<IndirectCallManipulatorManager>(*m_viewportInteraction))
{
}
@@ -13,15 +13,8 @@
namespace AzManipulatorTestFramework
{
// Null debug display for dummy draw calls
class NullDebugDisplayRequests : public AzFramework::DebugDisplayRequests
{
public:
virtual ~NullDebugDisplayRequests() = default;
};
ViewportInteraction::ViewportInteraction()
: m_nullDebugDisplayRequests(AZStd::make_unique<NullDebugDisplayRequests>())
ViewportInteraction::ViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
: m_debugDisplayRequests(AZStd::move(debugDisplayRequests))
{
AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusConnect(m_viewportId);
AzToolsFramework::ViewportInteraction::ViewportSettingsRequestBus::Handler::BusConnect(m_viewportId);
@@ -102,7 +95,7 @@ namespace AzManipulatorTestFramework
AzFramework::DebugDisplayRequests& ViewportInteraction::GetDebugDisplay()
{
return *m_nullDebugDisplayRequests;
return *m_debugDisplayRequests;
}
void ViewportInteraction::SetGridSnapping(const bool enabled)
@@ -26,7 +26,8 @@ namespace UnitTest
{
public:
GridSnappingFixture()
: m_viewportManipulatorInteraction(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>())
: m_viewportManipulatorInteraction(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>(
AZStd::make_shared<NullDebugDisplayRequests>()))
, m_actionDispatcher(
AZStd::make_unique<AzManipulatorTestFramework::ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction))
{
@@ -15,7 +15,8 @@ namespace UnitTest
{
public:
AValidViewportInteraction()
: m_viewportInteraction(AZStd::make_unique<AzManipulatorTestFramework::ViewportInteraction>())
: m_viewportInteraction(
AZStd::make_unique<AzManipulatorTestFramework::ViewportInteraction>(AZStd::make_shared<NullDebugDisplayRequests>()))
{
}
@@ -75,9 +75,11 @@ namespace UnitTest
void SetUpEditorFixtureImpl() override
{
m_directState =
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>());
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>(
AZStd::make_shared<NullDebugDisplayRequests>()));
m_busState =
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::IndirectCallManipulatorViewportInteraction>());
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::IndirectCallManipulatorViewportInteraction>(
AZStd::make_shared<NullDebugDisplayRequests>()));
m_cameraState =
AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
}
@@ -0,0 +1,3 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.58087 1.8457C8.88135 1.8457 7.99903 2.19115 6.93392 2.88204L6.92893 2.87676C6.30965 3.2791 5.82426 3.79917 5.22899 4.43697L5.22899 4.43697C4.86895 4.82273 4.46872 5.25156 3.97436 5.72345L4.40762 6.13135C6.90029 8.44469 8.28286 9.60136 9.56289 9.60136C10.2624 9.60136 11.1447 9.25592 12.2098 8.56503L12.2148 8.57031C12.9369 8.10117 13.5717 7.47196 14.368 6.68268L14.3681 6.68264C14.6677 6.38563 14.9902 6.06596 15.3489 5.72362L14.9156 5.31571C12.4229 3.00237 10.8609 1.8457 9.58087 1.8457ZM7.6529 3.64381L7.65238 3.64325C8.14738 3.13093 8.82452 2.81518 9.57127 2.81518C11.0878 2.81518 12.3171 4.11733 12.3171 5.72362C12.3171 6.53856 12.0007 7.27522 11.4909 7.80326L11.4914 7.80381C10.9964 8.31614 10.3192 8.63189 9.57249 8.63189C8.05599 8.63189 6.82663 7.32973 6.82663 5.72345C6.82663 4.90851 7.14307 4.17185 7.6529 3.64381ZM9.56659 3.78466C9.05074 3.78466 8.58461 4.0095 8.25119 4.37149L8.25649 4.3771C7.93789 4.72586 7.74192 5.20047 7.74192 5.72345C7.74192 6.79431 8.56359 7.66241 9.57717 7.66241C10.093 7.66241 10.5592 7.43756 10.8926 7.07558L10.8873 7.06997C11.2059 6.72121 11.4018 6.24659 11.4018 5.72362C11.4018 4.65276 10.5802 3.78466 9.56659 3.78466ZM2.97474 1.99964H6.70318C6.07867 2.40803 5.53108 2.87237 5.07056 3.38303H2.97474C2.38778 3.38303 1.896 3.86007 1.896 4.44841V13.035C1.896 13.6233 2.37192 14.1003 2.97474 14.1003H11.5094C12.0964 14.1003 12.5881 13.6392 12.5881 13.035H12.6199V9.26317C13.1109 8.93674 13.5803 8.5478 14 8.10987V13.035C14 14.4025 12.8895 15.4996 11.5253 15.4996H2.97474C1.61046 15.4996 0.5 14.4025 0.5 13.035V4.44841C0.5 3.09681 1.61046 1.99964 2.97474 1.99964Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1,3 @@
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M3 4.60547C3 2.94862 4.34315 1.60547 6 1.60547C7.65685 1.60547 9 2.94862 9 4.60547V5.84076H10V6.60547C10 7.53544 10 8.00043 9.89778 8.38193C9.62038 9.4172 8.81173 10.2258 7.77646 10.5032C7.39496 10.6055 6.92997 10.6055 6 10.6055C5.07003 10.6055 4.60504 10.6055 4.22354 10.5032C3.18827 10.2258 2.37962 9.4172 2.10222 8.38193C2 8.00043 2 7.53544 2 6.60547V5.84076H3V4.60547ZM5.25 6.89953V9.54659H6.75V6.89953H5.25ZM6 2.66429C4.89543 2.66429 4 3.55972 4 4.66429V5.84076L8 5.84076V4.66429C8 3.55972 7.10457 2.66429 6 2.66429Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 690 B

@@ -7,7 +7,9 @@
<file alias="prefab.svg">Entity/prefab.svg</file>
<file alias="prefab_edit.svg">Entity/prefab_edit.svg</file>
<file alias="prefab_edit_open.svg">Entity/prefab_edit_open.svg</file>
<file alias="prefab_edit_open_readonly.svg">Entity/prefab_edit_open_readonly.svg</file>
<file alias="prefab_edit_close.svg">Entity/prefab_edit_close.svg</file>
<file alias="readonly.svg">Entity/readonly.svg</file>
</qresource>
<qresource prefix="/Level">
<file alias="level.svg">Level/level.svg</file>
@@ -14,7 +14,6 @@
#define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000
#define AZ_TRAIT_DISABLE_FAILED_AP_CONNECTION_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_ATOM_RPI_TESTS true
#define AZ_TRAIT_DISABLE_FAILED_ARCHIVE_TESTS true
@@ -99,6 +99,18 @@ namespace AzToolsFramework
}
}
if (selection.GetSelectedAssetIds().empty())
{
for (auto& filePath : selection.GetSelectedFilePaths())
{
if (!filePath.empty())
{
selectedAsset = true;
m_ui->m_assetBrowserTreeViewWidget->SelectFileAtPath(filePath);
}
}
}
if (!selectedAsset)
{
m_ui->m_assetBrowserTreeViewWidget->SelectFolder(selection.GetDefaultDirectory());
@@ -10,18 +10,24 @@
#include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
#include <AzToolsFramework/AssetBrowser/EBusFindAssetTypeByName.h>
#if !defined(Q_MOC_RUN)
AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option")
#include <QRegExp>
AZ_POP_DISABLE_WARNING
#endif
namespace AzToolsFramework
{
namespace AssetBrowser
{
namespace
{
FilterConstType ProductsNoFoldersFilter()
FilterConstType EntryTypeNoFoldersFilter(AssetBrowserEntry::AssetEntryType entryType = AssetBrowserEntry::AssetEntryType::Product)
{
EntryTypeFilter* productFilter = new EntryTypeFilter();
productFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Product);
EntryTypeFilter* entryTypeFilter = new EntryTypeFilter();
entryTypeFilter->SetEntryType(entryType);
// in case entry is a source or folder, it may still contain relevant product
productFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
entryTypeFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
EntryTypeFilter* foldersFilter = new EntryTypeFilter();
foldersFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Folder);
@@ -30,7 +36,7 @@ namespace AzToolsFramework
noFoldersFilter->SetFilter(FilterConstType(foldersFilter));
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
compFilter->AddFilter(FilterConstType(productFilter));
compFilter->AddFilter(FilterConstType(entryTypeFilter));
compFilter->AddFilter(FilterConstType(noFoldersFilter));
return FilterConstType(compFilter);
@@ -79,15 +85,39 @@ namespace AzToolsFramework
void AssetSelectionModel::SetSelectedAssetIds(const AZStd::vector<AZ::Data::AssetId>& selectedAssetIds)
{
m_selectedFilePaths.clear();
m_selectedAssetIds = selectedAssetIds;
}
void AssetSelectionModel::SetSelectedAssetId(const AZ::Data::AssetId& selectedAssetId)
{
m_selectedFilePaths.clear();
m_selectedAssetIds.clear();
m_selectedAssetIds.push_back(selectedAssetId);
}
const AZStd::vector<AZStd::string>& AssetSelectionModel::GetSelectedFilePaths() const
{
return m_selectedFilePaths;
}
void AssetSelectionModel::SetSelectedFilePaths(const AZStd::vector<AZStd::string>& selectedFilePaths)
{
m_selectedAssetIds.clear();
m_selectedFilePaths = selectedFilePaths;
}
void AssetSelectionModel::SetSelectedFilePath(const AZStd::string& selectedFilePath)
{
m_selectedAssetIds.clear();
m_selectedFilePaths.clear();
m_selectedFilePaths.push_back(selectedFilePath);
}
void AssetSelectionModel::SetDefaultDirectory(AZStd::string_view defaultDirectory)
{
m_defaultDirectory = defaultDirectory;
@@ -136,7 +166,7 @@ namespace AzToolsFramework
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
compFilter->AddFilter(assetTypeFilterPtr);
compFilter->AddFilter(ProductsNoFoldersFilter());
compFilter->AddFilter(EntryTypeNoFoldersFilter());
selection.SetSelectionFilter(FilterConstType(compFilter));
selection.SetMultiselect(multiselect);
@@ -169,7 +199,7 @@ namespace AzToolsFramework
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
compFilter->AddFilter(anyAssetTypeFilterPtr);
compFilter->AddFilter(ProductsNoFoldersFilter());
compFilter->AddFilter(EntryTypeNoFoldersFilter());
selection.SetSelectionFilter(FilterConstType(compFilter));
selection.SetMultiselect(multiselect);
@@ -190,7 +220,28 @@ namespace AzToolsFramework
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
compFilter->AddFilter(assetGroupFilterPtr);
compFilter->AddFilter(ProductsNoFoldersFilter());
compFilter->AddFilter(EntryTypeNoFoldersFilter());
selection.SetSelectionFilter(FilterConstType(compFilter));
selection.SetMultiselect(multiselect);
return selection;
}
AssetSelectionModel AssetSelectionModel::SourceAssetTypeSelection(const QString& pattern, bool multiselect)
{
AssetSelectionModel selection;
RegExpFilter* patternFilter = new RegExpFilter();
patternFilter->SetFilterPattern(pattern);
patternFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
auto patternFilterPtr = FilterConstType(patternFilter);
selection.SetDisplayFilter(patternFilterPtr);
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
compFilter->AddFilter(patternFilterPtr);
compFilter->AddFilter(EntryTypeNoFoldersFilter(AssetBrowserEntry::AssetEntryType::Source));
selection.SetSelectionFilter(FilterConstType(compFilter));
selection.SetMultiselect(multiselect);
@@ -204,7 +255,7 @@ namespace AzToolsFramework
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::OR);
selection.SetDisplayFilter(FilterConstType(compFilter));
selection.SetSelectionFilter(ProductsNoFoldersFilter());
selection.SetSelectionFilter(EntryTypeNoFoldersFilter());
selection.SetMultiselect(multiselect);
return selection;
@@ -44,6 +44,10 @@ namespace AzToolsFramework
void SetSelectedAssetIds(const AZStd::vector<AZ::Data::AssetId>& selectedAssetIds);
void SetSelectedAssetId(const AZ::Data::AssetId& selectedAssetId);
const AZStd::vector<AZStd::string>& GetSelectedFilePaths() const;
void SetSelectedFilePaths(const AZStd::vector<AZStd::string>& selectedFilePaths);
void SetSelectedFilePath(const AZStd::string& selectedFilePath);
void SetDefaultDirectory(AZStd::string_view defaultDirectory);
AZStd::string_view GetDefaultDirectory() const;
@@ -60,6 +64,7 @@ namespace AzToolsFramework
static AssetSelectionModel AssetTypeSelection(const char* assetTypeName, bool multiselect = false);
static AssetSelectionModel AssetTypesSelection(const AZStd::vector<AZ::Data::AssetType>& assetTypes, bool multiselect = false);
static AssetSelectionModel AssetGroupSelection(const char* group, bool multiselect = false);
static AssetSelectionModel SourceAssetTypeSelection(const QString& pattern, bool multiselect = false);
static AssetSelectionModel EverythingSelection(bool multiselect = false);
private:
@@ -68,8 +73,12 @@ namespace AzToolsFramework
// some entries like folder should always be displayed, but not always selectable, thus 2 separate filters
FilterConstType m_selectionFilter;
FilterConstType m_displayFilter;
//! Selection can be based on asset ids (for products), or file paths (for sources)
//! These are mututally exclusive
AZStd::vector<AZ::Data::AssetId> m_selectedAssetIds;
AZStd::vector<AZStd::string> m_selectedFilePaths;
AZStd::vector<const AssetBrowserEntry*> m_results;
AZStd::string m_defaultDirectory;
@@ -251,6 +251,40 @@ namespace AzToolsFramework
return false;
}
//////////////////////////////////////////////////////////////////////////
// RegExpFilter
//////////////////////////////////////////////////////////////////////////
RegExpFilter::RegExpFilter()
: m_filterPattern("")
{
}
void RegExpFilter::SetFilterPattern(const QString& filterPattern)
{
m_filterPattern = filterPattern;
Q_EMIT updatedSignal();
}
QString RegExpFilter::GetNameInternal() const
{
return m_filterPattern;
}
bool RegExpFilter::MatchInternal(const AssetBrowserEntry* entry) const
{
// no filter pattern matches any asset
if (m_filterPattern.isEmpty())
{
return true;
}
// entry's name matches regular expression pattern
QRegExp regExp(m_filterPattern);
regExp.setPatternSyntax(QRegExp::Wildcard);
return regExp.exactMatch(entry->GetDisplayName());
}
//////////////////////////////////////////////////////////////////////////
// AssetTypeFilter
//////////////////////////////////////////////////////////////////////////
@@ -115,6 +115,28 @@ namespace AzToolsFramework
QString m_filterString;
};
//////////////////////////////////////////////////////////////////////////
// RegExpFilter
//////////////////////////////////////////////////////////////////////////
//! RegExpFilter filters assets based on a regular expression pattern
class RegExpFilter
: public AssetBrowserEntryFilter
{
Q_OBJECT
public:
RegExpFilter();
~RegExpFilter() override = default;
void SetFilterPattern(const QString& filterPattern);
protected:
QString GetNameInternal() const override;
bool MatchInternal(const AssetBrowserEntry* entry) const override;
private:
QString m_filterPattern;
};
//////////////////////////////////////////////////////////////////////////
// AssetTypeFilter
//////////////////////////////////////////////////////////////////////////
@@ -37,9 +37,9 @@ namespace AzToolsFramework
static void Reflect(AZ::ReflectContext* context);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
// ReadOnlyEntityPublicNotifications overrides ...
// ReadOnlyEntityPublicInterface overrides ...
bool IsReadOnly(const AZ::EntityId& entityId) override;
// ReadOnlyEntityQueryInterface overrides ...
void RefreshReadOnlyState(const EntityIdList& entityIds) override;
void RefreshReadOnlyStateForAllEntities() override;
@@ -50,7 +50,7 @@ namespace AzToolsFramework
return false;
}
void TraceLogger::PrepareLogFile(const AZStd::string& logFileName)
void TraceLogger::OpenLogFile(const AZStd::string& logFileName, bool clearLogFile)
{
using namespace AzFramework;
@@ -73,7 +73,7 @@ namespace AzToolsFramework
AZStd::string logPath;
StringFunc::Path::Join(logDirectory.c_str(), logFileName.c_str(), logPath);
m_logFile.reset(aznew LogFile(logPath.c_str()));
m_logFile.reset(aznew LogFile(logPath.c_str(), clearLogFile));
if (m_logFile)
{
m_logFile->SetMachineReadable(false);
@@ -81,7 +81,7 @@ namespace AzToolsFramework
{
m_logFile->AppendLog(LogFile::SEV_NORMAL, message.window.c_str(), message.message.c_str());
}
m_startupLogSink = {};
m_startupLogSink.clear();
m_logFile->FlushLog();
}
}
@@ -23,7 +23,7 @@ namespace AzToolsFramework
~TraceLogger();
//! Open log file and dump log sink into it
void PrepareLogFile(const AZStd::string& logFileName);
void OpenLogFile(const AZStd::string& logFileName, bool clearLogFile);
//! Add filter to ignore messages for windows with matching names
void AddWindowFilter(const AZStd::string& filter);
@@ -55,7 +55,8 @@ namespace AzToolsFramework
AZStd::string window;
AZStd::string message;
};
AZStd::vector<LogMessage> m_startupLogSink;
AZStd::list<LogMessage> m_startupLogSink;
AZStd::unordered_set<AZStd::string> m_windowFilters;
AZStd::unordered_set<AZStd::string> m_messageFilters;
AZStd::unique_ptr<AzFramework::LogFile> m_logFile;
@@ -191,8 +191,8 @@ namespace AzToolsFramework
{
m_manipulatorView->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState,
mouseInteraction);
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
}
void AngularManipulator::SetAxis(const AZ::Vector3& axis)
@@ -116,8 +116,8 @@ namespace AzToolsFramework
{
m_manipulatorView->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), m_localStart, MouseOver() }, debugDisplay, cameraState,
mouseInteraction);
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), m_localStart, MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
}
}
@@ -239,8 +239,8 @@ namespace AzToolsFramework
view->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ ApplySpace(localTransform), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState,
mouseInteraction);
ManipulatorState{ ApplySpace(localTransform), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
}
}
@@ -146,7 +146,7 @@ namespace AzToolsFramework
for (const auto& pair : m_manipulatorIdToPtrMap)
{
pair.second->Draw({ Interacting() }, debugDisplay, cameraState, mouseInteraction);
pair.second->Draw(ManipulatorManagerState{ Interacting() }, debugDisplay, cameraState, mouseInteraction);
}
RefreshMouseOverState(mouseInteraction.m_mousePick);
@@ -10,6 +10,15 @@
namespace AzToolsFramework
{
AZ::Transform ApplySpace(const AZ::Transform& localTransform, const AZ::Transform& space, const AZ::Vector3& nonUniformScale)
{
AZ::Transform result;
result.SetRotation(space.GetRotation() * localTransform.GetRotation());
result.SetTranslation(space.TransformPoint(nonUniformScale * localTransform.GetTranslation()));
result.SetUniformScale(space.GetUniformScale() * localTransform.GetUniformScale());
return result;
}
const AZ::Transform& ManipulatorSpace::GetSpace() const
{
return m_space;
@@ -32,11 +41,7 @@ namespace AzToolsFramework
AZ::Transform ManipulatorSpace::ApplySpace(const AZ::Transform& localTransform) const
{
AZ::Transform result;
result.SetRotation(m_space.GetRotation() * localTransform.GetRotation());
result.SetTranslation(m_space.TransformPoint(m_nonUniformScale * localTransform.GetTranslation()));
result.SetUniformScale(m_space.GetUniformScale() * localTransform.GetUniformScale());
return result;
return AzToolsFramework::ApplySpace(localTransform, m_space, m_nonUniformScale);
}
const AZ::Vector3& ManipulatorSpaceWithLocalPosition::GetLocalPosition() const
@@ -17,6 +17,8 @@ namespace AZ
namespace AzToolsFramework
{
AZ::Transform ApplySpace(const AZ::Transform& localTransform, const AZ::Transform& space, const AZ::Vector3& nonUniformScale);
//! Handles location for manipulators which have a global space but no local transformation.
class ManipulatorSpace
{
@@ -383,8 +383,8 @@ namespace AzToolsFramework
debugDisplay.DrawLine(quadBoundVisual.m_corner1, quadBoundVisual.m_corner2);
debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_axis2Color, m_mouseOverColor).GetAsVector4());
debugDisplay.DrawLine(quadBoundVisual.m_corner4, quadBoundVisual.m_corner1);
debugDisplay.DrawLine(quadBoundVisual.m_corner2, quadBoundVisual.m_corner3);
debugDisplay.DrawLine(quadBoundVisual.m_corner1, quadBoundVisual.m_corner4);
if (manipulatorState.m_mouseOver)
{
@@ -738,15 +738,16 @@ namespace AzToolsFramework
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AZStd::unique_ptr<ManipulatorViewQuad> CreateManipulatorViewQuad(
const PlanarManipulator& planarManipulator,
const AZ::Vector3& axis1,
const AZ::Vector3& axis2,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const AZ::Vector3& offset,
const float size)
{
AZStd::unique_ptr<ManipulatorViewQuad> viewQuad = AZStd::make_unique<ManipulatorViewQuad>();
viewQuad->m_axis1 = planarManipulator.GetAxis1();
viewQuad->m_axis2 = planarManipulator.GetAxis2();
viewQuad->m_axis1 = axis1;
viewQuad->m_axis2 = axis2;
viewQuad->m_size = size;
viewQuad->m_offset = offset;
viewQuad->m_axis1Color = axis1Color;
@@ -382,7 +382,8 @@ namespace AzToolsFramework
// Helpers to create various manipulator views.
AZStd::unique_ptr<ManipulatorViewQuad> CreateManipulatorViewQuad(
const PlanarManipulator& planarManipulator,
const AZ::Vector3& axis1,
const AZ::Vector3& axis2,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const AZ::Vector3& offset,
@@ -145,8 +145,8 @@ namespace AzToolsFramework
{
view->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
debugDisplay, cameraState, mouseInteraction);
}
}
@@ -202,8 +202,8 @@ namespace AzToolsFramework
{
view->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
debugDisplay, cameraState, mouseInteraction);
}
}
@@ -90,8 +90,8 @@ namespace AzToolsFramework
{
view->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState,
mouseInteraction);
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
}
}
@@ -94,8 +94,8 @@ namespace AzToolsFramework
{
m_manipulatorView->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
debugDisplay, cameraState, mouseInteraction);
}
}
@@ -166,8 +166,8 @@ namespace AzToolsFramework
{
m_manipulatorView->Draw(
GetManipulatorManagerId(), managerState, GetManipulatorId(),
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState,
mouseInteraction);
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay,
cameraState, mouseInteraction);
}
void SurfaceManipulator::InvalidateImpl()
@@ -19,6 +19,21 @@ namespace AzToolsFramework
static const AZ::Color LinearManipulatorZAxisColor = AZ::Color(0.0f, 0.0f, 1.0f, 1.0f);
static const AZ::Color SurfaceManipulatorColor = AZ::Color(1.0f, 1.0f, 0.0f, 0.5f);
static TranslationManipulatorsViewCreateInfo DefaultTranslationManipulatorViewCreateInfo()
{
TranslationManipulatorsViewCreateInfo createInfo;
createInfo.axis1Color = LinearManipulatorXAxisColor;
createInfo.axis2Color = LinearManipulatorYAxisColor;
createInfo.axis3Color = LinearManipulatorZAxisColor;
createInfo.surfaceColor = SurfaceManipulatorColor;
createInfo.linearAxisLength = LinearManipulatorAxisLength();
createInfo.linearConeLength = LinearManipulatorConeLength();
createInfo.linearConeRadius = LinearManipulatorConeRadius();
createInfo.planarAxisLength = PlanarManipulatorAxisLength();
createInfo.surfaceRadius = SurfaceManipulatorRadius();
return createInfo;
}
TranslationManipulators::TranslationManipulators(
const Dimensions dimensions, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale)
: m_dimensions(dimensions)
@@ -231,17 +246,36 @@ namespace AzToolsFramework
}
}
void TranslationManipulators::ConfigureView2d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
{
ConfigureLinearView(
translationManipulatorViewCreateInfo.linearAxisLength, translationManipulatorViewCreateInfo.linearConeLength,
translationManipulatorViewCreateInfo.linearConeRadius, translationManipulatorViewCreateInfo.axis1Color,
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
ConfigurePlanarView(
translationManipulatorViewCreateInfo.planarAxisLength, translationManipulatorViewCreateInfo.linearAxisLength,
translationManipulatorViewCreateInfo.linearConeLength, translationManipulatorViewCreateInfo.axis1Color,
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
}
void TranslationManipulators::ConfigureView3d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
{
ConfigureView2d(translationManipulatorViewCreateInfo);
ConfigureSurfaceView(translationManipulatorViewCreateInfo.surfaceRadius, translationManipulatorViewCreateInfo.surfaceColor);
}
void TranslationManipulators::ConfigureLinearView(
const float axisLength,
const float coneLength,
const float coneRadius,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const AZ::Color& axis3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
{
const AZ::Color axesColor[] = { axis1Color, axis2Color, axis3Color };
const auto configureLinearView =
[lineBoundWidth = m_lineBoundWidth, coneLength = LinearManipulatorConeLength(), axisLength,
coneRadius = LinearManipulatorConeRadius()](LinearManipulator* linearManipulator, const AZ::Color& color)
const auto configureLinearView = [lineBoundWidth = m_lineBoundWidth, coneLength, axisLength,
coneRadius](LinearManipulator* linearManipulator, const AZ::Color& color)
{
const auto lineLength = axisLength - coneLength;
@@ -259,25 +293,21 @@ namespace AzToolsFramework
}
void TranslationManipulators::ConfigurePlanarView(
const float planeSize,
const float planarAxisLength,
const float linearAxisLength,
const float linearConeLength,
const AZ::Color& plane1Color,
const AZ::Color& plane2Color /*= AZ::Color(0.0f, 1.0f, 0.0f, 0.5f)*/,
const AZ::Color& plane3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
{
const AZ::Color planesColor[] = { plane1Color, plane2Color, plane3Color };
const float linearAxisLength = LinearManipulatorAxisLength();
const float linearConeLength = LinearManipulatorConeLength();
for (size_t manipulatorIndex = 0; manipulatorIndex < m_planarManipulators.size(); ++manipulatorIndex)
{
const auto& planarManipulator = *m_planarManipulators[manipulatorIndex];
const AZStd::shared_ptr<ManipulatorViewQuad> manipulatorView = CreateManipulatorViewQuad(
*m_planarManipulators[manipulatorIndex], planesColor[manipulatorIndex], planesColor[(manipulatorIndex + 1) % 3],
(planarManipulator.GetAxis1() + planarManipulator.GetAxis2()) *
(((linearAxisLength - linearConeLength) * 0.5f) - (planeSize * 0.5f)),
planeSize);
m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ manipulatorView });
m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ CreateManipulatorViewQuadForPlanarTranslationManipulator(
planarManipulator.GetAxis1(), planarManipulator.GetAxis2(), planesColor[manipulatorIndex],
planesColor[(manipulatorIndex + 1) % 3], linearAxisLength, linearConeLength, planarAxisLength) });
}
}
@@ -325,19 +355,25 @@ namespace AzToolsFramework
void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators)
{
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ());
translationManipulators->ConfigurePlanarView(
PlanarManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor, LinearManipulatorZAxisColor);
translationManipulators->ConfigureLinearView(
LinearManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor, LinearManipulatorZAxisColor);
translationManipulators->ConfigureSurfaceView(SurfaceManipulatorRadius(), SurfaceManipulatorColor);
translationManipulators->ConfigureView3d(DefaultTranslationManipulatorViewCreateInfo());
}
void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators)
{
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY());
translationManipulators->ConfigurePlanarView(
PlanarManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor);
translationManipulators->ConfigureLinearView(
LinearManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor);
translationManipulators->ConfigureView2d(DefaultTranslationManipulatorViewCreateInfo());
}
AZStd::shared_ptr<ManipulatorViewQuad> CreateManipulatorViewQuadForPlanarTranslationManipulator(
const AZ::Vector3& axis1,
const AZ::Vector3& axis2,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const float linearAxisLength,
const float linearConeLength,
const float planarAxisLength)
{
const AZ::Vector3 offset = (axis1 + axis2) * (((linearAxisLength - linearConeLength) * 0.5f) - (planarAxisLength * 0.5f));
return CreateManipulatorViewQuad(axis1, axis2, axis1Color, axis2Color, offset, planarAxisLength);
}
} // namespace AzToolsFramework
@@ -15,6 +15,20 @@
namespace AzToolsFramework
{
//! Parameters to configure the appearance of the TranslationManipulators view(s).
struct TranslationManipulatorsViewCreateInfo
{
float linearAxisLength;
float linearConeLength;
float linearConeRadius;
float planarAxisLength;
float surfaceRadius;
AZ::Color axis1Color;
AZ::Color axis2Color;
AZ::Color axis3Color;
AZ::Color surfaceColor;
};
//! TranslationManipulators is an aggregation of 3 linear manipulators, 3 planar manipulators
//! and one surface manipulator who share the same transform.
class TranslationManipulators : public Manipulators
@@ -23,6 +37,9 @@ namespace AzToolsFramework
AZ_RTTI(TranslationManipulators, "{D5E49EA2-30E0-42BC-A51D-6A7F87818260}")
AZ_CLASS_ALLOCATOR(TranslationManipulators, AZ::SystemAllocator, 0)
TranslationManipulators(TranslationManipulators&&) = delete;
TranslationManipulators& operator=(TranslationManipulators&&) = delete;
//! How many dimensions does this translation manipulator have.
enum class Dimensions
{
@@ -52,26 +69,31 @@ namespace AzToolsFramework
void SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3 = AZ::Vector3::CreateAxisZ());
void ConfigureView2d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo);
void ConfigureView3d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo);
//! Sets the bound width to use for the line/axis of a linear manipulator.
void SetLineBoundWidth(float lineBoundWidth);
private:
void ConfigurePlanarView(
float planeSize,
float linearAxisLength,
float linearConeLength,
const AZ::Color& plane1Color,
const AZ::Color& plane2Color = AZ::Color(0.0f, 1.0f, 0.0f, 0.5f),
const AZ::Color& plane3Color = AZ::Color(0.0f, 0.0f, 1.0f, 0.5f));
void ConfigureLinearView(
float axisLength,
float coneLength,
float coneRadius,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
const AZ::Color& axis3Color = AZ::Color(0.0f, 0.0f, 1.0f, 0.5f));
void ConfigureSurfaceView(float radius, const AZ::Color& color);
//! Sets the bound width to use for the line/axis of a linear manipulator.
void SetLineBoundWidth(float lineBoundWidth);
private:
AZ_DISABLE_COPY_MOVE(TranslationManipulators)
// Manipulators
void ProcessManipulators(const AZStd::function<void(BaseManipulator*)>&) override;
@@ -131,4 +153,12 @@ namespace AzToolsFramework
void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators);
void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators);
AZStd::shared_ptr<ManipulatorViewQuad> CreateManipulatorViewQuadForPlanarTranslationManipulator(
const AZ::Vector3& axis1,
const AZ::Vector3& axis2,
const AZ::Color& axis1Color,
const AZ::Color& axis2Color,
float linearAxisLength,
float linearConeLength,
float planarAxisLength);
} // namespace AzToolsFramework
@@ -150,6 +150,24 @@ namespace AzToolsFramework
return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success;
}
// some assets may come in from the JSON serialzier with no AssetID, but have an asset hint
// this attempts to fix up the assets using the assetHint field
void FixUpInvalidAssets(AZ::Data::Asset<AZ::Data::AssetData>& asset)
{
if (!asset.GetId().IsValid() && !asset.GetHint().empty())
{
AZ::Data::AssetId assetId;
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, asset.GetHint().c_str(),
AZ::Data::s_invalidAssetType, false);
if (assetId.IsValid())
{
asset.Create(assetId, false);
}
}
}
bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadFlags flags)
{
// When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will
@@ -164,13 +182,17 @@ namespace AzToolsFramework
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
}
auto tracker = AZ::Data::SerializedAssetTracker{};
tracker.SetAssetFixUp(&FixUpInvalidAssets);
AZ::JsonDeserializerSettings settings;
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
// specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta
// data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations.
settings.m_metadata.Add(static_cast<AZ::JsonEntityIdSerializer::JsonEntityIdMapper*>(&entityIdMapper));
settings.m_metadata.Add(&entityIdMapper);
settings.m_metadata.Add(tracker);
AZ::JsonSerializationResult::ResultCode result =
AZ::JsonSerialization::Load(instance, prefabDom, settings);
@@ -203,13 +225,16 @@ namespace AzToolsFramework
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
}
auto tracker = AZ::Data::SerializedAssetTracker{};
tracker.SetAssetFixUp(&FixUpInvalidAssets);
AZ::JsonDeserializerSettings settings;
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
// specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta
// data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations.
settings.m_metadata.Add(static_cast<AZ::JsonEntityIdSerializer::JsonEntityIdMapper*>(&entityIdMapper));
settings.m_metadata.Add(&entityIdMapper);
settings.m_metadata.Create<AZ::Data::SerializedAssetTracker>();
settings.m_metadata.Add(tracker);
AZ::JsonSerializationResult::ResultCode result =
AZ::JsonSerialization::Load(instance, prefabDom, settings);
@@ -246,29 +271,8 @@ namespace AzToolsFramework
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
}
// some assets may come in from the JSON serialzier with no AssetID, but have an asset hint
// this attempts to fix up the assets using the assetHint field
auto fixUpInvalidAssets = [](AZ::Data::Asset<AZ::Data::AssetData>& asset)
{
if (!asset.GetId().IsValid() && !asset.GetHint().empty())
{
AZ::Data::AssetId assetId;
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
assetId,
&AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
asset.GetHint().c_str(),
AZ::Data::s_invalidAssetType,
false);
if (assetId.IsValid())
{
asset.Create(assetId, false);
}
}
};
auto tracker = AZ::Data::SerializedAssetTracker{};
tracker.SetAssetFixUp(fixUpInvalidAssets);
tracker.SetAssetFixUp(&FixUpInvalidAssets);
AZ::JsonDeserializerSettings settings;
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
@@ -12,6 +12,7 @@
#include <AzToolsFramework/ContainerEntity/ContainerEntityInterface.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
#include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
#include <AzToolsFramework/Prefab/Instance/Instance.h>
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
#include <AzToolsFramework/Prefab/PrefabFocusNotificationBus.h>
@@ -74,6 +75,13 @@ namespace AzToolsFramework::Prefab
"Prefab - PrefabFocusHandler - "
"Focus Mode Interface could not be found. "
"Check that it is being correctly initialized.");
m_readOnlyEntityQueryInterface = AZ::Interface<ReadOnlyEntityQueryInterface>::Get();
AZ_Assert(
m_readOnlyEntityQueryInterface,
"Prefab - PrefabFocusHandler - "
"ReadOnly Entity Query Interface could not be found. "
"Check that it is being correctly initialized.");
}
PrefabFocusOperationResult PrefabFocusHandler::FocusOnOwningPrefab(AZ::EntityId entityId)
@@ -186,6 +194,8 @@ namespace AzToolsFramework::Prefab
// Close all container entities in the old path.
CloseInstanceContainers(m_instanceFocusHierarchy);
AZ::EntityId previousContainerEntityId = m_focusedInstanceContainerEntityId;
// Do not store the container for the root instance, use an invalid EntityId instead.
m_focusedInstanceContainerEntityId = focusedInstance->get().GetParentInstance().has_value() ? focusedInstance->get().GetContainerEntityId() : AZ::EntityId();
m_focusedTemplateId = focusedInstance->get().GetTemplateId();
@@ -201,6 +211,12 @@ namespace AzToolsFramework::Prefab
m_focusModeInterface->SetFocusRoot(containerEntityId);
}
// Refresh the read-only cache, if the interface is initialized.
if (m_readOnlyEntityQueryInterface)
{
m_readOnlyEntityQueryInterface->RefreshReadOnlyState({ previousContainerEntityId, m_focusedInstanceContainerEntityId });
}
// Refresh path variables.
RefreshInstanceFocusList();
RefreshInstanceFocusPath();
@@ -22,6 +22,7 @@ namespace AzToolsFramework
{
class ContainerEntityInterface;
class FocusModeInterface;
class ReadOnlyEntityQueryInterface;
}
namespace AzToolsFramework::Prefab
@@ -93,6 +94,7 @@ namespace AzToolsFramework::Prefab
ContainerEntityInterface* m_containerEntityInterface = nullptr;
FocusModeInterface* m_focusModeInterface = nullptr;
InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr;
ReadOnlyEntityQueryInterface* m_readOnlyEntityQueryInterface = nullptr;
};
} // namespace AzToolsFramework::Prefab
@@ -918,6 +918,18 @@ namespace AzToolsFramework
}
}
bool PrefabPublicHandler::IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const
{
if (InstanceOptionalReference instanceReference = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
instanceReference.has_value())
{
TemplateReference templateReference = m_prefabSystemComponentInterface->FindTemplate(instanceReference->get().GetTemplateId());
return (templateReference.has_value()) && (templateReference->get().IsProcedural());
}
return false;
}
bool PrefabPublicHandler::IsInstanceContainerEntity(AZ::EntityId entityId) const
{
InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
@@ -54,6 +54,7 @@ namespace AzToolsFramework
PrefabOperationResult GenerateUndoNodesForEntityChangeAndUpdateCache(AZ::EntityId entityId, UndoSystem::URSequencePoint* parentUndoBatch) override;
bool IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const override;
bool IsInstanceContainerEntity(AZ::EntityId entityId) const override;
bool IsLevelInstanceContainerEntity(AZ::EntityId entityId) const override;
AZ::EntityId GetInstanceContainerEntityId(AZ::EntityId entityId) const override;
@@ -101,6 +101,13 @@ namespace AzToolsFramework
*/
virtual PrefabOperationResult GenerateUndoNodesForEntityChangeAndUpdateCache(
AZ::EntityId entityId, UndoSystem::URSequencePoint* parentUndoBatch) = 0;
/**
* Detects if an entity is owned by a procedural prefab.
* @param entityId The entity to query.
* @return True if the entity is owned by a procedural prefab instance, false otherwise.
*/
virtual bool IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const = 0;
/**
* Detects if an entity is the container entity for its owning prefab instance.
@@ -8,10 +8,12 @@
#include <API/ToolsApplicationAPI.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Component/Entity.h>
#include <AzCore/RTTI/BehaviorContext.h>
#include <AzToolsFramework/ToolsComponents/EditorLockComponent.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityComponent.h>
#include <Prefab/PrefabSystemComponentInterface.h>
#include <Prefab/PrefabSystemScriptingHandler.h>
#include <AzCore/Component/Entity.h>
#include <Prefab/EditorPrefabComponent.h>
#include <ToolsComponents/TransformComponent.h>
@@ -72,6 +74,9 @@ namespace AzToolsFramework::Prefab
entities, commonRoot, &topLevelEntities);
auto containerEntity = AZStd::make_unique<AZ::Entity>();
containerEntity->CreateComponent<Components::TransformComponent>();
containerEntity->CreateComponent<Components::EditorLockComponent>();
containerEntity->CreateComponent<Components::EditorVisibilityComponent>();
containerEntity->CreateComponent<Prefab::EditorPrefabComponent>();
for (AZ::Entity* entity : topLevelEntities)
@@ -860,18 +860,20 @@ namespace AzToolsFramework
return;
}
bool isDuringUndoRedo = false;
EBUS_EVENT_RESULT(isDuringUndoRedo, AzToolsFramework::ToolsApplicationRequests::Bus, IsDuringUndoRedo);
if (!isDuringUndoRedo)
bool suppressTransformChangedEvent = m_suppressTransformChangedEvent;
// temporarily disable calling OnTransformChanged, because CheckApplyCachedWorldTransform is not guaranteed
// to call it when m_cachedWorldTransform is identity. We send it manually later.
m_suppressTransformChangedEvent = false;
// When parent comes online, compute local TM from world TM.
CheckApplyCachedWorldTransform(parentTransform->GetWorldTM());
if (!m_initialized)
{
// When parent comes online, compute local TM from world TM.
CheckApplyCachedWorldTransform(parentTransform->GetWorldTM());
}
else
{
// During undo operations, just apply our local TM.
m_initialized = true;
// If this is the first time this entity is being activated, manually compute OnTransformChanged
// this can occur when either the entity first created or undo/redo command is performed
OnTransformChanged(AZ::Transform::Identity(), parentTransform->GetWorldTM());
}
m_suppressTransformChangedEvent = suppressTransformChangedEvent;
auto& parentChildIds = GetParentTransformComponent()->m_childrenEntityIds;
if (parentChildIds.end() == AZStd::find(parentChildIds.begin(), parentChildIds.end(), GetEntityId()))
@@ -242,6 +242,9 @@ namespace AzToolsFramework
// element is used rather than a data element.
bool m_addNonUniformScaleButton = false;
// Used to check whether entity was just created vs manually reactivated. Set true after OnEntityActivated is called the first time.
bool m_initialized = false;
// Deprecated
AZ::InterpolationMode m_interpolatePosition;
AZ::InterpolationMode m_interpolateRotation;
@@ -47,6 +47,7 @@
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
#include <AzToolsFramework/FocusMode/FocusModeInterface.h>
#include <AzToolsFramework/ToolsComponents/ComponentAssetMimeDataContainer.h>
#include <AzToolsFramework/ToolsComponents/ComponentMimeData.h>
@@ -313,7 +314,7 @@ namespace AzToolsFramework
if (isEditorOnly)
{
return QIcon(QString(":/Icons/Entity_Editor_Only.svg"));
return QIcon(QString(":/Entity/entity_editoronly.svg"));
}
AZ::Entity* entity = nullptr;
@@ -322,10 +323,10 @@ namespace AzToolsFramework
if (!isInitiallyActive)
{
return QIcon(QString(":/Icons/Entity_Not_Active.svg"));
return QIcon(QString(":/Entity/entity_notactive.svg"));
}
return QIcon(QString(":/Icons/Entity.svg"));
return QIcon(QString(":/Entity/entity.svg"));
}
QVariant EntityOutlinerListModel::GetEntityTooltip(const AZ::EntityId& id) const
@@ -1994,9 +1995,13 @@ namespace AzToolsFramework
, m_lockCheckBoxes(parent, "Lock", EntityOutlinerListModel::PartiallyLockedRole, EntityOutlinerListModel::LockedAncestorRole)
{
m_editorEntityFrameworkInterface = AZ::Interface<AzToolsFramework::EditorEntityUiInterface>::Get();
AZ_Assert((m_editorEntityFrameworkInterface != nullptr),
"EntityOutlinerItemDelegate requires a EditorEntityFrameworkInterface instance on Construction.");
m_readOnlyEntityPublicInterface = AZ::Interface<AzToolsFramework::ReadOnlyEntityPublicInterface>::Get();
AZ_Assert(
(m_readOnlyEntityPublicInterface != nullptr),
"EntityOutlinerItemDelegate requires a ReadOnlyEntityPublicInterface instance on Construction.");
}
EntityOutlinerItemDelegate::CheckboxGroup::CheckboxGroup(QWidget* parent, AZStd::string prefix,
@@ -2108,6 +2113,12 @@ namespace AzToolsFramework
}
PaintEntityNameAsRichText(painter, customOption, index);
// Paint Read-Only icon if necessary
if (m_readOnlyEntityPublicInterface->IsReadOnly(entityId))
{
PaintReadOnlyIcon(painter, option, index);
}
}
break;
default:
@@ -2166,10 +2177,10 @@ namespace AzToolsFramework
backgroundPath.addRect(backgroundRect);
QColor backgroundColor = m_hoverColor;
QColor backgroundColor = s_hoverColor;
if (isSelected)
{
backgroundColor = m_selectedColor;
backgroundColor = s_selectedColor;
}
painter->fillPath(backgroundPath, backgroundColor);
@@ -2336,6 +2347,20 @@ namespace AzToolsFramework
EntityOutlinerListModel::s_paintingName = false;
}
void EntityOutlinerItemDelegate::PaintReadOnlyIcon(QPainter* painter, const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const
{
// Build the rect that will be used to paint the icon
QRect readOnlyRect = QRect(option.rect.topLeft() + s_readOnlyOffset, QSize(s_readOnlyRadius * 2, s_readOnlyRadius * 2));
painter->save();
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setPen(Qt::NoPen);
painter->setBrush(s_readOnlyBackgroundColor);
painter->drawEllipse(readOnlyRect.center(), s_readOnlyRadius, s_readOnlyRadius);
s_readOnlyIcon.paint(painter, readOnlyRect);
painter->restore();
}
QSize EntityOutlinerItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& /*index*/) const
{
// Get the height of a tall character...
@@ -38,6 +38,7 @@ namespace AzToolsFramework
{
class EditorEntityUiInterface;
class FocusModeInterface;
class ReadOnlyEntityPublicInterface;
namespace EntityOutliner
{
@@ -344,6 +345,9 @@ namespace AzToolsFramework
// Paint the entity name using rich text
void PaintEntityNameAsRichText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
// Paint the read-only icon on the entity
void PaintReadOnlyIcon(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
struct CheckboxGroup
{
EntityOutlinerCheckBox m_default;
@@ -372,10 +376,17 @@ namespace AzToolsFramework
// this is a cache, and is hence mutable
mutable QRect m_cachedBoundingRectOfTallCharacter;
const QColor m_selectedColor = QColor(255, 255, 255, 45);
const QColor m_hoverColor = QColor(255, 255, 255, 30);
inline static const QColor s_selectedColor = QColor(255, 255, 255, 45);
inline static const QColor s_hoverColor = QColor(255, 255, 255, 30);
inline static const QColor s_readOnlyBackgroundColor = QColor("#444444");
inline static const QPoint s_readOnlyOffset = QPoint(10, 10);
inline static const int s_readOnlyRadius = 6;
QIcon s_readOnlyIcon = QIcon(QString(":/Entity/readonly.svg"));
EditorEntityUiInterface* m_editorEntityFrameworkInterface = nullptr;
ReadOnlyEntityPublicInterface* m_readOnlyEntityPublicInterface = nullptr;
};
}
@@ -27,6 +27,7 @@
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Prefab/EditorPrefabComponent.h>
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
#include <AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h>
#include <AzToolsFramework/Prefab/PrefabFocusInterface.h>
#include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
#include <AzToolsFramework/Prefab/PrefabLoaderInterface.h>
@@ -565,9 +566,7 @@ namespace AzToolsFramework
EditorRequestBus::BroadcastResult(position, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter);
}
// Instantiating from context menu always puts the instance at the root level
auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabFilePath, parentId, position);
if (!createPrefabOutcome.IsSuccess())
{
WarnUserOfError("Prefab Instantiation Error",createPrefabOutcome.GetError());
@@ -594,15 +593,13 @@ namespace AzToolsFramework
}
else
{
// otherwise return since it needs to be inside an authored prefab
return;
EditorRequestBus::BroadcastResult(position, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter);
}
// Instantiating from context menu always puts the instance at the root level
auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabAssetPath, parentId, position);
if (!createPrefabOutcome.IsSuccess())
{
WarnUserOfError("Prefab Instantiation Error", createPrefabOutcome.GetError());
WarnUserOfError("Procedural Prefab Instantiation Error", createPrefabOutcome.GetError());
}
}
}
@@ -1268,7 +1265,14 @@ namespace AzToolsFramework
}
else
{
s_editorEntityUiInterface->RegisterEntity(entityId, m_prefabUiHandler.GetHandlerId());
if (s_prefabPublicInterface->IsOwnedByProceduralPrefabInstance(entityId))
{
s_editorEntityUiInterface->RegisterEntity(entityId, m_proceduralPrefabUiHandler.GetHandlerId());
}
else
{
s_editorEntityUiInterface->RegisterEntity(entityId, m_prefabUiHandler.GetHandlerId());
}
// Register entity as a container
s_containerEntityInterface->RegisterEntityAsContainer(entityId);
@@ -18,10 +18,11 @@
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
#include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h>
#include <AzToolsFramework/UI/Prefab/LevelRootUiHandler.h>
#include <AzToolsFramework/UI/Prefab/PrefabIntegrationBus.h>
#include <AzToolsFramework/UI/Prefab/PrefabIntegrationInterface.h>
#include <AzToolsFramework/UI/Prefab/PrefabUiHandler.h>
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.h>
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabUiHandler.h>
#include <AzQtComponents/Components/Widgets/Card.h>
@@ -92,12 +93,18 @@ namespace AzToolsFramework
void ExecuteSavePrefabDialog(TemplateId templateId, bool useSaveAllPrefabsPreference) override;
private:
// Used to handle the UI for the level root
// Used to handle the UI for the level root.
LevelRootUiHandler m_levelRootUiHandler;
// Used to handle the UI for prefab entities
// Used to handle the UI for prefab entities.
PrefabUiHandler m_prefabUiHandler;
// Used to handle the UI for procedural prefab entities.
ProceduralPrefabUiHandler m_proceduralPrefabUiHandler;
// Ensures entities owned by procedural prefab instances are marked as read-only correctly.
ProceduralPrefabReadOnlyHandler m_proceduralPrefabReadOnlyHandler;
// Context menu item handlers
static void ContextMenu_CreatePrefab(AzToolsFramework::EntityIdList selectedEntities);
static void ContextMenu_InstantiatePrefab();
@@ -23,17 +23,6 @@ namespace AzToolsFramework
{
AzFramework::EntityContextId PrefabUiHandler::s_editorEntityContextId = AzFramework::EntityContextId::CreateNull();
const QColor PrefabUiHandler::m_backgroundColor = QColor("#444444");
const QColor PrefabUiHandler::m_backgroundHoverColor = QColor("#5A5A5A");
const QColor PrefabUiHandler::m_backgroundSelectedColor = QColor("#656565");
const QColor PrefabUiHandler::m_prefabCapsuleColor = QColor("#1E252F");
const QColor PrefabUiHandler::m_prefabCapsuleDisabledColor = QColor("#35383C");
const QColor PrefabUiHandler::m_prefabCapsuleEditColor = QColor("#4A90E2");
const QString PrefabUiHandler::m_prefabIconPath = QString(":/Entity/prefab.svg");
const QString PrefabUiHandler::m_prefabEditIconPath = QString(":/Entity/prefab_edit.svg");
const QString PrefabUiHandler::m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open.svg");
const QString PrefabUiHandler::m_prefabEditCloseIconPath = QString(":/Entity/prefab_edit_close.svg");
PrefabUiHandler::PrefabUiHandler()
{
m_prefabPublicInterface = AZ::Interface<Prefab::PrefabPublicInterface>::Get();
@@ -46,7 +46,7 @@ namespace AzToolsFramework
void OnOutlinerItemCollapse(const QModelIndex& index) const override;
bool OnEntityDoubleClick(AZ::EntityId entityId) const override;
private:
protected:
Prefab::PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr;
Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr;
@@ -56,17 +56,17 @@ namespace AzToolsFramework
static AzFramework::EntityContextId s_editorEntityContextId;
static constexpr int m_prefabCapsuleRadius = 6;
static constexpr int m_prefabBorderThickness = 2;
static const QColor m_backgroundColor;
static const QColor m_backgroundHoverColor;
static const QColor m_backgroundSelectedColor;
static const QColor m_prefabCapsuleColor;
static const QColor m_prefabCapsuleDisabledColor;
static const QColor m_prefabCapsuleEditColor;
static const QString m_prefabIconPath;
static const QString m_prefabEditIconPath;
static const QString m_prefabEditOpenIconPath;
static const QString m_prefabEditCloseIconPath;
int m_prefabCapsuleRadius = 6;
int m_prefabBorderThickness = 2;
QColor m_backgroundColor = QColor("#444444");
QColor m_backgroundHoverColor = QColor("#5A5A5A");
QColor m_backgroundSelectedColor = QColor("#656565");
QColor m_prefabCapsuleColor = QColor("#1E252F");
QColor m_prefabCapsuleDisabledColor = QColor("#35383C");
QColor m_prefabCapsuleEditColor = QColor("#4A90E2");
QString m_prefabIconPath = QString(":/Entity/prefab.svg");
QString m_prefabEditIconPath = QString(":/Entity/prefab_edit.svg");
QString m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open.svg");
QString m_prefabEditCloseIconPath = QString(":/Entity/prefab_edit_close.svg");
};
} // namespace AzToolsFramework
@@ -0,0 +1,68 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
#include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
namespace AzToolsFramework
{
namespace Prefab
{
ProceduralPrefabReadOnlyHandler::ProceduralPrefabReadOnlyHandler()
{
m_prefabPublicInterface = AZ::Interface<PrefabPublicInterface>::Get();
AZ_Assert(
m_prefabPublicInterface != nullptr,
"ProceduralPrefabReadOnlyHandler requires a PrefabPublicInterface instance on Initialize.");
m_prefabFocusPublicInterface = AZ::Interface<PrefabFocusPublicInterface>::Get();
AZ_Assert(
m_prefabFocusPublicInterface != nullptr,
"ProceduralPrefabReadOnlyHandler requires a PrefabFocusPublicInterface instance on Initialize.");
AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull();
EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId);
ReadOnlyEntityQueryRequestBus::Handler::BusConnect(editorEntityContextId);
// Refresh the whole read-only cache
if (auto readOnlyEntityQueryInterface = AZ::Interface<ReadOnlyEntityQueryInterface>::Get())
{
readOnlyEntityQueryInterface->RefreshReadOnlyStateForAllEntities();
}
}
ProceduralPrefabReadOnlyHandler ::~ProceduralPrefabReadOnlyHandler()
{
ReadOnlyEntityQueryRequestBus::Handler::BusDisconnect();
}
void ProceduralPrefabReadOnlyHandler::IsReadOnly(const AZ::EntityId& entityId, bool& isReadOnly)
{
if(m_prefabPublicInterface->IsOwnedByProceduralPrefabInstance(entityId))
{
// All entities nested inside a procedural prefabs should always be marked as read-only.
if (!m_prefabPublicInterface->IsInstanceContainerEntity(entityId))
{
isReadOnly = true;
}
// The container entity of a procedural prefab should only be marked as read-only when the prefab is being edited.
if (m_prefabFocusPublicInterface->IsOwningPrefabBeingFocused(entityId))
{
isReadOnly = true;
}
}
}
} // namespace Prefab
} // namespace AzToolsFramework
@@ -0,0 +1,43 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/RTTI/RTTI.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityBus.h>
namespace AzToolsFramework
{
namespace Prefab
{
class PrefabFocusPublicInterface;
class PrefabPublicInterface;
//! Ensures entities in a procedural prefab are correctly reported as read-only.
class ProceduralPrefabReadOnlyHandler
: public ReadOnlyEntityQueryRequestBus::Handler
{
public:
AZ_CLASS_ALLOCATOR(ProceduralPrefabReadOnlyHandler, AZ::SystemAllocator, 0);
AZ_RTTI(AzToolsFramework::ProceduralPrefabReadOnlyHandler, "{A2D72461-8CA3-45EE-81D2-4976BC0B6AE9}");
ProceduralPrefabReadOnlyHandler();
~ProceduralPrefabReadOnlyHandler() override;
// ReadOnlyEntityQueryRequestBus overrides ...
void IsReadOnly(const AZ::EntityId& entityId, bool& isReadOnly) override;
private:
PrefabPublicInterface* m_prefabPublicInterface = nullptr;
PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr;
};
} // namespace Prefab
} // namespace AzToolsFramework
@@ -0,0 +1,32 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabUiHandler.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
namespace AzToolsFramework
{
ProceduralPrefabUiHandler::ProceduralPrefabUiHandler()
{
m_prefabCapsuleColor = QColor("#361561");
m_prefabCapsuleDisabledColor = QColor("#4B3455");
m_prefabCapsuleEditColor = QColor("#361561");
m_prefabIconPath = QString(":/Entity/prefab_edit.svg");
m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open_readonly.svg");
}
QString ProceduralPrefabUiHandler::GenerateItemTooltip(AZ::EntityId entityId) const
{
if (AZ::IO::Path path = m_prefabPublicInterface->GetOwningInstancePrefabPath(entityId); !path.empty())
{
return QObject::tr("Double click to inspect.\n%1").arg(path.Native().data());
}
return QString();
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzToolsFramework/UI/Prefab/PrefabUiHandler.h>
#include <AzFramework/Entity/EntityContextBus.h>
namespace AzToolsFramework
{
namespace Prefab
{
class PrefabFocusPublicInterface;
class PrefabPublicInterface;
};
//! Implements the Editor UI for Procedural Prefabs.
class ProceduralPrefabUiHandler
: public PrefabUiHandler
{
public:
AZ_CLASS_ALLOCATOR(ProceduralPrefabUiHandler, AZ::SystemAllocator, 0);
AZ_RTTI(AzToolsFramework::ProceduralPrefabUiHandler, "{3A3DF9FF-9C2E-4439-B7B4-72173B5A3502}", PrefabUiHandler);
ProceduralPrefabUiHandler();
~ProceduralPrefabUiHandler() override = default;
QString GenerateItemTooltip(AZ::EntityId entityId) const override;
};
} // namespace AzToolsFramework
@@ -45,6 +45,7 @@ AZ_POP_DISABLE_WARNING
#include <AzToolsFramework/AssetBrowser/EBusFindAssetTypeByName.h>
#include <AzToolsFramework/ComponentMode/ComponentModeDelegate.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
#include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
#include <AzToolsFramework/Slice/SliceDataFlagsCommand.h>
@@ -497,6 +498,9 @@ namespace AzToolsFramework
m_prefabPublicInterface = AZ::Interface<Prefab::PrefabPublicInterface>::Get();
AZ_Assert(m_prefabPublicInterface != nullptr, "EntityPropertyEditor requires a PrefabPublicInterface instance on Initialize.");
m_readOnlyEntityPublicInterface = AZ::Interface<ReadOnlyEntityPublicInterface>::Get();
AZ_Assert(m_readOnlyEntityPublicInterface != nullptr, "EntityPropertyEditor requires a ReadOnlyEntityPublicInterface instance on Initialize.");
setObjectName("EntityPropertyEditor");
setAcceptDrops(true);
@@ -535,10 +539,6 @@ namespace AzToolsFramework
model->setItem(row, 0, m_comboItems[row]);
}
m_gui->m_statusComboBox->setModel(model);
m_gui->m_statusComboBox->setStyleSheet("QComboBox {border: 0px; border-radius:3px; background-color:#555555; color:white}"
"QComboBox:on {background-color:#e9e9e9; color:black; border:0px}"
"QComboBox::down-arrow:on {image: url(:/stylesheet/img/dropdowns/black_down_arrow.png)}"
"QComboBox::drop-down {border-radius: 3p}");
AzQtComponents::ComboBox::addCustomCheckStateStyle(m_gui->m_statusComboBox);
EnableEditor(true);
m_sceneIsNew = true;
@@ -565,6 +565,12 @@ namespace AzToolsFramework
AZ::EntitySystemBus::Handler::BusConnect();
EntityPropertyEditorRequestBus::Handler::BusConnect();
EditorWindowUIRequestBus::Handler::BusConnect();
AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull();
EditorEntityContextRequestBus::BroadcastResult(
editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId);
ReadOnlyEntityPublicNotificationBus::Handler::BusConnect(editorEntityContextId);
m_spacer = nullptr;
m_emptyIcon = QIcon();
@@ -614,6 +620,7 @@ namespace AzToolsFramework
{
qApp->removeEventFilter(this);
ReadOnlyEntityPublicNotificationBus::Handler::BusDisconnect();
EditorWindowUIRequestBus::Handler::BusDisconnect();
EntityPropertyEditorRequestBus::Handler::BusDisconnect();
ToolsApplicationEvents::Bus::Handler::BusDisconnect();
@@ -973,7 +980,7 @@ namespace AzToolsFramework
m_gui->m_entityDetailsLabel->setVisible(false);
// If we're in edit mode, make the name field editable.
m_gui->m_entityNameEditor->setReadOnly(!m_gui->m_componentListContents->isEnabled());
m_gui->m_entityNameEditor->setReadOnly(!m_gui->m_componentListContents->isEnabled() || m_selectionContainsReadOnlyEntity);
// get the name of the entity.
auto entity = GetSelectedEntityById(entityId);
@@ -1062,6 +1069,12 @@ namespace AzToolsFramework
bool EntityPropertyEditor::CanAddComponentsToSelection(const SelectionEntityTypeInfo& selectionEntityTypeInfo) const
{
if (m_selectionContainsReadOnlyEntity)
{
// Can't add components if there is a read only entity in the selection
return false;
}
if (selectionEntityTypeInfo == SelectionEntityTypeInfo::Mixed ||
selectionEntityTypeInfo == SelectionEntityTypeInfo::None)
{
@@ -1126,6 +1139,17 @@ namespace AzToolsFramework
m_selectedEntityIds.clear();
GetSelectedEntities(m_selectedEntityIds);
// Check if any of the selected entities are marked as read only
m_selectionContainsReadOnlyEntity = false;
for (const auto& entityId : m_selectedEntityIds)
{
if (m_readOnlyEntityPublicInterface->IsReadOnly(entityId))
{
m_selectionContainsReadOnlyEntity = true;
break;
}
}
SourceControlFileInfo scFileInfo;
ToolsApplicationRequests::Bus::BroadcastResult(scFileInfo, &ToolsApplicationRequests::GetSceneSourceControlInfo);
@@ -1681,6 +1705,12 @@ namespace AzToolsFramework
componentEditor->UpdateExpandability();
componentEditor->InvalidateAll(!componentInFilter ? m_filterString.c_str() : nullptr);
// If we are in read only mode, then show the components as disabled
if (m_selectionContainsReadOnlyEntity)
{
componentEditor->mockDisabledState(true);
}
if (!componentEditor->GetPropertyEditor()->HasFilteredOutNodes() || componentEditor->GetPropertyEditor()->HasVisibleNodes())
{
for (AZ::Component* componentInstance : componentInstances)
@@ -3077,6 +3107,7 @@ namespace AzToolsFramework
}
}
m_gui->m_statusComboBox->setDisabled(m_selectionContainsReadOnlyEntity);
m_gui->m_statusComboBox->setVisible(!m_isSystemEntityEditor && !m_isLevelEntityEditor);
m_gui->m_statusComboBox->style()->unpolish(m_gui->m_statusComboBox);
m_gui->m_statusComboBox->style()->polish(m_gui->m_statusComboBox);
@@ -3304,7 +3335,8 @@ namespace AzToolsFramework
const auto& componentsToEdit = GetSelectedComponents();
const bool hasComponents = !m_selectedEntityIds.empty() && !componentsToEdit.empty();
const bool allowRemove = hasComponents && AreComponentsRemovable(componentsToEdit);
// Don't allow components to be removed/cut/enabled/disabled if read only
const bool allowRemove = hasComponents && AreComponentsRemovable(componentsToEdit) && !m_selectionContainsReadOnlyEntity;
const bool allowCopy = hasComponents && AreComponentsCopyable(componentsToEdit);
m_actionToDeleteComponents->setEnabled(allowRemove);
@@ -3366,6 +3398,12 @@ namespace AzToolsFramework
return false;
}
if (m_selectionContainsReadOnlyEntity)
{
// Can't paste components if there is a read only entity in the selection
return false;
}
// Grab component data from clipboard, if exists
const QMimeData* mimeData = ComponentMimeData::GetComponentMimeDataFromClipboard();
@@ -5727,6 +5765,14 @@ namespace AzToolsFramework
SaveComponentEditorState();
}
void EntityPropertyEditor::OnReadOnlyEntityStatusChanged(const AZ::EntityId& entityId, [[maybe_unused]] bool readOnly)
{
if (IsEntitySelected(entityId))
{
UpdateContents();
}
}
void EntityPropertyEditor::OnEditorModeActivated(
[[maybe_unused]] const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode)
{
@@ -29,6 +29,7 @@
#include <AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h>
#include <AzToolsFramework/ComponentMode/EditorComponentModeBus.h>
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityBus.h>
#include <AzToolsFramework/ToolsComponents/ComponentMimeData.h>
#include <AzToolsFramework/ToolsComponents/EditorInspectorComponentBus.h>
#include <AzQtComponents/Components/O3DEStylesheet.h>
@@ -62,6 +63,7 @@ namespace AzToolsFramework
class ComponentPaletteWidget;
class ComponentModeCollectionInterface;
struct SourceControlFileInfo;
class ReadOnlyEntityPublicInterface;
namespace AssetBrowser
{
@@ -116,6 +118,7 @@ namespace AzToolsFramework
, public AZ::EntitySystemBus::Handler
, public AZ::TickBus::Handler
, private EditorWindowUIRequestBus::Handler
, private ReadOnlyEntityPublicNotificationBus::Handler
{
Q_OBJECT;
public:
@@ -253,6 +256,9 @@ namespace AzToolsFramework
// EditorWindowRequestBus overrides
void SetEditorUiEnabled(bool enable) override;
// ReadOnlyEntityPublicNotificationBus overrides ...
void OnReadOnlyEntityStatusChanged(const AZ::EntityId& entityId, bool readOnly) override;
bool IsEntitySelected(const AZ::EntityId& id) const;
bool IsSingleEntitySelected(const AZ::EntityId& id) const;
@@ -623,6 +629,9 @@ namespace AzToolsFramework
Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr;
bool m_prefabsAreEnabled = false;
ReadOnlyEntityPublicInterface* m_readOnlyEntityPublicInterface = nullptr;
bool m_selectionContainsReadOnlyEntity = false;
// Reordering row widgets within the RPE.
static constexpr float MoveFadeSeconds = 0.5f;
@@ -191,7 +191,7 @@
</size>
</property>
<property name="styleSheet">
<string notr="true">background-color:rgb(51, 51, 51)</string>
<string notr="true">QWidget#m_darkBox { background-color:rgb(51, 51, 51) }</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="spacing">
@@ -444,6 +444,9 @@
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="styleSheet">
<string notr="true">background-color:rgb(51, 51, 51)</string>
</property>
</widget>
</item>
<item>
@@ -39,7 +39,12 @@ namespace AzToolsFramework
typeFilter->SetAssetType(filterType);
typeFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
m_assetBrowserFilterModel->SetFilter(FilterConstType(typeFilter));
SetFilter(FilterConstType(typeFilter));
}
void AssetCompleterModel::SetFilter(FilterConstType filter)
{
m_assetBrowserFilterModel->SetFilter(filter);
RefreshAssetList();
}
@@ -120,9 +125,6 @@ namespace AzToolsFramework
int rows = m_assetBrowserFilterModel->rowCount(index);
if (rows == 0)
{
if (index != QModelIndex()) {
AZ_Error("AssetCompleterModel", false, "No children detected in FetchResources()");
}
return;
}
@@ -131,7 +133,7 @@ namespace AzToolsFramework
QModelIndex childIndex = m_assetBrowserFilterModel->index(i, 0, index);
AssetBrowserEntry* childEntry = GetAssetEntry(m_assetBrowserFilterModel->mapToSource(childIndex));
if (childEntry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product)
if (childEntry->GetEntryType() == m_entryType)
{
ProductAssetBrowserEntry* productEntry = static_cast<ProductAssetBrowserEntry*>(childEntry);
AZStd::string assetName;
@@ -167,7 +169,6 @@ namespace AzToolsFramework
return m_assets[index.row()].m_displayName;
}
const AZ::Data::AssetId AssetCompleterModel::GetAssetIdFromIndex(const QModelIndex& index)
{
if (!index.isValid())
@@ -177,4 +178,19 @@ namespace AzToolsFramework
return m_assets[index.row()].m_assetId;
}
const AZStd::string_view AssetCompleterModel::GetPathFromIndex(const QModelIndex& index)
{
if (!index.isValid())
{
return "";
}
return m_assets[index.row()].m_path;
}
void AssetCompleterModel::SetFetchEntryType(AssetBrowserEntry::AssetEntryType entryType)
{
m_entryType = entryType;
}
}
@@ -32,6 +32,7 @@ namespace AzToolsFramework
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void SetFilter(AZ::Data::AssetType filterType);
void SetFilter(FilterConstType filter);
void RefreshAssetList();
void SearchStringHighlight(QString searchString);
@@ -39,6 +40,9 @@ namespace AzToolsFramework
const AZStd::string_view GetNameFromIndex(const QModelIndex& index);
const AZ::Data::AssetId GetAssetIdFromIndex(const QModelIndex& index);
const AZStd::string_view GetPathFromIndex(const QModelIndex& index);
void SetFetchEntryType(AssetBrowserEntry::AssetEntryType entryType);
private:
struct AssetItem
@@ -57,6 +61,8 @@ namespace AzToolsFramework
AZStd::vector<AssetItem> m_assets;
//! String that will be highlighted in the suggestions
QString m_highlightString;
AssetBrowserEntry::AssetEntryType m_entryType = AssetBrowserEntry::AssetEntryType::Product;
};
}
@@ -1288,7 +1288,7 @@ namespace AzToolsFramework
return newCtrl;
}
void AssetPropertyHandlerDefault::ConsumeAttribute(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName)
void AssetPropertyHandlerDefault::ConsumeAttributeInternal(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName)
{
(void)debugName;
@@ -1487,6 +1487,11 @@ namespace AzToolsFramework
}
}
void AssetPropertyHandlerDefault::ConsumeAttribute(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName)
{
ConsumeAttributeInternal(GUI, attrib, attrValue, debugName);
}
void AssetPropertyHandlerDefault::WriteGUIValuesIntoProperty(size_t index, PropertyAssetCtrl* GUI, property_t& instance, InstanceDataNode* node)
{
(void)index;
@@ -1629,8 +1634,8 @@ namespace AzToolsFramework
void RegisterAssetPropertyHandler()
{
EBUS_EVENT(PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew AssetPropertyHandlerDefault());
EBUS_EVENT(PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SimpleAssetPropertyHandlerDefault());
PropertyTypeRegistrationMessages::Bus::Broadcast(&PropertyTypeRegistrationMessages::RegisterPropertyType, aznew AssetPropertyHandlerDefault());
PropertyTypeRegistrationMessages::Bus::Broadcast(&PropertyTypeRegistrationMessages::RegisterPropertyType, aznew SimpleAssetPropertyHandlerDefault());
}
}
@@ -175,10 +175,11 @@ namespace AzToolsFramework
virtual void SetFolderSelection(const AZStd::string& /* folderPath */) {}
virtual void ClearAssetInternal();
void ConfigureAutocompleter();
virtual void ConfigureAutocompleter();
void RefreshAutocompleter();
void EnableAutocompleter();
void DisableAutocompleter();
const QModelIndex GetSourceIndex(const QModelIndex& index);
void HandleFieldClear();
AZStd::string AddDefaultSuffix(const AZStd::string& filename);
@@ -235,20 +236,19 @@ namespace AzToolsFramework
void SetSelectedAssetID(const AZ::Data::AssetId& newID, const AZ::Data::AssetType& newType);
void SetCurrentAssetHint(const AZStd::string& hint);
void SetDefaultAssetID(const AZ::Data::AssetId& defaultID);
void PopupAssetPicker();
virtual void PopupAssetPicker();
void OnClearButtonClicked();
void UpdateAssetDisplay();
void OnLineEditFocus(bool focus);
virtual void OnEditButtonClicked();
void OnThumbnailClicked();
void OnCompletionModelReset();
void OnAutocomplete(const QModelIndex& index);
virtual void OnAutocomplete(const QModelIndex& index);
void OnTextChange(const QString& text);
void OnReturnPressed();
void ShowContextMenu(const QPoint& pos);
private:
const QModelIndex GetSourceIndex(const QModelIndex& index);
void UpdateThumbnail();
};
@@ -270,7 +270,8 @@ namespace AzToolsFramework
virtual void UpdateWidgetInternalTabbing(PropertyAssetCtrl* widget) override { widget->UpdateTabOrder(); }
virtual QWidget* CreateGUI(QWidget* pParent) override;
virtual void ConsumeAttribute(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName) override;
static void ConsumeAttributeInternal(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName);
void ConsumeAttribute(PropertyAssetCtrl* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName) override;
virtual void WriteGUIValuesIntoProperty(size_t index, PropertyAssetCtrl* GUI, property_t& instance, InstanceDataNode* node) override;
virtual bool ReadValuesIntoGUI(size_t index, PropertyAssetCtrl* GUI, const property_t& instance, InstanceDataNode* node) override;
};
@@ -15,12 +15,14 @@
#include <AzCore/Slice/SliceComponent.h>
#include <AzCore/std/containers/unordered_map.h>
#include <AzCore/std/parallel/binary_semaphore.h>
#include <AzCore/std/smart_ptr/make_shared.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/UserSettings/UserSettingsComponent.h>
#include <AzTest/AzTest.h>
#include <AZTestShared/Math/MathTestHelpers.h>
#include <AZTestShared/Utils/Utils.h>
#include <AzFramework/UnitTest/TestDebugDisplayRequests.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/API/ViewportEditorModeTrackerInterface.h>
#include <AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h>
@@ -235,6 +237,13 @@ namespace UnitTest
return toolsApp;
}
//! It is possible to override this in classes deriving from ToolsApplicationFixture to provide alternate
//! implementations of the DebugDisplayRequests interface (e.g. TestDebugDisplayRequests).
virtual AZStd::shared_ptr<AzFramework::DebugDisplayRequests> CreateDebugDisplayRequests()
{
return AZStd::make_shared<NullDebugDisplayRequests>();
}
protected:
TestEditorActions m_editorActions;
ToolsApplicationMessageHandler m_messageHandler; // used to suppress trace messages in test output
@@ -21,6 +21,7 @@
#include <AzToolsFramework/Commands/EntityManipulatorCommand.h>
#include <AzToolsFramework/Commands/SelectionCommand.h>
#include <AzToolsFramework/Entity/EditorEntityTransformBus.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
#include <AzToolsFramework/Manipulators/ManipulatorManager.h>
#include <AzToolsFramework/Manipulators/ManipulatorSnapping.h>
#include <AzToolsFramework/Manipulators/RotationManipulators.h>
@@ -1019,6 +1020,7 @@ namespace AzToolsFramework
EditorManipulatorCommandUndoRedoRequestBus::Handler::BusConnect(entityContextId);
EditorContextMenuBus::Handler::BusConnect();
ViewportInteraction::ViewportSettingsNotificationBus::Handler::BusConnect(ViewportUi::DefaultViewportId);
ReadOnlyEntityPublicNotificationBus::Handler::BusConnect(entityContextId);
CreateTransformModeSelectionCluster();
CreateSpaceSelectionCluster();
@@ -1054,6 +1056,7 @@ namespace AzToolsFramework
m_pivotOverrideFrame.Reset();
ReadOnlyEntityPublicNotificationBus::Handler::BusDisconnect();
ViewportInteraction::ViewportSettingsNotificationBus::Handler::BusDisconnect();
EditorContextMenuBus::Handler::BusConnect();
EditorManipulatorCommandUndoRedoRequestBus::Handler::BusDisconnect();
@@ -3623,6 +3626,18 @@ namespace AzToolsFramework
m_selectedEntityIds.erase(focusRoot);
}
}
// Do not create manipulators for any entities marked as read only
if (auto readOnlyEntityPublicInterface = AZ::Interface<ReadOnlyEntityPublicInterface>::Get())
{
AZStd::erase_if(
m_selectedEntityIds,
[readOnlyEntityPublicInterface](auto entityId)
{
return readOnlyEntityPublicInterface->IsReadOnly(entityId);
}
);
}
}
void EditorTransformComponentSelection::OnTransformChanged(
@@ -3830,6 +3845,14 @@ namespace AzToolsFramework
m_snappingCluster.TrySetVisible(m_viewportUiVisible && !m_selectedEntityIds.empty());
}
void EditorTransformComponentSelection::OnReadOnlyEntityStatusChanged(const AZ::EntityId& entityId, [[maybe_unused]] bool readOnly)
{
if (IsEntitySelected(entityId))
{
RefreshSelectedEntityIdsAndRegenerateManipulators();
}
}
namespace ETCS
{
// little raii wrapper to switch a value from true to false and back
@@ -20,6 +20,7 @@
#include <AzToolsFramework/Commands/EntityManipulatorCommand.h>
#include <AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h>
#include <AzToolsFramework/Editor/EditorContextMenuBus.h>
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityBus.h>
#include <AzToolsFramework/Manipulators/BaseManipulator.h>
#include <AzToolsFramework/ToolsComponents/EditorLockComponentBus.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
@@ -160,6 +161,7 @@ namespace AzToolsFramework
, private EditorManipulatorCommandUndoRedoRequestBus::Handler
, private AZ::TransformNotificationBus::MultiHandler
, private ViewportInteraction::ViewportSettingsNotificationBus::Handler
, private ReadOnlyEntityPublicNotificationBus::Handler
{
public:
AZ_CLASS_ALLOCATOR_DECL
@@ -297,6 +299,9 @@ namespace AzToolsFramework
// ViewportSettingsNotificationBus overrides ...
void OnGridSnappingChanged(bool enabled) override;
// ReadOnlyEntityPublicNotificationBus overrides ...
void OnReadOnlyEntityStatusChanged(const AZ::EntityId& entityId, bool readOnly) override;
// Helpers to safely interact with the TransformBus (requests).
void SetEntityWorldTranslation(AZ::EntityId entityId, const AZ::Vector3& worldTranslation);
void SetEntityLocalTranslation(AZ::EntityId entityId, const AZ::Vector3& localTranslation);
@@ -768,6 +768,10 @@ set(FILES
UI/Prefab/PrefabUiHandler.cpp
UI/Prefab/PrefabViewportFocusPathHandler.h
UI/Prefab/PrefabViewportFocusPathHandler.cpp
UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.h
UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.cpp
UI/Prefab/Procedural/ProceduralPrefabUiHandler.h
UI/Prefab/Procedural/ProceduralPrefabUiHandler.cpp
UI/Notifications/ToastNotificationsView.cpp
UI/Notifications/ToastNotificationsView.h
UI/Notifications/ToastBus.h
@@ -96,4 +96,22 @@ namespace AzToolsFramework
// Verify the child entity is no longer marked as read-only
EXPECT_FALSE(m_readOnlyEntityPublicInterface->IsReadOnly(m_entityMap[ChildEntityName]));
}
TEST_F(ReadOnlyEntityFixture, EnsureCacheIsClearedCorrectlyEvenIfUnchanged)
{
// Create a handler that sets all entities to read-only.
ReadOnlyHandlerAlwaysTrue alwaysTrueHandler;
{
// Create a handler that sets the child entity to read-only.
ReadOnlyHandlerEntityId entityIdHandler(m_entityMap[ChildEntityName]);
// Verify the child entity is marked as read-only
EXPECT_TRUE(m_readOnlyEntityPublicInterface->IsReadOnly(m_entityMap[ChildEntityName]));
}
// When the handler goes out of scope, it calls RefreshReadOnlyStateForAllEntities and refreshes the cache.
// Verify the child entity is still marked as read-only
EXPECT_TRUE(m_readOnlyEntityPublicInterface->IsReadOnly(m_entityMap[ChildEntityName]));
}
}
@@ -7,12 +7,16 @@
*/
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzManipulatorTestFramework/AzManipulatorTestFramework.h>
#include <AzManipulatorTestFramework/DirectManipulatorViewportInteraction.h>
#include <AzManipulatorTestFramework/ImmediateModeActionDispatcher.h>
#include <AzTest/AzTest.h>
#include <AzToolsFramework/Application/ToolsApplication.h>
#include <AzToolsFramework/Manipulators/RotationManipulators.h>
#include <AzToolsFramework/Manipulators/ManipulatorManager.h>
#include <AzToolsFramework/Manipulators/ManipulatorView.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzToolsFramework/Manipulators/RotationManipulators.h>
#include <AzToolsFramework/Manipulators/TranslationManipulators.h>
#include <AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h>
#include <AzToolsFramework/UnitTest/ToolsTestApplication.h>
#include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
@@ -21,8 +25,7 @@ namespace UnitTest
{
using namespace AzToolsFramework;
class ManipulatorViewTest
: public AllocatorsTestFixture
class ManipulatorViewTest : public AllocatorsTestFixture
{
AZStd::unique_ptr<AZ::SerializeContext> m_serializeContext;
@@ -32,7 +35,7 @@ namespace UnitTest
m_serializeContext = AZStd::make_unique<AZ::SerializeContext>();
m_app.Start(AzFramework::Application::Descriptor());
// Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is
// shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash
// shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash
// in the unit tests.
AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize);
}
@@ -51,12 +54,9 @@ namespace UnitTest
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given
const AZ::Transform orientation =
AZ::Transform::CreateFromQuaternion(
AZ::Quaternion::CreateFromAxisAngle(
AZ::Vector3::CreateAxisX(), AZ::DegToRad(-90.0f)));
AZ::Transform::CreateFromQuaternion(AZ::Quaternion::CreateRotationX(AZ::DegToRad(-90.0f)));
const AZ::Transform translation =
AZ::Transform::CreateTranslation(AZ::Vector3(5.0f, 0.0f, 10.0f));
const AZ::Transform translation = AZ::Transform::CreateTranslation(AZ::Vector3(5.0f, 0.0f, 10.0f));
const AZ::Transform manipulatorSpace = translation * orientation;
// create a rotation manipulator in an arbitrary space
@@ -67,8 +67,7 @@ namespace UnitTest
// When
const AZ::Vector3 worldCameraPosition = AZ::Vector3(5.0f, -10.0f, 10.0f);
// transform the view direction to the space of the manipulator (space + local transform)
const AZ::Vector3 viewDirection =
CalculateViewDirection(rotationManipulators, worldCameraPosition);
const AZ::Vector3 viewDirection = CalculateViewDirection(rotationManipulators, worldCameraPosition);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -84,8 +83,7 @@ namespace UnitTest
cameraState.m_position = AZ::Vector3::CreateAxisY(20.0f);
cameraState.m_forward = -AZ::Vector3::CreateAxisY();
const float scale =
AzToolsFramework::CalculateScreenToWorldMultiplier(AZ::Vector3::CreateZero(), cameraState);
const float scale = AzToolsFramework::CalculateScreenToWorldMultiplier(AZ::Vector3::CreateZero(), cameraState);
EXPECT_NEAR(scale, 2.0f, std::numeric_limits<float>::epsilon());
}
@@ -96,9 +94,57 @@ namespace UnitTest
cameraState.m_position = AZ::Vector3::CreateAxisY(20.0f);
cameraState.m_forward = -AZ::Vector3::CreateAxisY();
const float scale =
AzToolsFramework::CalculateScreenToWorldMultiplier(AZ::Vector3::CreateAxisX(-10.0f), cameraState);
const float scale = AzToolsFramework::CalculateScreenToWorldMultiplier(AZ::Vector3::CreateAxisX(-10.0f), cameraState);
EXPECT_NEAR(scale, 2.0f, std::numeric_limits<float>::epsilon());
}
TEST_F(ManipulatorViewTest, ManipulatorViewQuadDrawsAtCorrectPositionWhenManipulatorSpaceIsScaledUniformlyAndNonUniformly)
{
// Given
// simulate a custom manipulator space (e.g. entity transform) and a local offset within that space (e.g. spline vertex position)
const AZ::Transform space =
AZ::Transform::CreateTranslation(AZ::Vector3(2.0f, -3.0f, -4.0f)) * AZ::Transform::CreateUniformScale(2.0f);
const AZ::Vector3 localPosition = AZ::Vector3(2.0f, -2.0f, 0.0f);
const AZ::Vector3 nonUniformScale = AZ::Vector3(2.0f, 3.0f, 4.0f);
const AZ::Transform combinedTransform =
AzToolsFramework::ApplySpace(AZ::Transform::CreateTranslation(localPosition), space, nonUniformScale);
// create a manipulator state based on the space and local position
AzToolsFramework::ManipulatorState manipulatorState{};
manipulatorState.m_worldFromLocal = combinedTransform;
manipulatorState.m_nonUniformScale = nonUniformScale;
// note: This is zero as the localPosition is already encoded in the combinedTransform
manipulatorState.m_localPosition = AZ::Vector3::CreateZero();
// camera (go to position format) - 10.00, -15.00, 6.00, -90.00, 0.00
const AzFramework::CameraState cameraState = AzFramework::CreateDefaultCamera(
AZ::Transform::CreateFromMatrix3x3AndTranslation(
AZ::Matrix3x3::CreateRotationX(AZ::DegToRad(-90.0f)), AZ::Vector3(10.0f, -15.0f, 6.0f)),
AZ::Vector2(1280, 720));
// test debug display instance to record vertices that were output
auto testDebugDisplayRequests = AZStd::make_shared<TestDebugDisplayRequests>();
auto planarTranslationViewQuad = CreateManipulatorViewQuadForPlanarTranslationManipulator(
AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Color::CreateZero(), AZ::Color::CreateZero(), 2.2f, 0.2f, 1.0f);
// When
// draw the quad as it would be for a manipulator
planarTranslationViewQuad->Draw(
AzToolsFramework::ManipulatorManagerId(1), AzToolsFramework::ManipulatorManagerState{ false },
AzToolsFramework::ManipulatorId(1), manipulatorState, *testDebugDisplayRequests, cameraState,
AzToolsFramework::ViewportInteraction::MouseInteraction{});
const AZStd::vector<AZ::Vector3> expectedDisplayPositions = {
AZ::Vector3(10.5f, -13.5f, -4.0f), AZ::Vector3(11.5f, -13.5f, -4.0f), AZ::Vector3(10.5f, -14.5f, -4.0f),
AZ::Vector3(11.5f, -14.5f, -4.0f), AZ::Vector3(10.5f, -13.5f, -4.0f), AZ::Vector3(10.5f, -14.5f, -4.0f),
AZ::Vector3(11.5f, -14.5f, -4.0f), AZ::Vector3(11.5f, -13.5f, -4.0f)
};
// Then
const auto points = testDebugDisplayRequests->GetPoints();
// quad vertices appear in the expected position (not offset or scaled incorrectly by space scale)
using ::testing::UnorderedPointwise;
EXPECT_THAT(points, UnorderedPointwise(ContainerIsClose(), expectedDisplayPositions));
}
} // namespace UnitTest
@@ -0,0 +1,185 @@
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Asset/AssetSerializer.h>
#include <AzCore/Serialization/Json/JsonUtils.h>
#include <AzCore/Component/Component.h>
#include <Prefab/PrefabTestFixture.h>
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
namespace UnitTest
{
using PrefabInstantiateTest = PrefabTestFixture;
struct MockAsset : AZ::Data::AssetData
{
AZ_RTTI(MockAsset, "{DAB98A3F-1714-4B95-AACB-8C150B0D0628}", AZ::Data::AssetData);
AZ_CLASS_ALLOCATOR(MockAsset, AZ::SystemAllocator, 0);
static void Reflect(AZ::ReflectContext* context)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<MockAsset>()->Field("data", &MockAsset::m_data);
}
}
float m_data = 1.f;
};
struct MockAssetComponent : AZ::Component
{
AZ_COMPONENT(MockAssetComponent, "{D81B0D06-B495-479E-832A-A63079FD6D37}");
static void Reflect(AZ::ReflectContext* context)
{
MockAsset::Reflect(context);
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<MockAssetComponent>()
->Field("asset", &MockAssetComponent::m_asset);
}
}
void Activate() override{}
void Deactivate() override{}
AZ::Data::Asset<MockAsset> m_asset;
};
class MockAssetHandler : public AZ::Data::AssetHandler
{
public:
AZ_CLASS_ALLOCATOR(MockAssetHandler, AZ::SystemAllocator, 0);
AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override
{
(void)id;
EXPECT_TRUE(type == azrtti_typeid<MockAsset>());
if (type == azrtti_typeid<MockAsset>())
{
return aznew MockAsset();
}
return nullptr;
}
LoadResult LoadAssetData(const AZ::Data::Asset<AZ::Data::AssetData>&, AZStd::shared_ptr<AZ::Data::AssetDataStream>, const AZ::Data::AssetFilterCB&) override
{
return LoadResult::Error;
}
void DestroyAsset(AZ::Data::AssetPtr ptr) override
{
EXPECT_TRUE(ptr->GetType() == azrtti_typeid<MockAsset>());
delete ptr;
}
void GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes) override
{
assetTypes.push_back(azrtti_typeid<MockAsset>());
}
};
struct PrefabFixupTest : PrefabInstantiateTest
{
void SetUpEditorFixtureImpl() override
{
PrefabInstantiateTest::SetUpEditorFixtureImpl();
AZ::SerializeContext* context = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(context, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
ASSERT_NE(context, nullptr);
MockAssetComponent::Reflect(context);
AZ::Data::AssetManager::Instance().RegisterHandler(&m_handler, azrtti_typeid<MockAsset>());
auto entity = aznew AZ::Entity();
auto mockAssetComponent = entity->CreateComponent<MockAssetComponent>();
mockAssetComponent->m_asset =
AZ::Data::Asset<MockAsset>(AZ::Uuid::CreateNull(), AZ::Data::AssetType::CreateNull(), "test.asset");
auto newInstance = AZ::Interface<PrefabSystemComponentInterface>::Get()->CreatePrefab({ entity }, {}, "test.prefab");
AZStd::string prefabString;
ASSERT_TRUE(m_prefabLoaderInterface->SaveTemplateToString(newInstance->GetTemplateId(), prefabString));
m_prefabSystemComponent->RemoveAllTemplates();
AZ::Outcome<PrefabDom, AZStd::string> readPrefabFileResult = AZ::JsonSerializationUtils::ReadJsonString(prefabString);
ASSERT_TRUE(readPrefabFileResult.IsSuccess());
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
m_assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, "test.asset", azrtti_typeid<MockAsset>(),
true); // True to register the asset and generate an AssetId for lookup
m_prefabDom = readPrefabFileResult.TakeValue();
}
void TearDownEditorFixtureImpl() override
{
PrefabInstantiateTest::TearDownEditorFixtureImpl();
AZ::Data::AssetManager::Instance().UnregisterHandler(&m_handler);
}
void CheckInstance(const Instance& instance)
{
const AZ::Entity* loadedEntity = nullptr;
instance.GetConstEntities(
[&loadedEntity](const AZ::Entity& entity)
{
loadedEntity = &entity;
return false;
});
auto loadedComponent = loadedEntity->FindComponent<MockAssetComponent>();
ASSERT_NE(loadedComponent, nullptr);
ASSERT_STREQ(loadedComponent->m_asset.GetHint().c_str(), "test.asset");
ASSERT_EQ(loadedComponent->m_asset->GetId(), m_assetId);
}
MockAssetHandler m_handler;
PrefabDom m_prefabDom;
AZ::Data::AssetId m_assetId;
};
TEST_F(PrefabFixupTest, Test_LoadInstanceFromPrefabDom_Overload1)
{
Instance instance;
ASSERT_TRUE(PrefabDomUtils::LoadInstanceFromPrefabDom(instance, m_prefabDom));
CheckInstance(instance);
}
TEST_F(PrefabFixupTest, Test_LoadInstanceFromPrefabDom_Overload2)
{
Instance instance;
AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>> referencedAssets;
ASSERT_TRUE(PrefabDomUtils::LoadInstanceFromPrefabDom(instance, m_prefabDom, referencedAssets));
CheckInstance(instance);
}
TEST_F(PrefabFixupTest, Test_LoadInstanceFromPrefabDom_Overload3)
{
Instance instance;
AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>> referencedAssets;
Instance::EntityList entityList;
(PrefabDomUtils::LoadInstanceFromPrefabDom(instance, entityList, m_prefabDom));
CheckInstance(instance);
}
}
@@ -11,6 +11,8 @@
#include <AzCore/Component/TransformBus.h>
#include <AzToolsFramework/Prefab/PrefabDomUtils.h>
#include <AzToolsFramework/Prefab/PrefabLoaderInterface.h>
#include <AzToolsFramework/ToolsComponents/TransformComponent.h>
#include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
#include <Prefab/PrefabTestComponent.h>
#include <Prefab/PrefabTestDomUtils.h>
@@ -50,6 +52,15 @@ namespace UnitTest
GetApplication()->RegisterComponentDescriptor(PrefabTestComponent::CreateDescriptor());
GetApplication()->RegisterComponentDescriptor(PrefabTestComponentWithUnReflectedTypeMember::CreateDescriptor());
AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
m_undoStack, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetUndoStack);
AZ_Assert(m_undoStack, "Failed to look up undo stack from tools application");
}
void PrefabTestFixture::TearDownEditorFixtureImpl()
{
m_undoStack = nullptr;
}
AZStd::unique_ptr<ToolsTestApplication> PrefabTestFixture::CreateTestApplication()
@@ -57,12 +68,25 @@ namespace UnitTest
return AZStd::make_unique<PrefabTestToolsApplication>("PrefabTestApplication");
}
void PrefabTestFixture::CreateRootPrefab()
{
auto entityOwnershipService = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
ASSERT_TRUE(entityOwnershipService != nullptr);
entityOwnershipService->CreateNewLevelPrefab("UnitTestRoot.prefab", "");
auto rootEntityReference = entityOwnershipService->GetRootPrefabInstance()->get().GetContainerEntity();
ASSERT_TRUE(rootEntityReference.has_value());
auto& rootEntity = rootEntityReference->get();
rootEntity.Deactivate();
rootEntity.CreateComponent<AzToolsFramework::Components::TransformComponent>();
rootEntity.Activate();
}
void PrefabTestFixture::PropagateAllTemplateChanges()
{
m_prefabSystemComponent->OnSystemTick();
}
AZ::Entity* PrefabTestFixture::CreateEntity(const char* entityName, const bool shouldActivate)
AZ::Entity* PrefabTestFixture::CreateEntity(AZStd::string entityName, const bool shouldActivate)
{
// Circumvent the EntityContext system and generate a new entity with a transformcomponent
AZ::Entity* newEntity = aznew AZ::Entity(entityName);
@@ -76,8 +100,43 @@ namespace UnitTest
return newEntity;
}
AZ::EntityId PrefabTestFixture::CreateEntityUnderRootPrefab(AZStd::string name, AZ::EntityId parentId)
{
auto createResult = m_prefabPublicInterface->CreateEntity(parentId, AZ::Vector3());
AZ_Assert(createResult.IsSuccess(), "Failed to create entity: %s", createResult.GetError().c_str());
AZ::EntityId entityId = createResult.GetValue();
AZ::Entity* entity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
entity->Deactivate();
entity->SetName(name);
// Normally, in invalid parent ID should automatically parent us to the root prefab, but currently in the unit test
// environment entities aren't created with a default transform component, so CreateEntity won't correctly parent.
// We get the actual target parent ID here, then create our missing transform component.
if (!parentId.IsValid())
{
auto prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
parentId = prefabEditorEntityOwnershipInterface->GetRootPrefabInstance()->get().GetContainerEntityId();
}
auto transform = aznew AzToolsFramework::Components::TransformComponent;
transform->SetParent(parentId);
entity->AddComponent(transform);
entity->Activate();
// Update our undo cache entry to include the rename / reparent as one atomic operation.
m_prefabPublicInterface->GenerateUndoNodesForEntityChangeAndUpdateCache(entityId, m_undoStack->GetTop());
m_prefabSystemComponent->OnSystemTick();
return entityId;
}
void PrefabTestFixture::CompareInstances(const AzToolsFramework::Prefab::Instance& instanceA,
const AzToolsFramework::Prefab::Instance& instanceB, bool shouldCompareLinkIds, bool shouldCompareContainerEntities)
const AzToolsFramework::Prefab::Instance& instanceB, bool shouldCompareLinkIds, bool shouldCompareContainerEntities)
{
AzToolsFramework::Prefab::TemplateId templateAId = instanceA.GetTemplateId();
AzToolsFramework::Prefab::TemplateId templateBId = instanceB.GetTemplateId();
@@ -131,6 +190,24 @@ namespace UnitTest
}
}
void PrefabTestFixture::ProcessDeferredUpdates()
{
// Force a prefab propagation for updates that are deferred to the next tick.
m_prefabSystemComponent->OnSystemTick();
}
void PrefabTestFixture::Undo()
{
m_undoStack->Undo();
ProcessDeferredUpdates();
}
void PrefabTestFixture::Redo()
{
m_undoStack->Redo();
ProcessDeferredUpdates();
}
void PrefabTestFixture::AddRequiredEditorComponents(AZ::Entity* entity)
{
ASSERT_TRUE(entity != nullptr);
@@ -49,13 +49,15 @@ namespace UnitTest
inline static const char* CarPrefabMockFilePath = "SomePathToCar";
void SetUpEditorFixtureImpl() override;
void TearDownEditorFixtureImpl() override;
AZStd::unique_ptr<ToolsTestApplication> CreateTestApplication() override;
void CreateRootPrefab();
AZ::Entity* CreateEntity(AZStd::string entityName, const bool shouldActivate = true);
AZ::EntityId CreateEntityUnderRootPrefab(AZStd::string name, AZ::EntityId parentId = AZ::EntityId());
void PropagateAllTemplateChanges();
AZ::Entity* CreateEntity(const char* entityName, const bool shouldActivate = true);
void CompareInstances(const Instance& instanceA, const Instance& instanceB, bool shouldCompareLinkIds = true,
bool shouldCompareContainerEntities = true);
@@ -64,6 +66,15 @@ namespace UnitTest
//! Validates that all entities within a prefab instance are in 'Active' state.
void ValidateInstanceEntitiesActive(Instance& instance);
// Kicks off any updates scheduled for the next tick
virtual void ProcessDeferredUpdates();
// Performs an undo operation and ensures the tick-scheduled updates happen
void Undo();
// Performs a redo operation and ensures the tick-scheduled updates happen
void Redo();
void AddRequiredEditorComponents(AZ::Entity* entity);
PrefabSystemComponent* m_prefabSystemComponent = nullptr;
@@ -71,5 +82,6 @@ namespace UnitTest
PrefabPublicInterface* m_prefabPublicInterface = nullptr;
InstanceUpdateExecutorInterface* m_instanceUpdateExecutorInterface = nullptr;
InstanceToTemplateInterface* m_instanceToTemplateInterface = nullptr;
AzToolsFramework::UndoSystem::UndoStack* m_undoStack = nullptr;
};
}
@@ -37,16 +37,11 @@ namespace UnitTest
m_model->Initialize();
m_modelTester =
AZStd::make_unique<QAbstractItemModelTester>(m_model.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
m_undoStack, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetUndoStack);
AZ_Assert(m_undoStack, "Failed to look up undo stack from tools application");
// Create a new root prefab - the synthetic "NewLevel.prefab" that comes in by default isn't suitable for outliner tests
// because it's created before the EditorEntityModel that our EntityOutlinerListModel subscribes to, and we want to
// recreate it as part of the fixture regardless.
auto entityOwnershipService = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
entityOwnershipService->CreateNewLevelPrefab("UnitTestRoot.prefab", "");
CreateRootPrefab();
}
void TearDownEditorFixtureImpl() override
@@ -125,7 +120,7 @@ namespace UnitTest
}
// Kicks off any updates scheduled for the next tick
void ProcessDeferredUpdates()
void ProcessDeferredUpdates() override
{
// Force a prefab propagation for updates that are deferred to the next tick.
PropagateAllTemplateChanges();
@@ -133,24 +128,9 @@ namespace UnitTest
// Ensure the model process its entity update queue
m_model->ProcessEntityUpdates();
}
// Performs an undo operation and ensures the tick-scheduled updates happen
void Undo()
{
m_undoStack->Undo();
ProcessDeferredUpdates();
}
// Performs a redo operation and ensures the tick-scheduled updates happen
void Redo()
{
m_undoStack->Redo();
ProcessDeferredUpdates();
}
AZStd::unique_ptr<AzToolsFramework::EntityOutlinerListModel> m_model;
AZStd::unique_ptr<QAbstractItemModelTester> m_modelTester;
AzToolsFramework::UndoSystem::UndoStack* m_undoStack = nullptr;
};
TEST_F(EntityOutlinerTest, TestCreateFlatHierarchyUndoAndRedoWorks)
@@ -74,7 +74,7 @@ set(FILES
Prefab/PrefabEntityAliasTests.cpp
Prefab/PrefabInstanceToTemplatePropagatorTests.cpp
Prefab/PrefabInstantiateTests.cpp
Prefab/PrefabInstantiateTests.cpp
Prefab/PrefabAssetFixupTests.cpp
Prefab/PrefabLoadTemplateTests.cpp
Prefab/PrefabTestComponent.cpp
Prefab/PrefabTestComponent.h
@@ -299,7 +299,7 @@ void android_main(android_app* appState)
{
// Adding a start up banner so you can see when the game is starting up in amongst the logcat spam
LOGI("****************************************************************");
LOGI("* Amazon Lumberyard - Launching Game... *");
LOGI("* Launching Game... *");
LOGI("****************************************************************");
// setup the system command handler which are guaranteed to be called on the same
@@ -21,6 +21,7 @@
#include <QApplication>
#include <QDir>
#include <QMessageBox>
#include <QInputDialog>
namespace O3DE::ProjectManager
{
@@ -111,6 +112,11 @@ namespace O3DE::ProjectManager
}
}
if (!RegisterEngine(interactive))
{
return false;
}
const AZ::CommandLine* commandLine = GetCommandLine();
AZ_Assert(commandLine, "Failed to get command line");
@@ -165,6 +171,86 @@ namespace O3DE::ProjectManager
return m_entity != nullptr;
}
bool Application::RegisterEngine(bool interactive)
{
// get this engine's info
auto engineInfoOutcome = m_pythonBindings->GetEngineInfo();
if (!engineInfoOutcome)
{
if (interactive)
{
QMessageBox::critical(nullptr,
QObject::tr("Failed to get engine info"),
QObject::tr("A valid engine.json could not be found or loaded. "
"Please verify a valid engine.json file exists in %1")
.arg(GetEngineRoot()));
}
AZ_Error("Project Manager", false, "Failed to get engine info");
return false;
}
EngineInfo engineInfo = engineInfoOutcome.GetValue();
if (engineInfo.m_registered)
{
return true;
}
bool forceRegistration = false;
// check if an engine with this name is already registered
auto existingEngineResult = m_pythonBindings->GetEngineInfo(engineInfo.m_name);
if (existingEngineResult)
{
if (!interactive)
{
AZ_Error("Project Manager", false, "An engine with the name %s is already registered with the path %s",
engineInfo.m_name.toUtf8().constData(), engineInfo.m_path.toUtf8().constData());
return false;
}
// get the updated engine name unless the user wants to cancel
bool okPressed = false;
const EngineInfo& otherEngineInfo = existingEngineResult.GetValue();
engineInfo.m_name = QInputDialog::getText(nullptr,
QObject::tr("Engine '%1' already registered").arg(engineInfo.m_name),
QObject::tr("An engine named '%1' is already registered.<br /><br />"
"<b>Current path</b><br />%2<br/><br />"
"<b>New path</b><br />%3<br /><br />"
"Press 'OK' to force registration, or provide a new engine name below.<br />"
"Alternatively, press `Cancel` to close the Project Manager and resolve the issue manually.")
.arg(engineInfo.m_name, otherEngineInfo.m_path, engineInfo.m_path),
QLineEdit::Normal,
engineInfo.m_name,
&okPressed);
if (!okPressed)
{
// user elected not to change the name or force registration
return false;
}
forceRegistration = true;
}
auto registerOutcome = m_pythonBindings->SetEngineInfo(engineInfo, forceRegistration);
if (!registerOutcome)
{
if (interactive)
{
ProjectUtils::DisplayDetailedError(QObject::tr("Failed to register engine"), registerOutcome);
}
AZ_Error("Project Manager", false, "Failed to register engine %s : %s",
engineInfo.m_path.toUtf8().constData(), registerOutcome.GetError().first.c_str());
return false;
}
return true;
}
void Application::TearDown()
{
if (m_entity)
@@ -34,6 +34,7 @@ namespace O3DE::ProjectManager
private:
bool InitLog(const char* logName);
bool RegisterEngine(bool interactive);
AZStd::unique_ptr<PythonBindings> m_pythonBindings;
QSharedPointer<QCoreApplication> m_app;
@@ -25,13 +25,16 @@ namespace O3DE::ProjectManager
QString m_name;
QString m_thirdPartyPath;
// from o3de_manifest.json
QString m_path;
// from o3de_manifest.json
QString m_defaultProjectsFolder;
QString m_defaultGemsFolder;
QString m_defaultTemplatesFolder;
QString m_defaultRestrictedFolder;
bool m_registered = false;
bool IsValid() const;
};
} // namespace O3DE::ProjectManager
@@ -11,6 +11,7 @@
#include <FormFolderBrowseEditWidget.h>
#include <PythonBindingsInterface.h>
#include <PathValidator.h>
#include <ProjectUtils.h>
#include <AzQtComponents/Utilities/DesktopUtilities.h>
#include <QVBoxLayout>
@@ -114,10 +115,10 @@ namespace O3DE::ProjectManager
engineInfo.m_defaultGemsFolder = m_defaultGems->lineEdit()->text();
engineInfo.m_defaultTemplatesFolder = m_defaultProjectTemplates->lineEdit()->text();
bool result = PythonBindingsInterface::Get()->SetEngineInfo(engineInfo);
auto result = PythonBindingsInterface::Get()->SetEngineInfo(engineInfo);
if (!result)
{
QMessageBox::critical(this, tr("Engine Settings"), tr("Failed to save engine settings."));
ProjectUtils::DisplayDetailedError(tr("Failed to save engine settings"), result, this);
}
}
else
@@ -14,6 +14,7 @@
#include <GemRepo/GemRepoInspector.h>
#include <PythonBindingsInterface.h>
#include <ProjectManagerDefs.h>
#include <ProjectUtils.h>
#include <QVBoxLayout>
#include <QHBoxLayout>
@@ -92,8 +93,7 @@ namespace O3DE::ProjectManager
return;
}
AZ::Outcome < void,
AZStd::pair<AZStd::string, AZStd::string>> addGemRepoResult = PythonBindingsInterface::Get()->AddGemRepo(repoUri);
auto addGemRepoResult = PythonBindingsInterface::Get()->AddGemRepo(repoUri);
if (addGemRepoResult.IsSuccess())
{
Reinit();
@@ -102,20 +102,7 @@ namespace O3DE::ProjectManager
else
{
QString failureMessage = tr("Failed to add gem repo: %1.").arg(repoUri);
if (!addGemRepoResult.GetError().second.empty())
{
QMessageBox addRepoError;
addRepoError.setIcon(QMessageBox::Critical);
addRepoError.setWindowTitle(failureMessage);
addRepoError.setText(addGemRepoResult.GetError().first.c_str());
addRepoError.setDetailedText(addGemRepoResult.GetError().second.c_str());
addRepoError.exec();
}
else
{
QMessageBox::critical(this, failureMessage, addGemRepoResult.GetError().first.c_str());
}
ProjectUtils::DisplayDetailedError(failureMessage, addGemRepoResult, this);
AZ_Error("Project Manager", false, failureMessage.toUtf8());
}
}
@@ -659,5 +659,24 @@ namespace O3DE::ProjectManager
return AZ::Success(QString(projectBuildPath.c_str()));
}
void DisplayDetailedError(const QString& title, const AZ::Outcome<void, AZStd::pair<AZStd::string, AZStd::string>>& outcome, QWidget* parent)
{
const AZStd::string& generalError = outcome.GetError().first;
const AZStd::string& detailedError = outcome.GetError().second;
if (!detailedError.empty())
{
QMessageBox errorDialog(parent);
errorDialog.setIcon(QMessageBox::Critical);
errorDialog.setWindowTitle(title);
errorDialog.setText(generalError.c_str());
errorDialog.setDetailedText(detailedError.c_str());
errorDialog.exec();
}
else
{
QMessageBox::critical(parent, title, generalError.c_str());
}
}
} // namespace ProjectUtils
} // namespace O3DE::ProjectManager

Some files were not shown because too many files have changed in this diff Show More