diff --git a/flutter/engine/src/flutter/fml/memory/ref_counted.h b/flutter/engine/src/flutter/fml/memory/ref_counted.h new file mode 100644 index 0000000000000000000000000000000000000000..6632aba5ab8a6aff92374515ba9fa7c2c5818f0b --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/ref_counted.h @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Provides a base class for reference-counted classes. + +#ifndef FLUTTER_FML_MEMORY_REF_COUNTED_H_ +#define FLUTTER_FML_MEMORY_REF_COUNTED_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted_internal.h" +#include "flutter/fml/memory/ref_ptr.h" + +namespace fml { + +// A base class for (thread-safe) reference-counted classes. Use like: +// +// class Foo : public RefCountedThreadSafe { +// ... +// }; +// +// |~Foo()| *may* be made private (e.g., to avoid accidental deletion of objects +// while there are still references to them), |Foo| should friend +// |RefCountedThreadSafe|; use |FML_FRIEND_REF_COUNTED_THREAD_SAFE()| +// for this: +// +// class Foo : public RefCountedThreadSafe { +// ... +// private: +// FML_FRIEND_REF_COUNTED_THREAD_SAFE(Foo); +// ~Foo(); +// ... +// }; +// +// Similarly, |Foo(...)| may be made private. In this case, there should either +// be a static factory method performing the requisite adoption: +// +// class Foo : public RefCountedThreadSafe { +// ... +// public: +// inline static RefPtr Create() { return AdoptRef(new Foo()); } +// ... +// private: +// Foo(); +// ... +// }; +// +// Or, to allow |MakeRefCounted()| to be used, use +// |FML_FRIEND_MAKE_REF_COUNTED()|: +// +// class Foo : public RefCountedThreadSafe { +// ... +// private: +// FML_FRIEND_MAKE_REF_COUNTED(Foo); +// Foo(); +// Foo(const Bar& bar, bool maybe); +// ... +// }; +// +// For now, we only have thread-safe reference counting, since that's all we +// need. It's easy enough to add thread-unsafe versions if necessary. +template +class RefCountedThreadSafe : public internal::RefCountedThreadSafeBase { + public: + // Adds a reference to this object. + // Inherited from the internal superclass: + // void AddRef() const; + + // Releases a reference to this object. This will destroy this object once the + // last reference is released. + void Release() const { + if (internal::RefCountedThreadSafeBase::Release()) { + delete static_cast(this); + } + } + + // Returns true if there is exactly one reference to this object. Use of this + // is subtle, and should usually be avoided. To assert that there is only one + // reference (typically held by the calling thread, possibly in a local + // variable), use |AssertHasOneRef()| instead. However, a use is: + // + // if (foo->HasOneRef()) { + // // Do something "fast", since |foo| is the only reference and no other + // // thread can get another reference. + // ... + // } else { + // // Do something slower, but still valid even if there were only one + // // reference. + // ... + // } + // + // Inherited from the internal superclass: + // bool HasOneRef(); + + // Asserts that there is exactly one reference to this object; does nothing in + // Release builds (when |NDEBUG| is defined). + // Inherited from the internal superclass: + // void AssertHasOneRef(); + + protected: + // Constructor. Note that the object is constructed with a reference count of + // 1, and then must be adopted (see |AdoptRef()| in ref_ptr.h). + RefCountedThreadSafe() {} + + // Destructor. Note that this object should only be destroyed via |Release()| + // (see above), or something that calls |Release()| (see, e.g., |RefPtr<>| in + // ref_ptr.h). + ~RefCountedThreadSafe() {} + + private: +#ifndef NDEBUG + template + friend RefPtr AdoptRef(U*); + // Marks the initial reference (assumed on construction) as adopted. This is + // only required for Debug builds (when |NDEBUG| is not defined). + // TODO(vtl): Should this really be private? This makes manual ref-counting + // and also writing one's own ref pointer class impossible. + void Adopt() { internal::RefCountedThreadSafeBase::Adopt(); } +#endif + + FML_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); +}; + +// If you subclass |RefCountedThreadSafe| and want to keep your destructor +// private, use this. (See the example above |RefCountedThreadSafe|.) +#define FML_FRIEND_REF_COUNTED_THREAD_SAFE(T) \ + friend class ::fml::RefCountedThreadSafe + +// If you want to keep your constructor(s) private and still want to use +// |MakeRefCounted()|, use this. (See the example above +// |RefCountedThreadSafe|.) +#define FML_FRIEND_MAKE_REF_COUNTED(T) \ + friend class ::fml::internal::MakeRefCountedHelper + +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_REF_COUNTED_H_ diff --git a/flutter/engine/src/flutter/fml/memory/ref_counted_internal.h b/flutter/engine/src/flutter/fml/memory/ref_counted_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..95f9e6fe75d63a597b75548646b6905c8fb42be1 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/ref_counted_internal.h @@ -0,0 +1,106 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Internal implementation details for ref_counted.h. + +#ifndef FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_ +#define FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_ + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +namespace fml { +namespace internal { + +// See ref_counted.h for comments on the public methods. +class RefCountedThreadSafeBase { + public: + void AddRef() const { +#ifndef NDEBUG + FML_DCHECK(!adoption_required_); + FML_DCHECK(!destruction_started_); +#endif + ref_count_.fetch_add(1u, std::memory_order_relaxed); + } + + bool HasOneRef() const { + return ref_count_.load(std::memory_order_acquire) == 1u; + } + + void AssertHasOneRef() const { FML_DCHECK(HasOneRef()); } + + protected: + RefCountedThreadSafeBase(); + ~RefCountedThreadSafeBase(); + + // Returns true if the object should self-delete. + bool Release() const { +#ifndef NDEBUG + FML_DCHECK(!adoption_required_); + FML_DCHECK(!destruction_started_); +#endif + FML_DCHECK(ref_count_.load(std::memory_order_acquire) != 0u); + // TODO(vtl): We could add the following: + // if (ref_count_.load(std::memory_order_relaxed) == 1u) { + // #ifndef NDEBUG + // destruction_started_= true; + // #endif + // return true; + // } + // This would be correct. On ARM (an Nexus 4), in *single-threaded* tests, + // this seems to make the destruction case marginally faster (barely + // measurable), and while the non-destruction case remains about the same + // (possibly marginally slower, but my measurements aren't good enough to + // have any confidence in that). I should try multithreaded/multicore tests. + if (ref_count_.fetch_sub(1u, std::memory_order_release) == 1u) { + std::atomic_thread_fence(std::memory_order_acquire); +#ifndef NDEBUG + destruction_started_ = true; +#endif + return true; + } + return false; + } + +#ifndef NDEBUG + void Adopt() { + FML_DCHECK(adoption_required_); + adoption_required_ = false; + } +#endif + + private: + mutable std::atomic_uint_fast32_t ref_count_; + +#ifndef NDEBUG + mutable bool adoption_required_ = false; + mutable bool destruction_started_ = false; +#endif + + FML_DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); +}; + +inline RefCountedThreadSafeBase::RefCountedThreadSafeBase() + : ref_count_(1u) +#ifndef NDEBUG + , + adoption_required_(true) +#endif +{ +} + +inline RefCountedThreadSafeBase::~RefCountedThreadSafeBase() { +#ifndef NDEBUG + FML_DCHECK(!adoption_required_); + // Should only be destroyed as a result of |Release()|. + FML_DCHECK(destruction_started_); +#endif +} + +} // namespace internal +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_REF_COUNTED_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/fml/memory/ref_counted_unittest.cc b/flutter/engine/src/flutter/fml/memory/ref_counted_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..06f80942a8969b18b837eca84a79976035f25d1f --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/ref_counted_unittest.cc @@ -0,0 +1,647 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file tests both ref_counted.h and ref_ptr.h (which the former includes). +// TODO(vtl): Possibly we could separate these tests out better, since a lot of +// it is actually testing |RefPtr|. + +#include "flutter/fml/memory/ref_counted.h" + +#include "flutter/fml/macros.h" +#include "gtest/gtest.h" + +// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) + +#if defined(__clang__) +#define ALLOW_PESSIMIZING_MOVE(code_line) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wpessimizing-move\"") code_line; \ + _Pragma("clang diagnostic pop") +#else +#define ALLOW_PESSIMIZING_MOVE(code_line) code_line; +#endif + +#if defined(__clang__) +#define ALLOW_SELF_MOVE(code_line) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wself-move\"") code_line; \ + _Pragma("clang diagnostic pop") +#else +#define ALLOW_SELF_MOVE(code_line) code_line; +#endif + +#if defined(__clang__) +#define ALLOW_SELF_ASSIGN_OVERLOADED(code_line) \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wself-assign-overloaded\"") \ + code_line; \ + _Pragma("clang diagnostic pop") +#else +#define ALLOW_SELF_ASSIGN_OVERLOADED(code_line) code_line; +#endif + +namespace fml { +namespace { + +class MyClass : public RefCountedThreadSafe { + protected: + MyClass(MyClass** created, bool* was_destroyed) + : was_destroyed_(was_destroyed) { + if (created) { + *created = this; + } + } + virtual ~MyClass() { + if (was_destroyed_) { + *was_destroyed_ = true; + } + } + + private: + FML_FRIEND_REF_COUNTED_THREAD_SAFE(MyClass); + FML_FRIEND_MAKE_REF_COUNTED(MyClass); + + bool* was_destroyed_; + + FML_DISALLOW_COPY_AND_ASSIGN(MyClass); +}; + +class MySubclass final : public MyClass { + private: + FML_FRIEND_REF_COUNTED_THREAD_SAFE(MySubclass); + FML_FRIEND_MAKE_REF_COUNTED(MySubclass); + + MySubclass(MySubclass** created, bool* was_destroyed) + : MyClass(nullptr, was_destroyed) { + if (created) { + *created = this; + } + } + ~MySubclass() override {} + + FML_DISALLOW_COPY_AND_ASSIGN(MySubclass); +}; + +TEST(RefCountedTest, Constructors) { + bool was_destroyed; + + { + // Default. + RefPtr r; + EXPECT_TRUE(r.get() == nullptr); + EXPECT_FALSE(r); + } + + { + // Nullptr. + RefPtr r(nullptr); + EXPECT_TRUE(r.get() == nullptr); + EXPECT_FALSE(r); + } + + { + MyClass* created = nullptr; + was_destroyed = false; + // Adopt, then RVO. + RefPtr r(MakeRefCounted(&created, &was_destroyed)); + EXPECT_TRUE(created); + EXPECT_EQ(created, r.get()); + EXPECT_TRUE(r); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MyClass* created = nullptr; + was_destroyed = false; + // Adopt, then move. + ALLOW_PESSIMIZING_MOVE(RefPtr r( + std::move(MakeRefCounted(&created, &was_destroyed)))) + EXPECT_TRUE(created); + EXPECT_EQ(created, r.get()); + EXPECT_TRUE(r); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MyClass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + // Copy. + // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) + RefPtr r2(r1); + EXPECT_TRUE(created); + EXPECT_EQ(created, r1.get()); + EXPECT_EQ(created, r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MyClass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + // From raw pointer. + RefPtr r2(created); + EXPECT_TRUE(created); + EXPECT_EQ(created, r1.get()); + EXPECT_EQ(created, r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + // Adopt, then "move". + RefPtr r(MakeRefCounted(&created, &was_destroyed)); + EXPECT_TRUE(created); + EXPECT_EQ(static_cast(created), r.get()); + EXPECT_TRUE(r); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + // Adopt, then "move". + ALLOW_PESSIMIZING_MOVE(RefPtr r( + std::move(MakeRefCounted(&created, &was_destroyed)))) + EXPECT_TRUE(created); + EXPECT_EQ(static_cast(created), r.get()); + EXPECT_TRUE(r); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + // "Copy". + RefPtr r2(r1); + EXPECT_TRUE(created); + EXPECT_EQ(static_cast(created), r1.get()); + EXPECT_EQ(static_cast(created), r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + // From raw pointer. + RefPtr r2(created); + EXPECT_TRUE(created); + EXPECT_EQ(static_cast(created), r1.get()); + EXPECT_EQ(static_cast(created), r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); +} + +TEST(RefCountedTest, NullAssignmentToNull) { + RefPtr r1; + // No-op null assignment using |nullptr|. + r1 = nullptr; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_FALSE(r1); + + RefPtr r2; + // No-op null assignment using copy constructor. + r1 = r2; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r2.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_FALSE(r2); + + // No-op null assignment using move constructor. + r1 = std::move(r2); + EXPECT_TRUE(r1.get() == nullptr); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_TRUE(r2.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, + // bugprone-use-after-move) + EXPECT_FALSE(r1); + EXPECT_FALSE(r2); + + RefPtr r3; + // No-op null assignment using "copy" constructor. + r1 = r3; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r3.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_FALSE(r3); + + // No-op null assignment using "move" constructor. + r1 = std::move(r3); + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r3.get() == nullptr); // NOLINT(bugprone-use-after-move) + EXPECT_FALSE(r1); + EXPECT_FALSE(r3); +} + +TEST(RefCountedTest, NonNullAssignmentToNull) { + bool was_destroyed; + + { + MyClass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + RefPtr r2; + // Copy assignment (to null ref pointer). + r2 = r1; + EXPECT_EQ(created, r1.get()); + EXPECT_EQ(created, r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MyClass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + RefPtr r2; + // Move assignment (to null ref pointer). + r2 = std::move(r1); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_TRUE(r1.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, + // bugprone-use-after-move) + EXPECT_EQ(created, r2.get()); + EXPECT_FALSE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + RefPtr r2; + // "Copy" assignment (to null ref pointer). + r2 = r1; + EXPECT_EQ(created, r1.get()); + EXPECT_EQ(static_cast(created), r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MySubclass* created = nullptr; + was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + RefPtr r2; + // "Move" assignment (to null ref pointer). + r2 = std::move(r1); + EXPECT_TRUE(r1.get() == nullptr); // NOLINT(bugprone-use-after-move) + EXPECT_EQ(static_cast(created), r2.get()); + EXPECT_FALSE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); +} + +TEST(RefCountedTest, NullAssignmentToNonNull) { + bool was_destroyed = false; + RefPtr r1(MakeRefCounted(nullptr, &was_destroyed)); + // Null assignment (to non-null ref pointer) using |nullptr|. + r1 = nullptr; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_TRUE(was_destroyed); + + was_destroyed = false; + r1 = MakeRefCounted(nullptr, &was_destroyed); + RefPtr r2; + // Null assignment (to non-null ref pointer) using copy constructor. + r1 = r2; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r2.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_FALSE(r2); + EXPECT_TRUE(was_destroyed); + + was_destroyed = false; + r1 = MakeRefCounted(nullptr, &was_destroyed); + // Null assignment using move constructor. + r1 = std::move(r2); + EXPECT_TRUE(r1.get() == nullptr); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_TRUE(r2.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, + // bugprone-use-after-move) + EXPECT_FALSE(r1); + EXPECT_FALSE(r2); + EXPECT_TRUE(was_destroyed); + + was_destroyed = false; + r1 = MakeRefCounted(nullptr, &was_destroyed); + RefPtr r3; + // Null assignment (to non-null ref pointer) using "copy" constructor. + r1 = r3; + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r3.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_FALSE(r3); + EXPECT_TRUE(was_destroyed); + + was_destroyed = false; + r1 = MakeRefCounted(nullptr, &was_destroyed); + // Null assignment (to non-null ref pointer) using "move" constructor. + r1 = std::move(r3); + EXPECT_TRUE(r1.get() == nullptr); + EXPECT_TRUE(r3.get() == nullptr); // NOLINT(bugprone-use-after-move) + EXPECT_FALSE(r1); + EXPECT_FALSE(r3); + EXPECT_TRUE(was_destroyed); +} + +TEST(RefCountedTest, NonNullAssignmentToNonNull) { + bool was_destroyed1; + bool was_destroyed2; + + { + was_destroyed1 = false; + was_destroyed2 = false; + RefPtr r1(MakeRefCounted(nullptr, &was_destroyed1)); + RefPtr r2(MakeRefCounted(nullptr, &was_destroyed2)); + // Copy assignment (to non-null ref pointer). + r2 = r1; + EXPECT_EQ(r1.get(), r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed1); + EXPECT_TRUE(was_destroyed2); + } + EXPECT_TRUE(was_destroyed1); + + { + was_destroyed1 = false; + was_destroyed2 = false; + RefPtr r1(MakeRefCounted(nullptr, &was_destroyed1)); + RefPtr r2(MakeRefCounted(nullptr, &was_destroyed2)); + // Move assignment (to non-null ref pointer). + r2 = std::move(r1); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_TRUE(r1.get() == nullptr); // NOLINT(clang-analyzer-cplusplus.Move, + // bugprone-use-after-move) + EXPECT_FALSE(r2.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed1); + EXPECT_TRUE(was_destroyed2); + } + EXPECT_TRUE(was_destroyed1); + + { + was_destroyed1 = false; + was_destroyed2 = false; + RefPtr r1(MakeRefCounted(nullptr, &was_destroyed1)); + RefPtr r2(MakeRefCounted(nullptr, &was_destroyed2)); + // "Copy" assignment (to non-null ref pointer). + r2 = r1; + EXPECT_EQ(r1.get(), r2.get()); + EXPECT_TRUE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed1); + EXPECT_TRUE(was_destroyed2); + } + EXPECT_TRUE(was_destroyed1); + + { + was_destroyed1 = false; + was_destroyed2 = false; + RefPtr r1(MakeRefCounted(nullptr, &was_destroyed1)); + RefPtr r2(MakeRefCounted(nullptr, &was_destroyed2)); + // Move assignment (to non-null ref pointer). + r2 = std::move(r1); + EXPECT_TRUE(r1.get() == nullptr); // NOLINT(bugprone-use-after-move) + EXPECT_FALSE(r2.get() == nullptr); + EXPECT_FALSE(r1); + EXPECT_TRUE(r2); + EXPECT_FALSE(was_destroyed1); + EXPECT_TRUE(was_destroyed2); + } + EXPECT_TRUE(was_destroyed1); +} + +TEST(RefCountedTest, SelfAssignment) { + bool was_destroyed; + + { + MyClass* created = nullptr; + was_destroyed = false; + // This line is marked NOLINT because the clang linter does not reason about + // the value of the reference count. In particular, the self-assignment + // below is handled in the copy constructor by a refcount increment then + // decrement. The linter sees only that the decrement might destroy the + // object. + RefPtr r(MakeRefCounted( // NOLINT + &created, &was_destroyed)); + // Copy. + ALLOW_SELF_ASSIGN_OVERLOADED(r = r); + EXPECT_EQ(created, r.get()); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); + + { + MyClass* created = nullptr; + was_destroyed = false; + RefPtr r(MakeRefCounted(&created, &was_destroyed)); + // Move. + ALLOW_SELF_MOVE(r = std::move(r)) + EXPECT_EQ(created, r.get()); + EXPECT_FALSE(was_destroyed); + } + EXPECT_TRUE(was_destroyed); +} + +TEST(RefCountedTest, Swap) { + MyClass* created1 = nullptr; + static bool was_destroyed1; + was_destroyed1 = false; + RefPtr r1(MakeRefCounted(&created1, &was_destroyed1)); + EXPECT_TRUE(created1); + EXPECT_EQ(created1, r1.get()); + + MyClass* created2 = nullptr; + static bool was_destroyed2; + was_destroyed2 = false; + RefPtr r2(MakeRefCounted(&created2, &was_destroyed2)); + EXPECT_TRUE(created2); + EXPECT_EQ(created2, r2.get()); + EXPECT_NE(created1, created2); + + r1.swap(r2); + EXPECT_EQ(created2, r1.get()); + EXPECT_EQ(created1, r2.get()); +} + +TEST(RefCountedTest, GetAndDereferenceOperators) { + // Note: We check here that .get(), operator*, and operator-> are const, but + // return non-const pointers/refs. + + MyClass* created = nullptr; + const RefPtr r(MakeRefCounted(&created, nullptr)); + MyClass* ptr = r.get(); // Assign to non-const pointer. + EXPECT_EQ(created, ptr); + ptr = r.operator->(); // Assign to non-const pointer. + EXPECT_EQ(created, ptr); + MyClass& ref = *r; // "Assign" to non-const reference. + EXPECT_EQ(created, &ref); +} + +// You can manually call |AddRef()| and |Release()| if you want. +TEST(RefCountedTest, AddRefRelease) { + MyClass* created = nullptr; + bool was_destroyed = false; + { + RefPtr r(MakeRefCounted(&created, &was_destroyed)); + EXPECT_EQ(created, r.get()); + created->AddRef(); + } + EXPECT_FALSE(was_destroyed); + created->Release(); + EXPECT_TRUE(was_destroyed); +} + +TEST(RefCountedTest, Mix) { + MySubclass* created = nullptr; + bool was_destroyed = false; + RefPtr r1(MakeRefCounted(&created, &was_destroyed)); + ASSERT_FALSE(was_destroyed); + EXPECT_TRUE(created->HasOneRef()); + created->AssertHasOneRef(); + + RefPtr r2 = r1; + ASSERT_FALSE(was_destroyed); + EXPECT_FALSE(created->HasOneRef()); + + r1 = nullptr; + ASSERT_FALSE(was_destroyed); + created->AssertHasOneRef(); + + { + RefPtr r3 = r2; + EXPECT_FALSE(created->HasOneRef()); + { + // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) + RefPtr r4(r3); + r2 = nullptr; + ASSERT_FALSE(was_destroyed); + EXPECT_FALSE(created->HasOneRef()); + } + ASSERT_FALSE(was_destroyed); + EXPECT_TRUE(created->HasOneRef()); + created->AssertHasOneRef(); + + r1 = RefPtr(static_cast(r3.get())); + ASSERT_FALSE(was_destroyed); + EXPECT_FALSE(created->HasOneRef()); + } + ASSERT_FALSE(was_destroyed); + EXPECT_TRUE(created->HasOneRef()); + created->AssertHasOneRef(); + + EXPECT_EQ(created, r1.get()); + + r1 = nullptr; + EXPECT_TRUE(was_destroyed); +} + +class MyPublicClass : public RefCountedThreadSafe { + public: + // Overloaded constructors work with |MakeRefCounted()|. + MyPublicClass() : has_num_(false), num_(0) {} + explicit MyPublicClass(int num) : has_num_(true), num_(num) {} + + ~MyPublicClass() {} + + bool has_num() const { return has_num_; } + int num() const { return num_; } + + private: + bool has_num_; + int num_; + + FML_DISALLOW_COPY_AND_ASSIGN(MyPublicClass); +}; + +// You can also just keep constructors and destructors public. Make sure that +// works (mostly that it compiles). +TEST(RefCountedTest, PublicCtorAndDtor) { + RefPtr r1 = MakeRefCounted(); + ASSERT_TRUE(r1); + EXPECT_FALSE(r1->has_num()); + + RefPtr r2 = MakeRefCounted(123); + ASSERT_TRUE(r2); + EXPECT_TRUE(r2->has_num()); + EXPECT_EQ(123, r2->num()); + EXPECT_NE(r1.get(), r2.get()); + + r1 = r2; + EXPECT_TRUE(r1->has_num()); + EXPECT_EQ(123, r1->num()); + EXPECT_EQ(r1.get(), r2.get()); + + r2 = nullptr; + EXPECT_FALSE(r2); + EXPECT_TRUE(r1->has_num()); + EXPECT_EQ(123, r1->num()); + + r1 = nullptr; + EXPECT_FALSE(r1); +} + +// The danger with having a public constructor or destructor is that certain +// things will compile. You should get some protection by assertions in Debug +// builds. +#ifndef NDEBUG +TEST(RefCountedTest, DebugChecks) { + { + MyPublicClass* p = new MyPublicClass(); + EXPECT_DEATH_IF_SUPPORTED( // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + delete p, "!adoption_required_"); + } + + { + MyPublicClass* p = new MyPublicClass(); + EXPECT_DEATH_IF_SUPPORTED( // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) + RefPtr r(p), "!adoption_required_"); + } + + { + RefPtr r(MakeRefCounted()); + EXPECT_DEATH_IF_SUPPORTED(delete r.get(), "destruction_started_"); + } +} +#endif + +// TODO(vtl): Add (threaded) stress tests. + +} // namespace +} // namespace fml + +// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks) diff --git a/flutter/engine/src/flutter/fml/memory/ref_ptr.h b/flutter/engine/src/flutter/fml/memory/ref_ptr.h new file mode 100644 index 0000000000000000000000000000000000000000..d90af4ac2aae7c94d8acedb16a3a0f4a01524e64 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/ref_ptr.h @@ -0,0 +1,272 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Provides a smart pointer class for intrusively reference-counted objects. + +#ifndef FLUTTER_FML_MEMORY_REF_PTR_H_ +#define FLUTTER_FML_MEMORY_REF_PTR_H_ + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_ptr_internal.h" + +namespace fml { + +// A smart pointer class for intrusively reference-counted objects (e.g., those +// subclassing |RefCountedThreadSafe| -- see ref_counted.h). +// +// Such objects require *adoption* to obtain the first |RefPtr|, which is +// accomplished using |AdoptRef| (see below). (This is due to such objects being +// constructed with a reference count of 1. The adoption requirement is +// enforced, at least in Debug builds, by assertions.) +// +// E.g., if |Foo| is an intrusively reference-counted class: +// +// // The |AdoptRef| may be put in a static factory method (e.g., if |Foo|'s +// // constructor is private). +// RefPtr my_foo_ptr(AdoptRef(new Foo())); +// +// // Now OK, since "my Foo" has been adopted ... +// RefPtr another_ptr_to_my_foo(my_foo_ptr.get()); +// +// // ... though this would preferable in this situation. +// RefPtr yet_another_ptr_to_my_foo(my_foo_ptr); +// +// Unlike Chromium's |scoped_refptr|, |RefPtr| is only explicitly constructible +// from a plain pointer (and not assignable). It is however implicitly +// constructible from |nullptr|. So: +// +// RefPtr foo(plain_ptr_to_adopted_foo); // OK. +// foo = plain_ptr_to_adopted_foo; // Not OK (doesn't compile). +// foo = RefPtr(plain_ptr_to_adopted_foo); // OK. +// foo = nullptr; // OK. +// +// And if we have |void MyFunction(RefPtr foo)|, calling it using +// |MyFunction(nullptr)| is also valid. +// +// Implementation note: For copy/move constructors/operator=s, we often have +// templated versions, so that the operation can be done on a |RefPtr|, where +// |U| is a subclass of |T|. However, we also have non-templated versions with +// |U = T|, since the templated versions don't count as copy/move +// constructors/operator=s for the purposes of causing the default copy +// constructor/operator= to be deleted. E.g., if we didn't declare any +// non-templated versions, we'd get the default copy constructor/operator= (we'd +// only not get the default move constructor/operator= by virtue of having a +// destructor)! (In fact, it'd suffice to only declare a non-templated move +// constructor or move operator=, which would cause the copy +// constructor/operator= to be deleted, but for clarity we include explicit +// non-templated versions of everything.) +template +class RefPtr final { + public: + RefPtr() : ptr_(nullptr) {} + RefPtr(std::nullptr_t) // NOLINT(google-explicit-constructor) + : ptr_(nullptr) {} + + // Explicit constructor from a plain pointer (to an object that must have + // already been adopted). (Note that in |T::T()|, references to |this| cannot + // be taken, since the object being constructed will not have been adopted + // yet.) + template + explicit RefPtr(U* p) : ptr_(p) { + if (ptr_) { + ptr_->AddRef(); + } + } + + // Copy constructor. + RefPtr(const RefPtr& r) // NOLINT(google-explicit-constructor) + : ptr_(r.ptr_) { + if (ptr_) { + ptr_->AddRef(); + } + } + + template + RefPtr(const RefPtr& r) // NOLINT(google-explicit-constructor) + : ptr_(r.ptr_) { + if (ptr_) { + ptr_->AddRef(); + } + } + + // Move constructor. + RefPtr(RefPtr&& r) : ptr_(r.ptr_) { // NOLINT(google-explicit-constructor) + r.ptr_ = nullptr; + } + + template + RefPtr(RefPtr&& r) : ptr_(r.ptr_) { // NOLINT(google-explicit-constructor) + r.ptr_ = nullptr; + } + + // Destructor. + ~RefPtr() { + if (ptr_) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) + ptr_->Release(); + } + } + + T* get() const { return ptr_; } + + T& operator*() const { + FML_DCHECK(ptr_); + return *ptr_; + } + + T* operator->() const { + FML_DCHECK(ptr_); + return ptr_; + } + + // Copy assignment. + RefPtr& operator=(const RefPtr& r) { + // Handle self-assignment. + if (r.ptr_ == ptr_) { + return *this; + } + if (r.ptr_) { + r.ptr_->AddRef(); + } + T* old_ptr = ptr_; + ptr_ = r.ptr_; + if (old_ptr) { + old_ptr->Release(); + } + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return *this; + } + + template + RefPtr& operator=(const RefPtr& r) { + if (reinterpret_cast(r.ptr_) == ptr_) { + return *this; + } + if (r.ptr_) { + r.ptr_->AddRef(); + } + T* old_ptr = ptr_; + ptr_ = r.ptr_; + if (old_ptr) { + old_ptr->Release(); + } + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return *this; + } + + // Move assignment. + // Note: Like |std::shared_ptr|, we support self-move and move assignment is + // equivalent to |RefPtr(std::move(r)).swap(*this)|. + RefPtr& operator=(RefPtr&& r) { + RefPtr(std::move(r)).swap(*this); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return *this; + } + + template + RefPtr& operator=(RefPtr&& r) { + RefPtr(std::move(r)).swap(*this); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return *this; + } + + void swap(RefPtr& r) { + T* p = ptr_; + ptr_ = r.ptr_; + r.ptr_ = p; + } + + // Returns a new |RefPtr| with the same contents as this pointer. Useful + // when a function takes a |RefPtr&&| argument and the caller wants to + // retain its reference (rather than moving it). + RefPtr Clone() const { return *this; } + + explicit operator bool() const { return !!ptr_; } + + template + bool operator==(const RefPtr& rhs) const { + return ptr_ == rhs.ptr_; + } + + template + bool operator!=(const RefPtr& rhs) const { + return !operator==(rhs); + } + + template + bool operator<(const RefPtr& rhs) const { + return ptr_ < rhs.ptr_; + } + + private: + template + friend class RefPtr; + + friend RefPtr AdoptRef(T*); + + enum AdoptTag { kAdopt }; + RefPtr(T* ptr, AdoptTag) : ptr_(ptr) { FML_DCHECK(ptr_); } + + T* ptr_; +}; + +// Adopts a newly-created |T|. Typically used in a static factory method, like: +// +// // static +// RefPtr Foo::Create() { +// return AdoptRef(new Foo()); +// } +template +inline RefPtr AdoptRef(T* ptr) { +#ifndef NDEBUG + ptr->Adopt(); +#endif + return RefPtr(ptr, RefPtr::kAdopt); +} + +// Constructs a |RefPtr| from a plain pointer (to an object that must +// have already been adoped). Avoids having to spell out the full type name. +// +// Foo* foo = ...; +// auto foo_ref = Ref(foo); +// +// (|foo_ref| will be of type |RefPtr|.) +template +inline RefPtr Ref(T* ptr) { + return RefPtr(ptr); +} + +// Creates an intrusively reference counted |T|, producing a |RefPtr| (and +// performing the required adoption). Use like: +// +// auto my_foo = MakeRefCounted(ctor_arg1, ctor_arg2); +// +// (|my_foo| will be of type |RefPtr|.) +template +RefPtr MakeRefCounted(Args&&... args) { + return internal::MakeRefCountedHelper::MakeRefCounted( + std::forward(args)...); +} + +} // namespace fml + +// Inject custom std::hash<> function object for |RefPtr|. +namespace std { +template +struct hash> { + using argument_type = fml::RefPtr; + using result_type = std::size_t; + + result_type operator()(const argument_type& ptr) const { + return std::hash()(ptr.get()); + } +}; +} // namespace std + +#endif // FLUTTER_FML_MEMORY_REF_PTR_H_ diff --git a/flutter/engine/src/flutter/fml/memory/ref_ptr_internal.h b/flutter/engine/src/flutter/fml/memory/ref_ptr_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..b38f943751854cd6765e3e18ed89c2f06131c2d0 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/ref_ptr_internal.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_ +#define FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_ + +#include + +#include "flutter/fml/macros.h" + +namespace fml { + +template +class RefPtr; + +template +RefPtr AdoptRef(T* ptr); + +namespace internal { + +// This is a wrapper class that can be friended for a particular |T|, if you +// want to make |T|'s constructor private, but still use |MakeRefCounted()| +// (below). (You can't friend partial specializations.) See |MakeRefCounted()| +// and |FML_FRIEND_MAKE_REF_COUNTED()|. +template +class MakeRefCountedHelper final { + public: + template + static RefPtr MakeRefCounted(Args&&... args) { + return AdoptRef(new T(std::forward(args)...)); + } +}; + +} // namespace internal +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_REF_PTR_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/fml/memory/task_runner_checker.cc b/flutter/engine/src/flutter/fml/memory/task_runner_checker.cc new file mode 100644 index 0000000000000000000000000000000000000000..5320c49153b4d9a58f8dc6864c182baa26ae54c0 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/task_runner_checker.cc @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/memory/task_runner_checker.h" + +namespace fml { + +TaskRunnerChecker::TaskRunnerChecker() + : initialized_queue_id_(InitTaskQueueId()), + subsumed_queue_ids_( + MessageLoopTaskQueues::GetInstance()->GetSubsumedTaskQueueId( + initialized_queue_id_)){}; + +TaskRunnerChecker::~TaskRunnerChecker() = default; + +bool TaskRunnerChecker::RunsOnCreationTaskRunner() const { + FML_CHECK(fml::MessageLoop::IsInitializedForCurrentThread()); + const auto current_queue_id = MessageLoop::GetCurrentTaskQueueId(); + if (RunsOnTheSameThread(current_queue_id, initialized_queue_id_)) { + return true; + } + for (auto& subsumed : subsumed_queue_ids_) { + if (RunsOnTheSameThread(current_queue_id, subsumed)) { + return true; + } + } + return false; +}; + +bool TaskRunnerChecker::RunsOnTheSameThread(TaskQueueId queue_a, + TaskQueueId queue_b) { + if (queue_a == queue_b) { + return true; + } + + auto queues = MessageLoopTaskQueues::GetInstance(); + if (queues->Owns(queue_a, queue_b)) { + return true; + } + if (queues->Owns(queue_b, queue_a)) { + return true; + } + return false; +}; + +TaskQueueId TaskRunnerChecker::InitTaskQueueId() { + MessageLoop::EnsureInitializedForCurrentThread(); + return MessageLoop::GetCurrentTaskQueueId(); +}; + +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/memory/task_runner_checker.h b/flutter/engine/src/flutter/fml/memory/task_runner_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..67e09b5e1c597847dbde293be6ce62837b1af2ae --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/task_runner_checker.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_ +#define FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_ + +#include "flutter/fml/message_loop.h" +#include "flutter/fml/task_runner.h" + +namespace fml { + +class TaskRunnerChecker final { + public: + TaskRunnerChecker(); + + ~TaskRunnerChecker(); + + bool RunsOnCreationTaskRunner() const; + + static bool RunsOnTheSameThread(TaskQueueId queue_a, TaskQueueId queue_b); + + private: + TaskQueueId initialized_queue_id_; + std::set subsumed_queue_ids_; + + TaskQueueId InitTaskQueueId(); +}; + +#if !defined(NDEBUG) +#define FML_DECLARE_TASK_RUNNER_CHECKER(c) fml::TaskRunnerChecker c +#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) \ + FML_DCHECK((c).RunsOnCreationTaskRunner()) +#else +#define FML_DECLARE_TASK_RUNNER_CHECKER(c) +#define FML_DCHECK_TASK_RUNNER_IS_CURRENT(c) ((void)0) +#endif + +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_TASK_RUNNER_CHECKER_H_ diff --git a/flutter/engine/src/flutter/fml/memory/task_runner_checker_unittest.cc b/flutter/engine/src/flutter/fml/memory/task_runner_checker_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..cd4de6d6e3b4c6ddd45f6e4fd214af7059313d22 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/task_runner_checker_unittest.cc @@ -0,0 +1,173 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/fml/memory/task_runner_checker.h" + +#include + +#include "flutter/fml/message_loop.h" +#include "flutter/fml/raster_thread_merger.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "flutter/fml/synchronization/waitable_event.h" +#include "gtest/gtest.h" + +namespace fml { +namespace testing { + +TEST(TaskRunnerCheckerTests, RunsOnCurrentTaskRunner) { + TaskRunnerChecker checker; + EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); +} + +TEST(TaskRunnerCheckerTests, FailsTheCheckIfOnDifferentTaskRunner) { + TaskRunnerChecker checker; + EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); + fml::MessageLoop* loop = nullptr; + fml::AutoResetWaitableEvent latch; + std::thread another_thread([&]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop = &fml::MessageLoop::GetCurrent(); + loop->GetTaskRunner()->PostTask([&]() { + EXPECT_EQ(checker.RunsOnCreationTaskRunner(), false); + latch.Signal(); + }); + loop->Run(); + }); + latch.Wait(); + loop->Terminate(); + another_thread.join(); + EXPECT_EQ(checker.RunsOnCreationTaskRunner(), true); +} + +TEST(TaskRunnerCheckerTests, SameTaskRunnerRunsOnTheSameThread) { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); + fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); + TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); + TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); + EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), true); +} + +TEST(TaskRunnerCheckerTests, RunsOnDifferentThreadsReturnsFalse) { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::MessageLoop& loop1 = fml::MessageLoop::GetCurrent(); + TaskQueueId a = loop1.GetTaskRunner()->GetTaskQueueId(); + fml::AutoResetWaitableEvent latch; + std::thread another_thread([&]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + fml::MessageLoop& loop2 = fml::MessageLoop::GetCurrent(); + TaskQueueId b = loop2.GetTaskRunner()->GetTaskQueueId(); + EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(a, b), false); + latch.Signal(); + }); + latch.Wait(); + another_thread.join(); +} + +TEST(TaskRunnerCheckerTests, MergedTaskRunnersRunsOnTheSameThread) { + fml::MessageLoop* loop1 = nullptr; + fml::AutoResetWaitableEvent latch1; + fml::AutoResetWaitableEvent term1; + std::thread thread1([&loop1, &latch1, &term1]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop1 = &fml::MessageLoop::GetCurrent(); + latch1.Signal(); + term1.Wait(); + }); + + fml::MessageLoop* loop2 = nullptr; + fml::AutoResetWaitableEvent latch2; + fml::AutoResetWaitableEvent term2; + std::thread thread2([&loop2, &latch2, &term2]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop2 = &fml::MessageLoop::GetCurrent(); + latch2.Signal(); + term2.Wait(); + }); + + latch1.Wait(); + latch2.Wait(); + fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); + fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); + const auto raster_thread_merger = + fml::MakeRefCounted(qid1, qid2); + const size_t kNumFramesMerged = 5; + + raster_thread_merger->MergeWithLease(kNumFramesMerged); + + // merged, running on the same thread + EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), true); + + for (size_t i = 0; i < kNumFramesMerged; i++) { + ASSERT_TRUE(raster_thread_merger->IsMerged()); + raster_thread_merger->DecrementLease(); + } + + ASSERT_FALSE(raster_thread_merger->IsMerged()); + + // un-merged, not running on the same thread + EXPECT_EQ(TaskRunnerChecker::RunsOnTheSameThread(qid1, qid2), false); + + term1.Signal(); + term2.Signal(); + thread1.join(); + thread2.join(); +} + +TEST(TaskRunnerCheckerTests, + PassesRunsOnCreationTaskRunnerIfOnDifferentTaskRunner) { + fml::MessageLoop* loop1 = nullptr; + fml::AutoResetWaitableEvent latch1; + std::thread thread1([&]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop1 = &fml::MessageLoop::GetCurrent(); + latch1.Signal(); + loop1->Run(); + }); + + fml::MessageLoop* loop2 = nullptr; + fml::AutoResetWaitableEvent latch2; + std::thread thread2([&]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop2 = &fml::MessageLoop::GetCurrent(); + latch2.Signal(); + loop2->Run(); + }); + + latch1.Wait(); + latch2.Wait(); + + fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); + fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); + fml::MessageLoopTaskQueues::GetInstance()->Merge(qid1, qid2); + + std::unique_ptr checker; + + fml::AutoResetWaitableEvent latch3; + loop2->GetTaskRunner()->PostTask([&]() { + checker = std::make_unique(); + EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); + latch3.Signal(); + }); + latch3.Wait(); + + fml::MessageLoopTaskQueues::GetInstance()->Unmerge(qid1, qid2); + + fml::AutoResetWaitableEvent latch4; + loop2->GetTaskRunner()->PostTask([&]() { + EXPECT_EQ(checker->RunsOnCreationTaskRunner(), true); + latch4.Signal(); + }); + latch4.Wait(); + + loop1->Terminate(); + loop2->Terminate(); + thread1.join(); + thread2.join(); +} + +} // namespace testing +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/memory/thread_checker.cc b/flutter/engine/src/flutter/fml/memory/thread_checker.cc new file mode 100644 index 0000000000000000000000000000000000000000..8a7e02385a1072f7277eac8a463be1d21311d4e2 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/thread_checker.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/memory/thread_checker.h" + +namespace fml { + +thread_local bool ThreadChecker::disable_next_failure_ = false; + +} diff --git a/flutter/engine/src/flutter/fml/memory/thread_checker.h b/flutter/engine/src/flutter/fml/memory/thread_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..220ea6fb67782d7651fd527dca4498ef1be85a8b --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/thread_checker.h @@ -0,0 +1,104 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// A class for checking that the current thread is/isn't the same as an initial +// thread. + +#ifndef FLUTTER_FML_MEMORY_THREAD_CHECKER_H_ +#define FLUTTER_FML_MEMORY_THREAD_CHECKER_H_ + +#include "flutter/fml/build_config.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +#if defined(FML_OS_WIN) +#include +#else +#include +#endif + +namespace fml { + +// A simple class that records the identity of the thread that it was created +// on, and at later points can tell if the current thread is the same as its +// creation thread. This class is thread-safe. +// +// Note: Unlike Chromium's |base::ThreadChecker|, this is *not* Debug-only (so +// #ifdef it out if you want something Debug-only). (Rationale: Having a +// |CalledOnValidThread()| that lies in Release builds seems bad. Moreover, +// there's a small space cost to having even an empty class. ) +class ThreadChecker final { + public: + static void DisableNextThreadCheckFailure() { disable_next_failure_ = true; } + + private: + static thread_local bool disable_next_failure_; + + public: +#if defined(FML_OS_WIN) + ThreadChecker() : self_(GetCurrentThreadId()) {} + ~ThreadChecker() {} + + bool IsCreationThreadCurrent() const { + bool result = GetCurrentThreadId() == self_; + if (!result && disable_next_failure_) { + disable_next_failure_ = false; + return true; + } + return result; + } + + private: + DWORD self_; + +#else + ThreadChecker() : self_(pthread_self()) {} + ~ThreadChecker() {} + + // Returns true if the current thread is the thread this object was created + // on and false otherwise. + bool IsCreationThreadCurrent() const { + pthread_t current_thread = pthread_self(); + bool is_creation_thread_current = !!pthread_equal(current_thread, self_); + if (disable_next_failure_ && !is_creation_thread_current) { + disable_next_failure_ = false; + return true; + } +#ifdef __APPLE__ + // TODO(https://github.com/flutter/flutter/issues/45272): Implement for + // other platforms. + if (!is_creation_thread_current) { + static const int buffer_length = 128; + char expected_thread[buffer_length]; + char actual_thread[buffer_length]; + if (0 == pthread_getname_np(current_thread, actual_thread, + buffer_length) && + 0 == pthread_getname_np(self_, expected_thread, buffer_length)) { + FML_DLOG(ERROR) << "Object referenced on a thread other than the one " + "on which it was created. Expected thread: '" + << expected_thread << "'. Actual thread: '" + << actual_thread << "'."; + } + } +#endif // __APPLE__ + return is_creation_thread_current; + } + + private: + pthread_t self_; +#endif +}; + +#if !defined(NDEBUG) +#define FML_DECLARE_THREAD_CHECKER(c) fml::ThreadChecker c +#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) \ + FML_DCHECK((c).IsCreationThreadCurrent()) +#else +#define FML_DECLARE_THREAD_CHECKER(c) +#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) ((void)0) +#endif + +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_THREAD_CHECKER_H_ diff --git a/flutter/engine/src/flutter/fml/memory/weak_ptr.h b/flutter/engine/src/flutter/fml/memory/weak_ptr.h new file mode 100644 index 0000000000000000000000000000000000000000..bd09610cf309cacc386e30626ab2b0326f5be0f3 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/weak_ptr.h @@ -0,0 +1,328 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file provides weak pointers and weak pointer factories that work like +// Chromium's |base::WeakPtr| and |base::WeakPtrFactory|. + +#ifndef FLUTTER_FML_MEMORY_WEAK_PTR_H_ +#define FLUTTER_FML_MEMORY_WEAK_PTR_H_ + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/memory/ref_counted.h" +#include "flutter/fml/memory/task_runner_checker.h" +#include "flutter/fml/memory/thread_checker.h" +#include "flutter/fml/memory/weak_ptr_internal.h" + +namespace fml { + +struct DebugThreadChecker { + FML_DECLARE_THREAD_CHECKER(checker); +}; + +struct DebugTaskRunnerChecker { + FML_DECLARE_TASK_RUNNER_CHECKER(checker); +}; + +// Forward declaration, so |WeakPtr| can friend it. +template +class WeakPtrFactory; + +// Class for "weak pointers" that can be invalidated. Valid weak pointers +// can only originate from a |WeakPtrFactory| (see below), though weak +// pointers are copyable and movable. +// +// Weak pointers are not in general thread-safe. They may only be *used* on +// a single thread, namely the same thread as the "originating" +// |WeakPtrFactory| (which can invalidate the weak pointers that it +// generates). +// +// However, weak pointers may be passed to other threads, reset on other +// threads, or destroyed on other threads. They may also be reassigned on +// other threads (in which case they should then only be used on the thread +// corresponding to the new "originating" |WeakPtrFactory|). +template +class WeakPtr { + public: + WeakPtr() : ptr_(nullptr) {} + + // Copy constructor. + // NOLINTNEXTLINE(google-explicit-constructor) + WeakPtr(const WeakPtr& r) = default; + + template + WeakPtr(const WeakPtr& r) // NOLINT(google-explicit-constructor) + : ptr_(static_cast(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {} + + // Move constructor. + WeakPtr(WeakPtr&& r) = default; + + template + WeakPtr(WeakPtr&& r) // NOLINT(google-explicit-constructor) + : ptr_(static_cast(r.ptr_)), + flag_(std::move(r.flag_)), + checker_(r.checker_) {} + + // The following methods are thread-friendly, in the sense that they may be + // called subject to additional synchronization. + + // Copy assignment. + WeakPtr& operator=(const WeakPtr& r) = default; + + // Move assignment. + WeakPtr& operator=(WeakPtr&& r) = default; + + void reset() { flag_ = nullptr; } + + // The following methods should only be called on the same thread as the + // "originating" |WeakPtrFactory|. + + explicit operator bool() const { + CheckThreadSafety(); + return flag_ && flag_->is_valid(); + } + + T* get() const { + CheckThreadSafety(); + return *this ? ptr_ : nullptr; + } + + T& operator*() const { + CheckThreadSafety(); + FML_DCHECK(*this); + return *get(); + } + + T* operator->() const { + CheckThreadSafety(); + FML_DCHECK(*this); + return get(); + } + + protected: + explicit WeakPtr(T* ptr, fml::RefPtr&& flag) + : ptr_(ptr), flag_(std::move(flag)) {} + + void CheckThreadSafety() const { + FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); + } + + private: + template + friend class WeakPtr; + + friend class WeakPtrFactory; + + explicit WeakPtr(T* ptr, + fml::RefPtr&& flag, + const DebugThreadChecker& checker) + : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {} + T* ptr_; + fml::RefPtr flag_; + DebugThreadChecker checker_; + + // Copy/move construction/assignment supported. +}; + +// Forward declaration, so |TaskRunnerAffineWeakPtr| can friend it. +template +class TaskRunnerAffineWeakPtrFactory; + +// A weak pointer that can be used in different threads as long as +// the threads are belong to the same |TaskRunner|. +// +// It is still not in general thread safe as |WeakPtr|. +template +class TaskRunnerAffineWeakPtr { + public: + TaskRunnerAffineWeakPtr() : ptr_(nullptr) {} + + TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr& r) = default; + + template + // NOLINTNEXTLINE(google-explicit-constructor) + TaskRunnerAffineWeakPtr(const TaskRunnerAffineWeakPtr& r) + : ptr_(static_cast(r.ptr_)), flag_(r.flag_), checker_(r.checker_) {} + + TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr&& r) = default; + + template + // NOLINTNEXTLINE(google-explicit-constructor) + TaskRunnerAffineWeakPtr(TaskRunnerAffineWeakPtr&& r) + : ptr_(static_cast(r.ptr_)), + flag_(std::move(r.flag_)), + checker_(r.checker_) {} + + ~TaskRunnerAffineWeakPtr() = default; + + TaskRunnerAffineWeakPtr& operator=(const TaskRunnerAffineWeakPtr& r) = + default; + + TaskRunnerAffineWeakPtr& operator=(TaskRunnerAffineWeakPtr&& r) = + default; + + void reset() { flag_ = nullptr; } + + // The following methods should only be called on the same thread as the + // "originating" |TaskRunnerAffineWeakPtrFactory|. + + explicit operator bool() const { + CheckThreadSafety(); + return flag_ && flag_->is_valid(); + } + + T* get() const { + CheckThreadSafety(); + return *this ? ptr_ : nullptr; + } + + T& operator*() const { + CheckThreadSafety(); + FML_DCHECK(*this); + return *get(); + } + + T* operator->() const { + CheckThreadSafety(); + FML_DCHECK(*this); + return get(); + } + + protected: + void CheckThreadSafety() const { + FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); + } + + private: + template + friend class TaskRunnerAffineWeakPtr; + friend class TaskRunnerAffineWeakPtrFactory; + + explicit TaskRunnerAffineWeakPtr( + T* ptr, + fml::RefPtr&& flag, + const DebugTaskRunnerChecker& checker) + : ptr_(ptr), flag_(std::move(flag)), checker_(checker) {} + + T* ptr_; + fml::RefPtr flag_; + DebugTaskRunnerChecker checker_; +}; + +// Class that produces (valid) |WeakPtr|s. Typically, this is used as a +// member variable of |T| (preferably the last one -- see below), and |T|'s +// methods control how weak pointers to it are vended. This class is not +// thread-safe, and should only be created, destroyed and used on a single +// thread. +// +// Example: +// +// class Controller { +// public: +// Controller() : ..., weak_factory_(this) {} +// ... +// +// void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); } +// void WorkComplete(const Result& result) { ... } +// +// private: +// ... +// +// // Member variables should appear before the |WeakPtrFactory|, to ensure +// // that any |WeakPtr|s to |Controller| are invalidated before its member +// // variables' destructors are executed. +// WeakPtrFactory weak_factory_; +// }; +// +// class Worker { +// public: +// static void StartNew(const WeakPtr& controller) { +// Worker* worker = new Worker(controller); +// // Kick off asynchronous processing.... +// } +// +// private: +// Worker(const WeakPtr& controller) : controller_(controller) {} +// +// void DidCompleteAsynchronousProcessing(const Result& result) { +// if (controller_) +// controller_->WorkComplete(result); +// } +// +// WeakPtr controller_; +// }; +template +class WeakPtrFactory { + public: + explicit WeakPtrFactory(T* ptr) + : ptr_(ptr), flag_(fml::MakeRefCounted()) { + FML_DCHECK(ptr_); + } + + ~WeakPtrFactory() { + CheckThreadSafety(); + flag_->Invalidate(); + } + + // Gets a new weak pointer, which will be valid until this object is + // destroyed. + WeakPtr GetWeakPtr() const { + return WeakPtr(ptr_, flag_.Clone(), checker_); + } + + private: + // Note: See weak_ptr_internal.h for an explanation of why we store the + // pointer here, instead of in the "flag". + T* const ptr_; + fml::RefPtr flag_; + + void CheckThreadSafety() const { + FML_DCHECK_CREATION_THREAD_IS_CURRENT(checker_.checker); + } + + DebugThreadChecker checker_; + + FML_DISALLOW_COPY_AND_ASSIGN(WeakPtrFactory); +}; + +// A type of |WeakPtrFactory| that produces |TaskRunnerAffineWeakPtr| instead of +// |WeakPtr|. +template +class TaskRunnerAffineWeakPtrFactory { + public: + explicit TaskRunnerAffineWeakPtrFactory(T* ptr) + : ptr_(ptr), flag_(fml::MakeRefCounted()) { + FML_DCHECK(ptr_); + } + + ~TaskRunnerAffineWeakPtrFactory() { + CheckThreadSafety(); + flag_->Invalidate(); + } + + // Gets a new weak pointer, which will be valid until this object is + // destroyed. + TaskRunnerAffineWeakPtr GetWeakPtr() const { + return TaskRunnerAffineWeakPtr(ptr_, flag_.Clone(), checker_); + } + + private: + // Note: See weak_ptr_internal.h for an explanation of why we store the + // pointer here, instead of in the "flag". + T* const ptr_; + fml::RefPtr flag_; + + void CheckThreadSafety() const { + FML_DCHECK_TASK_RUNNER_IS_CURRENT(checker_.checker); + } + + DebugTaskRunnerChecker checker_; + + FML_DISALLOW_COPY_AND_ASSIGN(TaskRunnerAffineWeakPtrFactory); +}; + +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_WEAK_PTR_H_ diff --git a/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.cc b/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.cc new file mode 100644 index 0000000000000000000000000000000000000000..02e73afa590c92465696b04358b2261378b1c167 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.cc @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/memory/weak_ptr_internal.h" + +#include "flutter/fml/logging.h" + +namespace fml { +namespace internal { + +WeakPtrFlag::WeakPtrFlag() : is_valid_(true) {} + +WeakPtrFlag::~WeakPtrFlag() { + // Should be invalidated before destruction. + FML_DCHECK(!is_valid_); +} + +void WeakPtrFlag::Invalidate() { + // Invalidation should happen exactly once. + FML_DCHECK(is_valid_); + is_valid_ = false; +} + +} // namespace internal +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.h b/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..d94ce7c6fa588a39ce625b612b9bb4f7780e2531 --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/weak_ptr_internal.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_MEMORY_WEAK_PTR_INTERNAL_H_ +#define FLUTTER_FML_MEMORY_WEAK_PTR_INTERNAL_H_ + +#include "flutter/fml/macros.h" +#include "flutter/fml/memory/ref_counted.h" + +namespace fml { +namespace internal { + +// |WeakPtr|s have a reference to a |WeakPtrFlag| to determine whether they +// are valid (non-null) or not. We do not store a |T*| in this object since +// there may also be |WeakPtr|s to the same object, where |U| is a superclass +// of |T|. +// +// This class in not thread-safe, though references may be released on any +// thread (allowing weak pointers to be destroyed/reset/reassigned on any +// thread). +class WeakPtrFlag : public fml::RefCountedThreadSafe { + public: + WeakPtrFlag(); + + ~WeakPtrFlag(); + + bool is_valid() const { return is_valid_; } + + void Invalidate(); + + private: + bool is_valid_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(WeakPtrFlag); +}; + +} // namespace internal +} // namespace fml + +#endif // FLUTTER_FML_MEMORY_WEAK_PTR_INTERNAL_H_ diff --git a/flutter/engine/src/flutter/fml/memory/weak_ptr_unittest.cc b/flutter/engine/src/flutter/fml/memory/weak_ptr_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d995ec993cfb9ca217a626d4fa8d2bec72b0bd3f --- /dev/null +++ b/flutter/engine/src/flutter/fml/memory/weak_ptr_unittest.cc @@ -0,0 +1,241 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define FML_USED_ON_EMBEDDER + +#include "flutter/fml/memory/weak_ptr.h" + +#include +#include + +#include "flutter/fml/message_loop.h" +#include "flutter/fml/raster_thread_merger.h" +#include "flutter/fml/synchronization/count_down_latch.h" +#include "gtest/gtest.h" + +namespace fml { +namespace { + +TEST(WeakPtrTest, Basic) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + EXPECT_EQ(&data, ptr.get()); +} + +TEST(WeakPtrTest, CopyConstruction) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + const WeakPtr& ptr2(ptr); + EXPECT_EQ(&data, ptr.get()); + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, MoveConstruction) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2(std::move(ptr)); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_EQ(nullptr, ptr.get()); // NOLINT + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, CopyAssignment) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2; + EXPECT_EQ(nullptr, ptr2.get()); + ptr2 = ptr; + EXPECT_EQ(&data, ptr.get()); + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, MoveAssignment) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2; + EXPECT_EQ(nullptr, ptr2.get()); + ptr2 = std::move(ptr); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_EQ(nullptr, ptr.get()); // NOLINT + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, Testable) { + int data = 0; + WeakPtrFactory factory(&data); + WeakPtr ptr; + EXPECT_EQ(nullptr, ptr.get()); + EXPECT_FALSE(ptr); + ptr = factory.GetWeakPtr(); + EXPECT_EQ(&data, ptr.get()); + EXPECT_TRUE(ptr); +} + +TEST(WeakPtrTest, OutOfScope) { + WeakPtr ptr; + EXPECT_EQ(nullptr, ptr.get()); + { + int data = 0; + WeakPtrFactory factory(&data); + ptr = factory.GetWeakPtr(); + } + EXPECT_EQ(nullptr, ptr.get()); +} + +TEST(WeakPtrTest, Multiple) { + WeakPtr a; + WeakPtr b; + { + int data = 0; + WeakPtrFactory factory(&data); + a = factory.GetWeakPtr(); + b = factory.GetWeakPtr(); + EXPECT_EQ(&data, a.get()); + EXPECT_EQ(&data, b.get()); + } + EXPECT_EQ(nullptr, a.get()); + EXPECT_EQ(nullptr, b.get()); +} + +TEST(WeakPtrTest, MultipleStaged) { + WeakPtr a; + { + int data = 0; + WeakPtrFactory factory(&data); + a = factory.GetWeakPtr(); + { WeakPtr b = factory.GetWeakPtr(); } + EXPECT_NE(a.get(), nullptr); + } + EXPECT_EQ(nullptr, a.get()); +} + +struct Base { + double member = 0.; +}; +struct Derived : public Base {}; + +TEST(WeakPtrTest, Dereference) { + Base data; + data.member = 123456.; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + EXPECT_EQ(&data, ptr.get()); + EXPECT_EQ(data.member, (*ptr).member); + EXPECT_EQ(data.member, ptr->member); +} + +TEST(WeakPtrTest, UpcastCopyConstruction) { + Derived data; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2(ptr); + EXPECT_EQ(&data, ptr.get()); + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, UpcastMoveConstruction) { + Derived data; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2(std::move(ptr)); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_EQ(nullptr, ptr.get()); // NOLINT + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, UpcastCopyAssignment) { + Derived data; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2; + EXPECT_EQ(nullptr, ptr2.get()); + ptr2 = ptr; + EXPECT_EQ(&data, ptr.get()); + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(WeakPtrTest, UpcastMoveAssignment) { + Derived data; + WeakPtrFactory factory(&data); + WeakPtr ptr = factory.GetWeakPtr(); + WeakPtr ptr2; + EXPECT_EQ(nullptr, ptr2.get()); + ptr2 = std::move(ptr); + // The clang linter flags the method called on the moved-from reference, but + // this is testing the move implementation, so it is marked NOLINT. + EXPECT_EQ(nullptr, ptr.get()); // NOLINT + EXPECT_EQ(&data, ptr2.get()); +} + +TEST(TaskRunnerAffineWeakPtrTest, ShouldNotCrashIfRunningOnTheSameTaskRunner) { + fml::MessageLoop* loop1 = nullptr; + fml::AutoResetWaitableEvent latch1; + fml::AutoResetWaitableEvent term1; + std::thread thread1([&loop1, &latch1, &term1]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + loop1 = &fml::MessageLoop::GetCurrent(); + latch1.Signal(); + term1.Wait(); + }); + + fml::MessageLoop* loop2 = nullptr; + fml::AutoResetWaitableEvent latch2; + fml::AutoResetWaitableEvent term2; + fml::AutoResetWaitableEvent loop2_task_finish_latch; + fml::AutoResetWaitableEvent loop2_task_start_latch; + std::thread thread2([&loop2, &latch2, &term2, &loop2_task_finish_latch, + &loop2_task_start_latch]() { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + int data = 0; + TaskRunnerAffineWeakPtrFactory factory(&data); + loop2 = &fml::MessageLoop::GetCurrent(); + + loop2->GetTaskRunner()->PostTask([&]() { + latch2.Signal(); + loop2_task_start_latch.Wait(); + TaskRunnerAffineWeakPtr ptr = factory.GetWeakPtr(); + EXPECT_EQ(*ptr, data); + loop2_task_finish_latch.Signal(); + }); + loop2->Run(); + term2.Wait(); + }); + + latch1.Wait(); + latch2.Wait(); + fml::TaskQueueId qid1 = loop1->GetTaskRunner()->GetTaskQueueId(); + fml::TaskQueueId qid2 = loop2->GetTaskRunner()->GetTaskQueueId(); + const auto raster_thread_merger = + fml::MakeRefCounted(qid1, qid2); + const size_t kNumFramesMerged = 5; + + raster_thread_merger->MergeWithLease(kNumFramesMerged); + + loop2_task_start_latch.Signal(); + loop2_task_finish_latch.Wait(); + + for (size_t i = 0; i < kNumFramesMerged; i++) { + ASSERT_TRUE(raster_thread_merger->IsMerged()); + raster_thread_merger->DecrementLease(); + } + + ASSERT_FALSE(raster_thread_merger->IsMerged()); + loop2->Terminate(); + + term1.Signal(); + term2.Signal(); + thread1.join(); + thread2.join(); +} + +} // namespace +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/synchronization/atomic_object.h b/flutter/engine/src/flutter/fml/synchronization/atomic_object.h new file mode 100644 index 0000000000000000000000000000000000000000..c5c25cb27cee55f30220f6ae0a02263b03f13204 --- /dev/null +++ b/flutter/engine/src/flutter/fml/synchronization/atomic_object.h @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_ +#define FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_ + +#include + +namespace fml { + +// A wrapper for an object instance that can be read or written atomically. +template +class AtomicObject { + public: + AtomicObject() = default; + explicit AtomicObject(T object) : object_(object) {} + + T Load() const { + std::scoped_lock lock(mutex_); + return object_; + } + + void Store(const T& object) { + std::scoped_lock lock(mutex_); + object_ = object; + } + + private: + mutable std::mutex mutex_; + T object_; +}; + +} // namespace fml + +#endif // FLUTTER_FML_SYNCHRONIZATION_ATOMIC_OBJECT_H_ diff --git a/flutter/engine/src/flutter/fml/synchronization/count_down_latch.cc b/flutter/engine/src/flutter/fml/synchronization/count_down_latch.cc new file mode 100644 index 0000000000000000000000000000000000000000..6273eacb6ad54b294e9e12a4faea23735b5cd71b --- /dev/null +++ b/flutter/engine/src/flutter/fml/synchronization/count_down_latch.cc @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/count_down_latch.h" + +#include "flutter/fml/logging.h" + +namespace fml { + +CountDownLatch::CountDownLatch(size_t count) : count_(count) { + if (count_ == 0) { + waitable_event_.Signal(); + } +} + +CountDownLatch::~CountDownLatch() = default; + +void CountDownLatch::Wait() { + waitable_event_.Wait(); +} + +void CountDownLatch::CountDown() { + if (--count_ == 0) { + waitable_event_.Signal(); + } +} + +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/synchronization/count_down_latch.h b/flutter/engine/src/flutter/fml/synchronization/count_down_latch.h new file mode 100644 index 0000000000000000000000000000000000000000..314db8d6e0c54a6231b6c7ad2dad27d66fa077cd --- /dev/null +++ b/flutter/engine/src/flutter/fml/synchronization/count_down_latch.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_ +#define FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_ + +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/synchronization/waitable_event.h" + +namespace fml { + +class CountDownLatch { + public: + explicit CountDownLatch(size_t count); + + ~CountDownLatch(); + + void Wait(); + + void CountDown(); + + private: + std::atomic_size_t count_; + ManualResetWaitableEvent waitable_event_; + + FML_DISALLOW_COPY_AND_ASSIGN(CountDownLatch); +}; + +} // namespace fml + +#endif // FLUTTER_FML_SYNCHRONIZATION_COUNT_DOWN_LATCH_H_ diff --git a/flutter/engine/src/flutter/fml/synchronization/count_down_latch_unittests.cc b/flutter/engine/src/flutter/fml/synchronization/count_down_latch_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..79b969a4e4afe0d289001c3f8ec07bb0fcea1c82 --- /dev/null +++ b/flutter/engine/src/flutter/fml/synchronization/count_down_latch_unittests.cc @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/count_down_latch.h" + +#include +#include + +#include "flutter/fml/build_config.h" +#include "flutter/fml/thread.h" +#include "flutter/testing/testing.h" + +namespace fml { + +TEST(CountDownLatchTest, CanWaitOnZero) { + CountDownLatch latch(0); + latch.Wait(); +} + +TEST(CountDownLatchTest, CanWait) { + fml::Thread thread("test_thread"); + const size_t count = 100; + size_t current_count = 0; + CountDownLatch latch(count); + auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch, + ¤t_count]() { + runner->PostTask([&latch, ¤t_count]() { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + current_count++; + latch.CountDown(); + }); + }; + for (size_t i = 0; i < count; ++i) { + decrement_latch_on_thread(); + } + latch.Wait(); + ASSERT_EQ(current_count, count); +} + +} // namespace fml diff --git a/flutter/engine/src/flutter/fml/synchronization/semaphore.cc b/flutter/engine/src/flutter/fml/synchronization/semaphore.cc new file mode 100644 index 0000000000000000000000000000000000000000..9746c19f21f97ec11dd01973cf5788eb5aa85fbe --- /dev/null +++ b/flutter/engine/src/flutter/fml/synchronization/semaphore.cc @@ -0,0 +1,193 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/semaphore.h" + +#include "flutter/fml/build_config.h" +#include "flutter/fml/logging.h" + +#if FML_OS_MACOSX +#include + +namespace fml { + +class PlatformSemaphore { + public: + explicit PlatformSemaphore(uint32_t count) + : sem_(dispatch_semaphore_create(count)), initial_(count) {} + + ~PlatformSemaphore() { + for (uint32_t i = 0; i < initial_; ++i) { + Signal(); + } + if (sem_ != nullptr) { + dispatch_release(reinterpret_cast(sem_)); + sem_ = nullptr; + } + } + + bool IsValid() const { return sem_ != nullptr; } + + bool Wait() { + if (sem_ == nullptr) { + return false; + } + return dispatch_semaphore_wait(sem_, DISPATCH_TIME_FOREVER) == 0; + } + + bool TryWait() { + if (sem_ == nullptr) { + return false; + } + + return dispatch_semaphore_wait(sem_, DISPATCH_TIME_NOW) == 0; + } + + void Signal() { + if (sem_ != nullptr) { + dispatch_semaphore_signal(sem_); + } + } + + private: + dispatch_semaphore_t sem_; + const uint32_t initial_; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore); +}; + +} // namespace fml + +#elif FML_OS_WIN +#include + +namespace fml { + +class PlatformSemaphore { + public: + explicit PlatformSemaphore(uint32_t count) + : _sem(CreateSemaphore(NULL, count, LONG_MAX, NULL)) {} + + ~PlatformSemaphore() { + if (_sem != nullptr) { + CloseHandle(_sem); + _sem = nullptr; + } + } + + bool IsValid() const { return _sem != nullptr; } + + bool Wait() { + if (_sem == nullptr) { + return false; + } + + return WaitForSingleObject(_sem, INFINITE) == WAIT_OBJECT_0; + } + + bool TryWait() { + if (_sem == nullptr) { + return false; + } + + return WaitForSingleObject(_sem, 0) == WAIT_OBJECT_0; + } + + void Signal() { + if (_sem != nullptr) { + ReleaseSemaphore(_sem, 1, NULL); + } + } + + private: + HANDLE _sem; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore); +}; + +} // namespace fml + +#else +#include +#include "flutter/fml/eintr_wrapper.h" + +namespace fml { + +class PlatformSemaphore { + public: + explicit PlatformSemaphore(uint32_t count) + : valid_(::sem_init(&sem_, 0 /* not shared */, count) == 0) {} + + ~PlatformSemaphore() { + if (valid_) { + int result = ::sem_destroy(&sem_); + (void)result; + // Can only be EINVAL which should not be possible since we checked for + // validity. + FML_DCHECK(result == 0); + } + } + + bool IsValid() const { return valid_; } + + bool Wait() { + if (!valid_) { + return false; + } + + return FML_HANDLE_EINTR(::sem_wait(&sem_)) == 0; + } + + bool TryWait() { + if (!valid_) { + return false; + } + + return FML_HANDLE_EINTR(::sem_trywait(&sem_)) == 0; + } + + void Signal() { + if (!valid_) { + return; + } + + ::sem_post(&sem_); + + return; + } + + private: + bool valid_; + sem_t sem_; + + FML_DISALLOW_COPY_AND_ASSIGN(PlatformSemaphore); +}; + +} // namespace fml + +#endif + +namespace fml { + +Semaphore::Semaphore(uint32_t count) : impl_(new PlatformSemaphore(count)) {} + +Semaphore::~Semaphore() = default; + +bool Semaphore::IsValid() const { + return impl_->IsValid(); +} + +bool Semaphore::Wait() { + return impl_->Wait(); +} + +bool Semaphore::TryWait() { + return impl_->TryWait(); +} + +void Semaphore::Signal() { + return impl_->Signal(); +} + +} // namespace fml diff --git a/flutter/engine/src/flutter/impeller/base/BUILD.gn b/flutter/engine/src/flutter/impeller/base/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1e33823d78fc3608d86a2c2024e66e963c365de3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../tools/impeller.gni") + +impeller_component("base") { + sources = [ + "allocation.cc", + "allocation.h", + "allocation_size.cc", + "allocation_size.h", + "backend_cast.h", + "comparable.cc", + "comparable.h", + "config.h", + "flags.h", + "mask.h", + "promise.cc", + "promise.h", + "strings.cc", + "strings.h", + "thread.cc", + "thread.h", + "thread_safety.cc", + "thread_safety.h", + "timing.h", + "validation.cc", + "validation.h", + "version.cc", + "version.h", + ] + + deps = [ "//flutter/fml" ] +} + +impeller_component("base_unittests") { + testonly = true + sources = [ + "allocation_size_unittests.cc", + "base_unittests.cc", + ] + deps = [ + ":base", + "//flutter/testing", + ] +} diff --git a/flutter/engine/src/flutter/impeller/base/README.md b/flutter/engine/src/flutter/impeller/base/README.md new file mode 100644 index 0000000000000000000000000000000000000000..08814d637966f6864f2ee79fef296bc0a86d2cc6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/README.md @@ -0,0 +1,4 @@ +# The Impeller Base Library + +Contains a number of utilities that should probably go in the base library in +the buildroot but whose use is not extensive enough to warrant a move yet. diff --git a/flutter/engine/src/flutter/impeller/base/allocation.cc b/flutter/engine/src/flutter/impeller/base/allocation.cc new file mode 100644 index 0000000000000000000000000000000000000000..88241f7994f540d7821dcecb1524cbdc0496b138 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/allocation.cc @@ -0,0 +1,118 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/allocation.h" + +#include +#include + +#include "impeller/base/validation.h" + +namespace impeller { + +Allocation::Allocation() = default; + +Allocation::~Allocation() { + ::free(buffer_); +} + +uint8_t* Allocation::GetBuffer() const { + return buffer_; +} + +Bytes Allocation::GetLength() const { + return length_; +} + +Bytes Allocation::GetReservedLength() const { + return reserved_; +} + +bool Allocation::Truncate(Bytes length, bool npot) { + const auto reserved = npot ? ReserveNPOT(length) : Reserve(length); + if (!reserved) { + return false; + } + length_ = length; + return true; +} + +uint32_t Allocation::NextPowerOfTwoSize(uint32_t x) { + if (x == 0) { + return 1; + } + + --x; + + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + + return x + 1; +} + +bool Allocation::ReserveNPOT(Bytes reserved) { + // Reserve at least one page of data. + reserved = std::max(Bytes{4096u}, reserved); + return Reserve(Bytes{NextPowerOfTwoSize(reserved.GetByteSize())}); +} + +bool Allocation::Reserve(Bytes reserved) { + if (reserved <= reserved_) { + return true; + } + + auto new_allocation = ::realloc(buffer_, reserved.GetByteSize()); + if (!new_allocation) { + // If new length is zero, a minimum non-zero sized allocation is returned. + // So this check will not trip and this routine will indicate success as + // expected. + VALIDATION_LOG << "Allocation failed. Out of host memory."; + return false; + } + + buffer_ = static_cast(new_allocation); + reserved_ = reserved; + + return true; +} + +std::shared_ptr CreateMappingWithCopy(const uint8_t* contents, + Bytes length) { + if (contents == nullptr) { + return nullptr; + } + + auto allocation = std::make_shared(); + if (!allocation->Truncate(length)) { + return nullptr; + } + + std::memmove(allocation->GetBuffer(), contents, length.GetByteSize()); + + return CreateMappingFromAllocation(allocation); +} + +std::shared_ptr CreateMappingFromAllocation( + const std::shared_ptr& allocation) { + if (!allocation) { + return nullptr; + } + return std::make_shared( + reinterpret_cast(allocation->GetBuffer()), // + allocation->GetLength().GetByteSize(), // + [allocation](auto, auto) {} // + ); +} + +std::shared_ptr CreateMappingWithString(std::string string) { + auto buffer = std::make_shared(std::move(string)); + return std::make_unique( + reinterpret_cast(buffer->c_str()), buffer->length(), + [buffer](auto, auto) {}); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/allocation.h b/flutter/engine/src/flutter/impeller/base/allocation.h new file mode 100644 index 0000000000000000000000000000000000000000..ae2337cc4d5de4b9e419fc28e30fd137cb28f035 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/allocation.h @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_ALLOCATION_H_ +#define FLUTTER_IMPELLER_BASE_ALLOCATION_H_ + +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/allocation_size.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Describes an allocation on the heap. +/// +/// Managing allocations through this utility makes it harder to +/// miss allocation failures. +/// +class Allocation { + public: + //---------------------------------------------------------------------------- + /// @brief Constructs a new zero-sized allocation. + /// + Allocation(); + + //---------------------------------------------------------------------------- + /// @brief Destroys the allocation. + /// + ~Allocation(); + + //---------------------------------------------------------------------------- + /// @brief Gets the pointer to the start of the allocation. + /// + /// This pointer is only valid till the next call to `Truncate`. + /// + /// @return The pointer to the start of the allocation. + /// + uint8_t* GetBuffer() const; + + //---------------------------------------------------------------------------- + /// @brief Gets the length of the allocation. + /// + /// @return The length. + /// + Bytes GetLength() const; + + //---------------------------------------------------------------------------- + /// @brief Gets the reserved length of the allocation. Calls to truncate + /// may be ignored till the length exceeds the reserved length. + /// + /// @return The reserved length. + /// + Bytes GetReservedLength() const; + + //---------------------------------------------------------------------------- + /// @brief Resize the underlying allocation to at least given number of + /// bytes. + /// + /// In case of failure, false is returned and the underlying + /// allocation remains unchanged. + /// + /// @warning Pointers to buffers obtained via previous calls to `GetBuffer` + /// may become invalid at this point. + /// + /// @param[in] length The length. + /// @param[in] npot Whether to round up the length to the next power of + /// two. + /// + /// @return If the underlying allocation was resized to the new size. + /// + [[nodiscard]] bool Truncate(Bytes length, bool npot = true); + + //---------------------------------------------------------------------------- + /// @brief Gets the next power of two size. + /// + /// @param[in] x The size. + /// + /// @return The next power of two of x. + /// + static uint32_t NextPowerOfTwoSize(uint32_t x); + + private: + uint8_t* buffer_ = nullptr; + Bytes length_; + Bytes reserved_; + + [[nodiscard]] bool Reserve(Bytes reserved); + + [[nodiscard]] bool ReserveNPOT(Bytes reserved); + + Allocation(const Allocation&) = delete; + + Allocation& operator=(const Allocation&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief Creates a mapping with copy of the bytes. +/// +/// @param[in] contents The contents +/// @param[in] length The length +/// +/// @return The new mapping or nullptr if the copy could not be performed. +/// +std::shared_ptr CreateMappingWithCopy(const uint8_t* contents, + Bytes length); + +//------------------------------------------------------------------------------ +/// @brief Creates a mapping from allocation. +/// +/// No data copy occurs. Only a reference to the underlying +/// allocation is bumped up. +/// +/// Changes to the underlying allocation will not be reflected in +/// the mapping and must not change. +/// +/// @param[in] allocation The allocation. +/// +/// @return A new mapping or nullptr if the argument allocation was invalid. +/// +std::shared_ptr CreateMappingFromAllocation( + const std::shared_ptr& allocation); + +//------------------------------------------------------------------------------ +/// @brief Creates a mapping with string data. +/// +/// Only a reference to the underlying string is bumped up and the +/// string is not copied. +/// +/// @param[in] string The string +/// +/// @return A new mapping or nullptr in case of allocation failures. +/// +std::shared_ptr CreateMappingWithString( + std::shared_ptr string); + +//------------------------------------------------------------------------------ +/// @brief Creates a mapping with string data. +/// +/// The string is copied. +/// +/// @param[in] string The string +/// +/// @return A new mapping or nullptr in case of allocation failures. +/// +std::shared_ptr CreateMappingWithString(std::string string); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_ALLOCATION_H_ diff --git a/flutter/engine/src/flutter/impeller/base/allocation_size.cc b/flutter/engine/src/flutter/impeller/base/allocation_size.cc new file mode 100644 index 0000000000000000000000000000000000000000..f79ae819a12d60dc6a6518ff4422cd722c360252 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/allocation_size.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/allocation_size.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/allocation_size.h b/flutter/engine/src/flutter/impeller/base/allocation_size.h new file mode 100644 index 0000000000000000000000000000000000000000..534a0458dc0b7d55c7e3706ff7f6c9d52983b9d4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/allocation_size.h @@ -0,0 +1,202 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_ALLOCATION_SIZE_H_ +#define FLUTTER_IMPELLER_BASE_ALLOCATION_SIZE_H_ + +#include +#include +#include +#include + +namespace impeller { + +enum class FromBytesTag { kFromBytes }; + +//------------------------------------------------------------------------------ +/// @brief Represents the size of an allocation in different units. +/// +/// Refer to the typedefs for Bytes, KiloBytes, MegaBytes, +/// Gigabytes, KibiBytes, MebiBytes, and GibiBytes below when using. +/// +/// Storage and all operations are always on unsigned units of +/// bytes. +/// +/// @tparam Period The number of bytes in 1 unit of the allocation size. +/// +template +class AllocationSize { + public: + //---------------------------------------------------------------------------- + /// @brief Create a zero allocation size. + /// + constexpr AllocationSize() = default; + + //---------------------------------------------------------------------------- + /// @brief Create an allocation size with the amount in the `Period` + /// number of bytes. + /// + /// @param[in] size The size in `Period` number of bytes. + /// + template >> + explicit constexpr AllocationSize(T size) + : bytes_(std::ceil(size) * Period) {} + + //---------------------------------------------------------------------------- + /// @brief Create an allocation size from another instance with a + /// different period. + /// + /// @param[in] other The other allocation size. + /// + /// @tparam OtherPeriod The period of the other allocation. + /// + template + explicit constexpr AllocationSize(const AllocationSize& other) + : bytes_(other.GetByteSize()) {} + + //---------------------------------------------------------------------------- + /// @brief Create an allocation size with the amount directly specified + /// in bytes. + /// + /// @param[in] byte_size The byte size. + /// @param[in] tag A tag for this constructor. + /// + constexpr AllocationSize(uint64_t byte_size, FromBytesTag) + : bytes_(byte_size) {} + + //---------------------------------------------------------------------------- + /// @return The byte size. + /// + constexpr uint64_t GetByteSize() const { return bytes_; } + + //---------------------------------------------------------------------------- + /// @return The number of `Periods` of bytes. + /// + constexpr double GetSize() const { + return GetByteSize() / static_cast(Period); + } + + //---------------------------------------------------------------------------- + /// @brief Convert the allocation size from one unit to another. + /// + /// Conversions are non-truncating. + /// + /// @tparam AllocationSize The allocation size to convert to. + /// + /// @return The new allocation size. + /// + template + constexpr AllocationSize ConvertTo() { + return AllocationSize{GetByteSize(), FromBytesTag::kFromBytes}; + } + + // The following relational operators can be replaced with a defaulted + // spaceship operator post C++20. + + constexpr bool operator<(const AllocationSize& other) const { + return bytes_ < other.bytes_; + } + + constexpr bool operator>(const AllocationSize& other) const { + return bytes_ > other.bytes_; + } + + constexpr bool operator>=(const AllocationSize& other) const { + return bytes_ >= other.bytes_; + } + + constexpr bool operator<=(const AllocationSize& other) const { + return bytes_ <= other.bytes_; + } + + constexpr bool operator==(const AllocationSize& other) const { + return bytes_ == other.bytes_; + } + + constexpr bool operator!=(const AllocationSize& other) const { + return bytes_ != other.bytes_; + } + + // Explicit casts. + + explicit constexpr operator bool() const { return bytes_ != 0u; } + + // Arithmetic operators (overflows are caller error). + + constexpr AllocationSize operator+(const AllocationSize& other) const { + return AllocationSize(bytes_ + other.GetByteSize(), + FromBytesTag::kFromBytes); + } + + constexpr AllocationSize operator-(const AllocationSize& other) const { + return AllocationSize(bytes_ - other.GetByteSize(), + FromBytesTag::kFromBytes); + } + + constexpr AllocationSize& operator+=(const AllocationSize& other) { + bytes_ += other.GetByteSize(); + return *this; + } + + constexpr AllocationSize& operator-=(const AllocationSize& other) { + bytes_ -= other.GetByteSize(); + return *this; + } + + private: + uint64_t bytes_ = {}; +}; + +using Bytes = AllocationSize<1u>; + +using KiloBytes = AllocationSize<1'000u>; +using MegaBytes = AllocationSize<1'000u * 1'000u>; +using GigaBytes = AllocationSize<1'000u * 1'000u * 1'000u>; + +using KibiBytes = AllocationSize<1'024u>; +using MebiBytes = AllocationSize<1'024u * 1'024u>; +using GibiBytes = AllocationSize<1'024u * 1'024u * 1'024u>; + +inline namespace allocation_size_literals { + +// NOLINTNEXTLINE +constexpr Bytes operator"" _bytes(unsigned long long int size) { + return Bytes{size}; +} + +// NOLINTNEXTLINE +constexpr KiloBytes operator"" _kb(unsigned long long int size) { + return KiloBytes{size}; +} + +// NOLINTNEXTLINE +constexpr MegaBytes operator"" _mb(unsigned long long int size) { + return MegaBytes{size}; +} + +// NOLINTNEXTLINE +constexpr GigaBytes operator"" _gb(unsigned long long int size) { + return GigaBytes{size}; +} + +// NOLINTNEXTLINE +constexpr KibiBytes operator"" _kib(unsigned long long int size) { + return KibiBytes{size}; +} + +// NOLINTNEXTLINE +constexpr MebiBytes operator"" _mib(unsigned long long int size) { + return MebiBytes{size}; +} + +// NOLINTNEXTLINE +constexpr GibiBytes operator"" _gib(unsigned long long int size) { + return GibiBytes{size}; +} + +} // namespace allocation_size_literals + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_ALLOCATION_SIZE_H_ diff --git a/flutter/engine/src/flutter/impeller/base/allocation_size_unittests.cc b/flutter/engine/src/flutter/impeller/base/allocation_size_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..dddae1eb084f66ec0a019039e766d84688043dfa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/allocation_size_unittests.cc @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/base/allocation_size.h" + +namespace impeller::testing { + +TEST(AllocationSizeTest, CanCreateTypedAllocations) { + auto bytes = Bytes{1024}; + ASSERT_EQ(bytes.GetByteSize(), 1024u); + + auto kilobytes = KiloBytes{5}; + ASSERT_EQ(kilobytes.GetByteSize(), 5u * 1e3); + + auto megabytes = MegaBytes{5}; + ASSERT_EQ(megabytes.GetByteSize(), 5u * 1e6); + + auto gigabytes = GigaBytes{5}; + ASSERT_EQ(gigabytes.GetByteSize(), 5u * 1e9); + + auto kibibytes = KibiBytes{1}; + ASSERT_EQ(kibibytes.GetByteSize(), 1024u); + + auto mebibytes = MebiBytes{1}; + ASSERT_EQ(mebibytes.GetByteSize(), 1048576u); + + auto gigibytes = GibiBytes{1}; + ASSERT_EQ(gigibytes.GetByteSize(), 1073741824u); +} + +TEST(AllocationSizeTest, CanCreateTypedAllocationsWithLiterals) { + using namespace allocation_size_literals; + ASSERT_EQ((1024_bytes).GetByteSize(), 1024u); + ASSERT_EQ((5_kb).GetByteSize(), 5u * 1e3); + ASSERT_EQ((5_mb).GetByteSize(), 5u * 1e6); + ASSERT_EQ((5_gb).GetByteSize(), 5u * 1e9); + ASSERT_EQ((1_kib).GetByteSize(), 1024u); + ASSERT_EQ((1_mib).GetByteSize(), 1048576u); + ASSERT_EQ((1_gib).GetByteSize(), 1073741824u); +} + +TEST(AllocationSizeTest, CanConvert) { + using namespace allocation_size_literals; + ASSERT_EQ((5_gb).ConvertTo().GetSize(), 5000u); +} + +TEST(AllocationSizeTest, ConversionsAreNonTruncating) { + using namespace allocation_size_literals; + ASSERT_DOUBLE_EQ((1500_bytes).ConvertTo().GetSize(), 1.5); + ASSERT_EQ((1500_bytes).ConvertTo().GetByteSize(), 1500u); +} + +TEST(AllocationSizeTest, CanGetFloatValues) { + using namespace allocation_size_literals; + ASSERT_DOUBLE_EQ((1500_bytes).ConvertTo().GetSize(), 1.5); +} + +TEST(AllocationSizeTest, RelationalOperatorsAreFunctional) { + using namespace allocation_size_literals; + + auto a = 1500_bytes; + auto b = 2500_bytes; + auto c = 0_bytes; + + ASSERT_TRUE(a != b); + ASSERT_FALSE(a == b); + ASSERT_TRUE(b > a); + ASSERT_TRUE(b >= a); + ASSERT_TRUE(a < b); + ASSERT_TRUE(a <= b); + ASSERT_TRUE(a); + ASSERT_FALSE(c); +} + +TEST(AllocationSizeTest, CanCast) { + using namespace allocation_size_literals; + { + auto a = KiloBytes{1500_bytes}; + ASSERT_DOUBLE_EQ(a.GetSize(), 1.5); + } + { + auto a = KiloBytes{Bytes{1500}}; + ASSERT_DOUBLE_EQ(a.GetSize(), 1.5); + } + + ASSERT_DOUBLE_EQ(MebiBytes{Bytes{4194304}}.GetSize(), 4); +} + +TEST(AllocationSizeTest, CanPerformSimpleArithmetic) { + using namespace allocation_size_literals; + { + auto a = 100_bytes; + auto b = 200_bytes; + ASSERT_EQ((a + b).GetByteSize(), 300u); + } + { + auto a = 100_bytes; + a += 200_bytes; + ASSERT_EQ(a.GetByteSize(), 300u); + } + { + auto a = 100_bytes; + a -= 50_bytes; + ASSERT_EQ(a.GetByteSize(), 50u); + } +} + +TEST(AllocationSizeTest, CanConstructWithArith) { + { + Bytes a(1u); + ASSERT_EQ(a.GetByteSize(), 1u); + } + { + Bytes a(1.5); + ASSERT_EQ(a.GetByteSize(), 2u); + } + { + Bytes a(1.5f); + ASSERT_EQ(a.GetByteSize(), 2u); + } +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/base/backend_cast.h b/flutter/engine/src/flutter/impeller/base/backend_cast.h new file mode 100644 index 0000000000000000000000000000000000000000..a67e4e3dd866355914ec3dee046fdff38c4aab52 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/backend_cast.h @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_BACKEND_CAST_H_ +#define FLUTTER_IMPELLER_BASE_BACKEND_CAST_H_ + +namespace impeller { + +template +class BackendCast { + public: + static Sub& Cast(Base& base) { return reinterpret_cast(base); } + + static const Sub& Cast(const Base& base) { + return reinterpret_cast(base); + } + + static Sub* Cast(Base* base) { return reinterpret_cast(base); } + + static const Sub* Cast(const Base* base) { + return reinterpret_cast(base); + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_BACKEND_CAST_H_ diff --git a/flutter/engine/src/flutter/impeller/base/base_unittests.cc b/flutter/engine/src/flutter/impeller/base/base_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..7c2d8365e67081e27601b9da6f1c32ad4f023a0a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/base_unittests.cc @@ -0,0 +1,449 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/base/mask.h" +#include "impeller/base/promise.h" +#include "impeller/base/strings.h" +#include "impeller/base/thread.h" + +namespace impeller { + +enum class MyMaskBits : uint32_t { + kFoo = 0, + kBar = 1 << 0, + kBaz = 1 << 1, + kBang = 1 << 2, +}; + +using MyMask = Mask; + +IMPELLER_ENUM_IS_MASK(MyMaskBits); + +namespace testing { + +struct Foo { + Mutex mtx; + int a IPLR_GUARDED_BY(mtx); +}; + +struct RWFoo { + RWMutex mtx; + int a IPLR_GUARDED_BY(mtx); +}; + +TEST(ThreadTest, CanCreateMutex) { + Foo f = {}; + + // f.a = 100; <--- Static analysis error. + f.mtx.Lock(); + f.a = 100; + f.mtx.Unlock(); +} + +TEST(ThreadTest, CanCreateMutexLock) { + Foo f = {}; + + // f.a = 100; <--- Static analysis error. + auto a = Lock(f.mtx); + f.a = 100; +} + +TEST(ThreadTest, CanCreateRWMutex) { + RWFoo f = {}; + + // f.a = 100; <--- Static analysis error. + f.mtx.LockWriter(); + f.a = 100; + f.mtx.UnlockWriter(); + // int b = f.a; <--- Static analysis error. + f.mtx.LockReader(); + [[maybe_unused]] int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) + f.mtx.UnlockReader(); +} + +TEST(ThreadTest, CanCreateRWMutexLock) { + RWFoo f = {}; + + // f.a = 100; <--- Static analysis error. + { + auto write_lock = WriterLock{f.mtx}; + f.a = 100; + } + + // int b = f.a; <--- Static analysis error. + { + auto read_lock = ReaderLock(f.mtx); + [[maybe_unused]] int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) + } + + // f.mtx.UnlockReader(); <--- Static analysis error. +} + +TEST(StringsTest, CanSPrintF) { + ASSERT_EQ(SPrintF("%sx%d", "Hello", 12), "Hellox12"); + ASSERT_EQ(SPrintF(""), ""); + ASSERT_EQ(SPrintF("Hello"), "Hello"); + ASSERT_EQ(SPrintF("%sx%.2f", "Hello", 12.122222), "Hellox12.12"); +} + +struct CVTest { + Mutex mutex; + ConditionVariable cv; + uint32_t rando_ivar IPLR_GUARDED_BY(mutex) = 0; +}; + +TEST(ConditionVariableTest, WaitUntil) { + CVTest test; + // test.rando_ivar = 12; // <--- Static analysis error + for (size_t i = 0; i < 2; ++i) { + test.mutex.Lock(); // <--- Static analysis error without this. + auto result = test.cv.WaitUntil( + test.mutex, + std::chrono::high_resolution_clock::now() + + std::chrono::milliseconds{10}, + [&]() IPLR_REQUIRES(test.mutex) { + test.rando_ivar = 12; // <-- Static analysics error without the + // IPLR_REQUIRES on the pred. + return false; + }); + test.mutex.Unlock(); + ASSERT_FALSE(result); + } + Lock lock(test.mutex); // <--- Static analysis error without this. + // The predicate never returns true. So return has to be due to a non-spurious + // wake. + ASSERT_EQ(test.rando_ivar, 12u); +} + +TEST(ConditionVariableTest, WaitFor) { + CVTest test; + // test.rando_ivar = 12; // <--- Static analysis error + for (size_t i = 0; i < 2; ++i) { + test.mutex.Lock(); // <--- Static analysis error without this. + auto result = test.cv.WaitFor( + test.mutex, std::chrono::milliseconds{10}, + [&]() IPLR_REQUIRES(test.mutex) { + test.rando_ivar = 12; // <-- Static analysics error without the + // IPLR_REQUIRES on the pred. + return false; + }); + test.mutex.Unlock(); + ASSERT_FALSE(result); + } + Lock lock(test.mutex); // <--- Static analysis error without this. + // The predicate never returns true. So return has to be due to a non-spurious + // wake. + ASSERT_EQ(test.rando_ivar, 12u); +} + +TEST(ConditionVariableTest, WaitForever) { + CVTest test; + // test.rando_ivar = 12; // <--- Static analysis error + for (size_t i = 0; i < 2; ++i) { + test.mutex.Lock(); // <--- Static analysis error without this. + test.cv.Wait(test.mutex, [&]() IPLR_REQUIRES(test.mutex) { + test.rando_ivar = 12; // <-- Static analysics error without + // the IPLR_REQUIRES on the pred. + return true; + }); + test.mutex.Unlock(); + } + Lock lock(test.mutex); // <--- Static analysis error without this. + // The wake only happens when the predicate returns true. + ASSERT_EQ(test.rando_ivar, 12u); +} + +TEST(ConditionVariableTest, TestsCriticalSectionAfterWaitForUntil) { + std::vector threads; + const auto kThreadCount = 10u; + + Mutex mtx; + ConditionVariable cv; + size_t sum = 0u; + + std::condition_variable start_cv; + std::mutex start_mtx; + bool start = false; + auto start_predicate = [&start]() { return start; }; + auto thread_main = [&]() { + { + std::unique_lock start_lock(start_mtx); + start_cv.wait(start_lock, start_predicate); + } + + mtx.Lock(); + cv.WaitFor(mtx, std::chrono::milliseconds{0u}, []() { return true; }); + auto old_val = sum; + std::this_thread::sleep_for(std::chrono::milliseconds{100u}); + sum = old_val + 1u; + mtx.Unlock(); + }; + // Launch all threads. They will wait for the start CV to be signaled. + for (size_t i = 0; i < kThreadCount; i++) { + threads.emplace_back(thread_main); + } + // Notify all threads that the test may start. + { + { + std::scoped_lock start_lock(start_mtx); + start = true; + } + start_cv.notify_all(); + } + // Join all threads. + ASSERT_EQ(threads.size(), kThreadCount); + for (size_t i = 0; i < kThreadCount; i++) { + threads[i].join(); + } + ASSERT_EQ(sum, kThreadCount); +} + +TEST(ConditionVariableTest, TestsCriticalSectionAfterWait) { + std::vector threads; + const auto kThreadCount = 10u; + + Mutex mtx; + ConditionVariable cv; + size_t sum = 0u; + + std::condition_variable start_cv; + std::mutex start_mtx; + bool start = false; + auto start_predicate = [&start]() { return start; }; + auto thread_main = [&]() { + { + std::unique_lock start_lock(start_mtx); + start_cv.wait(start_lock, start_predicate); + } + + mtx.Lock(); + cv.Wait(mtx, []() { return true; }); + auto old_val = sum; + std::this_thread::sleep_for(std::chrono::milliseconds{100u}); + sum = old_val + 1u; + mtx.Unlock(); + }; + // Launch all threads. They will wait for the start CV to be signaled. + for (size_t i = 0; i < kThreadCount; i++) { + threads.emplace_back(thread_main); + } + // Notify all threads that the test may start. + { + { + std::scoped_lock start_lock(start_mtx); + start = true; + } + start_cv.notify_all(); + } + // Join all threads. + ASSERT_EQ(threads.size(), kThreadCount); + for (size_t i = 0; i < kThreadCount; i++) { + threads[i].join(); + } + ASSERT_EQ(sum, kThreadCount); +} + +TEST(BaseTest, NoExceptionPromiseValue) { + NoExceptionPromise wrapper; + std::future future = wrapper.get_future(); + wrapper.set_value(123); + ASSERT_EQ(future.get(), 123); +} + +TEST(BaseTest, NoExceptionPromiseEmpty) { + auto wrapper = std::make_shared>(); + std::future future = wrapper->get_future(); + + // Destroy the empty promise with the future still pending. Verify that the + // process does not abort while destructing the promise. + wrapper.reset(); +} + +TEST(BaseTest, CanUseTypedMasks) { + { + MyMask mask; + ASSERT_EQ(static_cast(mask), 0u); + ASSERT_FALSE(mask); + } + + { + MyMask mask(MyMaskBits::kBar); + ASSERT_EQ(static_cast(mask), 1u); + ASSERT_TRUE(mask); + } + + { + MyMask mask2(MyMaskBits::kBar); + MyMask mask(mask2); + ASSERT_EQ(static_cast(mask), 1u); + ASSERT_TRUE(mask); + } + + { + MyMask mask2(MyMaskBits::kBar); + MyMask mask(std::move(mask2)); // NOLINT + ASSERT_EQ(static_cast(mask), 1u); + ASSERT_TRUE(mask); + } + + ASSERT_LT(MyMaskBits::kBar, MyMaskBits::kBaz); + ASSERT_LE(MyMaskBits::kBar, MyMaskBits::kBaz); + ASSERT_GT(MyMaskBits::kBaz, MyMaskBits::kBar); + ASSERT_GE(MyMaskBits::kBaz, MyMaskBits::kBar); + ASSERT_EQ(MyMaskBits::kBaz, MyMaskBits::kBaz); + ASSERT_NE(MyMaskBits::kBaz, MyMaskBits::kBang); + + { + MyMask m1(MyMaskBits::kBar); + MyMask m2(MyMaskBits::kBaz); + ASSERT_EQ(static_cast(m1 & m2), 0u); + ASSERT_FALSE(m1 & m2); + } + + { + MyMask m1(MyMaskBits::kBar); + MyMask m2(MyMaskBits::kBaz); + ASSERT_EQ(static_cast(m1 | m2), ((1u << 0u) | (1u << 1u))); + ASSERT_TRUE(m1 | m2); + } + + { + MyMask m1(MyMaskBits::kBar); + MyMask m2(MyMaskBits::kBaz); + ASSERT_EQ(static_cast(m1 ^ m2), ((1u << 0u) ^ (1u << 1u))); + ASSERT_TRUE(m1 ^ m2); + } + + { + MyMask m1(MyMaskBits::kBar); + ASSERT_EQ(static_cast(~m1), (~(1u << 0u))); + ASSERT_TRUE(m1); + } + + { + MyMask m1 = MyMaskBits::kBar; + MyMask m2 = MyMaskBits::kBaz; + m2 = m1; + ASSERT_EQ(m2, MyMaskBits::kBar); + } + + { + MyMask m = MyMaskBits::kBar | MyMaskBits::kBaz; + ASSERT_TRUE(m); + } + + { + MyMask m = MyMaskBits::kBar & MyMaskBits::kBaz; + ASSERT_FALSE(m); + } + + { + MyMask m = MyMaskBits::kBar ^ MyMaskBits::kBaz; + ASSERT_TRUE(m); + } + + { + MyMask m = ~MyMaskBits::kBar; + ASSERT_TRUE(m); + } + + { + MyMask m1 = MyMaskBits::kBar; + MyMask m2 = MyMaskBits::kBaz; + m2 |= m1; + ASSERT_EQ(m1, MyMaskBits::kBar); + MyMask pred = MyMaskBits::kBar | MyMaskBits::kBaz; + ASSERT_EQ(m2, pred); + } + + { + MyMask m1 = MyMaskBits::kBar; + MyMask m2 = MyMaskBits::kBaz; + m2 &= m1; + ASSERT_EQ(m1, MyMaskBits::kBar); + MyMask pred = MyMaskBits::kBar & MyMaskBits::kBaz; + ASSERT_EQ(m2, pred); + } + + { + MyMask m1 = MyMaskBits::kBar; + MyMask m2 = MyMaskBits::kBaz; + m2 ^= m1; + ASSERT_EQ(m1, MyMaskBits::kBar); + MyMask pred = MyMaskBits::kBar ^ MyMaskBits::kBaz; + ASSERT_EQ(m2, pred); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = x | MyMaskBits::kBaz; + ASSERT_TRUE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz | x; + ASSERT_TRUE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = x & MyMaskBits::kBaz; + ASSERT_FALSE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz & x; + ASSERT_FALSE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = x ^ MyMaskBits::kBaz; + ASSERT_TRUE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz ^ x; + ASSERT_TRUE(m); + } + + { + MyMask x = MyMaskBits::kBar; + MyMask m = ~x; + ASSERT_TRUE(m); + } + + { + MyMaskBits x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz; + ASSERT_TRUE(x < m); + ASSERT_TRUE(x <= m); + } + + { + MyMaskBits x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz; + ASSERT_FALSE(x == m); + } + + { + MyMaskBits x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz; + ASSERT_TRUE(x != m); + } + + { + MyMaskBits x = MyMaskBits::kBar; + MyMask m = MyMaskBits::kBaz; + ASSERT_FALSE(x > m); + ASSERT_FALSE(x >= m); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/comparable.cc b/flutter/engine/src/flutter/impeller/base/comparable.cc new file mode 100644 index 0000000000000000000000000000000000000000..58585c393fbd757fc4060626d75227894b5a5bb2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/comparable.cc @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/comparable.h" + +#include + +namespace impeller { + +static std::atomic_size_t sLastID; +UniqueID::UniqueID() : id(++sLastID) {} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/comparable.h b/flutter/engine/src/flutter/impeller/base/comparable.h new file mode 100644 index 0000000000000000000000000000000000000000..2f0c6e1e6513f6bca17552938b18aeea95e3ba2f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/comparable.h @@ -0,0 +1,114 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_COMPARABLE_H_ +#define FLUTTER_IMPELLER_BASE_COMPARABLE_H_ + +#include +#include +#include +#include +#include + +namespace impeller { + +struct UniqueID { + size_t id; + + UniqueID(); + + constexpr bool operator==(const UniqueID& other) const { + return id == other.id; + } +}; + +class ComparableBase {}; + +template +class Comparable : ComparableBase { + public: + virtual std::size_t GetHash() const = 0; + + virtual bool IsEqual(const Type& other) const = 0; +}; + +template < + class ComparableType, + class = std::enable_if_t>> +struct ComparableHash { + std::size_t operator()(const ComparableType& object) const { + return object.GetHash(); + } +}; + +template < + class ComparableType, + class = std::enable_if_t>> +struct ComparableEqual { + bool operator()(const ComparableType& lhs, const ComparableType& rhs) const { + return lhs.IsEqual(rhs); + } +}; + +template < + class ComparableType, + class = std::enable_if_t>> +bool DeepComparePointer(const std::shared_ptr& lhs, + const std::shared_ptr& rhs) { + if (lhs == rhs) { + return true; + } + + if (lhs && rhs) { + return lhs->IsEqual(*rhs); + } + + return false; +} + +template < + class Key, + class ComparableType, + class = std::enable_if_t>> +bool DeepCompareMap(const std::map>& lhs, + const std::map>& rhs) { + if (lhs.size() != rhs.size()) { + return false; + } + + for (auto i = lhs.begin(), j = rhs.begin(); i != lhs.end(); i++, j++) { + if (i->first != j->first) { + return false; + } + + if (!DeepComparePointer(i->second, j->second)) { + return false; + } + } + + return true; +} + +} // namespace impeller + +namespace std { + +template <> +struct hash { + constexpr std::size_t operator()(const impeller::UniqueID& id) { + return id.id; + } +}; + +template <> +struct less { + constexpr bool operator()(const impeller::UniqueID& lhs, + const impeller::UniqueID& rhs) const { + return lhs.id < rhs.id; + } +}; + +} // namespace std + +#endif // FLUTTER_IMPELLER_BASE_COMPARABLE_H_ diff --git a/flutter/engine/src/flutter/impeller/base/config.h b/flutter/engine/src/flutter/impeller/base/config.h new file mode 100644 index 0000000000000000000000000000000000000000..06c91869402d74c83ba8e937d431c3322fc1e10d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/config.h @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_CONFIG_H_ +#define FLUTTER_IMPELLER_BASE_CONFIG_H_ + +#include + +#include "flutter/fml/logging.h" + +#if defined(__GNUC__) || defined(__clang__) +#define IMPELLER_COMPILER_CLANG 1 +#else // defined(__GNUC__) || defined(__clang__) +#define IMPELLER_COMPILER_CLANG 0 +#endif // defined(__GNUC__) || defined(__clang__) + +#if IMPELLER_COMPILER_CLANG +#define IMPELLER_PRINTF_FORMAT(format_number, args_number) \ + __attribute__((format(printf, format_number, args_number))) +#else // IMPELLER_COMPILER_CLANG +#define IMPELLER_PRINTF_FORMAT(format_number, args_number) +#endif // IMPELLER_COMPILER_CLANG + +#define IMPELLER_UNIMPLEMENTED \ + impeller::ImpellerUnimplemented(__FUNCTION__, __FILE__, __LINE__); + +namespace impeller { + +[[noreturn]] inline void ImpellerUnimplemented(const char* method, + const char* file, + int line) { + FML_CHECK(false) << "Unimplemented: " << method << " in " << file << ":" + << line; + std::abort(); +} + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_CONFIG_H_ diff --git a/flutter/engine/src/flutter/impeller/base/flags.h b/flutter/engine/src/flutter/impeller/base/flags.h new file mode 100644 index 0000000000000000000000000000000000000000..cb581c34fe5a21801fedec07ed9ccfa449d42b99 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/flags.h @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_FLAGS_H_ +#define FLUTTER_IMPELLER_BASE_FLAGS_H_ + +namespace impeller { +struct Flags { + /// Whether to defer PSO construction until first use. Usage Will introduce + /// raster jank. + bool lazy_shader_mode = false; + /// When turned on DrawLine will use the experimental antialiased path. + bool antialiased_lines = false; +}; +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_FLAGS_H_ diff --git a/flutter/engine/src/flutter/impeller/base/mask.h b/flutter/engine/src/flutter/impeller/base/mask.h new file mode 100644 index 0000000000000000000000000000000000000000..97f30d7a7418e1837220210189d3ffae5131924b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/mask.h @@ -0,0 +1,230 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_MASK_H_ +#define FLUTTER_IMPELLER_BASE_MASK_H_ + +#include + +namespace impeller { + +template +struct MaskTraits { + static constexpr bool kIsMask = false; +}; + +//------------------------------------------------------------------------------ +/// @brief Declare this in the "impeller" namespace to make the enum +/// maskable. +/// +#define IMPELLER_ENUM_IS_MASK(enum_name) \ + template <> \ + struct MaskTraits { \ + static constexpr bool kIsMask = true; \ + }; + +//------------------------------------------------------------------------------ +/// @brief A mask of typed enums. +/// +/// @tparam EnumType_ The type of the enum. Must be an enum class. +/// +template +struct Mask { + using EnumType = EnumType_; + using MaskType = typename std::underlying_type::type; + + constexpr Mask() = default; + + constexpr Mask(const Mask& other) = default; + + constexpr Mask(Mask&& other) = default; + + constexpr Mask(EnumType type) // NOLINT(google-explicit-constructor) + : mask_(static_cast(type)) {} + + explicit constexpr Mask(MaskType mask) : mask_(static_cast(mask)) {} + + // All casts must be explicit. + + explicit constexpr operator MaskType() const { return mask_; } + + explicit constexpr operator bool() const { return !!mask_; } + + // The following relational operators can be replaced with a defaulted + // spaceship operator post C++20. + + constexpr bool operator<(const Mask& other) const { + return mask_ < other.mask_; + } + + constexpr bool operator>(const Mask& other) const { + return mask_ > other.mask_; + } + + constexpr bool operator>=(const Mask& other) const { + return mask_ >= other.mask_; + } + + constexpr bool operator<=(const Mask& other) const { + return mask_ <= other.mask_; + } + + constexpr bool operator==(const Mask& other) const { + return mask_ == other.mask_; + } + + constexpr bool operator!=(const Mask& other) const { + return mask_ != other.mask_; + } + + // Logical operators. + + constexpr bool operator!() const { return !mask_; } + + // Bitwise operators. + + constexpr Mask operator&(const Mask& other) const { + return Mask{mask_ & other.mask_}; + } + + constexpr Mask operator|(const Mask& other) const { + return Mask{mask_ | other.mask_}; + } + + constexpr Mask operator^(const Mask& other) const { + return Mask{mask_ ^ other.mask_}; + } + + constexpr Mask operator~() const { return Mask{~mask_}; } + + // Assignment operators. + + constexpr Mask& operator=(const Mask&) = default; + + constexpr Mask& operator=(Mask&&) = default; + + constexpr Mask& operator|=(const Mask& other) { + mask_ |= other.mask_; + return *this; + } + + constexpr Mask& operator&=(const Mask& other) { + mask_ &= other.mask_; + return *this; + } + + constexpr Mask& operator^=(const Mask& other) { + mask_ ^= other.mask_; + return *this; + } + + private: + MaskType mask_ = {}; +}; + +// Construction from Enum Types + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator|(const EnumType& lhs, + const EnumType& rhs) { + return Mask{lhs} | rhs; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator&(const EnumType& lhs, + const EnumType& rhs) { + return Mask{lhs} & rhs; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator^(const EnumType& lhs, + const EnumType& rhs) { + return Mask{lhs} ^ rhs; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator~(const EnumType& other) { + return ~Mask{other}; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator|(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} | rhs; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator&(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} & rhs; +} + +template < + typename EnumType, + typename std::enable_if::kIsMask, bool>::type = true> +inline constexpr Mask operator^(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} ^ rhs; +} + +// Relational operators with EnumType promotion. These can be replaced by a +// defaulted spaceship operator post C++20. + +template ::kIsMask, bool> = true> +inline constexpr bool operator<(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} < rhs; +} + +template ::kIsMask, bool> = true> +inline constexpr bool operator>(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} > rhs; +} + +template ::kIsMask, bool> = true> +inline constexpr bool operator<=(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} <= rhs; +} + +template ::kIsMask, bool> = true> +inline constexpr bool operator>=(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} >= rhs; +} + +template ::kIsMask, bool> = true> +inline constexpr bool operator==(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} == rhs; +} + +template ::kIsMask, bool> = true> +inline constexpr bool operator!=(const EnumType& lhs, + const Mask& rhs) { + return Mask{lhs} != rhs; +} + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_MASK_H_ diff --git a/flutter/engine/src/flutter/impeller/base/promise.cc b/flutter/engine/src/flutter/impeller/base/promise.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c7b7606636bdd8b37a1f0e1b9d0147232b3b07e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/promise.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/promise.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/promise.h b/flutter/engine/src/flutter/impeller/base/promise.h new file mode 100644 index 0000000000000000000000000000000000000000..9f7205eaab60b94d80b98ab259d20c16c5c1f1e1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/promise.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_PROMISE_H_ +#define FLUTTER_IMPELLER_BASE_PROMISE_H_ + +#include + +namespace impeller { + +template +std::future RealizedFuture(T t) { + std::promise promise; + auto future = promise.get_future(); + promise.set_value(std::move(t)); + return future; +} + +// Wraps a std::promise and completes the promise with a value during +// destruction if the promise does not already have a value. +// +// By default the std::promise destructor will complete an empty promise with an +// exception. This will fail because Flutter is built without exception support. +template +class NoExceptionPromise { + public: + NoExceptionPromise() = default; + + ~NoExceptionPromise() { + if (!value_set_) { + promise_.set_value({}); + } + } + + std::future get_future() { return promise_.get_future(); } + + void set_value(const T& value) { + promise_.set_value(value); + value_set_ = true; + } + + private: + std::promise promise_; + bool value_set_ = false; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_PROMISE_H_ diff --git a/flutter/engine/src/flutter/impeller/base/strings.cc b/flutter/engine/src/flutter/impeller/base/strings.cc new file mode 100644 index 0000000000000000000000000000000000000000..9623a11827966b80d25031d555810802798971cd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/strings.cc @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/strings.h" + +#include + +namespace impeller { + +IMPELLER_PRINTF_FORMAT(1, 2) +std::string SPrintF(const char* format, ...) { + std::string ret_val; + va_list list; + va_list list2; + va_start(list, format); + va_copy(list2, list); + if (auto string_length = ::vsnprintf(nullptr, 0, format, list); + string_length >= 0) { + auto buffer = reinterpret_cast(::malloc(string_length + 1)); + ::vsnprintf(buffer, string_length + 1, format, list2); + ret_val = std::string{buffer, static_cast(string_length)}; + ::free(buffer); + } + va_end(list2); + va_end(list); + return ret_val; +} + +bool HasPrefix(const std::string& string, const std::string& prefix) { + return string.find(prefix) == 0u; +} + +bool HasSuffix(const std::string& string, const std::string& suffix) { + auto position = string.rfind(suffix); + if (position == std::string::npos) { + return false; + } + return position == string.size() - suffix.size(); +} + +std::string StripPrefix(const std::string& string, + const std::string& to_strip) { + if (!HasPrefix(string, to_strip)) { + return string; + } + return string.substr(to_strip.length()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/strings.h b/flutter/engine/src/flutter/impeller/base/strings.h new file mode 100644 index 0000000000000000000000000000000000000000..cefe10343eb0e4c8ed180b434811dea5db92574b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/strings.h @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_STRINGS_H_ +#define FLUTTER_IMPELLER_BASE_STRINGS_H_ + +#include + +#include "impeller/base/config.h" + +namespace impeller { + +IMPELLER_PRINTF_FORMAT(1, 2) +std::string SPrintF(const char* format, ...); + +bool HasPrefix(const std::string& string, const std::string& prefix); + +bool HasSuffix(const std::string& string, const std::string& suffix); + +std::string StripPrefix(const std::string& string, const std::string& to_strip); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_STRINGS_H_ diff --git a/flutter/engine/src/flutter/impeller/base/thread.cc b/flutter/engine/src/flutter/impeller/base/thread.cc new file mode 100644 index 0000000000000000000000000000000000000000..0403b19cd6a81996144fcf4b05a21ff100c4b1c1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/thread.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/thread.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/thread.h b/flutter/engine/src/flutter/impeller/base/thread.h new file mode 100644 index 0000000000000000000000000000000000000000..ae9ae3badd4742a74d7c345fabd4114b5ece1e3d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/thread.h @@ -0,0 +1,270 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_THREAD_H_ +#define FLUTTER_IMPELLER_BASE_THREAD_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "impeller/base/thread_safety.h" + +namespace impeller { + +class ConditionVariable; + +class IPLR_CAPABILITY("mutex") Mutex { + public: + Mutex() = default; + + ~Mutex() = default; + + void Lock() IPLR_ACQUIRE() { mutex_.lock(); } + + void Unlock() IPLR_RELEASE() { mutex_.unlock(); } + + private: + friend class ConditionVariable; + + std::mutex mutex_; + + Mutex(const Mutex&) = delete; + + Mutex(Mutex&&) = delete; + + Mutex& operator=(const Mutex&) = delete; + + Mutex& operator=(Mutex&&) = delete; +}; + +class IPLR_CAPABILITY("mutex") RWMutex { + public: + RWMutex() = default; + + ~RWMutex() = default; + + void LockWriter() IPLR_ACQUIRE() { mutex_.lock(); } + + void UnlockWriter() IPLR_RELEASE() { mutex_.unlock(); } + + void LockReader() IPLR_ACQUIRE_SHARED() { mutex_.lock_shared(); } + + void UnlockReader() IPLR_RELEASE_SHARED() { mutex_.unlock_shared(); } + + private: + std::shared_mutex mutex_; + + RWMutex(const RWMutex&) = delete; + + RWMutex(RWMutex&&) = delete; + + RWMutex& operator=(const RWMutex&) = delete; + + RWMutex& operator=(RWMutex&&) = delete; +}; + +class IPLR_SCOPED_CAPABILITY Lock { + public: + explicit Lock(Mutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { + mutex_.Lock(); + } + + ~Lock() IPLR_RELEASE() { mutex_.Unlock(); } + + private: + Mutex& mutex_; + + Lock(const Lock&) = delete; + + Lock(Lock&&) = delete; + + Lock& operator=(const Lock&) = delete; + + Lock& operator=(Lock&&) = delete; +}; + +class IPLR_SCOPED_CAPABILITY ReaderLock { + public: + explicit ReaderLock(RWMutex& mutex) IPLR_ACQUIRE_SHARED(mutex) + : mutex_(mutex) { + mutex_.LockReader(); + } + + ~ReaderLock() IPLR_RELEASE() { mutex_.UnlockReader(); } + + private: + RWMutex& mutex_; + + ReaderLock(const ReaderLock&) = delete; + + ReaderLock(ReaderLock&&) = delete; + + ReaderLock& operator=(const ReaderLock&) = delete; + + ReaderLock& operator=(ReaderLock&&) = delete; +}; + +class IPLR_SCOPED_CAPABILITY WriterLock { + public: + explicit WriterLock(RWMutex& mutex) IPLR_ACQUIRE(mutex) : mutex_(mutex) { + mutex_.LockWriter(); + } + + ~WriterLock() IPLR_RELEASE() { mutex_.UnlockWriter(); } + + private: + RWMutex& mutex_; + + WriterLock(const WriterLock&) = delete; + + WriterLock(WriterLock&&) = delete; + + WriterLock& operator=(const WriterLock&) = delete; + + WriterLock& operator=(WriterLock&&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief A condition variable exactly similar to the one in libcxx with +/// two major differences: +/// +/// * On the Wait, WaitFor, and WaitUntil calls, static analysis +/// annotation are respected. +/// * There is no ability to wait on a condition variable and also +/// be susceptible to spurious wakes. This is because the +/// predicate is mandatory. +/// +class ConditionVariable { + public: + ConditionVariable() = default; + + ~ConditionVariable() = default; + + ConditionVariable(const ConditionVariable&) = delete; + + ConditionVariable& operator=(const ConditionVariable&) = delete; + + void NotifyOne() { cv_.notify_one(); } + + void NotifyAll() { cv_.notify_all(); } + + using Predicate = std::function; + + //---------------------------------------------------------------------------- + /// @brief Atomically unlocks the mutex and waits on the condition + /// variable up to a specified time point. Lock will be reacquired + /// when the wait exits. Spurious wakes may happen before the time + /// point is reached. In such cases the predicate is invoked and + /// it must return `false` for the wait to continue. The predicate + /// will be invoked with the mutex locked. + /// + /// @note Since the predicate is invoked with the mutex locked, if it + /// accesses other guarded resources, the predicate itself must be + /// decorated with the IPLR_REQUIRES directive. For instance, + /// + /// ```c++ + /// [] () IPLR_REQUIRES(mutex) { + /// return my_guarded_resource.should_stop_waiting; + /// } + /// ``` + /// + /// @param mutex The mutex. + /// @param[in] time_point The time point to wait to. + /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. + /// Must return false for the wait to + /// continue. + /// + /// @tparam Clock The clock type. + /// @tparam Duration The duration type. + /// + /// @return The value of the predicate at the end of the wait. + /// + template + bool WaitUntil(Mutex& mutex, + const std::chrono::time_point& time_point, + const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { + std::unique_lock lock(mutex.mutex_, std::adopt_lock); + const auto result = cv_.wait_until(lock, time_point, should_stop_waiting); + lock.release(); + return result; + } + + //---------------------------------------------------------------------------- + /// @brief Atomically unlocks the mutex and waits on the condition + /// variable for a designated duration. Lock will be reacquired + /// when the wait exits. Spurious wakes may happen before the time + /// point is reached. In such cases the predicate is invoked and + /// it must return `false` for the wait to continue. The predicate + /// will be invoked with the mutex locked. + /// + /// @note Since the predicate is invoked with the mutex locked, if it + /// accesses other guarded resources, the predicate itself must be + /// decorated with the IPLR_REQUIRES directive. For instance, + /// + /// ```c++ + /// [] () IPLR_REQUIRES(mutex) { + /// return my_guarded_resource.should_stop_waiting; + /// } + /// ``` + /// + /// @param mutex The mutex. + /// @param[in] duration The duration to wait for. + /// @param[in] should_stop_waiting The predicate invoked on spurious wakes. + /// Must return false for the wait to + /// continue. + /// + /// @tparam Representation The duration representation type. + /// @tparam Period The duration period type. + /// + /// @return The value of the predicate at the end of the wait. + /// + template + bool WaitFor(Mutex& mutex, + const std::chrono::duration& duration, + const Predicate& should_stop_waiting) IPLR_REQUIRES(mutex) { + return WaitUntil(mutex, std::chrono::steady_clock::now() + duration, + should_stop_waiting); + } + + //---------------------------------------------------------------------------- + /// @brief Atomically unlocks the mutex and waits on the condition + /// variable indefinitely till the predicate determines that the + /// wait must end. Lock will be reacquired when the wait exits. + /// Spurious wakes may happen before the time point is reached. In + /// such cases the predicate is invoked and it must return `false` + /// for the wait to continue. The predicate will be invoked with + /// the mutex locked. + /// + /// @note Since the predicate is invoked with the mutex locked, if it + /// accesses other guarded resources, the predicate itself must be + /// decorated with the IPLR_REQUIRES directive. For instance, + /// + /// ```c++ + /// [] () IPLR_REQUIRES(mutex) { + /// return my_guarded_resource.should_stop_waiting; + /// } + /// ``` + /// + /// @param mutex The mutex + /// @param[in] should_stop_waiting The should stop waiting + /// + void Wait(Mutex& mutex, const Predicate& should_stop_waiting) + IPLR_REQUIRES(mutex) { + std::unique_lock lock(mutex.mutex_, std::adopt_lock); + cv_.wait(lock, should_stop_waiting); + lock.release(); + } + + private: + std::condition_variable cv_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_THREAD_H_ diff --git a/flutter/engine/src/flutter/impeller/base/thread_safety.cc b/flutter/engine/src/flutter/impeller/base/thread_safety.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4188f669a4da155d5eb99cb5ef9773f7b47af05 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/thread_safety.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/thread_safety.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/thread_safety.h b/flutter/engine/src/flutter/impeller/base/thread_safety.h new file mode 100644 index 0000000000000000000000000000000000000000..da1aed3b5e7a5692f9a6e10ce58c73d3b6dec97c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/thread_safety.h @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_THREAD_SAFETY_H_ +#define FLUTTER_IMPELLER_BASE_THREAD_SAFETY_H_ + +#if defined(__clang__) +#define IPLR_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#else +#define IPLR_THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op +#endif + +#define IPLR_CAPABILITY(x) IPLR_THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) + +#define IPLR_SCOPED_CAPABILITY \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) + +#define IPLR_GUARDED_BY(x) IPLR_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) + +#define IPLR_PT_GUARDED_BY(x) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) + +#define IPLR_ACQUIRED_BEFORE(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) + +#define IPLR_ACQUIRED_AFTER(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) + +#define IPLR_REQUIRES(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) + +#define IPLR_REQUIRES_SHARED(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) + +#define IPLR_ACQUIRE(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) + +#define IPLR_ACQUIRE_SHARED(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) + +#define IPLR_RELEASE(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) + +#define IPLR_RELEASE_SHARED(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) + +#define IPLR_RELEASE_GENERIC(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__)) + +#define IPLR_TRY_ACQUIRE(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) + +#define IPLR_TRY_ACQUIRE_SHARED(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) + +#define IPLR_EXCLUDES(...) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) + +#define IPLR_ASSERT_CAPABILITY(x) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) + +#define IPLR_ASSERT_SHARED_CAPABILITY(x) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) + +#define IPLR_RETURN_CAPABILITY(x) \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) + +#define IPLR_NO_THREAD_SAFETY_ANALYSIS \ + IPLR_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + +#endif // FLUTTER_IMPELLER_BASE_THREAD_SAFETY_H_ diff --git a/flutter/engine/src/flutter/impeller/base/timing.h b/flutter/engine/src/flutter/impeller/base/timing.h new file mode 100644 index 0000000000000000000000000000000000000000..86ac48ceba327ae63c29c73a19cd933bb4296a93 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/timing.h @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_TIMING_H_ +#define FLUTTER_IMPELLER_BASE_TIMING_H_ + +#include + +namespace impeller { + +using MillisecondsF = std::chrono::duration; +using SecondsF = std::chrono::duration; +using Clock = std::chrono::high_resolution_clock; +using TimePoint = std::chrono::time_point; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_TIMING_H_ diff --git a/flutter/engine/src/flutter/impeller/base/validation.cc b/flutter/engine/src/flutter/impeller/base/validation.cc new file mode 100644 index 0000000000000000000000000000000000000000..987ad4b4e6aa417791d01d8ef9068ceb3053d062 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/validation.cc @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/validation.h" + +#include + +#include "flutter/fml/logging.h" + +namespace impeller { + +static std::atomic_int32_t sValidationLogsDisabledCount = 0; +static std::atomic_int32_t sValidationLogsAreFatal = 0; +static ValidationFailureCallback sValidationFailureCallback; + +void ImpellerValidationErrorsSetFatal(bool fatal) { + sValidationLogsAreFatal = fatal; +} + +void ImpellerValidationErrorsSetCallback(ValidationFailureCallback callback) { + sValidationFailureCallback = std::move(callback); +} + +ScopedValidationDisable::ScopedValidationDisable() { + sValidationLogsDisabledCount++; +} + +ScopedValidationDisable::~ScopedValidationDisable() { + sValidationLogsDisabledCount--; +} + +ScopedValidationFatal::ScopedValidationFatal() { + sValidationLogsAreFatal++; +} + +ScopedValidationFatal::~ScopedValidationFatal() { + sValidationLogsAreFatal--; +} + +ValidationLog::ValidationLog(const char* file, int line) + : file_(file), line_(line) {} + +ValidationLog::~ValidationLog() { + if (sValidationLogsDisabledCount <= 0) { + ImpellerValidationBreak(stream_.str().c_str(), file_, line_); + } +} + +std::ostream& ValidationLog::GetStream() { + return stream_; +} + +void ImpellerValidationBreak(const char* message, const char* file, int line) { + if (sValidationFailureCallback && + sValidationFailureCallback(message, file, line)) { + return; + } + const auto severity = + ImpellerValidationErrorsAreFatal() ? fml::LOG_FATAL : fml::LOG_ERROR; + auto fml_log = fml::LogMessage{severity, file, line, nullptr}; + fml_log.stream() << +#if FLUTTER_RELEASE + "Impeller validation: " << message; +#else // FLUTTER_RELEASE + "Break on '" << __FUNCTION__ + << "' to inspect point of failure: " << message; +#endif // FLUTTER_RELEASE +} + +bool ImpellerValidationErrorsAreFatal() { + return sValidationLogsAreFatal; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/validation.h b/flutter/engine/src/flutter/impeller/base/validation.h new file mode 100644 index 0000000000000000000000000000000000000000..789ea8c004aa8ec8dd1de41159611e2c3f4c16e0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/validation.h @@ -0,0 +1,93 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_VALIDATION_H_ +#define FLUTTER_IMPELLER_BASE_VALIDATION_H_ + +#include +#include + +namespace impeller { + +class ValidationLog { + public: + ValidationLog(const char* file, int line); + + ~ValidationLog(); + + std::ostream& GetStream(); + + private: + const char* file_ = nullptr; + int line_ = 0; + std::ostringstream stream_; + + ValidationLog(const ValidationLog&) = delete; + + ValidationLog(ValidationLog&&) = delete; + + ValidationLog& operator=(const ValidationLog&) = delete; + + ValidationLog& operator=(ValidationLog&&) = delete; +}; + +void ImpellerValidationBreak(const char* message, const char* file, int line); + +void ImpellerValidationErrorsSetFatal(bool fatal); + +bool ImpellerValidationErrorsAreFatal(); + +using ValidationFailureCallback = + std::function; + +//------------------------------------------------------------------------------ +/// @brief Sets a callback that callers (usually tests) can set to +/// intercept validation failures. +/// +/// Returning true from the callback indicates that Impeller can +/// continue and avoid any default behavior on tripping validation +/// (which could include process termination). +/// +/// @param[in] callback The callback +/// +void ImpellerValidationErrorsSetCallback(ValidationFailureCallback callback); + +struct ScopedValidationDisable { + ScopedValidationDisable(); + + ~ScopedValidationDisable(); + + ScopedValidationDisable(const ScopedValidationDisable&) = delete; + + ScopedValidationDisable& operator=(const ScopedValidationDisable&) = delete; +}; + +struct ScopedValidationFatal { + ScopedValidationFatal(); + + ~ScopedValidationFatal(); + + ScopedValidationFatal(const ScopedValidationFatal&) = delete; + + ScopedValidationFatal& operator=(const ScopedValidationFatal&) = delete; +}; + +} // namespace impeller + +//------------------------------------------------------------------------------ +/// Get a stream to the log Impeller uses for all validation errors. The +/// behavior of these logs is as follows: +/// +/// * Validation error are completely ignored in the Flutter release +/// runtime-mode. +/// * In non-release runtime-modes, validation logs are redirected to the +/// Flutter `INFO` log. These logs typically show up when verbose logging is +/// enabled. +/// * If `ImpellerValidationErrorsSetFatal` is set to `true`, validation logs +/// are fatal. The runtime-mode restriction still applies. This usually +/// happens in test environments. +/// +#define VALIDATION_LOG ::impeller::ValidationLog{__FILE__, __LINE__}.GetStream() + +#endif // FLUTTER_IMPELLER_BASE_VALIDATION_H_ diff --git a/flutter/engine/src/flutter/impeller/base/version.cc b/flutter/engine/src/flutter/impeller/base/version.cc new file mode 100644 index 0000000000000000000000000000000000000000..2a0beea76739d57fcfbcc1320350e93477a711bd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/version.cc @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/base/version.h" + +#include + +namespace impeller { + +std::optional Version::FromVector(const std::vector& version) { + if (version.size() == 0) { + return Version{0, 0, 0}; + } + if (version.size() == 1) { + return Version{version[0], 0, 0}; + } + if (version.size() == 2) { + return Version{version[0], version[1], 0}; + } + if (version.size() == 3) { + return Version{version[0], version[1], version[2]}; + } + return std::nullopt; +} + +std::string Version::ToString() const { + std::stringstream stream; + stream << major_version << "." << minor_version << "." << patch_version; + return stream.str(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/base/version.h b/flutter/engine/src/flutter/impeller/base/version.h new file mode 100644 index 0000000000000000000000000000000000000000..d2c67575bff3006ac989c4dd7aee9e96f97cbb20 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/base/version.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_BASE_VERSION_H_ +#define FLUTTER_IMPELLER_BASE_VERSION_H_ + +#include +#include +#include +#include +#include + +namespace impeller { + +struct Version { + public: + size_t major_version; + size_t minor_version; + size_t patch_version; + + constexpr explicit Version(size_t p_major = 0, + size_t p_minor = 0, + size_t p_patch = 0) + : major_version(p_major), + minor_version(p_minor), + patch_version(p_patch) {} + + static std::optional FromVector(const std::vector& version); + + constexpr bool IsAtLeast(const Version& other) const { + return std::tie(major_version, minor_version, patch_version) >= + std::tie(other.major_version, other.minor_version, + other.patch_version); + } + + std::string ToString() const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_BASE_VERSION_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/BUILD.gn b/flutter/engine/src/flutter/impeller/compiler/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5ea4c05b3e17e165be5aea87bf458715761aa05d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/BUILD.gn @@ -0,0 +1,118 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/shell/version/version.gni") + +impeller_component("utilities") { + # Current versions of libcxx have deprecated some of the UTF-16 string + # conversion APIs. + defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ] + + sources = [ + "utilities.cc", + "utilities.h", + ] + + public_deps = [ + "../base", + "../geometry", + "../runtime_stage", + "//flutter/fml", + ] +} + +impeller_component("compiler_lib") { + include_dirs = [ "//flutter/third_party/vulkan-deps/spirv-cross/src/" ] + + # Current versions of libcxx have deprecated some of the UTF-16 string + # conversion APIs. + defines = [ "_LIBCPP_DISABLE_DEPRECATION_WARNINGS" ] + + sources = [ + "code_gen_template.h", + "compiler.cc", + "compiler.h", + "compiler_backend.cc", + "compiler_backend.h", + "constants.cc", + "constants.h", + "include_dir.h", + "includer.cc", + "includer.h", + "logger.h", + "reflector.cc", + "reflector.h", + "runtime_stage_data.cc", + "runtime_stage_data.h", + "shader_bundle.cc", + "shader_bundle.h", + "shader_bundle_data.cc", + "shader_bundle_data.h", + "source_options.cc", + "source_options.h", + "spirv_compiler.cc", + "spirv_compiler.h", + "spirv_sksl.cc", + "spirv_sksl.h", + "switches.cc", + "switches.h", + "types.cc", + "types.h", + "uniform_sorter.cc", + "uniform_sorter.h", + ] + + public_deps = [ + ":utilities", + "../base", + "../geometry", + "../runtime_stage", + "//flutter/fml", + "//flutter/impeller/shader_bundle:shader_bundle_flatbuffers", + + # All third_party deps must be included by the global license script. + "//third_party/inja", + "//third_party/shaderc_flutter", + "//third_party/spirv_cross_flutter", + ] +} + +impeller_component("impellerc") { + target_type = "executable" + + sources = [ "impellerc_main.cc" ] + + deps = [ + ":compiler_lib", + "shader_lib", + ] + + metadata = { + entitlement_file_path = [ "impellerc" ] + } +} + +group("compiler") { + deps = [ ":impellerc" ] +} + +impeller_component("compiler_unittests") { + testonly = true + + output_name = "impellerc_unittests" + + sources = [ + "compiler_test.cc", + "compiler_test.h", + "compiler_unittests.cc", + "shader_bundle_unittests.cc", + "switches_unittests.cc", + ] + + deps = [ + ":compiler_lib", + "//flutter/testing:testing_lib", + ] +} diff --git a/flutter/engine/src/flutter/impeller/compiler/README.md b/flutter/engine/src/flutter/impeller/compiler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf44365babce9aa4ba02affac3419f18cad60879 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/README.md @@ -0,0 +1,7 @@ +# The Impeller Shader Compiler & Reflector + +Host side tooling that consumes [GLSL 4.60 (Core +Profile)](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf) +shaders and generates libraries suitable for consumption by an Impeller backend. +Along with said libraries, the reflector generates code and meta-data to +construct rendering and compute pipelines at runtime. diff --git a/flutter/engine/src/flutter/impeller/compiler/code_gen_template.h b/flutter/engine/src/flutter/impeller/compiler/code_gen_template.h new file mode 100644 index 0000000000000000000000000000000000000000..15246a28d5d67cc0dd1662bcfa9ae1d2587ebea4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/code_gen_template.h @@ -0,0 +1,259 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +namespace impeller { +namespace compiler { + +constexpr std::string_view kReflectionHeaderTemplate = + R"~~(// THIS FILE IS GENERATED BY impellerc. +// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL + +#pragma once + +{# Note: The nogncheck decorations are only to make GN not mad at the template#} +{# this file is generated from. There are no GN rule violations in the generated#} +{# file itself and the no-check declarations will be stripped in generated files.#} +#include "impeller/core/buffer_view.h" {# // nogncheck #} + +#include "impeller/core/sampler.h" {# // nogncheck #} + +#include "impeller/core/shader_types.h" {# // nogncheck #} + +#include "impeller/core/resource_binder.h" {# // nogncheck #} + +#include "impeller/core/texture.h" {# // nogncheck #} + + +namespace impeller { + +struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader { + // =========================================================================== + // Stage Info ================================================================ + // =========================================================================== + static constexpr std::string_view kLabel = "{{camel_case(shader_name)}}"; + static constexpr std::string_view kEntrypointName = "{{entrypoint}}"; + static constexpr ShaderStage kShaderStage = {{to_shader_stage(shader_stage)}}; + // The generator used to prepare these bindings. Metal generators may be used + // by GLES backends but GLES generators are unsuitable for the metal backend. + static constexpr std::string_view kGeneratorName = "{{get_generator_name()}}"; +{% if length(struct_definitions) > 0 %} + // =========================================================================== + // Struct Definitions ======================================================== + // =========================================================================== +{% for def in struct_definitions %} + +{% if last(def.members).array_elements == 0 %} + template +{% endif %} + struct {{def.name}} { +{% for member in def.members %} +{{" "}}{% if member.element_padding > 0 %}Padded<{{member.type}}, {{member.element_padding}}>{% else %}{{member.type}}{% endif %}{{" " + member.name}}{% if member.array_elements != "std::nullopt" %}[{% if member.array_elements == 0 %}FlexCount{% else %}{{member.array_elements}}{% endif %}]{% endif %}; // (offset {{member.offset}}, size {{member.byte_length}}) +{% endfor %} + }; // struct {{def.name}} (size {{def.byte_length}}) +{% endfor %} +{% endif %} +{% if length(buffers) > 0 %} + + // =========================================================================== + // Stage Uniform & Storage Buffers =========================================== + // =========================================================================== +{% for buffer in buffers %} + + static constexpr auto kResource{{camel_case(buffer.name)}} = ShaderUniformSlot { // {{buffer.name}} + "{{buffer.name}}", // name + {{buffer.ext_res_0}}u, // ext_res_0 + {{buffer.set}}u, // set + {{buffer.binding}}u, // binding + }; + static ShaderMetadata kMetadata{{camel_case(buffer.name)}}; +{% endfor %} +{% endif %} + + // =========================================================================== + // Stage Inputs ============================================================== + // =========================================================================== +{% for stage_input in stage_inputs %} + static constexpr auto kInput{{camel_case(stage_input.name)}} = ShaderStageIOSlot { // {{stage_input.name}} + "{{stage_input.name}}", // name + {{stage_input.location}}u, // attribute location + {{stage_input.descriptor_set}}u, // attribute set + {{stage_input.binding}}u, // attribute binding + {{stage_input.type.type_name}}, // type + {{stage_input.type.bit_width}}u, // bit width of type + {{stage_input.type.vec_size}}u, // vec size + {{stage_input.type.columns}}u, // number of columns + {{stage_input.offset}}u, // offset for interleaved layout + {{stage_input.relaxed_precision}}, // relaxed precision + }; +{% endfor %} + + static constexpr std::array kAllShaderStageInputs = { +{% for stage_input in stage_inputs %} + &kInput{{camel_case(stage_input.name)}}, // {{stage_input.name}} +{% endfor %} + }; + +{% if shader_stage == "vertex" %} + static constexpr auto kInterleavedLayout = ShaderStageBufferLayout { +{% if length(stage_inputs) > 0 %} + sizeof(PerVertexData), // stride for interleaved layout +{% else %} + 0u, +{% endif %} + 0u, // attribute binding + }; + static constexpr std::array kInterleavedBufferLayout = { + &kInterleavedLayout + }; +{% endif %} + +{% if length(sampled_images) > 0 %} + // =========================================================================== + // Sampled Images ============================================================ + // =========================================================================== +{% for sampled_image in sampled_images %} + + static constexpr auto kResource{{camel_case(sampled_image.name)}} = SampledImageSlot { // {{sampled_image.name}} + "{{sampled_image.name}}", // name + {{sampled_image.ext_res_0}}u, // ext_res_0 + {{sampled_image.set}}u, // set + {{sampled_image.binding}}u, // binding + }; + static ShaderMetadata kMetadata{{camel_case(sampled_image.name)}}; +{% endfor %} +{% endif %} + // =========================================================================== + // Stage Outputs ============================================================= + // =========================================================================== +{% for stage_output in stage_outputs %} + static constexpr auto kOutput{{camel_case(stage_output.name)}} = ShaderStageIOSlot { // {{stage_output.name}} + "{{stage_output.name}}", // name + {{stage_output.location}}u, // attribute location + {{stage_output.descriptor_set}}u, // attribute set + {{stage_output.binding}}u, // attribute binding + {{stage_output.type.type_name}}, // type + {{stage_output.type.bit_width}}u, // bit width of type + {{stage_output.type.vec_size}}u, // vec size + {{stage_output.type.columns}}u, // number of columns + {{stage_output.offset}}u, // offset for interleaved layout + {{stage_output.relaxed_precision}}, // relaxed precision + }; +{% endfor %} + static constexpr std::array kAllShaderStageOutputs = { +{% for stage_output in stage_outputs %} + &kOutput{{camel_case(stage_output.name)}}, // {{stage_output.name}} +{% endfor %} + }; + + // =========================================================================== + // Resource Binding Utilities ================================================ + // =========================================================================== + +{% for proto in bind_prototypes %} + /// {{proto.docstring}} + static {{proto.return_type}} Bind{{proto.name}}({% for arg in proto.args %} +{{arg.type_name}} {{arg.argument_name}}{% if not loop.is_last %}, {% endif %} +{% endfor %}) { + return {{ proto.args.0.argument_name }}.BindResource({% for arg in proto.args %} + {% if loop.is_first %} +{{to_shader_stage(shader_stage)}}, {{ proto.descriptor_type }}, kResource{{ proto.name }}, &kMetadata{{ proto.name }}, {% else %} +std::move({{ arg.argument_name }}){% if not loop.is_last %}, {% endif %} + {% endif %} + {% endfor %}); + } + +{% endfor %} + + // =========================================================================== + // Metadata for Vulkan ======================================================= + // =========================================================================== + static constexpr std::array kDescriptorSetLayouts{ +{% for subpass_input in subpass_inputs %} + DescriptorSetLayout{ + {{subpass_input.binding}}, // binding = {{subpass_input.binding}} + {{subpass_input.descriptor_type}}, // descriptor_type = {{subpass_input.descriptor_type}} + {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} + }, +{% endfor %} +{% for buffer in buffers %} + DescriptorSetLayout{ + {{buffer.binding}}, // binding = {{buffer.binding}} + {{buffer.descriptor_type}}, // descriptor_type = {{buffer.descriptor_type}} + {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} + }, +{% endfor %} +{% for sampled_image in sampled_images %} + DescriptorSetLayout{ + {{sampled_image.binding}}, // binding = {{sampled_image.binding}} + {{sampled_image.descriptor_type}}, // descriptor_type = {{sampled_image.descriptor_type}} + {{to_shader_stage(shader_stage)}}, // shader_stage = {{to_shader_stage(shader_stage)}} + }, +{% endfor %} + }; + +}; // struct {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader + +} // namespace impeller +)~~"; + +constexpr std::string_view kReflectionCCTemplate = + R"~~(// THIS FILE IS GENERATED BY impellerc. +// DO NOT EDIT OR CHECK THIS INTO SOURCE CONTROL + +#include "{{header_file_name}}" + +#include + +namespace impeller { + +using Shader = {{camel_case(shader_name)}}{{camel_case(shader_stage)}}Shader; + +{% for def in struct_definitions %} +// Sanity checks for {{def.name}} +{% if last(def.members).array_elements == 0 %} +static_assert(std::is_standard_layout_v>); +{% for member in def.members %} +static_assert(offsetof(Shader::{{def.name}}<0>, {{member.name}}) == {{member.offset}}); +{% endfor %} +{% else %} +static_assert(std::is_standard_layout_v); +static_assert(sizeof(Shader::{{def.name}}) == {{def.byte_length}}); +{% for member in def.members %} +static_assert(offsetof(Shader::{{def.name}}, {{member.name}}) == {{member.offset}}); +{% endfor %} +{% endif %} +{% endfor %} + +{% for buffer in buffers %} +ShaderMetadata Shader::kMetadata{{camel_case(buffer.name)}} = { + "{{buffer.name}}", // name + std::vector { + {% for member in buffer.type.members %} + ShaderStructMemberMetadata { + {{ member.base_type }}, // type + "{{ member.name }}", // name + {{ member.offset }}, // offset + {{ member.size }}, // size + {{ member.byte_length }}, // byte_length + {{ member.array_elements }}, // array_elements + }, + {% endfor %} + } // members +}; +{% endfor %} + +{% for sampled_image in sampled_images %} +ShaderMetadata Shader::kMetadata{{camel_case(sampled_image.name)}} = { + "{{sampled_image.name}}", // name + std::vector {}, // 0 members +}; +{% endfor %} + +} // namespace impeller +)~~"; + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler.cc b/flutter/engine/src/flutter/impeller/compiler/compiler.cc new file mode 100644 index 0000000000000000000000000000000000000000..a751f5f6dd385afe0289b1dc31bbbe7ffd2c2b8d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler.cc @@ -0,0 +1,547 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/compiler.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/paths.h" +#include "impeller/base/allocation.h" +#include "impeller/compiler/compiler_backend.h" +#include "impeller/compiler/constants.h" +#include "impeller/compiler/includer.h" +#include "impeller/compiler/logger.h" +#include "impeller/compiler/spirv_compiler.h" +#include "impeller/compiler/types.h" +#include "impeller/compiler/uniform_sorter.h" +#include "impeller/compiler/utilities.h" + +namespace impeller { +namespace compiler { + +namespace { +constexpr const char* kEGLImageExternalExtension = "GL_OES_EGL_image_external"; +constexpr const char* kEGLImageExternalExtension300 = + "GL_OES_EGL_image_external_essl3"; +} // namespace + +// This value should be <= 7372. UBOs can be larger on some devices but a +// performance cost will be paid. +// https://docs.qualcomm.com/bundle/publicresource/topics/80-78185-2/best_practices.html?product=1601111740035277#buffer-best-practices +static const uint32_t kMaxUniformBufferSize = 6208; + +static uint32_t ParseMSLVersion(const std::string& msl_version) { + std::stringstream sstream(msl_version); + std::string version_part; + uint32_t major = 1; + uint32_t minor = 2; + uint32_t patch = 0; + if (std::getline(sstream, version_part, '.')) { + major = std::stoi(version_part); + if (std::getline(sstream, version_part, '.')) { + minor = std::stoi(version_part); + if (std::getline(sstream, version_part, '.')) { + patch = std::stoi(version_part); + } + } + } + if (major < 1 || (major == 1 && minor < 2)) { + std::cerr << "--metal-version version must be at least 1.2. Have " + << msl_version << std::endl; + } + return spirv_cross::CompilerMSL::Options::make_msl_version(major, minor, + patch); +} + +static CompilerBackend CreateMSLCompiler( + const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options, + std::optional msl_version_override = {}) { + auto sl_compiler = std::make_shared(ir); + spirv_cross::CompilerMSL::Options sl_options; + sl_options.platform = + TargetPlatformToMSLPlatform(source_options.target_platform); + sl_options.msl_version = msl_version_override.value_or( + ParseMSLVersion(source_options.metal_version)); + sl_options.ios_use_simdgroup_functions = + sl_options.is_ios() && + sl_options.msl_version >= + spirv_cross::CompilerMSL::Options::make_msl_version(2, 4, 0); + sl_options.use_framebuffer_fetch_subpasses = true; + sl_compiler->set_msl_options(sl_options); + + // Sort the float and sampler uniforms according to their declared/decorated + // order. For user authored fragment shaders, the API for setting uniform + // values uses the index of the uniform in the declared order. By default, the + // metal backend of spirv-cross will order uniforms according to usage. To fix + // this, we use the sorted order and the add_msl_resource_binding API to force + // the ordering to match the declared order. Note that while this code runs + // for all compiled shaders, it will only affect vertex and fragment shaders + // due to the specified stage. + auto floats = + SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::Float); + auto images = + SortUniforms(&ir, sl_compiler.get(), spirv_cross::SPIRType::SampledImage); + + spv::ExecutionModel execution_model = + spv::ExecutionModel::ExecutionModelFragment; + if (source_options.type == SourceType::kVertexShader) { + execution_model = spv::ExecutionModel::ExecutionModelVertex; + } + + uint32_t buffer_offset = 0; + uint32_t sampler_offset = 0; + for (auto& float_id : floats) { + sl_compiler->add_msl_resource_binding( + {.stage = execution_model, + .basetype = spirv_cross::SPIRType::BaseType::Float, + .desc_set = sl_compiler->get_decoration(float_id, + spv::DecorationDescriptorSet), + .binding = + sl_compiler->get_decoration(float_id, spv::DecorationBinding), + .count = 1u, + .msl_buffer = buffer_offset}); + buffer_offset++; + } + for (auto& image_id : images) { + sl_compiler->add_msl_resource_binding({ + .stage = execution_model, + .basetype = spirv_cross::SPIRType::BaseType::SampledImage, + .desc_set = + sl_compiler->get_decoration(image_id, spv::DecorationDescriptorSet), + .binding = + sl_compiler->get_decoration(image_id, spv::DecorationBinding), + .count = 1u, + // A sampled image is both an image and a sampler, so both + // offsets need to be set or depending on the partiular shader + // the bindings may be incorrect. + .msl_texture = sampler_offset, + .msl_sampler = sampler_offset, + }); + sampler_offset++; + } + + return CompilerBackend(sl_compiler); +} + +static CompilerBackend CreateVulkanCompiler( + const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + auto gl_compiler = std::make_shared(ir); + spirv_cross::CompilerGLSL::Options sl_options; + sl_options.force_zero_initialized_variables = true; + sl_options.vertex.fixup_clipspace = true; + sl_options.vulkan_semantics = true; + gl_compiler->set_common_options(sl_options); + return CompilerBackend(gl_compiler); +} + +static CompilerBackend CreateGLSLCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + auto gl_compiler = std::make_shared(ir); + + // Walk the variables and insert the external image extension if any of them + // begins with the external texture prefix. Unfortunately, we can't walk + // `gl_compiler->get_shader_resources().separate_samplers` until the compiler + // is further along. + // + // Unfortunately, we can't just let the shader author add this extension and + // use `samplerExternalOES` directly because compiling to spirv requires the + // source language profile to be at least 310 ES, but this extension is + // incompatible with ES 310+. + for (auto& id : ir.ids_for_constant_or_variable) { + if (StringStartsWith(ir.get_name(id), kExternalTexturePrefix)) { + if (source_options.gles_language_version >= 300) { + gl_compiler->require_extension(kEGLImageExternalExtension300); + } else { + gl_compiler->require_extension(kEGLImageExternalExtension); + } + break; + } + } + + spirv_cross::CompilerGLSL::Options sl_options; + sl_options.force_zero_initialized_variables = true; + sl_options.vertex.fixup_clipspace = true; + if (source_options.target_platform == TargetPlatform::kOpenGLES || + source_options.target_platform == TargetPlatform::kRuntimeStageGLES || + source_options.target_platform == TargetPlatform::kRuntimeStageGLES3) { + sl_options.version = source_options.gles_language_version > 0 + ? source_options.gles_language_version + : 100; + sl_options.es = true; + if (source_options.target_platform == TargetPlatform::kRuntimeStageGLES3) { + sl_options.version = 300; + } + if (source_options.require_framebuffer_fetch && + source_options.type == SourceType::kFragmentShader) { + gl_compiler->remap_ext_framebuffer_fetch(0, 0, true); + } + gl_compiler->set_variable_type_remap_callback( + [&](const spirv_cross::SPIRType& type, const std::string& var_name, + std::string& name_of_type) { + if (StringStartsWith(var_name, kExternalTexturePrefix)) { + name_of_type = "samplerExternalOES"; + } + }); + } else { + sl_options.version = source_options.gles_language_version > 0 + ? source_options.gles_language_version + : 120; + sl_options.es = false; + } + gl_compiler->set_common_options(sl_options); + return CompilerBackend(gl_compiler); +} + +static CompilerBackend CreateSkSLCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + auto sksl_compiler = std::make_shared(ir); + return CompilerBackend(sksl_compiler); +} + +static bool EntryPointMustBeNamedMain(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kUnknown: + FML_UNREACHABLE(); + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kVulkan: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageVulkan: + return false; + case TargetPlatform::kSkSL: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + return true; + } + FML_UNREACHABLE(); +} + +static CompilerBackend CreateCompiler(const spirv_cross::ParsedIR& ir, + const SourceOptions& source_options) { + CompilerBackend compiler; + switch (source_options.target_platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kRuntimeStageMetal: + compiler = CreateMSLCompiler(ir, source_options); + break; + case TargetPlatform::kVulkan: + case TargetPlatform::kRuntimeStageVulkan: + compiler = CreateVulkanCompiler(ir, source_options); + break; + case TargetPlatform::kUnknown: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + compiler = CreateGLSLCompiler(ir, source_options); + break; + case TargetPlatform::kSkSL: + compiler = CreateSkSLCompiler(ir, source_options); + } + if (!compiler) { + return {}; + } + auto* backend = compiler.GetCompiler(); + if (!EntryPointMustBeNamedMain(source_options.target_platform) && + source_options.source_language == SourceLanguage::kGLSL) { + backend->rename_entry_point("main", source_options.entry_point_name, + ToExecutionModel(source_options.type)); + } + return compiler; +} + +namespace { +uint32_t CalculateUBOSize(const spirv_cross::Compiler* compiler) { + spirv_cross::ShaderResources resources = compiler->get_shader_resources(); + uint32_t result = 0; + for (const spirv_cross::Resource& ubo : resources.uniform_buffers) { + const spirv_cross::SPIRType& ubo_type = + compiler->get_type(ubo.base_type_id); + uint32_t size = compiler->get_declared_struct_size(ubo_type); + result += size; + } + return result; +} + +} // namespace + +Compiler::Compiler(const std::shared_ptr& source_mapping, + const SourceOptions& source_options, + Reflector::Options reflector_options) + : options_(source_options) { + if (!source_mapping || source_mapping->GetMapping() == nullptr) { + COMPILER_ERROR(error_stream_) + << "Could not read shader source or shader source was empty."; + return; + } + + if (source_options.target_platform == TargetPlatform::kUnknown) { + COMPILER_ERROR(error_stream_) << "Target platform not specified."; + return; + } + + SPIRVCompilerOptions spirv_options; + + // Make sure reflection is as effective as possible. The generated shaders + // will be processed later by backend specific compilers. + spirv_options.generate_debug_info = true; + + switch (options_.source_language) { + case SourceLanguage::kGLSL: + // Expects GLSL 4.60 (Core Profile). + // https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf + spirv_options.source_langauge = + shaderc_source_language::shaderc_source_language_glsl; + spirv_options.source_profile = SPIRVCompilerSourceProfile{ + shaderc_profile::shaderc_profile_core, // + 460, // + }; + break; + case SourceLanguage::kHLSL: + spirv_options.source_langauge = + shaderc_source_language::shaderc_source_language_hlsl; + break; + case SourceLanguage::kUnknown: + COMPILER_ERROR(error_stream_) << "Source language invalid."; + return; + } + + switch (source_options.target_platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: { + SPIRVCompilerTargetEnv target; + + if (source_options.use_half_textures) { + target.env = shaderc_target_env::shaderc_target_env_opengl; + target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; + target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0; + } else { + target.env = shaderc_target_env::shaderc_target_env_vulkan; + target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1; + target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3; + } + + spirv_options.target = target; + } break; + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kVulkan: + case TargetPlatform::kRuntimeStageVulkan: { + SPIRVCompilerTargetEnv target; + + target.env = shaderc_target_env::shaderc_target_env_vulkan; + target.version = shaderc_env_version::shaderc_env_version_vulkan_1_1; + target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_3; + + if (source_options.target_platform == + TargetPlatform::kRuntimeStageVulkan) { + spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND"); + spirv_options.relaxed_vulkan_rules = true; + } + spirv_options.target = target; + } break; + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: { + SPIRVCompilerTargetEnv target; + + target.env = shaderc_target_env::shaderc_target_env_opengl; + target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; + target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0; + + spirv_options.target = target; + spirv_options.macro_definitions.push_back("IMPELLER_GRAPHICS_BACKEND"); + } break; + case TargetPlatform::kSkSL: { + SPIRVCompilerTargetEnv target; + + target.env = shaderc_target_env::shaderc_target_env_opengl; + target.version = shaderc_env_version::shaderc_env_version_opengl_4_5; + target.spirv_version = shaderc_spirv_version::shaderc_spirv_version_1_0; + + // When any optimization level above 'zero' is enabled, the phi merges at + // loop continue blocks are rendered using syntax that is supported in + // GLSL, but not in SkSL. + // https://bugs.chromium.org/p/skia/issues/detail?id=13518. + spirv_options.optimization_level = + shaderc_optimization_level::shaderc_optimization_level_zero; + spirv_options.target = target; + spirv_options.macro_definitions.push_back("SKIA_GRAPHICS_BACKEND"); + } break; + case TargetPlatform::kUnknown: + COMPILER_ERROR(error_stream_) << "Target platform invalid."; + return; + } + + // Implicit definition that indicates that this compilation is for the device + // (instead of the host). + spirv_options.macro_definitions.push_back("IMPELLER_DEVICE"); + for (const auto& define : source_options.defines) { + spirv_options.macro_definitions.push_back(define); + } + + std::vector included_file_names; + spirv_options.includer = std::make_shared( + options_.working_directory, options_.include_dirs, + [&included_file_names](auto included_name) { + included_file_names.emplace_back(std::move(included_name)); + }); + + // SPIRV Generation. + SPIRVCompiler spv_compiler(source_options, source_mapping); + + spirv_assembly_ = spv_compiler.CompileToSPV( + error_stream_, spirv_options.BuildShadercOptions()); + + if (!spirv_assembly_) { + return; + } else { + included_file_names_ = std::move(included_file_names); + } + + // SL Generation. + spirv_cross::Parser parser( + reinterpret_cast(spirv_assembly_->GetMapping()), + spirv_assembly_->GetSize() / sizeof(uint32_t)); + // The parser and compiler must be run separately because the parser contains + // meta information (like type member names) that are useful for reflection. + parser.parse(); + + const auto parsed_ir = + std::make_shared(parser.get_parsed_ir()); + + auto sl_compiler = CreateCompiler(*parsed_ir, options_); + + if (!sl_compiler) { + COMPILER_ERROR(error_stream_) + << "Could not create compiler for target platform."; + return; + } + + uint32_t ubo_size = CalculateUBOSize(sl_compiler.GetCompiler()); + if (ubo_size > kMaxUniformBufferSize) { + COMPILER_ERROR(error_stream_) << "Uniform buffer size exceeds max (" + << kMaxUniformBufferSize << "): " << ubo_size; + return; + } + + // We need to invoke the compiler even if we don't use the SL mapping later + // for Vulkan. The reflector needs information that is only valid after a + // successful compilation call. + auto sl_compilation_result = + CreateMappingWithString(sl_compiler.GetCompiler()->compile()); + + // If the target is Vulkan, our shading language is SPIRV which we already + // have. We just need to strip it of debug information. If it isn't, we need + // to invoke the appropriate compiler to compile the SPIRV to the target SL. + if (source_options.target_platform == TargetPlatform::kVulkan || + source_options.target_platform == TargetPlatform::kRuntimeStageVulkan) { + auto stripped_spirv_options = spirv_options; + stripped_spirv_options.generate_debug_info = false; + sl_mapping_ = spv_compiler.CompileToSPV( + error_stream_, stripped_spirv_options.BuildShadercOptions()); + } else { + sl_mapping_ = sl_compilation_result; + } + + if (!sl_mapping_) { + COMPILER_ERROR(error_stream_) << "Could not generate SL from SPIRV"; + return; + } + + reflector_ = std::make_unique(std::move(reflector_options), // + parsed_ir, // + GetSLShaderSource(), // + sl_compiler // + ); + + if (!reflector_->IsValid()) { + COMPILER_ERROR(error_stream_) + << "Could not complete reflection on generated shader."; + return; + } + + is_valid_ = true; +} + +Compiler::~Compiler() = default; + +std::shared_ptr Compiler::GetSPIRVAssembly() const { + return spirv_assembly_; +} + +std::shared_ptr Compiler::GetSLShaderSource() const { + return sl_mapping_; +} + +bool Compiler::IsValid() const { + return is_valid_; +} + +std::string Compiler::GetSourcePrefix() const { + std::stringstream stream; + stream << options_.file_name << ": "; + return stream.str(); +} + +std::string Compiler::GetErrorMessages() const { + return error_stream_.str(); +} + +const std::vector& Compiler::GetIncludedFileNames() const { + return included_file_names_; +} + +static std::string JoinStrings(std::vector items, + const std::string& separator) { + std::stringstream stream; + for (size_t i = 0, count = items.size(); i < count; i++) { + const auto is_last = (i == count - 1); + + stream << items[i]; + if (!is_last) { + stream << separator; + } + } + return stream.str(); +} + +std::string Compiler::GetDependencyNames(const std::string& separator) const { + std::vector dependencies = included_file_names_; + dependencies.push_back(options_.file_name); + return JoinStrings(dependencies, separator); +} + +std::unique_ptr Compiler::CreateDepfileContents( + std::initializer_list targets_names) const { + // https://github.com/ninja-build/ninja/blob/master/src/depfile_parser.cc#L28 + const auto targets = JoinStrings(targets_names, " "); + const auto dependencies = GetDependencyNames(" "); + + std::stringstream stream; + stream << targets << ": " << dependencies << "\n"; + + auto contents = std::make_shared(stream.str()); + return std::make_unique( + reinterpret_cast(contents->data()), contents->size(), + [contents](auto, auto) {}); +} + +const Reflector* Compiler::GetReflector() const { + return reflector_.get(); +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler.h b/flutter/engine/src/flutter/impeller/compiler/compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..795aa6d12171116ec3f372887710077f2215fc5c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_H_ +#define FLUTTER_IMPELLER_COMPILER_COMPILER_H_ + +#include +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/compiler/include_dir.h" +#include "impeller/compiler/reflector.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/spirv_compiler.h" +#include "impeller/compiler/types.h" +#include "spirv_msl.hpp" +#include "spirv_parser.hpp" + +namespace impeller { +namespace compiler { + +class Compiler { + public: + Compiler(const std::shared_ptr& source_mapping, + const SourceOptions& options, + Reflector::Options reflector_options); + + ~Compiler(); + + bool IsValid() const; + + std::shared_ptr GetSPIRVAssembly() const; + + std::shared_ptr GetSLShaderSource() const; + + std::string GetErrorMessages() const; + + const std::vector& GetIncludedFileNames() const; + + std::unique_ptr CreateDepfileContents( + std::initializer_list targets) const; + + const Reflector* GetReflector() const; + + private: + SourceOptions options_; + std::shared_ptr spirv_assembly_; + std::shared_ptr sl_mapping_; + std::stringstream error_stream_; + std::unique_ptr reflector_; + std::vector included_file_names_; + bool is_valid_ = false; + + std::string GetSourcePrefix() const; + + std::string GetDependencyNames(const std::string& separator) const; + + Compiler(const Compiler&) = delete; + + Compiler& operator=(const Compiler&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_COMPILER_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler_backend.cc b/flutter/engine/src/flutter/impeller/compiler/compiler_backend.cc new file mode 100644 index 0000000000000000000000000000000000000000..58afead588383b3d9ce4ff815700e185f7735614 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler_backend.cc @@ -0,0 +1,113 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/compiler_backend.h" + +#include "impeller/base/comparable.h" + +namespace impeller { +namespace compiler { + +CompilerBackend::CompilerBackend(MSLCompiler compiler) + : CompilerBackend(Type::kMSL, compiler) {} + +CompilerBackend::CompilerBackend(GLSLCompiler compiler) + : CompilerBackend(compiler->get_common_options().vulkan_semantics + ? Type::kGLSLVulkan + : Type::kGLSL, + compiler) {} + +CompilerBackend::CompilerBackend(SkSLCompiler compiler) + : CompilerBackend(Type::kSkSL, compiler) {} + +CompilerBackend::CompilerBackend() = default; + +CompilerBackend::CompilerBackend(Type type, Compiler compiler) + : type_(type), compiler_(std::move(compiler)){}; + +CompilerBackend::~CompilerBackend() = default; + +const spirv_cross::Compiler* CompilerBackend::operator->() const { + return GetCompiler(); +} + +uint32_t CompilerBackend::GetExtendedMSLResourceBinding( + ExtendedResourceIndex index, + spirv_cross::ID id) const { + if (auto compiler = GetMSLCompiler()) { + switch (index) { + case ExtendedResourceIndex::kPrimary: + return compiler->get_automatic_msl_resource_binding(id); + case ExtendedResourceIndex::kSecondary: + return compiler->get_automatic_msl_resource_binding_secondary(id); + break; + } + } + if (auto compiler = GetGLSLCompiler()) { + return compiler->get_decoration(id, spv::Decoration::DecorationBinding); + } + const auto kOOBIndex = static_cast(-1); + return kOOBIndex; +} + +const spirv_cross::Compiler* CompilerBackend::GetCompiler() const { + if (auto compiler = GetGLSLCompiler()) { + return compiler; + } + + if (auto compiler = GetMSLCompiler()) { + return compiler; + } + + if (auto compiler = GetSkSLCompiler()) { + return compiler; + } + + return nullptr; +} + +spirv_cross::Compiler* CompilerBackend::GetCompiler() { + if (auto* msl = std::get_if(&compiler_)) { + return msl->get(); + } + if (auto* glsl = std::get_if(&compiler_)) { + return glsl->get(); + } + if (auto* sksl = std::get_if(&compiler_)) { + return sksl->get(); + } + return nullptr; +} + +const spirv_cross::CompilerMSL* CompilerBackend::GetMSLCompiler() const { + if (auto* msl = std::get_if(&compiler_)) { + return msl->get(); + } + return nullptr; +} + +const spirv_cross::CompilerGLSL* CompilerBackend::GetGLSLCompiler() const { + if (auto* glsl = std::get_if(&compiler_)) { + return glsl->get(); + } + return nullptr; +} + +const CompilerSkSL* CompilerBackend::GetSkSLCompiler() const { + if (auto* sksl = std::get_if(&compiler_)) { + return sksl->get(); + } + return nullptr; +} + +CompilerBackend::operator bool() const { + return !!GetCompiler(); +} + +CompilerBackend::Type CompilerBackend::GetType() const { + return type_; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler_backend.h b/flutter/engine/src/flutter/impeller/compiler/compiler_backend.h new file mode 100644 index 0000000000000000000000000000000000000000..3e24324b6c4e99decbcf266e7a6a3b342f4b7e08 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler_backend.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_ +#define FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_ + +#include +#include +#include + +#include "spirv_glsl.hpp" +#include "spirv_msl.hpp" +#include "spirv_sksl.h" + +namespace impeller { +namespace compiler { + +struct CompilerBackend { + using MSLCompiler = std::shared_ptr; + using GLSLCompiler = std::shared_ptr; + using SkSLCompiler = std::shared_ptr; + using Compiler = std::variant; + + enum class Type { + kMSL, + kGLSL, + kGLSLVulkan, + kSkSL, + }; + + explicit CompilerBackend(MSLCompiler compiler); + + explicit CompilerBackend(GLSLCompiler compiler); + + explicit CompilerBackend(SkSLCompiler compiler); + + CompilerBackend(Type type, Compiler compiler); + + CompilerBackend(); + + ~CompilerBackend(); + + Type GetType() const; + + const spirv_cross::Compiler* operator->() const; + + spirv_cross::Compiler* GetCompiler(); + + explicit operator bool() const; + + enum class ExtendedResourceIndex { + kPrimary, + kSecondary, + }; + uint32_t GetExtendedMSLResourceBinding(ExtendedResourceIndex index, + spirv_cross::ID id) const; + + const spirv_cross::Compiler* GetCompiler() const; + + private: + Type type_ = Type::kMSL; + Compiler compiler_; + + const spirv_cross::CompilerMSL* GetMSLCompiler() const; + + const spirv_cross::CompilerGLSL* GetGLSLCompiler() const; + + const CompilerSkSL* GetSkSLCompiler() const; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_COMPILER_BACKEND_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler_test.cc b/flutter/engine/src/flutter/impeller/compiler/compiler_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..06e2602611104407500894cb8d481aac05ebd5cd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler_test.cc @@ -0,0 +1,195 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/compiler_test.h" +#include "flutter/fml/paths.h" +#include "flutter/fml/process.h" + +#include +#include + +namespace impeller { +namespace compiler { +namespace testing { + +static std::string GetIntermediatesPath() { + auto test_name = flutter::testing::GetCurrentTestName(); + std::replace(test_name.begin(), test_name.end(), '/', '_'); + std::replace(test_name.begin(), test_name.end(), '.', '_'); + std::stringstream dir_name; + dir_name << test_name << "_" << std::to_string(fml::GetCurrentProcId()); + return fml::paths::JoinPaths( + {flutter::testing::GetFixturesPath(), dir_name.str()}); +} + +CompilerTest::CompilerTest() : intermediates_path_(GetIntermediatesPath()) { + intermediates_directory_ = + fml::OpenDirectory(intermediates_path_.c_str(), + true, // create if necessary + fml::FilePermission::kReadWrite); + FML_CHECK(intermediates_directory_.is_valid()); +} + +CompilerTest::~CompilerTest() { + intermediates_directory_.reset(); + + std::filesystem::remove_all(std::filesystem::path(intermediates_path_)); +} + +static std::string ReflectionHeaderName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".h"; + return stream.str(); +} + +static std::string ReflectionCCName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".cc"; + return stream.str(); +} + +static std::string ReflectionJSONName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".json"; + return stream.str(); +} + +static std::string SPIRVFileName(const char* fixture_name) { + std::stringstream stream; + stream << fixture_name << ".spv"; + return stream.str(); +} + +static std::string SLFileName(const char* fixture_name, + TargetPlatform platform) { + std::stringstream stream; + stream << fixture_name << "." << TargetPlatformSLExtension(platform); + return stream.str(); +} + +std::unique_ptr CompilerTest::GetReflectionJson( + const char* fixture_name) const { + auto filename = ReflectionJSONName(fixture_name); + auto fd = fml::OpenFileReadOnly(intermediates_directory_, filename.c_str()); + return fml::FileMapping::CreateReadOnly(fd); +} + +std::unique_ptr CompilerTest::GetShaderFile( + const char* fixture_name, + TargetPlatform platform) const { + auto filename = SLFileName(fixture_name, platform); + auto fd = fml::OpenFileReadOnly(intermediates_directory_, filename.c_str()); + return fml::FileMapping::CreateReadOnly(fd); +} + +bool CompilerTest::CanCompileAndReflect(const char* fixture_name, + SourceType source_type, + SourceLanguage source_language, + const char* entry_point_name) const { + std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping(fixture_name); + if (!fixture || !fixture->GetMapping()) { + VALIDATION_LOG << "Could not find shader in fixtures: " << fixture_name; + return false; + } + + SourceOptions source_options(fixture_name, source_type); + source_options.target_platform = GetParam(); + source_options.source_language = source_language; + source_options.working_directory = std::make_shared( + flutter::testing::OpenFixturesDirectory()); + source_options.entry_point_name = EntryPointFunctionNameFromSourceName( + fixture_name, SourceTypeFromFileName(fixture_name), source_language, + entry_point_name); + + Reflector::Options reflector_options; + reflector_options.header_file_name = ReflectionHeaderName(fixture_name); + reflector_options.shader_name = "shader_name"; + + Compiler compiler(fixture, source_options, reflector_options); + if (!compiler.IsValid()) { + VALIDATION_LOG << "Compilation failed: " << compiler.GetErrorMessages(); + return false; + } + + auto spirv_assembly = compiler.GetSPIRVAssembly(); + if (!spirv_assembly) { + VALIDATION_LOG << "No spirv was generated."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + SPIRVFileName(fixture_name).c_str(), + *spirv_assembly)) { + VALIDATION_LOG << "Could not write SPIRV intermediates."; + return false; + } + + auto sl_source = compiler.GetSLShaderSource(); + if (!sl_source) { + VALIDATION_LOG << "No SL source was generated."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + SLFileName(fixture_name, GetParam()).c_str(), + *sl_source)) { + VALIDATION_LOG << "Could not write SL intermediates."; + return false; + } + + if (TargetPlatformNeedsReflection(GetParam())) { + auto reflector = compiler.GetReflector(); + if (!reflector) { + VALIDATION_LOG + << "No reflector was found for target platform SL compiler."; + return false; + } + + auto reflection_json = reflector->GetReflectionJSON(); + auto reflection_header = reflector->GetReflectionHeader(); + auto reflection_source = reflector->GetReflectionCC(); + + if (!reflection_json) { + VALIDATION_LOG << "Reflection JSON was not found."; + return false; + } + + if (!reflection_header) { + VALIDATION_LOG << "Reflection header was not found."; + return false; + } + + if (!reflection_source) { + VALIDATION_LOG << "Reflection source was not found."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionHeaderName(fixture_name).c_str(), + *reflection_header)) { + VALIDATION_LOG << "Could not write reflection header intermediates."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionCCName(fixture_name).c_str(), + *reflection_source)) { + VALIDATION_LOG << "Could not write reflection CC intermediates."; + return false; + } + + if (!fml::WriteAtomically(intermediates_directory_, + ReflectionJSONName(fixture_name).c_str(), + *reflection_json)) { + VALIDATION_LOG << "Could not write reflection json intermediates."; + return false; + } + } + return true; +} + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler_test.h b/flutter/engine/src/flutter/impeller/compiler/compiler_test.h new file mode 100644 index 0000000000000000000000000000000000000000..59ba660dfe4284b062e9ca191e2d1f9b32041be1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler_test.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_ +#define FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_ + +#include "flutter/testing/testing.h" +#include "impeller/base/validation.h" +#include "impeller/compiler/compiler.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { +namespace testing { + +class CompilerTest : public ::testing::TestWithParam { + public: + CompilerTest(); + + ~CompilerTest(); + + std::unique_ptr GetReflectionJson( + const char* fixture_name) const; + + std::unique_ptr GetShaderFile( + const char* fixture_name, + TargetPlatform platform) const; + + bool CanCompileAndReflect( + const char* fixture_name, + SourceType source_type = SourceType::kUnknown, + SourceLanguage source_language = SourceLanguage::kGLSL, + const char* entry_point_name = "main") const; + + private: + std::string intermediates_path_; + fml::UniqueFD intermediates_directory_; + + CompilerTest(const CompilerTest&) = delete; + + CompilerTest& operator=(const CompilerTest&) = delete; +}; + +} // namespace testing +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_COMPILER_TEST_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/compiler_unittests.cc b/flutter/engine/src/flutter/impeller/compiler/compiler_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..afea65674c056c3a7a73c55b0a4cafc4cc181fa5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/compiler_unittests.cc @@ -0,0 +1,171 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/base/validation.h" +#include "impeller/compiler/compiler.h" +#include "impeller/compiler/compiler_test.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { +namespace testing { + +TEST(CompilerTest, ShaderKindMatchingIsSuccessful) { + ASSERT_EQ(SourceTypeFromFileName("hello.vert"), SourceType::kVertexShader); + ASSERT_EQ(SourceTypeFromFileName("hello.frag"), SourceType::kFragmentShader); + ASSERT_EQ(SourceTypeFromFileName("hello.comp"), SourceType::kComputeShader); + ASSERT_EQ(SourceTypeFromFileName("hello.msl"), SourceType::kUnknown); + ASSERT_EQ(SourceTypeFromFileName("hello.glsl"), SourceType::kUnknown); +} + +TEST_P(CompilerTest, CanCompile) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ASSERT_TRUE(CanCompileAndReflect("sample.vert")); + ASSERT_TRUE(CanCompileAndReflect("sample.vert", SourceType::kVertexShader)); + ASSERT_TRUE(CanCompileAndReflect("sample.vert", SourceType::kVertexShader, + SourceLanguage::kGLSL)); +} + +TEST_P(CompilerTest, CanCompileHLSL) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ASSERT_TRUE(CanCompileAndReflect( + "simple.vert.hlsl", SourceType::kVertexShader, SourceLanguage::kHLSL)); +} + +TEST_P(CompilerTest, CanCompileHLSLWithMultipleStages) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ASSERT_TRUE(CanCompileAndReflect("multiple_stages.hlsl", + SourceType::kVertexShader, + SourceLanguage::kHLSL, "VertexShader")); + ASSERT_TRUE(CanCompileAndReflect("multiple_stages.hlsl", + SourceType::kFragmentShader, + SourceLanguage::kHLSL, "FragmentShader")); +} + +TEST_P(CompilerTest, CanCompileComputeShader) { + if (!TargetPlatformIsMetal(GetParam())) { + GTEST_SKIP() + << "Only enabled on Metal backends till ES 3.2 support is added."; + } + ASSERT_TRUE(CanCompileAndReflect("sample.comp")); + ASSERT_TRUE(CanCompileAndReflect("sample.comp", SourceType::kComputeShader)); +} + +TEST_P(CompilerTest, MustFailDueToExceedingResourcesLimit) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ScopedValidationDisable disable_validation; + ASSERT_FALSE( + CanCompileAndReflect("resources_limit.vert", SourceType::kVertexShader)); +} + +TEST_P(CompilerTest, MustFailDueToMultipleLocationPerStructMember) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ScopedValidationDisable disable_validation; + ASSERT_FALSE(CanCompileAndReflect("struct_def_bug.vert")); +} + +TEST_P(CompilerTest, BindingBaseForFragShader) { + if (!TargetPlatformIsVulkan(GetParam())) { + GTEST_SKIP(); + } + + ASSERT_TRUE(CanCompileAndReflect("sample.vert", SourceType::kVertexShader)); + ASSERT_TRUE(CanCompileAndReflect("sample.frag", SourceType::kFragmentShader)); + + auto get_binding = [&](const char* fixture) -> uint32_t { + auto json_fd = GetReflectionJson(fixture); + nlohmann::json shader_json = nlohmann::json::parse(json_fd->GetMapping()); + return shader_json["buffers"][0]["binding"].get(); + }; + + auto vert_uniform_binding = get_binding("sample.vert"); + auto frag_uniform_binding = get_binding("sample.frag"); + + ASSERT_GT(frag_uniform_binding, vert_uniform_binding); +} + +TEST_P(CompilerTest, UniformsHaveBindingAndSet) { + if (GetParam() == TargetPlatform::kSkSL) { + GTEST_SKIP() << "Not supported with SkSL"; + } + ASSERT_TRUE(CanCompileAndReflect("sample_with_binding.vert", + SourceType::kVertexShader)); + ASSERT_TRUE(CanCompileAndReflect("sample.frag", SourceType::kFragmentShader)); + + struct binding_and_set { + uint32_t binding; + uint32_t set; + }; + + auto get_binding = [&](const char* fixture) -> binding_and_set { + auto json_fd = GetReflectionJson(fixture); + nlohmann::json shader_json = nlohmann::json::parse(json_fd->GetMapping()); + uint32_t binding = shader_json["buffers"][0]["binding"].get(); + uint32_t set = shader_json["buffers"][0]["set"].get(); + return {binding, set}; + }; + + auto vert_uniform_binding = get_binding("sample_with_binding.vert"); + auto frag_uniform_binding = get_binding("sample.frag"); + + ASSERT_EQ(frag_uniform_binding.set, 0u); + ASSERT_EQ(vert_uniform_binding.set, 3u); + ASSERT_EQ(vert_uniform_binding.binding, 17u); +} + +TEST_P(CompilerTest, SkSLTextureLookUpOrderOfOperations) { + if (GetParam() != TargetPlatform::kSkSL) { + GTEST_SKIP() << "Only supported on SkSL"; + } + ASSERT_TRUE( + CanCompileAndReflect("texture_lookup.frag", SourceType::kFragmentShader)); + + auto shader = GetShaderFile("texture_lookup.frag", GetParam()); + std::string_view shader_mapping( + reinterpret_cast(shader->GetMapping()), shader->GetSize()); + + constexpr std::string_view expected = + "textureA.eval(textureA_size * ( vec2(1.0) + flutter_FragCoord.xy));"; + + EXPECT_NE(shader_mapping.find(expected), std::string::npos); +} + +TEST_P(CompilerTest, CanCompileStructs) { + if (GetParam() != TargetPlatform::kSkSL) { + GTEST_SKIP() << "Only supported on SkSL"; + } + ASSERT_TRUE(CanCompileAndReflect("struct_internal.frag", + SourceType::kFragmentShader)); +} + +#define INSTANTIATE_TARGET_PLATFORM_TEST_SUITE_P(suite_name) \ + INSTANTIATE_TEST_SUITE_P( \ + suite_name, CompilerTest, \ + ::testing::Values(TargetPlatform::kOpenGLES, \ + TargetPlatform::kOpenGLDesktop, \ + TargetPlatform::kMetalDesktop, \ + TargetPlatform::kMetalIOS, TargetPlatform::kSkSL), \ + [](const ::testing::TestParamInfo& info) { \ + return TargetPlatformToString(info.param); \ + }); + +INSTANTIATE_TARGET_PLATFORM_TEST_SUITE_P(CompilerSuite); + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/constants.cc b/flutter/engine/src/flutter/impeller/compiler/constants.cc new file mode 100644 index 0000000000000000000000000000000000000000..e6ef34596a6f02c968c186836c61f835b22b4b52 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/constants.cc @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/constants.h" + +namespace impeller { +namespace compiler { + +// + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/constants.h b/flutter/engine/src/flutter/impeller/compiler/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..958a643aca542e23488e1e881e9984b43d8da0fa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/constants.h @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_CONSTANTS_H_ +#define FLUTTER_IMPELLER_COMPILER_CONSTANTS_H_ + +namespace impeller { +namespace compiler { + +constexpr char kExternalTexturePrefix[] = "SAMPLER_EXTERNAL_OES_"; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_CONSTANTS_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/impellerc_main.cc b/flutter/engine/src/flutter/impeller/compiler/impellerc_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4b54350378f0fd00f4c25528d4b7edc43ea7aab --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/impellerc_main.cc @@ -0,0 +1,315 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/fml/backtrace.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/file.h" +#include "flutter/fml/mapping.h" +#include "impeller/compiler/compiler.h" +#include "impeller/compiler/runtime_stage_data.h" +#include "impeller/compiler/shader_bundle.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/switches.h" +#include "impeller/compiler/types.h" +#include "impeller/compiler/utilities.h" + +namespace impeller { +namespace compiler { + +static Reflector::Options CreateReflectorOptions(const SourceOptions& options, + const Switches& switches) { + Reflector::Options reflector_options; + reflector_options.target_platform = options.target_platform; + reflector_options.entry_point_name = options.entry_point_name; + reflector_options.shader_name = + InferShaderNameFromPath(switches.source_file_name); + reflector_options.header_file_name = Utf8FromPath( + std::filesystem::path{switches.reflection_header_name}.filename()); + return reflector_options; +} + +/// Run the shader compiler to geneate SkSL reflection data. +/// If there is an error, prints error text and returns `nullptr`. +static std::shared_ptr CompileSkSL( + std::shared_ptr source_file_mapping, + const Switches& switches) { + auto options = switches.CreateSourceOptions(TargetPlatform::kSkSL); + + Reflector::Options sksl_reflector_options = + CreateReflectorOptions(options, switches); + sksl_reflector_options.target_platform = TargetPlatform::kSkSL; + + Compiler sksl_compiler = + Compiler(std::move(source_file_mapping), options, sksl_reflector_options); + if (!sksl_compiler.IsValid()) { + std::cerr << "Compilation to SkSL failed." << std::endl; + std::cerr << sksl_compiler.GetErrorMessages() << std::endl; + return nullptr; + } + return sksl_compiler.GetReflector()->GetRuntimeStageShaderData(); +} + +static bool OutputIPLR( + const Switches& switches, + const std::shared_ptr& source_file_mapping) { + FML_DCHECK(switches.iplr); + + RuntimeStageData stages; + std::shared_ptr sksl_shader; + if (TargetPlatformBundlesSkSL(switches.SelectDefaultTargetPlatform())) { + sksl_shader = CompileSkSL(source_file_mapping, switches); + if (!sksl_shader) { + return false; + } + stages.AddShader(sksl_shader); + } + + for (const auto& platform : switches.PlatformsToCompile()) { + if (platform == TargetPlatform::kSkSL) { + // Already handled above. + continue; + } + SourceOptions options = switches.CreateSourceOptions(platform); + + // Invoke the compiler and generate reflection data for a single shader. + + Reflector::Options reflector_options = + CreateReflectorOptions(options, switches); + Compiler compiler(source_file_mapping, options, reflector_options); + if (!compiler.IsValid()) { + std::cerr << "Compilation failed." << std::endl; + std::cerr << compiler.GetErrorMessages() << std::endl; + return false; + } + + auto reflector = compiler.GetReflector(); + if (reflector == nullptr) { + std::cerr << "Could not create reflector." << std::endl; + return false; + } + + auto stage_data = reflector->GetRuntimeStageShaderData(); + if (!stage_data) { + std::cerr << "Runtime stage information was nil." << std::endl; + return false; + } + + stages.AddShader(stage_data); + } + + auto stage_data_mapping = switches.json_format ? stages.CreateJsonMapping() + : stages.CreateMapping(); + if (!stage_data_mapping) { + std::cerr << "Runtime stage data could not be created." << std::endl; + return false; + } + if (!fml::WriteAtomically(*switches.working_directory, // + Utf8FromPath(switches.sl_file_name).c_str(), // + *stage_data_mapping // + )) { + std::cerr << "Could not write file to " << switches.sl_file_name + << std::endl; + return false; + } + // Tools that consume the runtime stage data expect the access mode to + // be 0644. + if (!SetPermissiveAccess(switches.sl_file_name)) { + return false; + } + return true; +} + +static bool OutputSLFile(const Compiler& compiler, const Switches& switches) { + // -------------------------------------------------------------------------- + /// 2. Output the source file. When in IPLR/RuntimeStage mode, output the + /// serialized IPLR flatbuffer. + /// + + auto sl_file_name = std::filesystem::absolute( + std::filesystem::current_path() / switches.sl_file_name); + if (!fml::WriteAtomically(*switches.working_directory, + Utf8FromPath(sl_file_name).c_str(), + *compiler.GetSLShaderSource())) { + std::cerr << "Could not write file to " << switches.sl_file_name + << std::endl; + return false; + } + return true; +} + +static bool OutputReflectionData(const Compiler& compiler, + const Switches& switches, + const SourceOptions& options) { + // -------------------------------------------------------------------------- + /// 3. Output shader reflection data. + /// May include a JSON file, a C++ header, and/or a C++ TU. + /// + + if (TargetPlatformNeedsReflection(options.target_platform)) { + if (!switches.reflection_json_name.empty()) { + auto reflection_json_name = std::filesystem::absolute( + std::filesystem::current_path() / switches.reflection_json_name); + if (!fml::WriteAtomically( + *switches.working_directory, + Utf8FromPath(reflection_json_name).c_str(), + *compiler.GetReflector()->GetReflectionJSON())) { + std::cerr << "Could not write reflection json to " + << switches.reflection_json_name << std::endl; + return false; + } + } + + if (!switches.reflection_header_name.empty()) { + auto reflection_header_name = + std::filesystem::absolute(std::filesystem::current_path() / + switches.reflection_header_name.c_str()); + if (!fml::WriteAtomically( + *switches.working_directory, + Utf8FromPath(reflection_header_name).c_str(), + *compiler.GetReflector()->GetReflectionHeader())) { + std::cerr << "Could not write reflection header to " + << switches.reflection_header_name << std::endl; + return false; + } + } + + if (!switches.reflection_cc_name.empty()) { + auto reflection_cc_name = + std::filesystem::absolute(std::filesystem::current_path() / + switches.reflection_cc_name.c_str()); + if (!fml::WriteAtomically(*switches.working_directory, + Utf8FromPath(reflection_cc_name).c_str(), + *compiler.GetReflector()->GetReflectionCC())) { + std::cerr << "Could not write reflection CC to " + << switches.reflection_cc_name << std::endl; + return false; + } + } + } + return true; +} + +static bool OutputDepfile(const Compiler& compiler, const Switches& switches) { + // -------------------------------------------------------------------------- + /// 4. Output a depfile. + /// + + if (!switches.depfile_path.empty()) { + std::string result_file; + switch (switches.SelectDefaultTargetPlatform()) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kSkSL: + case TargetPlatform::kVulkan: + result_file = switches.sl_file_name; + break; + case TargetPlatform::kUnknown: + result_file = switches.spirv_file_name; + break; + } + auto depfile_path = std::filesystem::absolute( + std::filesystem::current_path() / switches.depfile_path.c_str()); + if (!fml::WriteAtomically(*switches.working_directory, + Utf8FromPath(depfile_path).c_str(), + *compiler.CreateDepfileContents({result_file}))) { + std::cerr << "Could not write depfile to " << switches.depfile_path + << std::endl; + return false; + } + } + + return true; +} + +bool Main(const fml::CommandLine& command_line) { + fml::InstallCrashHandler(); + if (command_line.HasOption("help")) { + Switches::PrintHelp(std::cout); + return true; + } + + Switches switches(command_line); + if (!switches.AreValid(std::cerr)) { + std::cerr << "Invalid flags specified." << std::endl; + Switches::PrintHelp(std::cerr); + return false; + } + + if (!switches.shader_bundle.empty()) { + // Invoke the compiler multiple times to build a shader bundle with the + // given shader_bundle spec. + return GenerateShaderBundle(switches); + } + + std::shared_ptr source_file_mapping = + fml::FileMapping::CreateReadOnly(switches.source_file_name); + if (!source_file_mapping) { + std::cerr << "Could not open input file." << std::endl; + return false; + } + + if (switches.iplr && !OutputIPLR(switches, source_file_mapping)) { + return false; + } + + // Create at least one compiler to output the SL file, reflection data, and a + // depfile. + + SourceOptions options = switches.CreateSourceOptions(); + + // Invoke the compiler and generate reflection data for a single shader. + + Reflector::Options reflector_options = + CreateReflectorOptions(options, switches); + + Compiler compiler(source_file_mapping, options, reflector_options); + if (!compiler.IsValid()) { + std::cerr << "Compilation failed." << std::endl; + std::cerr << compiler.GetErrorMessages() << std::endl; + return false; + } + + auto spriv_file_name = std::filesystem::absolute( + std::filesystem::current_path() / switches.spirv_file_name); + if (!fml::WriteAtomically(*switches.working_directory, + Utf8FromPath(spriv_file_name).c_str(), + *compiler.GetSPIRVAssembly())) { + std::cerr << "Could not write file to " << switches.spirv_file_name + << std::endl; + return false; + } + + if (!switches.iplr && !OutputSLFile(compiler, switches)) { + return false; + } + + if (!OutputReflectionData(compiler, switches, options)) { + return false; + } + + if (!OutputDepfile(compiler, switches)) { + return false; + } + + return true; +} + +} // namespace compiler +} // namespace impeller + +int main(int argc, char const* argv[]) { + return impeller::compiler::Main( + fml::CommandLineFromPlatformOrArgcArgv(argc, argv)) + ? EXIT_SUCCESS + : EXIT_FAILURE; +} diff --git a/flutter/engine/src/flutter/impeller/compiler/include_dir.h b/flutter/engine/src/flutter/impeller/compiler/include_dir.h new file mode 100644 index 0000000000000000000000000000000000000000..2a40dd0e36973d3bb65b775e1eea79f2d0a70a3a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/include_dir.h @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_INCLUDE_DIR_H_ +#define FLUTTER_IMPELLER_COMPILER_INCLUDE_DIR_H_ + +#include +#include + +#include "flutter/fml/unique_fd.h" + +namespace impeller { +namespace compiler { + +struct IncludeDir { + std::shared_ptr dir; + std::string name; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_INCLUDE_DIR_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/includer.cc b/flutter/engine/src/flutter/impeller/compiler/includer.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9786532e114c1596e37b96bbd9c9d159c243d4e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/includer.cc @@ -0,0 +1,119 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/includer.h" + +#include + +#include "flutter/fml/paths.h" + +namespace impeller { +namespace compiler { + +Includer::Includer(std::shared_ptr working_directory, + std::vector include_dirs, + std::function on_file_included) + : working_directory_(std::move(working_directory)), + include_dirs_(std::move(include_dirs)), + on_file_included_(std::move(on_file_included)) {} + +// |shaderc::CompileOptions::IncluderInterface| +Includer::~Includer() = default; + +std::unique_ptr Includer::TryOpenMapping( + const IncludeDir& dir, + const char* requested_source) { + if (!dir.dir || !dir.dir->is_valid()) { + return nullptr; + } + + if (requested_source == nullptr) { + return nullptr; + } + + std::string source(requested_source); + if (source.empty()) { + return nullptr; + } + + auto mapping = fml::FileMapping::CreateReadOnly(*dir.dir, requested_source); + if (!mapping || !mapping->IsValid()) { + return nullptr; + } + + on_file_included_(fml::paths::JoinPaths({dir.name, requested_source})); + + return mapping; +} + +std::unique_ptr Includer::FindFirstMapping( + const char* requested_source) { + // Always try the working directory first no matter what the include + // directories are. + { + IncludeDir dir; + dir.name = "."; + dir.dir = working_directory_; + if (auto mapping = TryOpenMapping(dir, requested_source)) { + return mapping; + } + } + + for (const auto& include_dir : include_dirs_) { + if (auto mapping = TryOpenMapping(include_dir, requested_source)) { + return mapping; + } + } + return nullptr; +} + +shaderc_include_result* Includer::GetInclude(const char* requested_source, + shaderc_include_type type, + const char* requesting_source, + size_t include_depth) { + auto result = std::make_unique(); + + // Default initialize to failed inclusion. + result->source_name = ""; + result->source_name_length = 0; + + constexpr const char* kFileNotFoundMessage = "Included file not found."; + result->content = kFileNotFoundMessage; + result->content_length = ::strlen(kFileNotFoundMessage); + result->user_data = nullptr; + + if (!working_directory_ || !working_directory_->is_valid()) { + return result.release(); + } + + if (requested_source == nullptr) { + return result.release(); + } + + auto file = FindFirstMapping(requested_source); + + if (!file || file->GetMapping() == nullptr) { + return result.release(); + } + + auto includer_data = + std::make_unique(requested_source, std::move(file)); + + result->source_name = includer_data->file_name.c_str(); + result->source_name_length = includer_data->file_name.length(); + result->content = reinterpret_castcontent)>( + includer_data->mapping->GetMapping()); + result->content_length = includer_data->mapping->GetSize(); + result->user_data = includer_data.release(); + + return result.release(); +} + +void Includer::ReleaseInclude(shaderc_include_result* data) { + delete reinterpret_cast(data->user_data); + delete data; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/includer.h b/flutter/engine/src/flutter/impeller/compiler/includer.h new file mode 100644 index 0000000000000000000000000000000000000000..70123148006e23470c34aa9bbc6810815df29f10 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/includer.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_INCLUDER_H_ +#define FLUTTER_IMPELLER_COMPILER_INCLUDER_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/compiler/include_dir.h" +#include "shaderc/shaderc.hpp" + +namespace impeller { +namespace compiler { + +struct IncluderData { + std::string file_name; + std::unique_ptr mapping; + + IncluderData(std::string p_file_name, std::unique_ptr p_mapping) + : file_name(std::move(p_file_name)), mapping(std::move(p_mapping)) {} +}; + +class Includer final : public shaderc::CompileOptions::IncluderInterface { + public: + Includer(std::shared_ptr working_directory, + std::vector include_dirs, + std::function on_file_included); + + // |shaderc::CompileOptions::IncluderInterface| + ~Includer() override; + + // |shaderc::CompileOptions::IncluderInterface| + shaderc_include_result* GetInclude(const char* requested_source, + shaderc_include_type type, + const char* requesting_source, + size_t include_depth) override; + + // |shaderc::CompileOptions::IncluderInterface| + void ReleaseInclude(shaderc_include_result* data) override; + + private: + std::shared_ptr working_directory_; + std::vector include_dirs_; + std::function on_file_included_; + + std::unique_ptr TryOpenMapping( + const IncludeDir& dir, + const char* requested_source); + + std::unique_ptr FindFirstMapping( + const char* requested_source); + + Includer(const Includer&) = delete; + + Includer& operator=(const Includer&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_INCLUDER_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/logger.h b/flutter/engine/src/flutter/impeller/compiler/logger.h new file mode 100644 index 0000000000000000000000000000000000000000..11232d83a8449fef215d6b934d4b838b4254aed0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/logger.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_LOGGER_H_ +#define FLUTTER_IMPELLER_COMPILER_LOGGER_H_ + +#include +#include + +#include "flutter/fml/logging.h" + +namespace impeller { +namespace compiler { + +class AutoLogger { + public: + explicit AutoLogger(std::stringstream& logger) : logger_(logger) {} + + ~AutoLogger() { + logger_ << std::endl; + logger_.flush(); + } + + template + AutoLogger& operator<<(const T& object) { + logger_ << object; + return *this; + } + + private: + std::stringstream& logger_; + + AutoLogger(const AutoLogger&) = delete; + + AutoLogger& operator=(const AutoLogger&) = delete; +}; + +#define COMPILER_ERROR(stream) \ + ::impeller::compiler::AutoLogger(stream) << GetSourcePrefix() + +#define COMPILER_ERROR_NO_PREFIX(stream) \ + ::impeller::compiler::AutoLogger(stream) + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_LOGGER_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/reflector.cc b/flutter/engine/src/flutter/impeller/compiler/reflector.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba8ecb356940fcddbf10bb1d91db3df1cb6fbef9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/reflector.cc @@ -0,0 +1,1476 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/105732 + +#include "impeller/compiler/reflector.h" + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "fml/backtrace.h" +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/compiler/code_gen_template.h" +#include "impeller/compiler/shader_bundle_data.h" +#include "impeller/compiler/types.h" +#include "impeller/compiler/uniform_sorter.h" +#include "impeller/compiler/utilities.h" +#include "impeller/core/runtime_types.h" +#include "impeller/geometry/half.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/scalar.h" +#include "impeller/runtime_stage/runtime_stage.h" +#include "spirv_common.hpp" + +namespace impeller { +namespace compiler { + +static std::string ExecutionModelToString(spv::ExecutionModel model) { + switch (model) { + case spv::ExecutionModel::ExecutionModelVertex: + return "vertex"; + case spv::ExecutionModel::ExecutionModelFragment: + return "fragment"; + case spv::ExecutionModel::ExecutionModelGLCompute: + return "compute"; + default: + return "unsupported"; + } +} + +static std::string StringToShaderStage(const std::string& str) { + if (str == "vertex") { + return "ShaderStage::kVertex"; + } + + if (str == "fragment") { + return "ShaderStage::kFragment"; + } + + if (str == "compute") { + return "ShaderStage::kCompute"; + } + + return "ShaderStage::kUnknown"; +} + +Reflector::Reflector(Options options, + const std::shared_ptr& ir, + const std::shared_ptr& shader_data, + const CompilerBackend& compiler) + : options_(std::move(options)), + ir_(ir), + shader_data_(shader_data), + compiler_(compiler) { + if (!ir_ || !compiler_) { + return; + } + + if (auto template_arguments = GenerateTemplateArguments(); + template_arguments.has_value()) { + template_arguments_ = + std::make_unique(std::move(template_arguments.value())); + } else { + return; + } + + reflection_header_ = GenerateReflectionHeader(); + if (!reflection_header_) { + return; + } + + reflection_cc_ = GenerateReflectionCC(); + if (!reflection_cc_) { + return; + } + + runtime_stage_shader_ = GenerateRuntimeStageData(); + + shader_bundle_data_ = GenerateShaderBundleData(); + if (!shader_bundle_data_) { + return; + } + + is_valid_ = true; +} + +Reflector::~Reflector() = default; + +bool Reflector::IsValid() const { + return is_valid_; +} + +std::shared_ptr Reflector::GetReflectionJSON() const { + if (!is_valid_) { + return nullptr; + } + + auto json_string = + std::make_shared(template_arguments_->dump(2u)); + + return std::make_shared( + reinterpret_cast(json_string->data()), + json_string->size(), [json_string](auto, auto) {}); +} + +std::shared_ptr Reflector::GetReflectionHeader() const { + return reflection_header_; +} + +std::shared_ptr Reflector::GetReflectionCC() const { + return reflection_cc_; +} + +std::shared_ptr Reflector::GetRuntimeStageShaderData() + const { + return runtime_stage_shader_; +} + +std::shared_ptr Reflector::GetShaderBundleData() const { + return shader_bundle_data_; +} + +std::optional Reflector::GenerateTemplateArguments() const { + nlohmann::json root; + + const auto& entrypoints = compiler_->get_entry_points_and_stages(); + if (entrypoints.size() != 1) { + VALIDATION_LOG << "Incorrect number of entrypoints in the shader. Found " + << entrypoints.size() << " but expected 1."; + return std::nullopt; + } + + auto execution_model = entrypoints.front().execution_model; + { + root["entrypoint"] = options_.entry_point_name; + root["shader_name"] = options_.shader_name; + root["shader_stage"] = ExecutionModelToString(execution_model); + root["header_file_name"] = options_.header_file_name; + } + + const auto shader_resources = compiler_->get_shader_resources(); + + // Subpass Inputs. + { + auto& subpass_inputs = root["subpass_inputs"] = nlohmann::json::array_t{}; + if (auto subpass_inputs_json = + ReflectResources(shader_resources.subpass_inputs); + subpass_inputs_json.has_value()) { + for (auto subpass_input : subpass_inputs_json.value()) { + subpass_input["descriptor_type"] = "DescriptorType::kInputAttachment"; + subpass_inputs.emplace_back(std::move(subpass_input)); + } + } else { + return std::nullopt; + } + } + + // Uniform and storage buffers. + { + auto& buffers = root["buffers"] = nlohmann::json::array_t{}; + if (auto uniform_buffers_json = + ReflectResources(shader_resources.uniform_buffers); + uniform_buffers_json.has_value()) { + for (auto uniform_buffer : uniform_buffers_json.value()) { + uniform_buffer["descriptor_type"] = "DescriptorType::kUniformBuffer"; + buffers.emplace_back(std::move(uniform_buffer)); + } + } else { + return std::nullopt; + } + if (auto storage_buffers_json = + ReflectResources(shader_resources.storage_buffers); + storage_buffers_json.has_value()) { + for (auto uniform_buffer : storage_buffers_json.value()) { + uniform_buffer["descriptor_type"] = "DescriptorType::kStorageBuffer"; + buffers.emplace_back(std::move(uniform_buffer)); + } + } else { + return std::nullopt; + } + } + + { + auto& stage_inputs = root["stage_inputs"] = nlohmann::json::array_t{}; + if (auto stage_inputs_json = ReflectResources( + shader_resources.stage_inputs, + /*compute_offsets=*/execution_model == spv::ExecutionModelVertex); + stage_inputs_json.has_value()) { + stage_inputs = std::move(stage_inputs_json.value()); + } else { + return std::nullopt; + } + } + + { + auto combined_sampled_images = + ReflectResources(shader_resources.sampled_images); + auto images = ReflectResources(shader_resources.separate_images); + auto samplers = ReflectResources(shader_resources.separate_samplers); + if (!combined_sampled_images.has_value() || !images.has_value() || + !samplers.has_value()) { + return std::nullopt; + } + auto& sampled_images = root["sampled_images"] = nlohmann::json::array_t{}; + for (auto value : combined_sampled_images.value()) { + value["descriptor_type"] = "DescriptorType::kSampledImage"; + sampled_images.emplace_back(std::move(value)); + } + for (auto value : images.value()) { + value["descriptor_type"] = "DescriptorType::kImage"; + sampled_images.emplace_back(std::move(value)); + } + for (auto value : samplers.value()) { + value["descriptor_type"] = "DescriptorType::kSampledSampler"; + sampled_images.emplace_back(std::move(value)); + } + } + + if (auto stage_outputs = ReflectResources(shader_resources.stage_outputs); + stage_outputs.has_value()) { + root["stage_outputs"] = std::move(stage_outputs.value()); + } else { + return std::nullopt; + } + + { + auto& struct_definitions = root["struct_definitions"] = + nlohmann::json::array_t{}; + if (entrypoints.front().execution_model == + spv::ExecutionModel::ExecutionModelVertex && + !shader_resources.stage_inputs.empty()) { + if (auto struc = + ReflectPerVertexStructDefinition(shader_resources.stage_inputs); + struc.has_value()) { + struct_definitions.emplace_back(EmitStructDefinition(struc.value())); + } else { + // If there are stage inputs, it is an error to not generate a per + // vertex data struct for a vertex like shader stage. + return std::nullopt; + } + } + + std::set known_structs; + ir_->for_each_typed_id( + [&](uint32_t, const spirv_cross::SPIRType& type) { + if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) { + return; + } + // Skip structs that do not have layout offset decorations. + // These structs are used internally within the shader and are not + // part of the shader's interface. + for (size_t i = 0; i < type.member_types.size(); i++) { + if (!compiler_->has_member_decoration(type.self, i, + spv::DecorationOffset)) { + return; + } + } + if (known_structs.find(type.self) != known_structs.end()) { + // Iterating over types this way leads to duplicates which may cause + // duplicate struct definitions. + return; + } + known_structs.insert(type.self); + if (auto struc = ReflectStructDefinition(type.self); + struc.has_value()) { + struct_definitions.emplace_back( + EmitStructDefinition(struc.value())); + } + }); + } + + root["bind_prototypes"] = + EmitBindPrototypes(shader_resources, execution_model); + + return root; +} + +std::shared_ptr Reflector::GenerateReflectionHeader() const { + return InflateTemplate(kReflectionHeaderTemplate); +} + +std::shared_ptr Reflector::GenerateReflectionCC() const { + return InflateTemplate(kReflectionCCTemplate); +} + +static std::optional GetRuntimeStageBackend( + TargetPlatform target_platform) { + switch (target_platform) { + case TargetPlatform::kUnknown: + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kVulkan: + return std::nullopt; + case TargetPlatform::kRuntimeStageMetal: + return RuntimeStageBackend::kMetal; + case TargetPlatform::kRuntimeStageGLES: + return RuntimeStageBackend::kOpenGLES; + case TargetPlatform::kRuntimeStageGLES3: + return RuntimeStageBackend::kOpenGLES3; + case TargetPlatform::kRuntimeStageVulkan: + return RuntimeStageBackend::kVulkan; + case TargetPlatform::kSkSL: + return RuntimeStageBackend::kSkSL; + } + FML_UNREACHABLE(); +} + +std::shared_ptr Reflector::GenerateRuntimeStageData() + const { + auto backend = GetRuntimeStageBackend(options_.target_platform); + if (!backend.has_value()) { + return nullptr; + } + + const auto& entrypoints = compiler_->get_entry_points_and_stages(); + if (entrypoints.size() != 1u) { + VALIDATION_LOG << "Single entrypoint not found."; + return nullptr; + } + auto data = std::make_unique(); + data->entrypoint = options_.entry_point_name; + data->stage = entrypoints.front().execution_model; + data->shader = shader_data_; + data->backend = backend.value(); + + // Sort the IR so that the uniforms are in declaration order. + std::vector uniforms = + SortUniforms(ir_.get(), compiler_.GetCompiler()); + for (auto& sorted_id : uniforms) { + auto var = ir_->ids[sorted_id].get(); + const auto spir_type = compiler_->get_type(var.basetype); + UniformDescription uniform_description; + uniform_description.name = compiler_->get_name(var.self); + uniform_description.location = compiler_->get_decoration( + var.self, spv::Decoration::DecorationLocation); + uniform_description.binding = + compiler_->get_decoration(var.self, spv::Decoration::DecorationBinding); + uniform_description.type = spir_type.basetype; + uniform_description.rows = spir_type.vecsize; + uniform_description.columns = spir_type.columns; + uniform_description.bit_width = spir_type.width; + uniform_description.array_elements = GetArrayElements(spir_type); + FML_CHECK(data->backend != RuntimeStageBackend::kVulkan || + spir_type.basetype == + spirv_cross::SPIRType::BaseType::SampledImage) + << "Vulkan runtime effect had unexpected uniforms outside of the " + "uniform buffer object."; + data->uniforms.emplace_back(std::move(uniform_description)); + } + + const auto ubos = compiler_->get_shader_resources().uniform_buffers; + if (data->backend == RuntimeStageBackend::kVulkan && !ubos.empty()) { + if (ubos.size() != 1 && ubos[0].name != RuntimeStage::kVulkanUBOName) { + VALIDATION_LOG << "Expected a single UBO resource named " + "'" + << RuntimeStage::kVulkanUBOName + << "' " + "for Vulkan runtime stage backend."; + return nullptr; + } + + const auto& ubo = ubos[0]; + + size_t binding = + compiler_->get_decoration(ubo.id, spv::Decoration::DecorationBinding); + auto members = ReadStructMembers(ubo.type_id); + std::vector struct_layout; + size_t float_count = 0; + + for (size_t i = 0; i < members.size(); i += 1) { + const auto& member = members[i]; + std::vector bytes; + switch (member.underlying_type) { + case StructMember::UnderlyingType::kPadding: { + size_t padding_count = + (member.size + sizeof(float) - 1) / sizeof(float); + while (padding_count > 0) { + struct_layout.push_back(0); + padding_count--; + } + break; + } + case StructMember::UnderlyingType::kFloat: { + if (member.array_elements > 1) { + // For each array element member, insert 1 layout property per byte + // and 0 layout property per byte of padding + for (auto i = 0; i < member.array_elements; i++) { + for (auto j = 0u; j < member.size / sizeof(float); j++) { + struct_layout.push_back(1); + } + for (auto j = 0u; j < member.element_padding / sizeof(float); + j++) { + struct_layout.push_back(0); + } + } + } else { + size_t member_float_count = member.byte_length / sizeof(float); + float_count += member_float_count; + while (member_float_count > 0) { + struct_layout.push_back(1); + member_float_count--; + } + } + break; + } + case StructMember::UnderlyingType::kOther: + VALIDATION_LOG << "Non-floating-type struct member " << member.name + << " is not supported."; + return nullptr; + } + } + data->uniforms.emplace_back(UniformDescription{ + .name = ubo.name, + .location = binding, + .binding = binding, + .type = spirv_cross::SPIRType::Struct, + .struct_layout = std::move(struct_layout), + .struct_float_count = float_count, + }); + } + + // We only need to worry about storing vertex attributes. + if (entrypoints.front().execution_model == spv::ExecutionModelVertex) { + const auto inputs = compiler_->get_shader_resources().stage_inputs; + auto input_offsets = ComputeOffsets(inputs); + for (const auto& input : inputs) { + std::optional offset = GetOffset(input.id, input_offsets); + + const auto type = compiler_->get_type(input.type_id); + + InputDescription input_description; + input_description.name = input.name; + input_description.location = compiler_->get_decoration( + input.id, spv::Decoration::DecorationLocation); + input_description.set = compiler_->get_decoration( + input.id, spv::Decoration::DecorationDescriptorSet); + input_description.binding = compiler_->get_decoration( + input.id, spv::Decoration::DecorationBinding); + input_description.type = type.basetype; + input_description.bit_width = type.width; + input_description.vec_size = type.vecsize; + input_description.columns = type.columns; + input_description.offset = offset.value_or(0u); + data->inputs.emplace_back(std::move(input_description)); + } + } + + return data; +} + +std::shared_ptr Reflector::GenerateShaderBundleData() const { + const auto& entrypoints = compiler_->get_entry_points_and_stages(); + if (entrypoints.size() != 1u) { + VALIDATION_LOG << "Single entrypoint not found."; + return nullptr; + } + auto data = std::make_shared( + options_.entry_point_name, // + entrypoints.front().execution_model, // + options_.target_platform // + ); + data->SetShaderData(shader_data_); + + const auto uniforms = compiler_->get_shader_resources().uniform_buffers; + for (const auto& uniform : uniforms) { + ShaderBundleData::ShaderUniformStruct uniform_struct; + uniform_struct.name = uniform.name; + uniform_struct.ext_res_0 = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kPrimary, uniform.id); + uniform_struct.set = compiler_->get_decoration( + uniform.id, spv::Decoration::DecorationDescriptorSet); + uniform_struct.binding = compiler_->get_decoration( + uniform.id, spv::Decoration::DecorationBinding); + + const auto type = compiler_->get_type(uniform.type_id); + if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) { + std::cerr << "Error: Uniform \"" << uniform.name + << "\" is not a struct. All Flutter GPU shader uniforms must " + "be structs." + << std::endl; + return nullptr; + } + + size_t size_in_bytes = 0; + for (const auto& struct_member : ReadStructMembers(uniform.type_id)) { + size_in_bytes += struct_member.byte_length; + if (StringStartsWith(struct_member.name, "_PADDING_")) { + continue; + } + ShaderBundleData::ShaderUniformStructField uniform_struct_field; + uniform_struct_field.name = struct_member.name; + uniform_struct_field.type = struct_member.base_type; + uniform_struct_field.offset_in_bytes = struct_member.offset; + uniform_struct_field.element_size_in_bytes = struct_member.size; + uniform_struct_field.total_size_in_bytes = struct_member.byte_length; + uniform_struct_field.array_elements = struct_member.array_elements; + uniform_struct.fields.push_back(uniform_struct_field); + } + uniform_struct.size_in_bytes = size_in_bytes; + + data->AddUniformStruct(uniform_struct); + } + + const auto sampled_images = compiler_->get_shader_resources().sampled_images; + for (const auto& image : sampled_images) { + ShaderBundleData::ShaderUniformTexture uniform_texture; + uniform_texture.name = image.name; + uniform_texture.ext_res_0 = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kPrimary, image.id); + uniform_texture.set = compiler_->get_decoration( + image.id, spv::Decoration::DecorationDescriptorSet); + uniform_texture.binding = + compiler_->get_decoration(image.id, spv::Decoration::DecorationBinding); + data->AddUniformTexture(uniform_texture); + } + + // We only need to worry about storing vertex attributes. + if (entrypoints.front().execution_model == spv::ExecutionModelVertex) { + const auto inputs = compiler_->get_shader_resources().stage_inputs; + auto input_offsets = ComputeOffsets(inputs); + for (const auto& input : inputs) { + std::optional offset = GetOffset(input.id, input_offsets); + + const auto type = compiler_->get_type(input.type_id); + + InputDescription input_description; + input_description.name = input.name; + input_description.location = compiler_->get_decoration( + input.id, spv::Decoration::DecorationLocation); + input_description.set = compiler_->get_decoration( + input.id, spv::Decoration::DecorationDescriptorSet); + input_description.binding = compiler_->get_decoration( + input.id, spv::Decoration::DecorationBinding); + input_description.type = type.basetype; + input_description.bit_width = type.width; + input_description.vec_size = type.vecsize; + input_description.columns = type.columns; + input_description.offset = offset.value_or(0u); + data->AddInputDescription(std::move(input_description)); + } + } + + return data; +} + +std::optional Reflector::GetArrayElements( + const spirv_cross::SPIRType& type) const { + if (type.array.empty()) { + return std::nullopt; + } + FML_CHECK(type.array.size() == 1) + << "Multi-dimensional arrays are not supported."; + FML_CHECK(type.array_size_literal.front()) + << "Must use a literal for array sizes."; + return type.array.front(); +} + +static std::string ToString(CompilerBackend::Type type) { + switch (type) { + case CompilerBackend::Type::kMSL: + return "Metal Shading Language"; + case CompilerBackend::Type::kGLSL: + return "OpenGL Shading Language"; + case CompilerBackend::Type::kGLSLVulkan: + return "OpenGL Shading Language (Relaxed Vulkan Semantics)"; + case CompilerBackend::Type::kSkSL: + return "SkSL Shading Language"; + } + FML_UNREACHABLE(); +} + +std::shared_ptr Reflector::InflateTemplate( + std::string_view tmpl) const { + inja::Environment env; + env.set_trim_blocks(true); + env.set_lstrip_blocks(true); + + env.add_callback("camel_case", 1u, [](inja::Arguments& args) { + return ToCamelCase(args.at(0u)->get()); + }); + + env.add_callback("to_shader_stage", 1u, [](inja::Arguments& args) { + return StringToShaderStage(args.at(0u)->get()); + }); + + env.add_callback("get_generator_name", 0u, + [type = compiler_.GetType()](inja::Arguments& args) { + return ToString(type); + }); + + auto inflated_template = + std::make_shared(env.render(tmpl, *template_arguments_)); + + return std::make_shared( + reinterpret_cast(inflated_template->data()), + inflated_template->size(), [inflated_template](auto, auto) {}); +} + +std::vector Reflector::ComputeOffsets( + const spirv_cross::SmallVector& resources) const { + std::vector offsets(resources.size(), 0); + if (resources.size() == 0) { + return offsets; + } + for (const auto& resource : resources) { + const auto type = compiler_->get_type(resource.type_id); + auto location = compiler_->get_decoration( + resource.id, spv::Decoration::DecorationLocation); + // Malformed shader, will be caught later on. + if (location >= resources.size() || location < 0) { + location = 0; + } + offsets[location] = (type.width * type.vecsize) / 8; + } + for (size_t i = 1; i < resources.size(); i++) { + offsets[i] += offsets[i - 1]; + } + for (size_t i = resources.size() - 1; i > 0; i--) { + offsets[i] = offsets[i - 1]; + } + offsets[0] = 0; + + return offsets; +} + +std::optional Reflector::GetOffset( + spirv_cross::ID id, + const std::vector& offsets) const { + uint32_t location = + compiler_->get_decoration(id, spv::Decoration::DecorationLocation); + if (location >= offsets.size()) { + return std::nullopt; + } + return offsets[location]; +} + +std::optional Reflector::ReflectResource( + const spirv_cross::Resource& resource, + std::optional offset) const { + nlohmann::json::object_t result; + + result["name"] = resource.name; + result["descriptor_set"] = compiler_->get_decoration( + resource.id, spv::Decoration::DecorationDescriptorSet); + result["binding"] = compiler_->get_decoration( + resource.id, spv::Decoration::DecorationBinding); + result["set"] = compiler_->get_decoration( + resource.id, spv::Decoration::DecorationDescriptorSet); + result["location"] = compiler_->get_decoration( + resource.id, spv::Decoration::DecorationLocation); + result["index"] = + compiler_->get_decoration(resource.id, spv::Decoration::DecorationIndex); + result["ext_res_0"] = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kPrimary, resource.id); + result["ext_res_1"] = compiler_.GetExtendedMSLResourceBinding( + CompilerBackend::ExtendedResourceIndex::kSecondary, resource.id); + result["relaxed_precision"] = + compiler_->get_decoration( + resource.id, spv::Decoration::DecorationRelaxedPrecision) == 1; + result["offset"] = offset.value_or(0u); + auto type = ReflectType(resource.type_id); + if (!type.has_value()) { + return std::nullopt; + } + result["type"] = std::move(type.value()); + return result; +} + +std::optional Reflector::ReflectType( + const spirv_cross::TypeID& type_id) const { + nlohmann::json::object_t result; + + const auto type = compiler_->get_type(type_id); + + result["type_name"] = StructMember::BaseTypeToString(type.basetype); + result["bit_width"] = type.width; + result["vec_size"] = type.vecsize; + result["columns"] = type.columns; + auto& members = result["members"] = nlohmann::json::array_t{}; + if (type.basetype == spirv_cross::SPIRType::BaseType::Struct) { + for (const auto& struct_member : ReadStructMembers(type_id)) { + auto member = nlohmann::json::object_t{}; + member["name"] = struct_member.name; + member["type"] = struct_member.type; + member["base_type"] = + StructMember::BaseTypeToString(struct_member.base_type); + member["offset"] = struct_member.offset; + member["size"] = struct_member.size; + member["byte_length"] = struct_member.byte_length; + if (struct_member.array_elements.has_value()) { + member["array_elements"] = struct_member.array_elements.value(); + } else { + member["array_elements"] = "std::nullopt"; + } + members.emplace_back(std::move(member)); + } + } + + return result; +} + +std::optional Reflector::ReflectResources( + const spirv_cross::SmallVector& resources, + bool compute_offsets) const { + nlohmann::json::array_t result; + result.reserve(resources.size()); + std::vector offsets; + if (compute_offsets) { + offsets = ComputeOffsets(resources); + } + for (const auto& resource : resources) { + std::optional maybe_offset = std::nullopt; + if (compute_offsets) { + maybe_offset = GetOffset(resource.id, offsets); + } + if (auto reflected = ReflectResource(resource, maybe_offset); + reflected.has_value()) { + result.emplace_back(std::move(reflected.value())); + } else { + return std::nullopt; + } + } + return result; +} + +static std::string TypeNameWithPaddingOfSize(size_t size) { + std::stringstream stream; + stream << "Padding<" << size << ">"; + return stream.str(); +} + +struct KnownType { + std::string name; + size_t byte_size = 0; +}; + +static std::optional ReadKnownScalarType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::BaseType::Boolean: + return KnownType{ + .name = "bool", + .byte_size = sizeof(bool), + }; + case spirv_cross::SPIRType::BaseType::Float: + return KnownType{ + .name = "Scalar", + .byte_size = sizeof(Scalar), + }; + case spirv_cross::SPIRType::BaseType::Half: + return KnownType{ + .name = "Half", + .byte_size = sizeof(Half), + }; + case spirv_cross::SPIRType::BaseType::UInt: + return KnownType{ + .name = "uint32_t", + .byte_size = sizeof(uint32_t), + }; + case spirv_cross::SPIRType::BaseType::Int: + return KnownType{ + .name = "int32_t", + .byte_size = sizeof(int32_t), + }; + default: + break; + } + return std::nullopt; +} + +//------------------------------------------------------------------------------ +/// @brief Get the reflected struct size. In the vast majority of the +/// cases, this is the same as the declared struct size as given by +/// the compiler. But, additional padding may need to be introduced +/// after the end of the struct to keep in line with the alignment +/// requirement of the individual struct members. This method +/// figures out the actual size of the reflected struct that can be +/// referenced in native code. +/// +/// @param[in] members The members +/// +/// @return The reflected structure size. +/// +static size_t GetReflectedStructSize(const std::vector& members) { + auto struct_size = 0u; + for (const auto& member : members) { + struct_size += member.byte_length; + } + return struct_size; +} + +std::vector Reflector::ReadStructMembers( + const spirv_cross::TypeID& type_id) const { + const auto& struct_type = compiler_->get_type(type_id); + FML_CHECK(struct_type.basetype == spirv_cross::SPIRType::BaseType::Struct); + + std::vector result; + + size_t current_byte_offset = 0; + size_t max_member_alignment = 0; + + for (size_t i = 0; i < struct_type.member_types.size(); i++) { + const auto& member = compiler_->get_type(struct_type.member_types[i]); + const auto struct_member_offset = + compiler_->type_struct_member_offset(struct_type, i); + auto array_elements = GetArrayElements(member); + + if (struct_member_offset > current_byte_offset) { + const auto alignment_pad = struct_member_offset - current_byte_offset; + result.emplace_back(StructMember{ + TypeNameWithPaddingOfSize(alignment_pad), // type + spirv_cross::SPIRType::BaseType::Void, // basetype + SPrintF("_PADDING_%s_", + GetMemberNameAtIndex(struct_type, i).c_str()), // name + current_byte_offset, // offset + alignment_pad, // size + alignment_pad, // byte_length + std::nullopt, // array_elements + 0, // element_padding + }); + current_byte_offset += alignment_pad; + } + + max_member_alignment = + std::max(max_member_alignment, + (member.width / 8) * member.columns * member.vecsize); + + FML_CHECK(current_byte_offset == struct_member_offset); + + // A user defined struct. + if (member.basetype == spirv_cross::SPIRType::BaseType::Struct) { + const size_t size = + GetReflectedStructSize(ReadStructMembers(member.self)); + uint32_t stride = GetArrayStride<0>(struct_type, member, i); + if (stride == 0) { + stride = size; + } + uint32_t element_padding = stride - size; + result.emplace_back(StructMember{ + compiler_->get_name(member.self), // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + size, // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed 4x4 Matrix is special cased as we know how to work with + // those. + if (member.basetype == spirv_cross::SPIRType::BaseType::Float && // + member.width == sizeof(Scalar) * 8 && // + member.columns == 4 && // + member.vecsize == 4 // + ) { + uint32_t stride = GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(Matrix); + result.emplace_back(StructMember{ + "Matrix", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(Matrix), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed UintPoint32 (uvec2) + if (member.basetype == spirv_cross::SPIRType::BaseType::UInt && // + member.width == sizeof(uint32_t) * 8 && // + member.columns == 1 && // + member.vecsize == 2 // + ) { + uint32_t stride = + GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(UintPoint32); + result.emplace_back(StructMember{ + "UintPoint32", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(UintPoint32), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed UintPoint32 (ivec2) + if (member.basetype == spirv_cross::SPIRType::BaseType::Int && // + member.width == sizeof(int32_t) * 8 && // + member.columns == 1 && // + member.vecsize == 2 // + ) { + uint32_t stride = + GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(IPoint32); + result.emplace_back(StructMember{ + "IPoint32", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(IPoint32), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed Point (vec2). + if (member.basetype == spirv_cross::SPIRType::BaseType::Float && // + member.width == sizeof(float) * 8 && // + member.columns == 1 && // + member.vecsize == 2 // + ) { + uint32_t stride = GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(Point); + result.emplace_back(StructMember{ + "Point", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(Point), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed Vector3. + if (member.basetype == spirv_cross::SPIRType::BaseType::Float && // + member.width == sizeof(float) * 8 && // + member.columns == 1 && // + member.vecsize == 3 // + ) { + uint32_t stride = GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(Vector3); + result.emplace_back(StructMember{ + "Vector3", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(Vector3), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed Vector4. + if (member.basetype == spirv_cross::SPIRType::BaseType::Float && // + member.width == sizeof(float) * 8 && // + member.columns == 1 && // + member.vecsize == 4 // + ) { + uint32_t stride = GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(Vector4); + result.emplace_back(StructMember{ + "Vector4", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(Vector4), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed half Point (vec2). + if (member.basetype == spirv_cross::SPIRType::BaseType::Half && // + member.width == sizeof(Half) * 8 && // + member.columns == 1 && // + member.vecsize == 2 // + ) { + uint32_t stride = + GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(HalfVector2); + result.emplace_back(StructMember{ + "HalfVector2", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(HalfVector2), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed Half Float Vector3. + if (member.basetype == spirv_cross::SPIRType::BaseType::Half && // + member.width == sizeof(Half) * 8 && // + member.columns == 1 && // + member.vecsize == 3 // + ) { + uint32_t stride = + GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(HalfVector3); + result.emplace_back(StructMember{ + "HalfVector3", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(HalfVector3), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Tightly packed Half Float Vector4. + if (member.basetype == spirv_cross::SPIRType::BaseType::Half && // + member.width == sizeof(Half) * 8 && // + member.columns == 1 && // + member.vecsize == 4 // + ) { + uint32_t stride = + GetArrayStride(struct_type, member, i); + uint32_t element_padding = stride - sizeof(HalfVector4); + result.emplace_back(StructMember{ + "HalfVector4", // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + sizeof(HalfVector4), // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + + // Other isolated scalars (like bool, int, float/Scalar, etc..). + { + auto maybe_known_type = ReadKnownScalarType(member.basetype); + if (maybe_known_type.has_value() && // + member.columns == 1 && // + member.vecsize == 1 // + ) { + uint32_t stride = GetArrayStride<0>(struct_type, member, i); + if (stride == 0) { + stride = maybe_known_type.value().byte_size; + } + uint32_t element_padding = stride - maybe_known_type.value().byte_size; + // Add the type directly. + result.emplace_back(StructMember{ + maybe_known_type.value().name, // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + maybe_known_type.value().byte_size, // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + } + + // Catch all for unknown types. Just add the necessary padding to the struct + // and move on. + { + const size_t size = (member.width * member.columns * member.vecsize) / 8u; + uint32_t stride = GetArrayStride<0>(struct_type, member, i); + if (stride == 0) { + stride = size; + } + auto element_padding = stride - size; + result.emplace_back(StructMember{ + TypeNameWithPaddingOfSize(size), // type + member.basetype, // basetype + GetMemberNameAtIndex(struct_type, i), // name + struct_member_offset, // offset + size, // size + stride * array_elements.value_or(1), // byte_length + array_elements, // array_elements + element_padding, // element_padding + }); + current_byte_offset += stride * array_elements.value_or(1); + continue; + } + } + + if (max_member_alignment > 0u) { + const auto struct_length = current_byte_offset; + { + const auto excess = struct_length % max_member_alignment; + if (excess != 0) { + const auto padding = max_member_alignment - excess; + result.emplace_back(StructMember{ + TypeNameWithPaddingOfSize(padding), // type + spirv_cross::SPIRType::BaseType::Void, // basetype + "_PADDING_", // name + current_byte_offset, // offset + padding, // size + padding, // byte_length + std::nullopt, // array_elements + 0, // element_padding + }); + } + } + } + + return result; +} + +std::optional Reflector::ReflectStructDefinition( + const spirv_cross::TypeID& type_id) const { + const auto& type = compiler_->get_type(type_id); + if (type.basetype != spirv_cross::SPIRType::BaseType::Struct) { + return std::nullopt; + } + + const auto struct_name = compiler_->get_name(type_id); + if (struct_name.find("_RESERVED_IDENTIFIER_") != std::string::npos) { + return std::nullopt; + } + + auto struct_members = ReadStructMembers(type_id); + auto reflected_struct_size = GetReflectedStructSize(struct_members); + + StructDefinition struc; + struc.name = struct_name; + struc.byte_length = reflected_struct_size; + struc.members = std::move(struct_members); + return struc; +} + +nlohmann::json::object_t Reflector::EmitStructDefinition( + std::optional struc) const { + nlohmann::json::object_t result; + result["name"] = struc->name; + result["byte_length"] = struc->byte_length; + auto& members = result["members"] = nlohmann::json::array_t{}; + for (const auto& struct_member : struc->members) { + auto& member = members.emplace_back(nlohmann::json::object_t{}); + member["name"] = struct_member.name; + member["type"] = struct_member.type; + member["base_type"] = + StructMember::BaseTypeToString(struct_member.base_type); + member["offset"] = struct_member.offset; + member["byte_length"] = struct_member.byte_length; + if (struct_member.array_elements.has_value()) { + member["array_elements"] = struct_member.array_elements.value(); + } else { + member["array_elements"] = "std::nullopt"; + } + member["element_padding"] = struct_member.element_padding; + } + return result; +} + +struct VertexType { + std::string type_name; + spirv_cross::SPIRType::BaseType base_type; + std::string variable_name; + size_t byte_length = 0u; +}; + +static VertexType VertexTypeFromInputResource( + const spirv_cross::Compiler& compiler, + const spirv_cross::Resource* resource) { + VertexType result; + result.variable_name = resource->name; + const auto& type = compiler.get_type(resource->type_id); + result.base_type = type.basetype; + const auto total_size = type.columns * type.vecsize * type.width / 8u; + result.byte_length = total_size; + + if (type.basetype == spirv_cross::SPIRType::BaseType::Float && + type.columns == 1u && type.vecsize == 2u && + type.width == sizeof(float) * 8u) { + result.type_name = "Point"; + } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float && + type.columns == 1u && type.vecsize == 4u && + type.width == sizeof(float) * 8u) { + result.type_name = "Vector4"; + } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float && + type.columns == 1u && type.vecsize == 3u && + type.width == sizeof(float) * 8u) { + result.type_name = "Vector3"; + } else if (type.basetype == spirv_cross::SPIRType::BaseType::Float && + type.columns == 1u && type.vecsize == 1u && + type.width == sizeof(float) * 8u) { + result.type_name = "Scalar"; + } else if (type.basetype == spirv_cross::SPIRType::BaseType::Int && + type.columns == 1u && type.vecsize == 1u && + type.width == sizeof(int32_t) * 8u) { + result.type_name = "int32_t"; + } else { + // Catch all unknown padding. + result.type_name = TypeNameWithPaddingOfSize(total_size); + } + + return result; +} + +std::optional +Reflector::ReflectPerVertexStructDefinition( + const spirv_cross::SmallVector& stage_inputs) const { + // Avoid emitting a zero sized structure. The code gen templates assume a + // non-zero size. + if (stage_inputs.empty()) { + return std::nullopt; + } + + // Validate locations are contiguous and there are no duplicates. + std::set locations; + for (const auto& input : stage_inputs) { + auto location = compiler_->get_decoration( + input.id, spv::Decoration::DecorationLocation); + if (locations.count(location) != 0) { + // Duplicate location. Bail. + return std::nullopt; + } + locations.insert(location); + } + + for (size_t i = 0; i < locations.size(); i++) { + if (locations.count(i) != 1) { + // Locations are not contiguous. This usually happens when a single stage + // input takes multiple input slots. No reflection information can be + // generated for such cases anyway. So bail! It is up to the shader author + // to make sure one stage input maps to a single input slot. + return std::nullopt; + } + } + + auto input_for_location = + [&](uint32_t queried_location) -> const spirv_cross::Resource* { + for (const auto& input : stage_inputs) { + auto location = compiler_->get_decoration( + input.id, spv::Decoration::DecorationLocation); + if (location == queried_location) { + return &input; + } + } + // This really cannot happen with all the validation above. + FML_UNREACHABLE(); + return nullptr; + }; + + StructDefinition struc; + struc.name = "PerVertexData"; + struc.byte_length = 0u; + for (size_t i = 0; i < locations.size(); i++) { + auto resource = input_for_location(i); + if (resource == nullptr) { + return std::nullopt; + } + const auto vertex_type = + VertexTypeFromInputResource(*compiler_.GetCompiler(), resource); + + auto member = StructMember{ + vertex_type.type_name, // type + vertex_type.base_type, // base type + vertex_type.variable_name, // name + struc.byte_length, // offset + vertex_type.byte_length, // size + vertex_type.byte_length, // byte_length + std::nullopt, // array_elements + 0, // element_padding + }; + struc.byte_length += vertex_type.byte_length; + struc.members.emplace_back(std::move(member)); + } + return struc; +} + +std::optional Reflector::GetMemberNameAtIndexIfExists( + const spirv_cross::SPIRType& parent_type, + size_t index) const { + if (parent_type.type_alias != 0) { + return GetMemberNameAtIndexIfExists( + compiler_->get_type(parent_type.type_alias), index); + } + + if (auto found = ir_->meta.find(parent_type.self); found != ir_->meta.end()) { + const auto& members = found->second.members; + if (index < members.size() && !members[index].alias.empty()) { + return members[index].alias; + } + } + return std::nullopt; +} + +std::string Reflector::GetMemberNameAtIndex( + const spirv_cross::SPIRType& parent_type, + size_t index, + std::string suffix) const { + if (auto name = GetMemberNameAtIndexIfExists(parent_type, index); + name.has_value()) { + return name.value(); + } + static std::atomic_size_t sUnnamedMembersID; + std::stringstream stream; + stream << "unnamed_" << sUnnamedMembersID++ << suffix; + return stream.str(); +} + +std::vector Reflector::ReflectBindPrototypes( + const spirv_cross::ShaderResources& resources, + spv::ExecutionModel execution_model) const { + std::vector prototypes; + for (const auto& uniform_buffer : resources.uniform_buffers) { + auto& proto = prototypes.emplace_back(BindPrototype{}); + proto.return_type = "bool"; + proto.name = ToCamelCase(uniform_buffer.name); + proto.descriptor_type = "DescriptorType::kUniformBuffer"; + { + std::stringstream stream; + stream << "Bind uniform buffer for resource named " << uniform_buffer.name + << "."; + proto.docstring = stream.str(); + } + proto.args.push_back(BindPrototypeArgument{ + .type_name = "ResourceBinder&", + .argument_name = "command", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "BufferView", + .argument_name = "view", + }); + } + for (const auto& storage_buffer : resources.storage_buffers) { + auto& proto = prototypes.emplace_back(BindPrototype{}); + proto.return_type = "bool"; + proto.name = ToCamelCase(storage_buffer.name); + proto.descriptor_type = "DescriptorType::kStorageBuffer"; + { + std::stringstream stream; + stream << "Bind storage buffer for resource named " << storage_buffer.name + << "."; + proto.docstring = stream.str(); + } + proto.args.push_back(BindPrototypeArgument{ + .type_name = "ResourceBinder&", + .argument_name = "command", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "BufferView", + .argument_name = "view", + }); + } + for (const auto& sampled_image : resources.sampled_images) { + auto& proto = prototypes.emplace_back(BindPrototype{}); + proto.return_type = "bool"; + proto.name = ToCamelCase(sampled_image.name); + proto.descriptor_type = "DescriptorType::kSampledImage"; + { + std::stringstream stream; + stream << "Bind combined image sampler for resource named " + << sampled_image.name << "."; + proto.docstring = stream.str(); + } + proto.args.push_back(BindPrototypeArgument{ + .type_name = "ResourceBinder&", + .argument_name = "command", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "std::shared_ptr", + .argument_name = "texture", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "raw_ptr", + .argument_name = "sampler", + }); + } + for (const auto& separate_image : resources.separate_images) { + auto& proto = prototypes.emplace_back(BindPrototype{}); + proto.return_type = "bool"; + proto.name = ToCamelCase(separate_image.name); + proto.descriptor_type = "DescriptorType::kImage"; + { + std::stringstream stream; + stream << "Bind separate image for resource named " << separate_image.name + << "."; + proto.docstring = stream.str(); + } + proto.args.push_back(BindPrototypeArgument{ + .type_name = "Command&", + .argument_name = "command", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "std::shared_ptr", + .argument_name = "texture", + }); + } + for (const auto& separate_sampler : resources.separate_samplers) { + auto& proto = prototypes.emplace_back(BindPrototype{}); + proto.return_type = "bool"; + proto.name = ToCamelCase(separate_sampler.name); + proto.descriptor_type = "DescriptorType::kSampler"; + { + std::stringstream stream; + stream << "Bind separate sampler for resource named " + << separate_sampler.name << "."; + proto.docstring = stream.str(); + } + proto.args.push_back(BindPrototypeArgument{ + .type_name = "Command&", + .argument_name = "command", + }); + proto.args.push_back(BindPrototypeArgument{ + .type_name = "std::shared_ptr", + .argument_name = "sampler", + }); + } + return prototypes; +} + +nlohmann::json::array_t Reflector::EmitBindPrototypes( + const spirv_cross::ShaderResources& resources, + spv::ExecutionModel execution_model) const { + const auto prototypes = ReflectBindPrototypes(resources, execution_model); + nlohmann::json::array_t result; + for (const auto& res : prototypes) { + auto& item = result.emplace_back(nlohmann::json::object_t{}); + item["return_type"] = res.return_type; + item["name"] = res.name; + item["docstring"] = res.docstring; + item["descriptor_type"] = res.descriptor_type; + auto& args = item["args"] = nlohmann::json::array_t{}; + for (const auto& arg : res.args) { + auto& json_arg = args.emplace_back(nlohmann::json::object_t{}); + json_arg["type_name"] = arg.type_name; + json_arg["argument_name"] = arg.argument_name; + } + } + return result; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/reflector.h b/flutter/engine/src/flutter/impeller/compiler/reflector.h new file mode 100644 index 0000000000000000000000000000000000000000..0bbd59477d017d81515a2d674eb6534ccb822b2e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/reflector.h @@ -0,0 +1,283 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_ +#define FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_ + +#include +#include +#include + +#include "flutter/fml/mapping.h" +#include "fml/logging.h" +#include "impeller/compiler/compiler_backend.h" +#include "impeller/compiler/runtime_stage_data.h" +#include "impeller/compiler/shader_bundle_data.h" +#include "inja/inja.hpp" +#include "spirv_common.hpp" +#include "spirv_msl.hpp" +#include "spirv_parser.hpp" + +namespace impeller { +namespace compiler { + +struct StructMember { + // Runtime stages on Vulkan use this information to validate that a struct + // only contains floats and encode where padding gets inserted. + enum class UnderlyingType { + kPadding, + kFloat, + kOther, + }; + + std::string type; + spirv_cross::SPIRType::BaseType base_type; + std::string name; + size_t offset = 0u; + size_t size = 0u; + size_t byte_length = 0u; + std::optional array_elements = std::nullopt; + size_t element_padding = 0u; + UnderlyingType underlying_type = UnderlyingType::kOther; + + static std::string BaseTypeToString(spirv_cross::SPIRType::BaseType type) { + using Type = spirv_cross::SPIRType::BaseType; + switch (type) { + case Type::Void: + return "ShaderType::kVoid"; + case Type::Boolean: + return "ShaderType::kBoolean"; + case Type::SByte: + return "ShaderType::kSignedByte"; + case Type::UByte: + return "ShaderType::kUnsignedByte"; + case Type::Short: + return "ShaderType::kSignedShort"; + case Type::UShort: + return "ShaderType::kUnsignedShort"; + case Type::Int: + return "ShaderType::kSignedInt"; + case Type::UInt: + return "ShaderType::kUnsignedInt"; + case Type::Int64: + return "ShaderType::kSignedInt64"; + case Type::UInt64: + return "ShaderType::kUnsignedInt64"; + case Type::AtomicCounter: + return "ShaderType::kAtomicCounter"; + case Type::Half: + return "ShaderType::kHalfFloat"; + case Type::Float: + return "ShaderType::kFloat"; + case Type::Double: + return "ShaderType::kDouble"; + case Type::Struct: + return "ShaderType::kStruct"; + case Type::Image: + return "ShaderType::kImage"; + case Type::SampledImage: + return "ShaderType::kSampledImage"; + case Type::Sampler: + return "ShaderType::kSampler"; + default: + return "ShaderType::kUnknown"; + } + FML_UNREACHABLE(); + } + + static UnderlyingType DetermineUnderlyingType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Void: + return UnderlyingType::kPadding; + case spirv_cross::SPIRType::Float: + return UnderlyingType::kFloat; + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Boolean: + case spirv_cross::SPIRType::SByte: + case spirv_cross::SPIRType::UByte: + case spirv_cross::SPIRType::Short: + case spirv_cross::SPIRType::UShort: + case spirv_cross::SPIRType::Int: + case spirv_cross::SPIRType::UInt: + case spirv_cross::SPIRType::Int64: + case spirv_cross::SPIRType::UInt64: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Half: + case spirv_cross::SPIRType::Double: + case spirv_cross::SPIRType::Struct: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::SampledImage: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::Char: + default: + return UnderlyingType::kOther; + } + FML_UNREACHABLE(); + } + + StructMember(std::string p_type, + spirv_cross::SPIRType::BaseType p_base_type, + std::string p_name, + size_t p_offset, + size_t p_size, + size_t p_byte_length, + std::optional p_array_elements, + size_t p_element_padding, + UnderlyingType p_underlying_type = UnderlyingType::kOther) + : type(std::move(p_type)), + base_type(p_base_type), + name(std::move(p_name)), + offset(p_offset), + size(p_size), + byte_length(p_byte_length), + array_elements(p_array_elements), + element_padding(p_element_padding), + underlying_type(DetermineUnderlyingType(p_base_type)) {} +}; + +class Reflector { + public: + struct Options { + TargetPlatform target_platform = TargetPlatform::kUnknown; + std::string entry_point_name; + std::string shader_name; + std::string header_file_name; + }; + + Reflector(Options options, + const std::shared_ptr& ir, + const std::shared_ptr& shader_data, + const CompilerBackend& compiler); + + ~Reflector(); + + bool IsValid() const; + + std::shared_ptr GetReflectionJSON() const; + + std::shared_ptr GetReflectionHeader() const; + + std::shared_ptr GetReflectionCC() const; + + std::shared_ptr GetRuntimeStageShaderData() const; + + std::shared_ptr GetShaderBundleData() const; + + private: + struct StructDefinition { + std::string name; + size_t byte_length = 0u; + std::vector members; + }; + + struct BindPrototypeArgument { + std::string type_name; + std::string argument_name; + }; + + struct BindPrototype { + std::string name; + std::string return_type; + std::string docstring; + std::string descriptor_type = ""; + std::vector args; + }; + + const Options options_; + const std::shared_ptr ir_; + const std::shared_ptr shader_data_; + const CompilerBackend compiler_; + std::unique_ptr template_arguments_; + std::shared_ptr reflection_header_; + std::shared_ptr reflection_cc_; + std::shared_ptr runtime_stage_shader_; + std::shared_ptr shader_bundle_data_; + bool is_valid_ = false; + + std::optional GenerateTemplateArguments() const; + + std::shared_ptr GenerateReflectionHeader() const; + + std::shared_ptr GenerateReflectionCC() const; + + std::shared_ptr GenerateRuntimeStageData() const; + + std::shared_ptr GenerateShaderBundleData() const; + + std::shared_ptr InflateTemplate(std::string_view tmpl) const; + + std::optional ReflectResource( + const spirv_cross::Resource& resource, + std::optional offset) const; + + std::optional ReflectResources( + const spirv_cross::SmallVector& resources, + bool compute_offsets = false) const; + + std::vector ComputeOffsets( + const spirv_cross::SmallVector& resources) const; + + std::optional GetOffset(spirv_cross::ID id, + const std::vector& offsets) const; + + std::optional ReflectType( + const spirv_cross::TypeID& type_id) const; + + nlohmann::json::object_t EmitStructDefinition( + std::optional struc) const; + + std::optional ReflectStructDefinition( + const spirv_cross::TypeID& type_id) const; + + std::vector ReflectBindPrototypes( + const spirv_cross::ShaderResources& resources, + spv::ExecutionModel execution_model) const; + + nlohmann::json::array_t EmitBindPrototypes( + const spirv_cross::ShaderResources& resources, + spv::ExecutionModel execution_model) const; + + std::optional ReflectPerVertexStructDefinition( + const spirv_cross::SmallVector& stage_inputs) + const; + + std::optional GetMemberNameAtIndexIfExists( + const spirv_cross::SPIRType& parent_type, + size_t index) const; + + std::string GetMemberNameAtIndex(const spirv_cross::SPIRType& parent_type, + size_t index, + std::string suffix = "") const; + + std::vector ReadStructMembers( + const spirv_cross::TypeID& type_id) const; + + std::optional GetArrayElements( + const spirv_cross::SPIRType& type) const; + + template + uint32_t GetArrayStride(const spirv_cross::SPIRType& struct_type, + const spirv_cross::SPIRType& member_type, + uint32_t index) const { + auto element_count = GetArrayElements(member_type).value_or(1); + if (element_count <= 1) { + return Size; + } + return compiler_->type_struct_member_array_stride(struct_type, index); + }; + + Reflector(const Reflector&) = delete; + + Reflector& operator=(const Reflector&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_REFLECTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.cc b/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.cc new file mode 100644 index 0000000000000000000000000000000000000000..c7b28a6184fc48eafe7c165288079632dc59c513 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.cc @@ -0,0 +1,412 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/runtime_stage_data.h" + +#include +#include +#include +#include + +#include "fml/backtrace.h" +#include "impeller/core/runtime_types.h" +#include "inja/inja.hpp" + +#include "impeller/base/validation.h" +#include "impeller/runtime_stage/runtime_stage_flatbuffers.h" +#include "runtime_stage_types_flatbuffers.h" + +namespace impeller { +namespace compiler { + +RuntimeStageData::RuntimeStageData() = default; + +RuntimeStageData::~RuntimeStageData() = default; + +void RuntimeStageData::AddShader(const std::shared_ptr& data) { + FML_DCHECK(data); + FML_DCHECK(data_.find(data->backend) == data_.end()); + data_[data->backend] = data; +} + +static std::optional ToStage(spv::ExecutionModel stage) { + switch (stage) { + case spv::ExecutionModel::ExecutionModelVertex: + return fb::Stage::kVertex; + case spv::ExecutionModel::ExecutionModelFragment: + return fb::Stage::kFragment; + case spv::ExecutionModel::ExecutionModelGLCompute: + return fb::Stage::kCompute; + default: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +static std::optional ToJsonStage(spv::ExecutionModel stage) { + switch (stage) { + case spv::ExecutionModel::ExecutionModelVertex: + return fb::Stage::kVertex; + case spv::ExecutionModel::ExecutionModelFragment: + return fb::Stage::kFragment; + case spv::ExecutionModel::ExecutionModelGLCompute: + return fb::Stage::kCompute; + default: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +static std::optional ToUniformType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Float: + return fb::UniformDataType::kFloat; + case spirv_cross::SPIRType::SampledImage: + return fb::UniformDataType::kSampledImage; + case spirv_cross::SPIRType::Struct: + return fb::UniformDataType::kStruct; + case spirv_cross::SPIRType::Boolean: + case spirv_cross::SPIRType::SByte: + case spirv_cross::SPIRType::UByte: + case spirv_cross::SPIRType::Short: + case spirv_cross::SPIRType::UShort: + case spirv_cross::SPIRType::Int: + case spirv_cross::SPIRType::UInt: + case spirv_cross::SPIRType::Int64: + case spirv_cross::SPIRType::UInt64: + case spirv_cross::SPIRType::Half: + case spirv_cross::SPIRType::Double: + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Char: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Void: + return std::nullopt; + } + FML_UNREACHABLE(); +} +static std::optional ToInputType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Boolean: + return fb::InputDataType::kBoolean; + case spirv_cross::SPIRType::SByte: + return fb::InputDataType::kSignedByte; + case spirv_cross::SPIRType::UByte: + return fb::InputDataType::kUnsignedByte; + case spirv_cross::SPIRType::Short: + return fb::InputDataType::kSignedShort; + case spirv_cross::SPIRType::UShort: + return fb::InputDataType::kUnsignedShort; + case spirv_cross::SPIRType::Int: + return fb::InputDataType::kSignedInt; + case spirv_cross::SPIRType::UInt: + return fb::InputDataType::kUnsignedInt; + case spirv_cross::SPIRType::Int64: + return fb::InputDataType::kSignedInt64; + case spirv_cross::SPIRType::UInt64: + return fb::InputDataType::kUnsignedInt64; + case spirv_cross::SPIRType::Float: + return fb::InputDataType::kFloat; + case spirv_cross::SPIRType::Double: + return fb::InputDataType::kDouble; + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Void: + case spirv_cross::SPIRType::Half: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Struct: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::SampledImage: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::Char: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +static std::optional ToJsonType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Boolean: + return 0; // fb::UniformDataType::kBoolean; + case spirv_cross::SPIRType::SByte: + return 1; // fb::UniformDataType::kSignedByte; + case spirv_cross::SPIRType::UByte: + return 2; // fb::UniformDataType::kUnsignedByte; + case spirv_cross::SPIRType::Short: + return 3; // fb::UniformDataType::kSignedShort; + case spirv_cross::SPIRType::UShort: + return 4; // fb::UniformDataType::kUnsignedShort; + case spirv_cross::SPIRType::Int: + return 5; // fb::UniformDataType::kSignedInt; + case spirv_cross::SPIRType::UInt: + return 6; // fb::UniformDataType::kUnsignedInt; + case spirv_cross::SPIRType::Int64: + return 7; // fb::UniformDataType::kSignedInt64; + case spirv_cross::SPIRType::UInt64: + return 8; // fb::UniformDataType::kUnsignedInt64; + case spirv_cross::SPIRType::Half: + return 9; // b::UniformDataType::kHalfFloat; + case spirv_cross::SPIRType::Float: + return 10; // fb::UniformDataType::kFloat; + case spirv_cross::SPIRType::Double: + return 11; // fb::UniformDataType::kDouble; + case spirv_cross::SPIRType::SampledImage: + return 12; // fb::UniformDataType::kSampledImage; + case spirv_cross::SPIRType::Struct: + return 13; + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Char: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Void: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +static const char* kStageKey = "stage"; +static const char* kTargetPlatformKey = "target_platform"; +static const char* kEntrypointKey = "entrypoint"; +static const char* kUniformsKey = "uniforms"; +static const char* kShaderKey = "shader"; +static const char* kUniformNameKey = "name"; +static const char* kUniformLocationKey = "location"; +static const char* kUniformTypeKey = "type"; +static const char* kUniformRowsKey = "rows"; +static const char* kUniformColumnsKey = "columns"; +static const char* kUniformBitWidthKey = "bit_width"; +static const char* kUniformArrayElementsKey = "array_elements"; + +static std::string RuntimeStageBackendToString(RuntimeStageBackend backend) { + switch (backend) { + case RuntimeStageBackend::kSkSL: + return "sksl"; + case RuntimeStageBackend::kMetal: + return "metal"; + case RuntimeStageBackend::kOpenGLES: + return "opengles"; + case RuntimeStageBackend::kVulkan: + return "vulkan"; + case RuntimeStageBackend::kOpenGLES3: + return "opengles3"; + } +} + +std::shared_ptr RuntimeStageData::CreateJsonMapping() const { + // Runtime Stage Data JSON format + // { + // "sksl": { + // "stage": 0, + // "entrypoint": "", + // "shader": "", + // "uniforms": [ + // { + // "name": "..", + // "location": 0, + // "type": 0, + // "rows": 0, + // "columns": 0, + // "bit_width": 0, + // "array_elements": 0, + // } + // ] + // }, + // "metal": ... + // }, + nlohmann::json root; + + for (const auto& kvp : data_) { + nlohmann::json platform_object; + + const auto stage = ToJsonStage(kvp.second->stage); + if (!stage.has_value()) { + VALIDATION_LOG << "Invalid runtime stage."; + return nullptr; + } + platform_object[kStageKey] = static_cast(stage.value()); + platform_object[kEntrypointKey] = kvp.second->entrypoint; + + if (kvp.second->shader->GetSize() > 0u) { + std::string shader( + reinterpret_cast(kvp.second->shader->GetMapping()), + kvp.second->shader->GetSize()); + platform_object[kShaderKey] = shader.c_str(); + } + + auto& uniforms = platform_object[kUniformsKey] = nlohmann::json::array_t{}; + for (const auto& uniform : kvp.second->uniforms) { + nlohmann::json uniform_object; + uniform_object[kUniformNameKey] = uniform.name.c_str(); + uniform_object[kUniformLocationKey] = uniform.location; + uniform_object[kUniformRowsKey] = uniform.rows; + uniform_object[kUniformColumnsKey] = uniform.columns; + + auto uniform_type = ToJsonType(uniform.type); + if (!uniform_type.has_value()) { + VALIDATION_LOG << "Invalid uniform type for runtime stage."; + return nullptr; + } + + uniform_object[kUniformTypeKey] = uniform_type.value(); + uniform_object[kUniformBitWidthKey] = uniform.bit_width; + uniform_object[kUniformArrayElementsKey] = + uniform.array_elements.value_or(0); + + uniforms.push_back(uniform_object); + } + + root[RuntimeStageBackendToString(kvp.first)] = platform_object; + } + + auto json_string = std::make_shared(root.dump(2u)); + + return std::make_shared( + reinterpret_cast(json_string->data()), + json_string->size(), [json_string](auto, auto) {}); +} + +std::unique_ptr RuntimeStageData::CreateStageFlatbuffer( + impeller::RuntimeStageBackend backend) const { + auto kvp = data_.find(backend); + if (kvp == data_.end()) { + return nullptr; + } + + auto runtime_stage = std::make_unique(); + runtime_stage->entrypoint = kvp->second->entrypoint; + const auto stage = ToStage(kvp->second->stage); + if (!stage.has_value()) { + VALIDATION_LOG << "Invalid runtime stage."; + return nullptr; + } + runtime_stage->stage = stage.value(); + if (!kvp->second->shader) { + VALIDATION_LOG << "No shader specified for runtime stage."; + return nullptr; + } + if (kvp->second->shader->GetSize() > 0u) { + runtime_stage->shader = { + kvp->second->shader->GetMapping(), + kvp->second->shader->GetMapping() + kvp->second->shader->GetSize()}; + } + for (const auto& uniform : kvp->second->uniforms) { + auto desc = std::make_unique(); + + desc->name = uniform.name; + if (desc->name.empty()) { + VALIDATION_LOG << "Uniform name cannot be empty."; + return nullptr; + } + desc->location = uniform.location; + desc->rows = uniform.rows; + desc->columns = uniform.columns; + auto uniform_type = ToUniformType(uniform.type); + if (!uniform_type.has_value()) { + VALIDATION_LOG << "Invalid uniform type for runtime stage."; + return nullptr; + } + desc->type = uniform_type.value(); + desc->bit_width = uniform.bit_width; + if (uniform.array_elements.has_value()) { + desc->array_elements = uniform.array_elements.value(); + } + + for (const auto& byte_type : uniform.struct_layout) { + desc->struct_layout.push_back(static_cast(byte_type)); + } + desc->struct_float_count = uniform.struct_float_count; + + runtime_stage->uniforms.emplace_back(std::move(desc)); + } + + for (const auto& input : kvp->second->inputs) { + auto desc = std::make_unique(); + + desc->name = input.name; + + if (desc->name.empty()) { + VALIDATION_LOG << "Stage input name cannot be empty."; + return nullptr; + } + desc->location = input.location; + desc->set = input.set; + desc->binding = input.binding; + auto input_type = ToInputType(input.type); + if (!input_type.has_value()) { + VALIDATION_LOG << "Invalid uniform type for runtime stage."; + return nullptr; + } + desc->type = input_type.value(); + desc->bit_width = input.bit_width; + desc->vec_size = input.vec_size; + desc->columns = input.columns; + desc->offset = input.offset; + + runtime_stage->inputs.emplace_back(std::move(desc)); + } + + return runtime_stage; +} + +std::unique_ptr +RuntimeStageData::CreateMultiStageFlatbuffer() const { + // The high level object API is used here for writing to the buffer. This is + // just a convenience. + auto runtime_stages = std::make_unique(); + + for (const auto& kvp : data_) { + auto runtime_stage = CreateStageFlatbuffer(kvp.first); + switch (kvp.first) { + case RuntimeStageBackend::kSkSL: + runtime_stages->sksl = std::move(runtime_stage); + break; + case RuntimeStageBackend::kMetal: + runtime_stages->metal = std::move(runtime_stage); + break; + case RuntimeStageBackend::kOpenGLES: + runtime_stages->opengles = std::move(runtime_stage); + break; + case RuntimeStageBackend::kVulkan: + runtime_stages->vulkan = std::move(runtime_stage); + break; + case RuntimeStageBackend::kOpenGLES3: + runtime_stages->opengles3 = std::move(runtime_stage); + break; + } + } + return runtime_stages; +} + +std::shared_ptr RuntimeStageData::CreateMapping() const { + auto runtime_stages = CreateMultiStageFlatbuffer(); + if (!runtime_stages) { + return nullptr; + } + + auto builder = std::make_shared(); + builder->Finish(fb::RuntimeStages::Pack(*builder.get(), runtime_stages.get()), + fb::RuntimeStagesIdentifier()); + return std::make_shared(builder->GetBufferPointer(), + builder->GetSize(), + [builder](auto, auto) {}); +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.h b/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.h new file mode 100644 index 0000000000000000000000000000000000000000..bffb1f94e70518c20e19bb2c7cc69a6519b95e44 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/runtime_stage_data.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_ +#define FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_ + +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/compiler/types.h" +#include "impeller/core/runtime_types.h" +#include "runtime_stage_types_flatbuffers.h" +#include "spirv_parser.hpp" + +namespace impeller { +namespace compiler { + +class RuntimeStageData { + public: + struct Shader { + Shader() = default; + + std::string entrypoint; + spv::ExecutionModel stage; + std::vector uniforms; + std::vector inputs; + std::shared_ptr shader; + RuntimeStageBackend backend; + + Shader(const Shader&) = delete; + Shader& operator=(const Shader&) = delete; + }; + + RuntimeStageData(); + + ~RuntimeStageData(); + + void AddShader(const std::shared_ptr& data); + + std::unique_ptr CreateStageFlatbuffer( + impeller::RuntimeStageBackend backend) const; + + std::unique_ptr CreateMultiStageFlatbuffer() const; + + std::shared_ptr CreateJsonMapping() const; + + std::shared_ptr CreateMapping() const; + + private: + std::map> data_; + + RuntimeStageData(const RuntimeStageData&) = delete; + + RuntimeStageData& operator=(const RuntimeStageData&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_RUNTIME_STAGE_DATA_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_bundle.cc b/flutter/engine/src/flutter/impeller/compiler/shader_bundle.cc new file mode 100644 index 0000000000000000000000000000000000000000..155029148cc51c73e8d55d346beb9b509cc9e0a9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_bundle.cc @@ -0,0 +1,256 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/shader_bundle.h" +#include "impeller/compiler/compiler.h" +#include "impeller/compiler/reflector.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" + +#include "impeller/compiler/utilities.h" +#include "impeller/runtime_stage/runtime_stage.h" +#include "impeller/shader_bundle/shader_bundle_flatbuffers.h" +#include "third_party/json/include/nlohmann/json.hpp" + +namespace impeller { +namespace compiler { + +std::optional ParseShaderBundleConfig( + const std::string& bundle_config_json, + std::ostream& error_stream) { + auto json = nlohmann::json::parse(bundle_config_json, nullptr, false); + if (json.is_discarded() || !json.is_object()) { + error_stream << "The shader bundle is not a valid JSON object." + << std::endl; + return std::nullopt; + } + + ShaderBundleConfig bundle; + for (auto& [shader_name, shader_value] : json.items()) { + if (bundle.find(shader_name) != bundle.end()) { + error_stream << "Duplicate shader \"" << shader_name << "\"." + << std::endl; + return std::nullopt; + } + if (!shader_value.is_object()) { + error_stream << "Invalid shader entry \"" << shader_name + << "\": Entry is not a JSON object." << std::endl; + return std::nullopt; + } + + ShaderConfig shader; + + if (!shader_value.contains("file")) { + error_stream << "Invalid shader entry \"" << shader_name + << "\": Missing required \"file\" field." << std::endl; + return std::nullopt; + } + shader.source_file_name = shader_value["file"]; + + if (!shader_value.contains("type")) { + error_stream << "Invalid shader entry \"" << shader_name + << "\": Missing required \"type\" field." << std::endl; + return std::nullopt; + } + shader.type = SourceTypeFromString(shader_value["type"]); + if (shader.type == SourceType::kUnknown) { + error_stream << "Invalid shader entry \"" << shader_name + << "\": Shader type " << shader_value["type"] + << " is unknown." << std::endl; + return std::nullopt; + } + + shader.language = shader_value.contains("language") + ? ToSourceLanguage(shader_value["language"]) + : SourceLanguage::kGLSL; + if (shader.language == SourceLanguage::kUnknown) { + error_stream << "Invalid shader entry \"" << shader_name + << "\": Unknown language type " << shader_value["language"] + << "." << std::endl; + return std::nullopt; + } + + shader.entry_point = shader_value.contains("entry_point") + ? shader_value["entry_point"] + : "main"; + + bundle[shader_name] = shader; + } + + return bundle; +} + +static std::unique_ptr +GenerateShaderBackendFB(TargetPlatform target_platform, + SourceOptions& options, + const std::string& shader_name, + const ShaderConfig& shader_config) { + auto result = std::make_unique(); + + std::shared_ptr source_file_mapping = + fml::FileMapping::CreateReadOnly(shader_config.source_file_name); + if (!source_file_mapping) { + std::cerr << "Could not open file for bundled shader \"" << shader_name + << "\"." << std::endl; + return nullptr; + } + + /// Override options. + options.target_platform = target_platform; + options.file_name = shader_name; // This is just used for error messages. + options.type = shader_config.type; + options.source_language = shader_config.language; + options.entry_point_name = EntryPointFunctionNameFromSourceName( + shader_config.source_file_name, options.type, options.source_language, + shader_config.entry_point); + + Reflector::Options reflector_options; + reflector_options.target_platform = options.target_platform; + reflector_options.entry_point_name = options.entry_point_name; + reflector_options.shader_name = shader_name; + + Compiler compiler(source_file_mapping, options, reflector_options); + if (!compiler.IsValid()) { + std::cerr << "Compilation failed for bundled shader \"" << shader_name + << "\"." << std::endl; + std::cerr << compiler.GetErrorMessages() << std::endl; + return nullptr; + } + + auto reflector = compiler.GetReflector(); + if (reflector == nullptr) { + std::cerr << "Could not create reflector for bundled shader \"" + << shader_name << "\"." << std::endl; + return nullptr; + } + + auto bundle_data = reflector->GetShaderBundleData(); + if (!bundle_data) { + std::cerr << "Bundled shader information was nil for \"" << shader_name + << "\"." << std::endl; + return nullptr; + } + + result = bundle_data->CreateFlatbuffer(); + if (!result) { + std::cerr << "Failed to create flatbuffer for bundled shader \"" + << shader_name << "\"." << std::endl; + return nullptr; + } + + return result; +} + +static std::unique_ptr GenerateShaderFB( + SourceOptions options, + const std::string& shader_name, + const ShaderConfig& shader_config) { + auto result = std::make_unique(); + result->name = shader_name; + result->metal_ios = GenerateShaderBackendFB( + TargetPlatform::kMetalIOS, options, shader_name, shader_config); + if (!result->metal_ios) { + return nullptr; + } + result->metal_desktop = GenerateShaderBackendFB( + TargetPlatform::kMetalDesktop, options, shader_name, shader_config); + if (!result->metal_desktop) { + return nullptr; + } + result->opengl_es = GenerateShaderBackendFB( + TargetPlatform::kOpenGLES, options, shader_name, shader_config); + if (!result->opengl_es) { + return nullptr; + } + result->opengl_desktop = GenerateShaderBackendFB( + TargetPlatform::kOpenGLDesktop, options, shader_name, shader_config); + if (!result->opengl_desktop) { + return nullptr; + } + result->vulkan = GenerateShaderBackendFB(TargetPlatform::kVulkan, options, + shader_name, shader_config); + if (!result->vulkan) { + return nullptr; + } + return result; +} + +std::optional GenerateShaderBundleFlatbuffer( + const std::string& bundle_config_json, + const SourceOptions& options) { + // -------------------------------------------------------------------------- + /// 1. Parse the bundle configuration. + /// + + std::optional bundle_config = + ParseShaderBundleConfig(bundle_config_json, std::cerr); + if (!bundle_config) { + return std::nullopt; + } + + // -------------------------------------------------------------------------- + /// 2. Build the deserialized shader bundle. + /// + + fb::shaderbundle::ShaderBundleT shader_bundle; + + for (const auto& [shader_name, shader_config] : bundle_config.value()) { + std::unique_ptr shader = + GenerateShaderFB(options, shader_name, shader_config); + if (!shader) { + return std::nullopt; + } + shader_bundle.shaders.push_back(std::move(shader)); + } + + return shader_bundle; +} + +bool GenerateShaderBundle(Switches& switches) { + // -------------------------------------------------------------------------- + /// 1. Parse the shader bundle and generate the flatbuffer result. + /// + + auto shader_bundle = GenerateShaderBundleFlatbuffer( + switches.shader_bundle, switches.CreateSourceOptions()); + if (!shader_bundle.has_value()) { + // Specific error messages are already handled by + // GenerateShaderBundleFlatbuffer. + return false; + } + + // -------------------------------------------------------------------------- + /// 2. Serialize the shader bundle and write to disk. + /// + + auto builder = std::make_shared(); + builder->Finish(fb::shaderbundle::ShaderBundle::Pack(*builder.get(), + &shader_bundle.value()), + fb::shaderbundle::ShaderBundleIdentifier()); + auto mapping = std::make_shared( + builder->GetBufferPointer(), builder->GetSize(), + [builder](auto, auto) {}); + + auto sl_file_name = std::filesystem::absolute( + std::filesystem::current_path() / switches.sl_file_name); + + if (!fml::WriteAtomically(*switches.working_directory, // + Utf8FromPath(sl_file_name).c_str(), // + *mapping // + )) { + std::cerr << "Could not write file to " << switches.sl_file_name + << std::endl; + return false; + } + // Tools that consume the runtime stage data expect the access mode to + // be 0644. + if (!SetPermissiveAccess(sl_file_name)) { + return false; + } + + return true; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_bundle.h b/flutter/engine/src/flutter/impeller/compiler/shader_bundle.h new file mode 100644 index 0000000000000000000000000000000000000000..abdf528ec5f31a9060bfffbeeed7a3277ea6b689 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_bundle.h @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_ +#define FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_ + +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/switches.h" +#include "impeller/shader_bundle/shader_bundle_flatbuffers.h" + +namespace impeller { +namespace compiler { + +/// @brief Parse a shader bundle configuration from a given JSON string. +/// +/// @note Exposed only for testing purposes. Use `GenerateShaderBundle` +/// directly. +std::optional ParseShaderBundleConfig( + const std::string& bundle_config_json, + std::ostream& error_stream); + +/// @brief Parses the JSON shader bundle configuration and invokes the +/// compiler multiple times to produce a shader bundle flatbuffer. +/// +/// @note Exposed only for testing purposes. Use `GenerateShaderBundle` +/// directly. +std::optional GenerateShaderBundleFlatbuffer( + const std::string& bundle_config_json, + const SourceOptions& options); + +/// @brief Parses the JSON shader bundle configuration and invokes the +/// compiler multiple times to produce a shader bundle flatbuffer, which +/// is then output to the `sl` file. +bool GenerateShaderBundle(Switches& switches); + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.cc b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.cc new file mode 100644 index 0000000000000000000000000000000000000000..f84afa479fac3845dd513dc5b36cc81bd0fd82ec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.cc @@ -0,0 +1,241 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/shader_bundle_data.h" + +#include + +#include "impeller/shader_bundle/shader_bundle_flatbuffers.h" + +#include "impeller/base/validation.h" + +namespace impeller { +namespace compiler { + +ShaderBundleData::ShaderBundleData(std::string entrypoint, + spv::ExecutionModel stage, + TargetPlatform target_platform) + : entrypoint_(std::move(entrypoint)), + stage_(stage), + target_platform_(target_platform) {} + +ShaderBundleData::~ShaderBundleData() = default; + +void ShaderBundleData::AddUniformStruct(ShaderUniformStruct uniform_struct) { + uniform_structs_.emplace_back(std::move(uniform_struct)); +} + +void ShaderBundleData::AddUniformTexture(ShaderUniformTexture uniform_texture) { + uniform_textures_.emplace_back(std::move(uniform_texture)); +} + +void ShaderBundleData::AddInputDescription(InputDescription input) { + inputs_.emplace_back(std::move(input)); +} + +void ShaderBundleData::SetShaderData(std::shared_ptr shader) { + shader_ = std::move(shader); +} + +static std::optional ToStage( + spv::ExecutionModel stage) { + switch (stage) { + case spv::ExecutionModel::ExecutionModelVertex: + return fb::shaderbundle::ShaderStage::kVertex; + case spv::ExecutionModel::ExecutionModelFragment: + return fb::shaderbundle::ShaderStage::kFragment; + case spv::ExecutionModel::ExecutionModelGLCompute: + return fb::shaderbundle::ShaderStage::kCompute; + default: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +static std::optional ToUniformType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Boolean: + return fb::shaderbundle::UniformDataType::kBoolean; + case spirv_cross::SPIRType::SByte: + return fb::shaderbundle::UniformDataType::kSignedByte; + case spirv_cross::SPIRType::UByte: + return fb::shaderbundle::UniformDataType::kUnsignedByte; + case spirv_cross::SPIRType::Short: + return fb::shaderbundle::UniformDataType::kSignedShort; + case spirv_cross::SPIRType::UShort: + return fb::shaderbundle::UniformDataType::kUnsignedShort; + case spirv_cross::SPIRType::Int: + return fb::shaderbundle::UniformDataType::kSignedInt; + case spirv_cross::SPIRType::UInt: + return fb::shaderbundle::UniformDataType::kUnsignedInt; + case spirv_cross::SPIRType::Int64: + return fb::shaderbundle::UniformDataType::kSignedInt64; + case spirv_cross::SPIRType::UInt64: + return fb::shaderbundle::UniformDataType::kUnsignedInt64; + case spirv_cross::SPIRType::Half: + return fb::shaderbundle::UniformDataType::kHalfFloat; + case spirv_cross::SPIRType::Float: + return fb::shaderbundle::UniformDataType::kFloat; + case spirv_cross::SPIRType::Double: + return fb::shaderbundle::UniformDataType::kDouble; + case spirv_cross::SPIRType::SampledImage: + return fb::shaderbundle::UniformDataType::kSampledImage; + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Char: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::Struct: + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Void: + return std::nullopt; + } + FML_UNREACHABLE(); +} +static std::optional ToInputType( + spirv_cross::SPIRType::BaseType type) { + switch (type) { + case spirv_cross::SPIRType::Boolean: + return fb::shaderbundle::InputDataType::kBoolean; + case spirv_cross::SPIRType::SByte: + return fb::shaderbundle::InputDataType::kSignedByte; + case spirv_cross::SPIRType::UByte: + return fb::shaderbundle::InputDataType::kUnsignedByte; + case spirv_cross::SPIRType::Short: + return fb::shaderbundle::InputDataType::kSignedShort; + case spirv_cross::SPIRType::UShort: + return fb::shaderbundle::InputDataType::kUnsignedShort; + case spirv_cross::SPIRType::Int: + return fb::shaderbundle::InputDataType::kSignedInt; + case spirv_cross::SPIRType::UInt: + return fb::shaderbundle::InputDataType::kUnsignedInt; + case spirv_cross::SPIRType::Int64: + return fb::shaderbundle::InputDataType::kSignedInt64; + case spirv_cross::SPIRType::UInt64: + return fb::shaderbundle::InputDataType::kUnsignedInt64; + case spirv_cross::SPIRType::Float: + return fb::shaderbundle::InputDataType::kFloat; + case spirv_cross::SPIRType::Double: + return fb::shaderbundle::InputDataType::kDouble; + case spirv_cross::SPIRType::Unknown: + case spirv_cross::SPIRType::Void: + case spirv_cross::SPIRType::Half: + case spirv_cross::SPIRType::AtomicCounter: + case spirv_cross::SPIRType::Struct: + case spirv_cross::SPIRType::Image: + case spirv_cross::SPIRType::SampledImage: + case spirv_cross::SPIRType::Sampler: + case spirv_cross::SPIRType::AccelerationStructure: + case spirv_cross::SPIRType::RayQuery: + case spirv_cross::SPIRType::ControlPointArray: + case spirv_cross::SPIRType::Interpolant: + case spirv_cross::SPIRType::Char: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +std::unique_ptr +ShaderBundleData::CreateFlatbuffer() const { + auto shader_bundle = std::make_unique(); + + // The high level object API is used here for writing to the buffer. This is + // just a convenience. + shader_bundle->entrypoint = entrypoint_; + const auto stage = ToStage(stage_); + if (!stage.has_value()) { + VALIDATION_LOG << "Invalid shader bundle."; + return nullptr; + } + shader_bundle->stage = stage.value(); + // This field is ignored, so just set it to anything. + if (!shader_) { + VALIDATION_LOG << "No shader specified for shader bundle."; + return nullptr; + } + if (shader_->GetSize() > 0u) { + shader_bundle->shader = {shader_->GetMapping(), + shader_->GetMapping() + shader_->GetSize()}; + } + for (const auto& uniform : uniform_structs_) { + auto desc = std::make_unique(); + + desc->name = uniform.name; + if (desc->name.empty()) { + VALIDATION_LOG << "Uniform name cannot be empty."; + return nullptr; + } + desc->ext_res_0 = uniform.ext_res_0; + desc->set = uniform.set; + desc->binding = uniform.binding; + desc->size_in_bytes = uniform.size_in_bytes; + + for (const auto& field : uniform.fields) { + auto field_desc = + std::make_unique(); + field_desc->name = field.name; + auto type = ToUniformType(field.type); + if (!type.has_value()) { + VALIDATION_LOG << " Invalid shader type " << field.type << "."; + return nullptr; + } + field_desc->type = type.value(); + field_desc->offset_in_bytes = field.offset_in_bytes; + field_desc->element_size_in_bytes = field.element_size_in_bytes; + field_desc->total_size_in_bytes = field.total_size_in_bytes; + field_desc->array_elements = field.array_elements.value_or(0); + desc->fields.push_back(std::move(field_desc)); + } + + shader_bundle->uniform_structs.emplace_back(std::move(desc)); + } + + for (const auto& texture : uniform_textures_) { + auto desc = std::make_unique(); + desc->name = texture.name; + if (desc->name.empty()) { + VALIDATION_LOG << "Uniform name cannot be empty."; + return nullptr; + } + desc->ext_res_0 = texture.ext_res_0; + desc->set = texture.set; + desc->binding = texture.binding; + shader_bundle->uniform_textures.emplace_back(std::move(desc)); + } + + for (const auto& input : inputs_) { + auto desc = std::make_unique(); + + desc->name = input.name; + + if (desc->name.empty()) { + VALIDATION_LOG << "Stage input name cannot be empty."; + return nullptr; + } + desc->location = input.location; + desc->set = input.set; + desc->binding = input.binding; + auto input_type = ToInputType(input.type); + if (!input_type.has_value()) { + VALIDATION_LOG << "Invalid uniform type for runtime stage."; + return nullptr; + } + desc->type = input_type.value(); + desc->bit_width = input.bit_width; + desc->vec_size = input.vec_size; + desc->columns = input.columns; + desc->offset = input.offset; + + shader_bundle->inputs.emplace_back(std::move(desc)); + } + + return shader_bundle; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.h b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.h new file mode 100644 index 0000000000000000000000000000000000000000..f33c54792e2f7f3eeed1e67cbded2ac049ae1373 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_data.h @@ -0,0 +1,82 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_ +#define FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_ + +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/compiler/types.h" +#include "impeller/shader_bundle/shader_bundle_flatbuffers.h" + +namespace impeller { +namespace compiler { + +class ShaderBundleData { + public: + struct ShaderUniformStructField { + std::string name; + spirv_cross::SPIRType::BaseType type = + spirv_cross::SPIRType::BaseType::Float; + size_t offset_in_bytes = 0u; + size_t element_size_in_bytes = 0u; + size_t total_size_in_bytes = 0u; + std::optional array_elements = std::nullopt; + }; + + struct ShaderUniformStruct { + std::string name; + size_t ext_res_0 = 0u; + size_t set = 0u; + size_t binding = 0u; + size_t size_in_bytes = 0u; + std::vector fields; + }; + + struct ShaderUniformTexture { + std::string name; + size_t ext_res_0 = 0u; + size_t set = 0u; + size_t binding = 0u; + }; + + ShaderBundleData(std::string entrypoint, + spv::ExecutionModel stage, + TargetPlatform target_platform); + + ~ShaderBundleData(); + + void AddUniformStruct(ShaderUniformStruct uniform_struct); + + void AddUniformTexture(ShaderUniformTexture uniform_texture); + + void AddInputDescription(InputDescription input); + + void SetShaderData(std::shared_ptr shader); + + void SetSkSLData(std::shared_ptr sksl); + + std::unique_ptr CreateFlatbuffer() const; + + private: + const std::string entrypoint_; + const spv::ExecutionModel stage_; + const TargetPlatform target_platform_; + std::vector uniform_structs_; + std::vector uniform_textures_; + std::vector inputs_; + std::shared_ptr shader_; + std::shared_ptr sksl_; + + ShaderBundleData(const ShaderBundleData&) = delete; + + ShaderBundleData& operator=(const ShaderBundleData&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SHADER_BUNDLE_DATA_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_bundle_unittests.cc b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d79c2aa5d4a4b6a4e92de24abaa6152d7fd2e2f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_bundle_unittests.cc @@ -0,0 +1,218 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" +#include "impeller/compiler/shader_bundle.h" + +#include "flutter/testing/testing.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" +#include "impeller/shader_bundle/shader_bundle_flatbuffers.h" + +namespace impeller { +namespace compiler { +namespace testing { + +const std::string kUnlitFragmentBundleConfig = + "\"UnlitFragment\": {\"type\": \"fragment\", \"file\": " + "\"shaders/flutter_gpu_unlit.frag\"}"; +const std::string kUnlitVertexBundleConfig = + "\"UnlitVertex\": {\"type\": \"vertex\", \"file\": " + "\"shaders/flutter_gpu_unlit.vert\"}"; + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsForInvalidJSON) { + std::string bundle = ""; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), + "The shader bundle is not a valid JSON object.\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsWhenEntryNotObject) { + std::string bundle = "{\"UnlitVertex\": []}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ( + error.str().c_str(), + "Invalid shader entry \"UnlitVertex\": Entry is not a JSON object.\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsWhenMissingFile) { + std::string bundle = "{\"UnlitVertex\": {\"type\": \"vertex\"}}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), + "Invalid shader entry \"UnlitVertex\": Missing required " + "\"file\" field.\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsWhenMissingType) { + std::string bundle = + "{\"UnlitVertex\": {\"file\": \"shaders/flutter_gpu_unlit.vert\"}}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), + "Invalid shader entry \"UnlitVertex\": Missing required " + "\"type\" field.\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsForInvalidType) { + std::string bundle = + "{\"UnlitVertex\": {\"type\": \"invalid\", \"file\": " + "\"shaders/flutter_gpu_unlit.vert\"}}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), + "Invalid shader entry \"UnlitVertex\": Shader type " + "\"invalid\" is unknown.\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigFailsForInvalidLanguage) { + std::string bundle = + "{\"UnlitVertex\": {\"type\": \"vertex\", \"language\": \"invalid\", " + "\"file\": \"shaders/flutter_gpu_unlit.vert\"}}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_FALSE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), + "Invalid shader entry \"UnlitVertex\": Unknown language type " + "\"invalid\".\n"); +} + +TEST(ShaderBundleTest, ParseShaderBundleConfigReturnsExpectedConfig) { + std::string bundle = + "{" + kUnlitVertexBundleConfig + ", " + kUnlitFragmentBundleConfig + "}"; + std::stringstream error; + auto result = ParseShaderBundleConfig(bundle, error); + ASSERT_TRUE(result.has_value()); + ASSERT_STREQ(error.str().c_str(), ""); + + // NOLINTBEGIN(bugprone-unchecked-optional-access) + auto maybe_vertex = result->find("UnlitVertex"); + auto maybe_fragment = result->find("UnlitFragment"); + ASSERT_TRUE(maybe_vertex != result->end()); + ASSERT_TRUE(maybe_fragment != result->end()); + auto vertex = maybe_vertex->second; + auto fragment = maybe_fragment->second; + // NOLINTEND(bugprone-unchecked-optional-access) + + EXPECT_EQ(vertex.type, SourceType::kVertexShader); + EXPECT_EQ(vertex.language, SourceLanguage::kGLSL); + EXPECT_STREQ(vertex.entry_point.c_str(), "main"); + EXPECT_STREQ(vertex.source_file_name.c_str(), + "shaders/flutter_gpu_unlit.vert"); + + EXPECT_EQ(fragment.type, SourceType::kFragmentShader); + EXPECT_EQ(fragment.language, SourceLanguage::kGLSL); + EXPECT_STREQ(fragment.entry_point.c_str(), "main"); + EXPECT_STREQ(fragment.source_file_name.c_str(), + "shaders/flutter_gpu_unlit.frag"); +} + +template +const T* FindByName(const std::vector>& collection, + const std::string& name) { + const auto maybe = std::find_if( + collection.begin(), collection.end(), + [&name](const std::unique_ptr& value) { return value->name == name; }); + if (maybe == collection.end()) { + return nullptr; + } + return maybe->get(); +} + +TEST(ShaderBundleTest, GenerateShaderBundleFlatbufferProducesCorrectResult) { + std::string fixtures_path = flutter::testing::GetFixturesPath(); + std::string config = + "{\"UnlitFragment\": {\"type\": \"fragment\", \"file\": \"" + + fixtures_path + + "/flutter_gpu_unlit.frag\"}, \"UnlitVertex\": {\"type\": " + "\"vertex\", \"file\": \"" + + fixtures_path + "/flutter_gpu_unlit.vert\"}}"; + + SourceOptions options; + options.target_platform = TargetPlatform::kRuntimeStageMetal; + options.source_language = SourceLanguage::kGLSL; + + std::optional bundle = + GenerateShaderBundleFlatbuffer(config, options); + ASSERT_TRUE(bundle.has_value()); + + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + const auto& shaders = bundle->shaders; + const auto* vertex = FindByName(shaders, "UnlitVertex"); + const auto* fragment = FindByName(shaders, "UnlitFragment"); + ASSERT_NE(vertex, nullptr); + ASSERT_NE(fragment, nullptr); + + // -------------------------------------------------------------------------- + /// Verify vertex shader. + /// + + EXPECT_STREQ(vertex->metal_desktop->entrypoint.c_str(), + "flutter_gpu_unlit_vertex_main"); + EXPECT_EQ(vertex->metal_desktop->stage, + fb::shaderbundle::ShaderStage::kVertex); + + // Inputs. + ASSERT_EQ(vertex->metal_desktop->inputs.size(), 1u); + const auto& v_in_position = vertex->metal_desktop->inputs[0]; + EXPECT_STREQ(v_in_position->name.c_str(), "position"); + EXPECT_EQ(v_in_position->location, 0u); + EXPECT_EQ(v_in_position->set, 0u); + EXPECT_EQ(v_in_position->binding, 0u); + EXPECT_EQ(v_in_position->type, fb::shaderbundle::InputDataType::kFloat); + EXPECT_EQ(v_in_position->bit_width, 32u); + EXPECT_EQ(v_in_position->vec_size, 2u); + EXPECT_EQ(v_in_position->columns, 1u); + EXPECT_EQ(v_in_position->offset, 0u); + + // Uniforms. + ASSERT_EQ(vertex->metal_desktop->uniform_structs.size(), 1u); + const auto* vert_info = + FindByName(vertex->metal_desktop->uniform_structs, "VertInfo"); + ASSERT_NE(vert_info, nullptr); + EXPECT_EQ(vert_info->ext_res_0, 0u); + EXPECT_EQ(vert_info->set, 0u); + EXPECT_EQ(vert_info->binding, 0u); + ASSERT_EQ(vert_info->fields.size(), 2u); + const auto& mvp = vert_info->fields[0]; + EXPECT_STREQ(mvp->name.c_str(), "mvp"); + EXPECT_EQ(mvp->type, fb::shaderbundle::UniformDataType::kFloat); + EXPECT_EQ(mvp->offset_in_bytes, 0u); + EXPECT_EQ(mvp->element_size_in_bytes, 64u); + EXPECT_EQ(mvp->total_size_in_bytes, 64u); + EXPECT_EQ(mvp->array_elements, 0u); + const auto& color = vert_info->fields[1]; + EXPECT_STREQ(color->name.c_str(), "color"); + EXPECT_EQ(color->type, fb::shaderbundle::UniformDataType::kFloat); + EXPECT_EQ(color->offset_in_bytes, 64u); + EXPECT_EQ(color->element_size_in_bytes, 16u); + EXPECT_EQ(color->total_size_in_bytes, 16u); + EXPECT_EQ(color->array_elements, 0u); + + // -------------------------------------------------------------------------- + /// Verify fragment shader. + /// + + EXPECT_STREQ(fragment->metal_desktop->entrypoint.c_str(), + "flutter_gpu_unlit_fragment_main"); + EXPECT_EQ(fragment->metal_desktop->stage, + fb::shaderbundle::ShaderStage::kFragment); + + // Inputs (not recorded for fragment shaders). + ASSERT_EQ(fragment->metal_desktop->inputs.size(), 0u); + + // Uniforms. + ASSERT_EQ(fragment->metal_desktop->inputs.size(), 0u); +} + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/BUILD.gn b/flutter/engine/src/flutter/impeller/compiler/shader_lib/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9317feafc76cd112033d1645253dce6535fbc542 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/BUILD.gn @@ -0,0 +1,10 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +group("shader_lib") { + deps = [ + "./flutter", + "./impeller", + ] +} diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/BUILD.gn b/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cf85043ddcd16cd54af789846cb7ed992a623678 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/BUILD.gn @@ -0,0 +1,8 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +copy("flutter") { + sources = [ "runtime_effect.glsl" ] + outputs = [ "$root_out_dir/shader_lib/flutter/{{source_file_part}}" ] +} diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/runtime_effect.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/runtime_effect.glsl new file mode 100644 index 0000000000000000000000000000000000000000..4a06bf45530988f1ea9c8c1ab016b15c3c8dfb95 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/flutter/runtime_effect.glsl @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef RUNTIME_EFFECT_GLSL_ +#define RUNTIME_EFFECT_GLSL_ + +#if defined(IMPELLER_GRAPHICS_BACKEND) + +// Note: The GLES backend uses name matching for attribute locations. This name +// must match the name of the attribute output in: +// impeller/entity/shaders/runtime_effect.vert +in vec2 _fragCoord; +vec2 FlutterFragCoord() { + return _fragCoord; +} + +#elif defined(SKIA_GRAPHICS_BACKEND) + +vec2 FlutterFragCoord() { + return gl_FragCoord.xy; +} + +#else +#error "Runtime effect builtins are not supported for this graphics backend." +#endif + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/BUILD.gn b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5609ce4d3aaa9d0af37c46d1cff00049a99c9054 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +copy("impeller") { + sources = [ + "blending.glsl", + "branching.glsl", + "color.glsl", + "conical_gradient_uniform_fill.glsl", + "constants.glsl", + "conversions.glsl", + "dithering.glsl", + "external_texture_oes.glsl", + "gaussian.glsl", + "gradient.glsl", + "math.glsl", + "path.glsl", + "texture.glsl", + "tile_mode.glsl", + "transform.glsl", + "types.glsl", + ] + outputs = [ "$root_out_dir/shader_lib/impeller/{{source_file_part}}" ] +} diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/blending.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/blending.glsl new file mode 100644 index 0000000000000000000000000000000000000000..59352f2bd22d208f2cbcf2216bd79d03d872e4eb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/blending.glsl @@ -0,0 +1,216 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BLENDING_GLSL_ +#define BLENDING_GLSL_ + +#include +#include +#include +#include + +/// Composite a blended color onto the destination. +/// All three parameters are unpremultiplied. Returns a premultiplied result. +/// +/// This routine is the same as `ApplyBlendedColor` in +/// `impeller/geometry/color.cc`. +f16vec4 IPApplyBlendedColor(f16vec4 dst, f16vec4 src, f16vec3 blend_result) { + dst = IPHalfPremultiply(dst); + src = + // Use the blended color for areas where the source and destination + // colors overlap. + IPHalfPremultiply(f16vec4(blend_result, src.a * dst.a)) + + // Use the original source color for any remaining non-overlapping areas. + IPHalfPremultiply(src) * (1.0hf - dst.a); + + // Source-over composite the blended source color atop the destination. + return src + dst * (1.0hf - src.a); +} + +//------------------------------------------------------------------------------ +/// HSV utilities. +/// + +float16_t IPLuminosity(f16vec3 color) { + return color.r * 0.3hf + color.g * 0.59hf + color.b * 0.11hf; +} + +/// Scales the color's luma by the amount necessary to place the color +/// components in a 1-0 range. +f16vec3 IPClipColor(f16vec3 color) { + float16_t lum = IPLuminosity(color); + float16_t mn = min(min(color.r, color.g), color.b); + float16_t mx = max(max(color.r, color.g), color.b); + // `lum - mn` and `mx - lum` will always be >= 0 in the following conditions, + // so adding a tiny value is enough to make these divisions safe. + if (mn < 0.0hf) { + color = lum + (((color - lum) * lum) / (lum - mn + kEhCloseEnoughHalf)); + } + if (mx > 1.0hf) { + color = lum + + (((color - lum) * (1.0hf - lum)) / (mx - lum + kEhCloseEnoughHalf)); + } + return color; +} + +f16vec3 IPSetLuminosity(f16vec3 color, float16_t luminosity) { + float16_t relative_lum = luminosity - IPLuminosity(color); + return IPClipColor(color + relative_lum); +} + +float16_t IPSaturation(f16vec3 color) { + return max(max(color.r, color.g), color.b) - + min(min(color.r, color.g), color.b); +} + +f16vec3 IPSetSaturation(f16vec3 color, float16_t saturation) { + float16_t mn = min(min(color.r, color.g), color.b); + float16_t mx = max(max(color.r, color.g), color.b); + return (mn < mx) ? ((color - mn) * saturation) / (mx - mn) : f16vec3(0.0hf); +} + +//------------------------------------------------------------------------------ +/// Color blend functions. +/// +/// These routines take two unpremultiplied RGB colors and output a third color. +/// They can be combined with any alpha compositing operation. When these blend +/// functions are used for drawing Entities in Impeller, the output is always +/// applied to the destination using `SourceOver` alpha compositing. +/// + +f16vec3 IPBlendScreen(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingscreen + return dst + src - (dst * src); +} + +f16vec3 IPBlendHardLight(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendinghardlight + return IPHalfVec3Choose(dst * (2.0hf * src), + IPBlendScreen(dst, 2.0hf * src - 1.0hf), src); +} + +f16vec3 IPBlendOverlay(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingoverlay + // HardLight, but with reversed parameters. + return IPBlendHardLight(src, dst); +} + +f16vec3 IPBlendDarken(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingdarken + return min(dst, src); +} + +f16vec3 IPBlendLighten(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendinglighten + return max(dst, src); +} + +f16vec3 IPBlendColorDodge(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingcolordodge + + f16vec3 color = min(f16vec3(1.0hf), dst / (1.0hf - src)); + + if (dst.r < kEhCloseEnoughHalf) { + color.r = 0.0hf; + } + if (dst.g < kEhCloseEnoughHalf) { + color.g = 0.0hf; + } + if (dst.b < kEhCloseEnoughHalf) { + color.b = 0.0hf; + } + + if (1.0hf - src.r < kEhCloseEnoughHalf) { + color.r = 1.0hf; + } + if (1.0hf - src.g < kEhCloseEnoughHalf) { + color.g = 1.0hf; + } + if (1.0hf - src.b < kEhCloseEnoughHalf) { + color.b = 1.0hf; + } + + return color; +} + +f16vec3 IPBlendColorBurn(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingcolorburn + + f16vec3 color = 1.0hf - min(f16vec3(1.0hf), (1.0hf - dst) / src); + + if (1.0hf - dst.r < kEhCloseEnoughHalf) { + color.r = 1.0hf; + } + if (1.0hf - dst.g < kEhCloseEnoughHalf) { + color.g = 1.0hf; + } + if (1.0hf - dst.b < kEhCloseEnoughHalf) { + color.b = 1.0hf; + } + + if (src.r < kEhCloseEnoughHalf) { + color.r = 0.0hf; + } + if (src.g < kEhCloseEnoughHalf) { + color.g = 0.0hf; + } + if (src.b < kEhCloseEnoughHalf) { + color.b = 0.0hf; + } + + return color; +} + +f16vec3 IPBlendSoftLight(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingsoftlight + + f16vec3 D = + IPHalfVec3ChooseCutoff(((16.0hf * dst - 12.0hf) * dst + 4.0hf) * dst, // + sqrt(dst), // + dst, // + 0.25hf); + + return IPHalfVec3Choose(dst - (1.0hf - 2.0hf * src) * dst * (1.0hf - dst), // + dst + (2.0hf * src - 1.0hf) * (D - dst), // + src); +} + +f16vec3 IPBlendDifference(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingdifference + return abs(dst - src); +} + +f16vec3 IPBlendExclusion(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingexclusion + return dst + src - 2.0hf * dst * src; +} + +f16vec3 IPBlendMultiply(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingmultiply + return dst * src; +} + +f16vec3 IPBlendHue(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendinghue + return IPSetLuminosity(IPSetSaturation(src, IPSaturation(dst)), + IPLuminosity(dst)); +} + +f16vec3 IPBlendSaturation(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingsaturation + return IPSetLuminosity(IPSetSaturation(dst, IPSaturation(src)), + IPLuminosity(dst)); +} + +f16vec3 IPBlendColor(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingcolor + return IPSetLuminosity(src, IPLuminosity(dst)); +} + +f16vec3 IPBlendLuminosity(f16vec3 dst, f16vec3 src) { + // https://www.w3.org/TR/compositing-1/#blendingluminosity + return IPSetLuminosity(dst, IPLuminosity(src)); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/branching.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/branching.glsl new file mode 100644 index 0000000000000000000000000000000000000000..4441e6a5618277862c1375dde44c0bab8a716e5f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/branching.glsl @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BRANCHING_GLSL_ +#define BRANCHING_GLSL_ + +#include +#include + +/// Perform an equality check for each vec3 component. +/// +/// Returns 1.0 if x == y, otherwise 0.0. +BoolV3 IPVec3IsEqual(vec3 x, float y) { + vec3 diff = abs(x - y); + return vec3(diff.r < kEhCloseEnough, // + diff.g < kEhCloseEnough, // + diff.b < kEhCloseEnough); +} + +/// Perform a branchless greater than check. +/// +/// Returns 1.0 if x > y, otherwise 0.0. +BoolF IPFloatIsGreaterThan(float x, float y) { + return max(sign(x - y), 0); +} + +/// Perform a branchless greater than check for each vec3 component. +/// +/// Returns 1.0 if x > y, otherwise 0.0. +BoolV3 IPVec3IsGreaterThan(vec3 x, vec3 y) { + return max(sign(x - y), 0); +} + +/// Perform a branchless less than check. +/// +/// Returns 1.0 if x < y, otherwise 0.0. +BoolF IPFloatIsLessThan(float x, float y) { + return max(sign(y - x), 0); +} + +/// For each vec3 component, if value > cutoff, return b, otherwise return a. +vec3 IPVec3ChooseCutoff(vec3 a, vec3 b, vec3 value, float cutoff) { + return mix(a, b, IPVec3IsGreaterThan(value, vec3(cutoff))); +} + +/// For each vec3 component, if value > 0.5, return b, otherwise return a. +vec3 IPVec3Choose(vec3 a, vec3 b, vec3 value) { + return IPVec3ChooseCutoff(a, b, value, 0.5); +} + +/// Perform a branchless greater than check for each vec3 component. +/// +/// Returns 1.0 if x > y, otherwise 0.0. +f16vec3 IPHalfVec3IsGreaterThan(f16vec3 x, f16vec3 y) { + return max(sign(x - y), float16_t(0.0hf)); +} + +/// For each vec3 component, if value > cutoff, return b, otherwise return a. +f16vec3 IPHalfVec3ChooseCutoff(f16vec3 a, + f16vec3 b, + f16vec3 value, + float16_t cutoff) { + return mix(a, b, IPHalfVec3IsGreaterThan(value, f16vec3(cutoff))); +} + +/// For each vec3 component, if value > 0.5, return b, otherwise return a. +f16vec3 IPHalfVec3Choose(f16vec3 a, f16vec3 b, f16vec3 value) { + return IPHalfVec3ChooseCutoff(a, b, value, float16_t(0.5hf)); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/color.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/color.glsl new file mode 100644 index 0000000000000000000000000000000000000000..310e22e779f76f18598ebd52a4ea9522e0319a59 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/color.glsl @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COLOR_GLSL_ +#define COLOR_GLSL_ + +#include +#include + +/// Convert a premultiplied color (a color which has its color components +/// multiplied with its alpha value) to an unpremultiplied color. +/// +/// Returns (0, 0, 0, 0) if the alpha component is 0. +vec4 IPUnpremultiply(vec4 color) { + if (color.a == 0) { + return vec4(0); + } + return vec4(color.rgb / color.a, color.a); +} + +/// Convert a premultiplied color (a color which has its color components +/// multiplied with its alpha value) to an unpremultiplied color. +/// +/// Returns (0, 0, 0, 0) if the alpha component is 0. +f16vec4 IPHalfUnpremultiply(f16vec4 color) { + if (color.a == 0.0hf) { + return f16vec4(0.0hf); + } + return f16vec4(color.rgb / color.a, color.a); +} + +/// Convert an unpremultiplied color (a color which has its color components +/// separated from its alpha value) to a premultiplied color. +/// +/// Returns (0, 0, 0, 0) if the alpha component is 0. +vec4 IPPremultiply(vec4 color) { + return vec4(color.rgb * color.a, color.a); +} + +/// Convert an unpremultiplied color (a color which has its color components +/// separated from its alpha value) to a premultiplied color. +/// +/// Returns (0, 0, 0, 0) if the alpha component is 0. +f16vec4 IPHalfPremultiply(f16vec4 color) { + return f16vec4(color.rgb * color.a, color.a); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_fill.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_fill.glsl new file mode 100644 index 0000000000000000000000000000000000000000..3c6cb7b9665c296436b62d62912b24441a0830ec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_fill.glsl @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ +#define CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ + +#include + +uniform sampler2D texture_sampler; + +uniform FragInfo { + highp vec2 center; + float radius; + float tile_mode; + vec4 decal_border_color; + float texture_sampler_y_coord_scale; + float alpha; + vec2 half_texel; + vec2 focus; + float focus_radius; +} +frag_info; + +vec4 DoConicalGradientTextureFill(vec2 res) { + if (res.y < 0.0) { + return vec4(0); + } + + float t = res.x; + vec4 result = + IPSampleLinearWithTileMode(texture_sampler, // + vec2(t, 0.5), // + frag_info.texture_sampler_y_coord_scale, // + frag_info.half_texel, // + frag_info.tile_mode, // + frag_info.decal_border_color); + result = IPPremultiply(result) * frag_info.alpha; + return result; +} + +#endif // CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_uniform_fill.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_uniform_fill.glsl new file mode 100644 index 0000000000000000000000000000000000000000..776ac784e2d8a304351ae42edf6e25d5a13d3ebe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conical_gradient_uniform_fill.glsl @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ +#define CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ + +precision highp float; + +#include + +uniform FragInfo { + highp vec2 center; + vec2 focus; + float focus_radius; + float radius; + float tile_mode; + float alpha; + float colors_length; + vec4 decal_border_color; + vec4 colors[256]; + vec4 stop_pairs[128]; +} +frag_info; + +vec4 DoConicalGradientUniformFill(vec2 res) { + float t = res.x; + vec4 result_color = vec4(0); + if (res.y < 0.0 || + ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal)) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + vec2 prev_stop = frag_info.stop_pairs[0].xy; + bool even = false; + for (int i = 1; i < frag_info.colors_length; i++) { + // stop_pairs[i/2].xy = values for stop i + // stop_pairs[i/2].zw = values for stop i+1 + vec2 cur_stop = even ? frag_info.stop_pairs[i / 2].xy + : frag_info.stop_pairs[i / 2].zw; + even = !even; + // stop.x == t value + // stop.y == inverse_delta to next stop + if (t >= prev_stop.x && t <= cur_stop.x) { + if (cur_stop.y > 1000.0) { + result_color = frag_info.colors[i]; + } else { + float ratio = (t - prev_stop.x) * cur_stop.y; + result_color = + mix(frag_info.colors[i - 1], frag_info.colors[i], ratio); + } + break; + } + prev_stop = cur_stop; + } + } + + result_color = IPPremultiply(result_color) * frag_info.alpha; + return result_color; +} + +#endif // CONICAL_GRADIENT_UNIFORM_FILL_GLSL_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/constants.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/constants.glsl new file mode 100644 index 0000000000000000000000000000000000000000..f211cbae9700e627f9233df848c5289eb1998e3b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/constants.glsl @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONSTANTS_GLSL_ +#define CONSTANTS_GLSL_ + +#include + +const float kEhCloseEnough = 0.000001; + +// 1/1024. +const float16_t kEhCloseEnoughHalf = 0.0009765625hf; + +// 1 / (2 * pi) +const float k1Over2Pi = 0.1591549430918; + +// sqrt(2 * pi) +const float kSqrtTwoPi = 2.50662827463; + +// sqrt(2) / 2 == 1 / sqrt(2) +const float kHalfSqrtTwo = 0.70710678118; + +// sqrt(3) +const float kSqrtThree = 1.73205080757; + +// The default mip bias to use when sampling textures. +// This value biases towards sampling from a lower mip level (bigger size), +// which results in sharper looking images when mip sampling is enabled. This is +// the same constant that Skia uses. +const float kDefaultMipBias = -0.475; + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conversions.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conversions.glsl new file mode 100644 index 0000000000000000000000000000000000000000..1a84771678da6d8f892cf2532c7a045aa6735a2f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/conversions.glsl @@ -0,0 +1,15 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONVERSIONS_GLSL_ +#define CONVERSIONS_GLSL_ + +vec2 IPRemapCoords(vec2 coords, float y_coord_scale) { + if (y_coord_scale < 0.0) { + coords.y = 1.0 - coords.y; + } + return coords; +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/dithering.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/dithering.glsl new file mode 100644 index 0000000000000000000000000000000000000000..5494c4ecee45cdc0dc4d947c745bd931ec9d8ce1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/dithering.glsl @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DITHERING_GLSL_ +#define DITHERING_GLSL_ + +#include + +/// The dithering rate, which is 1.0 / 64.0, or 0.015625. +const float kDitherRate = 1.0 / 64.0; + +/// Returns the closest color to the input color using 8x8 ordered dithering. +/// +/// Ordered dithering divides the output into a grid of cells, and then assigns +/// a different threshold to each cell. The threshold is used to determine if +/// the color should be rounded up (white) or down (black). +// +/// This technique was chosen mostly because Skia also uses it: +/// https://github.com/google/skia/blob/f9de059517a6f58951510fc7af0cba21e13dd1a8/src/opts/SkRasterPipeline_opts.h#L1717 +/// +/// See also: +/// - https://en.wikipedia.org/wiki/Ordered_dithering +/// - https://surma.dev/things/ditherpunk/ +/// - https://shader-tutorial.dev/advanced/color-banding-dithering/ +vec4 IPOrderedDither8x8(vec4 color, vec2 dest) { + // Get the x and y coordinates of the pixel in the 8x8 grid. + uint x = uint(dest.x) % 8; + uint y = uint(dest.y); + y ^= x; + + // Get the dither value from the matrix. + uint m = (y & 1) << 5 | // + (x & 1) << 4 | // + (y & 2) << 2 | // + (x & 2) << 1 | // + (y & 4) >> 1 | // + (x & 4) >> 2; // + + // Scale that dither to [0,1), then (-0.5,+0.5), here using 63/128 = 0.4921875 + // as 0.5-epsilon. We want to make sure our dither is less than 0.5 in either + // direction to keep exact values like 0 and 1 unchanged after rounding. + float dither = float(m) * (2.0 / 128.0) - (63.0 / 128.0); + + // Apply the dither to the color. + color.rgb += dither * kDitherRate; + + return color; +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/external_texture_oes.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/external_texture_oes.glsl new file mode 100644 index 0000000000000000000000000000000000000000..ece31ed69aa0e81c3aa43910ff3cb17f6f8e2537 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/external_texture_oes.glsl @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +/// A triangle wave. 0->0, 1->1, 2->0, and so on... works with negative numbers. +float TriangleWave(float x) { + return abs(mod(x + 1, 2) - 1); +} + +/// OES_EGL_image_external states that only CLAMP_TO_EDGE is valid, so we +/// emulate all other tile modes here by remapping the texture coordinates. +vec4 IPSampleWithTileModeOES(sampler2D tex, + vec2 coords, + float x_tile_mode, + float y_tile_mode) { + if (x_tile_mode == kTileModeDecal && (coords.x < 0 || coords.x >= 1) || + y_tile_mode == kTileModeDecal && (coords.y < 0 || coords.y >= 1)) { + return vec4(0); + } + + if (x_tile_mode == kTileModeRepeat) { + coords.x = mod(coords.x, 1); + } else if (x_tile_mode == kTileModeMirror) { + coords.x = TriangleWave(coords.x); + } + + if (y_tile_mode == kTileModeRepeat) { + coords.y = mod(coords.y, 1); + } else if (y_tile_mode == kTileModeMirror) { + coords.y = TriangleWave(coords.y); + } + + return texture(tex, coords); +} diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gaussian.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gaussian.glsl new file mode 100644 index 0000000000000000000000000000000000000000..fef2a39aa59c5cf7a2cc92a877b3dc7577f6c038 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gaussian.glsl @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GAUSSIAN_GLSL_ +#define GAUSSIAN_GLSL_ + +#include +#include + +/// Gaussian distribution function. +float IPGaussian(float x, float sigma) { + float variance = sigma * sigma; + return exp(-0.5f * x * x / variance) / (kSqrtTwoPi * sigma); +} + +/// Equivalent to `IPGaussian(float x, float sigma)` but executed 4x. +vec4 IPGaussian(vec4 x, float sigma) { + float variance = sigma * sigma; + return exp(-0.5f * x * x / variance) / (kSqrtTwoPi * sigma); +} + +/// Gaussian distribution function. +float16_t IPHalfGaussian(float16_t x, float16_t sigma) { + float16_t variance = sigma * sigma; + return exp(-0.5hf * x * x / variance) / (float16_t(kSqrtTwoPi) * sigma); +} + +/// Abramowitz and Stegun erf approximation. +float16_t IPErf(float16_t x) { + float16_t a = abs(x); + // 0.278393*x + 0.230389*x^2 + 0.078108*x^4 + 1 + float16_t b = + (0.278393hf + (0.230389hf + 0.078108hf * a * a) * a) * a + 1.0hf; + return sign(x) * (1.0hf - 1.0hf / (b * b * b * b)); +} + +/// Vec2 variation for the Abramowitz and Stegun erf approximation. +f16vec2 IPVec2Erf(f16vec2 x) { + f16vec2 a = abs(x); + // 0.278393*x + 0.230389*x^2 + 0.078108*x^4 + 1 + f16vec2 b = (0.278393hf + (0.230389hf + 0.078108hf * a * a) * a) * a + 1.0hf; + return sign(x) * (1.0hf - 1.0hf / (b * b * b * b)); +} + +/// The indefinite integral of the Gaussian function. +/// Uses a very close approximation of Erf. +float16_t IPGaussianIntegral(float16_t x, float16_t sigma) { + // ( 1 + erf( x * (sqrt(2) / (2 * sigma) ) ) / 2 + return (1.0hf + IPErf(x * (float16_t(kHalfSqrtTwo) / sigma))) * 0.5hf; +} + +/// Vec2 variation for the indefinite integral of the Gaussian function. +/// Uses a very close approximation of Erf. +f16vec2 IPVec2GaussianIntegral(f16vec2 x, float16_t sigma) { + // ( 1 + erf( x * (sqrt(2) / (2 * sigma) ) ) / 2 + return (1.0hf + IPVec2Erf(x * (float16_t(kHalfSqrtTwo) / sigma))) * 0.5hf; +} + +/// Simpler (but less accurate) approximation of the Gaussian integral. +vec2 IPVec2FastGaussianIntegral(vec2 x, float sigma) { + return 1.0 / (1.0 + exp(-kSqrtThree / sigma * x)); +} + +/// Equivalent to `IPVec2FastGaussianIntegral(vec2 x, float sigma)` but operated +/// 4x instead of 2x. +vec4 IPVec4FastGaussianIntegral(vec4 x, float sigma) { + return 1.0 / (1.0 + exp(-kSqrtThree / sigma * x)); +} + +/// Simpler (but less accurate) approximation of the Gaussian integral. +f16vec2 IPHalfVec2FastGaussianIntegral(f16vec2 x, float16_t sigma) { + return 1.0hf / (1.0hf + exp(float16_t(-kSqrtThree) / sigma * x)); +} + +/// Simple logistic sigmoid with a domain of [-1, 1] and range of [0, 1]. +float16_t IPSigmoid(float16_t x) { + return 1.03731472073hf / (1.0hf + exp(-4.0hf * x)) - 0.0186573603638hf; +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gradient.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gradient.glsl new file mode 100644 index 0000000000000000000000000000000000000000..6f2b87f24a8f3d7c2772375979800d2fa27f7fe3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/gradient.glsl @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GRADIENT_GLSL_ +#define GRADIENT_GLSL_ + +#include +#include + +mat3 IPMapToUnitX(vec2 p0, vec2 p1) { + // Returns a matrix that maps [p0, p1] to [(0, 0), (1, 0)]. Results are + // undefined if p0 = p1. + return mat3(0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) * + IPMat3Inverse(mat3(p1.y - p0.y, p0.x - p1.x, 0.0, p1.x - p0.x, + p1.y - p0.y, 0.0, p0.x, p0.y, 1.0)); +} + +vec2 IPComputeConicalTRadial(vec2 c0, float r0, vec2 c1, float r1, vec2 pos) { + float d_radius = r1 - r0; + float scale = 1.0 / d_radius; + float scale_sign = sign(d_radius); + float bias = r0 / d_radius; + + vec2 pt = (pos - c0) * scale; + float t = length(pt) * scale_sign - bias; + return vec2(t, 1.0); +} + +vec2 IPComputeConicalTStrip(vec2 c0, float r0, vec2 c1, float r1, vec2 pos) { + float d_center = distance(c0, c1); + mat3 transform = IPMapToUnitX(c0, c1); + float r = r0 / d_center; + float r_2 = r * r; + + vec2 pt = (transform * vec3(pos.xy, 1.0)).xy; + float t = r_2 - pt.y * pt.y; + if (t < 0.0) { + return vec2(0.0, -1.0); + } + t = pt.x + sqrt(t); + return vec2(t, 1.0); +} + +vec2 IPComputeConicalTConical(vec2 c0, float r0, vec2 c1, float r1, vec2 pos) { + const float scalar_nearly_zero = 1.0 / float(1 << 12); + float d_center = distance(c0, c1); + // See https://skia.org/docs/dev/design/conical/ for details on how this + // algorithm works. Calculate f and swap inputs if necessary (steps 1 and + // 2). + float f = r0 / (r0 - r1); + + bool is_swapped = abs(f - 1.0) < scalar_nearly_zero; + if (is_swapped) { + vec2 tmp_pt = c0; + c0 = c1; + c1 = tmp_pt; + f = 0.0; + } + + // Apply mapping from [Cf, C1] to unit x, and apply the precalculations from + // steps 3 and 4, all in the same transform. + vec2 cf = c0 * (1.0 - f) + c1 * f; + mat3 transform = IPMapToUnitX(cf, c1); + + float scale_x = abs(1.0 - f); + float scale_y = scale_x; + float local_r1 = abs(r1 - r0) / d_center; + bool is_focal_on_circle = abs(local_r1 - 1.0) < scalar_nearly_zero; + if (is_focal_on_circle) { + scale_x *= 0.5; + scale_y *= 0.5; + } else { + scale_x *= local_r1 / (local_r1 * local_r1 - 1.0); + scale_y /= sqrt(abs(local_r1 * local_r1 - 1.0)); + } + transform = + mat3(scale_x, 0.0, 0.0, 0.0, scale_y, 0.0, 0.0, 0.0, 1.0) * transform; + + vec2 pt = (transform * vec3(pos.xy, 1.0)).xy; + + // Continue with step 5 onward. + float inv_r1 = 1.0 / local_r1; + float d_radius_sign = sign(1.0 - f); + bool is_well_behaved = !is_focal_on_circle && local_r1 > 1.0; + + float x_t = -1.0; + if (is_focal_on_circle) { + x_t = dot(pt, pt) / pt.x; + } else if (is_well_behaved) { + x_t = length(pt) - pt.x * inv_r1; + } else { + float temp = pt.x * pt.x - pt.y * pt.y; + if (temp >= 0.0) { + if (is_swapped || d_radius_sign < 0.0) { + x_t = -sqrt(temp) - pt.x * inv_r1; + } else { + x_t = sqrt(temp) - pt.x * inv_r1; + } + } + } + + if (!is_well_behaved && x_t < 0.0) { + return vec2(0.0, -1.0); + } + + float t = f + d_radius_sign * x_t; + if (is_swapped) { + t = 1.0 - t; + } + return vec2(t, 1.0); +} + +/// Compute the t value for a conical gradient at point `p` between the 2 +/// circles defined by (c0, r0) and (c1, r1). The returned vec2 encapsulates 't' +/// as its x component and validity status as its y component, with positive y +/// indicating a valid result. +/// +/// The code is migrated from Skia Graphite. See +/// https://github.com/google/skia/blob/ddf987d2ab3314ee0e80ac1ae7dbffb44a87d394/src/sksl/sksl_graphite_frag.sksl#L541-L666. +vec2 IPComputeConicalT(float kind, + vec2 c0, + float r0, + vec2 c1, + float r1, + vec2 pos) { + if (kind == 0.0) { + return vec2(0.0, -1.0); + } else if (kind == 1.0) { + return IPComputeConicalTRadial(c0, r0, c1, r1, pos); + } else if (kind == 2.0) { + return IPComputeConicalTStrip(c0, r0, c1, r1, pos); + } else { + return IPComputeConicalTConical(c0, r0, c1, r1, pos); + } +} + +/// Compute the indexes and mix coefficient used to mix colors for an +/// arbitrarily sized color gradient. +/// +/// The returned values are the lower index, upper index, and mix +/// coefficient. +vec3 IPComputeFixedGradientValues(float t, float colors_length) { + float rough_index = (colors_length - 1) * t; + float lower_index = floor(rough_index); + float upper_index = ceil(rough_index); + float scale = rough_index - lower_index; + + return vec3(lower_index, upper_index, scale); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/math.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/math.glsl new file mode 100644 index 0000000000000000000000000000000000000000..2c0651a1c2330c3823533b5225e95e2a771442c1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/math.glsl @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MATH_GLSL_ +#define MATH_GLSL_ + +// pow(x, y) crashes the shader compiler on the Nexus 5. +// See also: https://skia-review.googlesource.com/c/skia/+/148480 +#ifdef IMPELLER_TARGET_OPENGLES +#define POW(x, y) exp2(y* log2(x)) +#else +#define POW(x, y) pow(x, y) +#endif + +#endif // MATH_GLSL_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/path.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/path.glsl new file mode 100644 index 0000000000000000000000000000000000000000..1705d7427089ec5f338b2b16c1a447fea27c00e6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/path.glsl @@ -0,0 +1,165 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PATH_GLSL_ +#define PATH_GLSL_ + +struct LineData { + vec2 p1; + vec2 p2; +}; + +struct QuadData { + vec2 p1; + vec2 cp; + vec2 p2; +}; + +struct CubicData { + vec2 p1; + vec2 cp1; + vec2 cp2; + vec2 p2; +}; + +struct QuadDecomposition { + float a0; + float a2; + float u0; + float u_scale; + uint line_count; + float steps; +}; + +struct PathComponent { + uint index; // Location in buffer + uint count; // Number of points. 4 = cubic, 3 = quad, 2 = line. +}; + +/// Solve for point on a quadratic Bezier curve defined by starting point `p1`, +/// control point `cp`, and end point `p2` at time `t`. +vec2 QuadraticSolve(QuadData quad, float t) { + return (1.0 - t) * (1.0 - t) * quad.p1 + // + 2.0 * (1.0 - t) * t * quad.cp + // + t * t * quad.p2; +} + +vec2 CubicSolve(CubicData cubic, float t) { + return (1. - t) * (1. - t) * (1. - t) * cubic.p1 + // + 3 * (1. - t) * (1. - t) * t * cubic.cp1 + // + 3 * (1. - t) * t * t * cubic.cp2 + // + t * t * t * cubic.p2; +} + +/// Used to approximate quadratic curves using parabola. +/// +/// See +/// https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html +float ApproximateParabolaIntegral(float x) { + float d = 0.67; + return x / (1.0 - d + sqrt(sqrt(pow(d, 4) + 0.25 * x * x))); +} + +bool isfinite(float f) { + return !isnan(f) && !isinf(f); +} + +float Cross(vec2 p1, vec2 p2) { + return p1.x * p2.y - p1.y * p2.x; +} + +QuadData GenerateQuadraticFromCubic(CubicData cubic, + uint index, + float quad_count) { + float t0 = index / quad_count; + float t1 = (index + 1) / quad_count; + + // calculate the subsegment + vec2 sub_p1 = CubicSolve(cubic, t0); + vec2 sub_p2 = CubicSolve(cubic, t1); + QuadData quad = QuadData(3.0 * (cubic.cp1 - cubic.p1), // + 3.0 * (cubic.cp2 - cubic.cp1), // + 3.0 * (cubic.p2 - cubic.cp2)); + float sub_scale = (t1 - t0) * (1.0 / 3.0); + vec2 sub_cp1 = sub_p1 + sub_scale * QuadraticSolve(quad, t0); + vec2 sub_cp2 = sub_p2 - sub_scale * QuadraticSolve(quad, t1); + + vec2 quad_p1x2 = 3.0 * sub_cp1 - sub_p1; + vec2 quad_p2x2 = 3.0 * sub_cp2 - sub_p2; + + return QuadData(sub_p1, // + ((quad_p1x2 + quad_p2x2) / 4.0), // + sub_p2); +} + +uint EstimateQuadraticCount(CubicData cubic, float accuracy) { + // The maximum error, as a vector from the cubic to the best approximating + // quadratic, is proportional to the third derivative, which is constant + // across the segment. Thus, the error scales down as the third power of + // the number of subdivisions. Our strategy then is to subdivide `t` evenly. + // + // This is an overestimate of the error because only the component + // perpendicular to the first derivative is important. But the simplicity is + // appealing. + + // This magic number is the square of 36 / sqrt(3). + // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html + float max_hypot2 = 432.0 * accuracy * accuracy; + + vec2 err_v = (3.0 * cubic.cp2 - cubic.p2) - (3.0 * cubic.cp1 - cubic.p1); + float err = dot(err_v, err_v); + return uint(max(1., ceil(pow(err * (1.0 / max_hypot2), 1. / 6.0)))); +} + +QuadDecomposition DecomposeQuad(QuadData quad, float tolerance) { + float sqrt_tolerance = sqrt(tolerance); + + vec2 d01 = quad.cp - quad.p1; + vec2 d12 = quad.p2 - quad.cp; + vec2 dd = d01 - d12; + // This should never happen, but if it does happen be more defensive - + // otherwise we'll get NaNs down the line. + if (dd == vec2(0.)) { + return QuadDecomposition(0., 0., 0., 0., 0, 0.); + } + float c = Cross(quad.p2 - quad.p1, dd); + float x0 = dot(d01, dd) * 1. / c; + float x2 = dot(d12, dd) * 1. / c; + float scale = abs(c / (sqrt(dd.x * dd.x + dd.y * dd.y) * (x2 - x0))); + + float a0 = ApproximateParabolaIntegral(x0); + float a2 = ApproximateParabolaIntegral(x2); + float val = 0.f; + if (isfinite(scale)) { + float da = abs(a2 - a0); + float sqrt_scale = sqrt(scale); + if ((x0 < 0 && x2 < 0) || (x0 >= 0 && x2 >= 0)) { + val = da * sqrt_scale; + } else { + // cusp case + float xmin = sqrt_tolerance / sqrt_scale; + val = sqrt_tolerance * da / ApproximateParabolaIntegral(xmin); + } + } + float u0 = ApproximateParabolaIntegral(a0); + float u2 = ApproximateParabolaIntegral(a2); + float u_scale = 1. / (u2 - u0); + + uint line_count = uint(max(1., ceil(0.5 * val / sqrt_tolerance)) + 1.); + float steps = 1. / line_count; + + return QuadDecomposition(a0, a2, u0, u_scale, line_count, steps); +} + +vec2 GenerateLineFromQuad(QuadData quad, + uint index, + QuadDecomposition decomposition) { + float u = index * decomposition.steps; + float a = decomposition.a0 + (decomposition.a2 - decomposition.a0) * u; + float t = (ApproximateParabolaIntegral(a) - decomposition.u0) * + decomposition.u_scale; + return QuadraticSolve(quad, t); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/prefix_sum.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/prefix_sum.glsl new file mode 100644 index 0000000000000000000000000000000000000000..a232d4da5dd85d5a15ba1a7c6bc3df115f1f60ed --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/prefix_sum.glsl @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Parallel exclusive prefix sum computes the prefix in place in storage. +// BLOCK_SIZE is the overall storage size while ident must be the global +// x identifier. +#define ExclusivePrefixSum(ident, storage, BLOCK_SIZE) \ + do { \ + uint offset = 1; \ + for (uint n = BLOCK_SIZE / 2; n > 0; n /= 2) { \ + if (ident < n) { \ + uint ai = offset * (2 * ident + 1) - 1; \ + uint bi = offset * (2 * ident + 2) - 1; \ + storage[bi] += storage[ai]; \ + } \ + offset *= 2; \ + barrier(); \ + } \ + \ + if (ident == 0) { \ + storage[BLOCK_SIZE - 1] = 0; \ + } \ + barrier(); \ + \ + for (uint n = 1; n < BLOCK_SIZE; n *= 2) { \ + offset /= 2; \ + barrier(); \ + if (ident < n) { \ + uint ai = offset * (2 * ident + 1) - 1; \ + uint bi = offset * (2 * ident + 2) - 1; \ + uint temp = storage[ai]; \ + storage[ai] = storage[bi]; \ + storage[bi] += temp; \ + } \ + } \ + barrier(); \ + } while (false) diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/texture.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/texture.glsl new file mode 100644 index 0000000000000000000000000000000000000000..98628069bb77a199fc2e019796c69a2461b748e5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/texture.glsl @@ -0,0 +1,157 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef TEXTURE_GLSL_ +#define TEXTURE_GLSL_ + +#include +#include +#include +#include + +/// Sample from a texture. +/// +/// If `y_coord_scale` < 0.0, the Y coordinate is flipped. This is useful +/// for Impeller graphics backends that use a flipped framebuffer coordinate +/// space. +/// +/// A negative mip bias is applied to improve the sharpness of scaled down +/// images when mip sampling is enabled. See `kDefaultMipBias` for more detail. +vec4 IPSample(sampler2D texture_sampler, vec2 coords, float y_coord_scale) { + return texture(texture_sampler, IPRemapCoords(coords, y_coord_scale), + kDefaultMipBias); +} + +/// Sample from a texture. +/// +/// If `y_coord_scale` < 0.0, the Y coordinate is flipped. This is useful +/// for Impeller graphics backends that use a flipped framebuffer coordinate +/// space. +/// The range of `coords` will be mapped from [0, 1] to [half_texel, 1 - +/// half_texel] +vec4 IPSampleLinear(sampler2D texture_sampler, + vec2 coords, + float y_coord_scale, + vec2 half_texel) { + coords.x = mix(half_texel.x, 1 - half_texel.x, coords.x); + coords.y = mix(half_texel.y, 1 - half_texel.y, coords.y); + return IPSample(texture_sampler, coords, y_coord_scale); +} + +/// Remap a float using a tiling mode. +/// +/// When `tile_mode` is `kTileModeDecal`, no tiling is applied and `t` is +/// returned. In all other cases, a value between 0 and 1 is returned by tiling +/// `t`. +/// When `t` is between [0 to 1), the original unchanged `t` is always returned. +highp float IPFloatTile(highp float t, float tile_mode) { + if (tile_mode == kTileModeClamp) { + t = clamp(t, 0.0, 1.0); + } else if (tile_mode == kTileModeRepeat) { + t = fract(t); + } else if (tile_mode == kTileModeMirror) { + highp float t1 = t - 1; + highp float t2 = t1 - 2 * floor(t1 * 0.5) - 1; + t = abs(t2); + } + return t; +} + +/// Remap a vec2 using a tiling mode. +/// +/// Runs each component of the vec2 through `IPFloatTile`. +vec2 IPVec2Tile(vec2 coords, float x_tile_mode, float y_tile_mode) { + return vec2(IPFloatTile(coords.x, x_tile_mode), + IPFloatTile(coords.y, y_tile_mode)); +} + +/// Sample a texture, emulating a specific tile mode. +/// +/// This is useful for Impeller graphics backend that don't have native support +/// for Decal. +vec4 IPSampleWithTileMode(sampler2D tex, + vec2 coords, + float x_tile_mode, + float y_tile_mode) { + if (x_tile_mode == kTileModeDecal && (coords.x < 0 || coords.x >= 1) || + y_tile_mode == kTileModeDecal && (coords.y < 0 || coords.y >= 1)) { + return vec4(0); + } + + return texture(tex, coords, kDefaultMipBias); +} + +/// Sample a texture, emulating a specific tile mode. +/// +/// This is useful for Impeller graphics backend that don't have native support +/// for Decal. +f16vec4 IPHalfSampleWithTileMode(f16sampler2D tex, + vec2 coords, + float x_tile_mode, + float y_tile_mode) { + if (x_tile_mode == kTileModeDecal && (coords.x < 0.0 || coords.x >= 1.0) || + y_tile_mode == kTileModeDecal && (coords.y < 0.0 || coords.y >= 1.0)) { + return f16vec4(0.0hf); + } + + return texture(tex, coords, float16_t(kDefaultMipBias)); +} + +/// Sample a texture, emulating a specific tile mode. +/// +/// This is useful for Impeller graphics backend that don't have native support +/// for Decal. +/// The range of `coords` will be mapped from [0, 1] to [half_texel, 1 - +/// half_texel] +vec4 IPSampleLinearWithTileMode(sampler2D tex, + vec2 coords, + float y_coord_scale, + vec2 half_texel, + float x_tile_mode, + float y_tile_mode, + vec4 decal_border_color) { + if (x_tile_mode == kTileModeDecal && (coords.x < 0 || coords.x >= 1) || + y_tile_mode == kTileModeDecal && (coords.y < 0 || coords.y >= 1)) { + return decal_border_color; + } + + return IPSampleLinear(tex, IPVec2Tile(coords, x_tile_mode, y_tile_mode), + y_coord_scale, half_texel); +} + +/// Sample a texture with decal tile mode. +vec4 IPSampleDecal(sampler2D texture_sampler, vec2 coords) { + if (any(lessThan(coords, vec2(0))) || + any(greaterThanEqual(coords, vec2(1)))) { + return vec4(0); + } + return texture(texture_sampler, coords, kDefaultMipBias); +} + +/// Sample a texture with decal tile mode. +f16vec4 IPHalfSampleDecal(f16sampler2D texture_sampler, vec2 coords) { + if (any(lessThan(coords, vec2(0))) || + any(greaterThanEqual(coords, vec2(1)))) { + return f16vec4(0.0); + } + return texture(texture_sampler, coords, float16_t(kDefaultMipBias)); +} + +/// Sample a texture, emulating a specific tile mode. +/// +/// This is useful for Impeller graphics backend that don't have native support +/// for Decal. +/// The range of `coords` will be mapped from [0, 1] to [half_texel, 1 - +/// half_texel] +vec4 IPSampleLinearWithTileMode(sampler2D tex, + vec2 coords, + float y_coord_scale, + vec2 half_texel, + float tile_mode, + vec4 decal_border_color) { + return IPSampleLinearWithTileMode(tex, coords, y_coord_scale, half_texel, + tile_mode, tile_mode, decal_border_color); +} + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/tile_mode.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/tile_mode.glsl new file mode 100644 index 0000000000000000000000000000000000000000..31e2bd576538ba2e9eb91953ade5e85f862fc9a0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/tile_mode.glsl @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// These values must correspond to the order of the items in the +// 'Entity::TileMode' enum class. +const float kTileModeClamp = 0; +const float kTileModeRepeat = 1; +const float kTileModeMirror = 2; +const float kTileModeDecal = 3; diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/transform.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/transform.glsl new file mode 100644 index 0000000000000000000000000000000000000000..f84696d96ff3013ef201d29a73f107c2202d5c12 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/transform.glsl @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef TRANSFORM_GLSL_ +#define TRANSFORM_GLSL_ + +/// Returns the Cartesian coordinates of `position` in `transform` space. +vec2 IPVec2TransformPosition(mat4 matrix, vec2 point) { + vec4 transformed = matrix * vec4(point, 0, 1); + return transformed.xy / transformed.w; +} + +// Returns the transformed gl_Position for a given glyph position in a glyph +// atlas. +vec4 IPPositionForGlyphPosition(mat4 mvp, + vec2 unit_position, + vec2 destination_position, + vec2 destination_size) { + mat4 translation = mat4(1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + destination_position.xy, 0, 1); + return mvp * translation * + vec4(unit_position.x * destination_size.x, + unit_position.y * destination_size.y, 0.0, 1.0); +} + +#ifdef IMPELLER_TARGET_OPENGLES + +// Shim matrix `inverse` for versions that lack it. +// TODO: This could be gated on GLSL < 1.4. +mat3 IPMat3Inverse(mat3 m) { + float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2]; + float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2]; + float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2]; + + float b01 = a22 * a11 - a12 * a21; + float b11 = -a22 * a10 + a12 * a20; + float b21 = a21 * a10 - a11 * a20; + + float det = a00 * b01 + a01 * b11 + a02 * b21; + + return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11), b11, + (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10), b21, + (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / + det; +} + +#else // IMPELLER_TARGET_OPENGLES + +mat3 IPMat3Inverse(mat3 m) { + return inverse(m); +} + +#endif // IMPELLER_TARGET_OPENGLES + +#endif // TRANSFORM_GLSL_ diff --git a/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/types.glsl b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/types.glsl new file mode 100644 index 0000000000000000000000000000000000000000..ad1a0e86cf93fbdf7c24752208e43b5e9b459410 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/shader_lib/impeller/types.glsl @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef TYPES_GLSL_ +#define TYPES_GLSL_ + +#extension GL_AMD_gpu_shader_half_float : enable +#extension GL_AMD_gpu_shader_half_float_fetch : enable +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable + +#ifndef IMPELLER_TARGET_METAL_IOS + +precision mediump sampler2D; + +#define float16_t float +#define f16vec2 vec2 +#define f16vec3 vec3 +#define f16vec4 vec4 +#define f16mat4 mat4 +#define f16sampler2D sampler2D + +#endif // IMPELLER_TARGET_METAL + +#define BoolF float +#define BoolV2 vec2 +#define BoolV3 vec3 +#define BoolV4 vec4 + +#endif diff --git a/flutter/engine/src/flutter/impeller/compiler/source_options.cc b/flutter/engine/src/flutter/impeller/compiler/source_options.cc new file mode 100644 index 0000000000000000000000000000000000000000..ace19b5f1f825a71a9333db957d6c5daac3eb6d9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/source_options.cc @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/source_options.h" + +namespace impeller { +namespace compiler { + +SourceOptions::SourceOptions() = default; + +SourceOptions::SourceOptions(const std::string& file_name, + SourceType source_type) + : type(source_type == SourceType::kUnknown + ? SourceTypeFromFileName(file_name) + : source_type), + file_name(file_name) {} + +SourceOptions::~SourceOptions() = default; + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/source_options.h b/flutter/engine/src/flutter/impeller/compiler/source_options.h new file mode 100644 index 0000000000000000000000000000000000000000..89011f7158892dd5136493b34f4994e0295ab420 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/source_options.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SOURCE_OPTIONS_H_ +#define FLUTTER_IMPELLER_COMPILER_SOURCE_OPTIONS_H_ + +#include +#include +#include +#include + +#include "flutter/fml/unique_fd.h" +#include "impeller/compiler/include_dir.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { + +struct SourceOptions { + SourceType type = SourceType::kUnknown; + TargetPlatform target_platform = TargetPlatform::kUnknown; + SourceLanguage source_language = SourceLanguage::kUnknown; + std::shared_ptr working_directory; + std::vector include_dirs; + std::string file_name = "main.glsl"; + std::string entry_point_name = "main"; + uint32_t gles_language_version = 100; + std::vector defines; + bool json_format = false; + std::string metal_version; + + /// @brief Whether half-precision textures should be supported, requiring + /// opengl semantics. Only used on metal targets. + bool use_half_textures = false; + + /// @brief Whether the GLSL framebuffer fetch extension will be required. + /// + /// Only used on OpenGLES targets. + bool require_framebuffer_fetch = false; + + SourceOptions(); + + ~SourceOptions(); + + explicit SourceOptions(const std::string& file_name, + SourceType source_type = SourceType::kUnknown); +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SOURCE_OPTIONS_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.cc b/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e0f66f5002d1f875269c3d27f1529c441be2f60 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.cc @@ -0,0 +1,320 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/spirv_compiler.h" + +#include + +#include "impeller/compiler/logger.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { + +SPIRVCompiler::SPIRVCompiler(const SourceOptions& options, + std::shared_ptr sources) + : options_(options), sources_(std::move(sources)) {} + +SPIRVCompiler::~SPIRVCompiler() = default; + +std::shared_ptr SPIRVCompiler::CompileToSPV( + std::stringstream& stream, + const shaderc::CompileOptions& spirv_options) const { + if (!sources_ || sources_->GetMapping() == nullptr) { + COMPILER_ERROR(stream) << "Invalid sources for SPIRV Compiler."; + return nullptr; + } + + shaderc::Compiler spv_compiler; + if (!spv_compiler.IsValid()) { + COMPILER_ERROR(stream) << "Could not initialize the " + << SourceLanguageToString(options_.source_language) + << " to SPIRV compiler."; + return nullptr; + } + + const auto shader_kind = ToShaderCShaderKind(options_.type); + + if (shader_kind == shaderc_shader_kind::shaderc_glsl_infer_from_source) { + COMPILER_ERROR(stream) << "Could not figure out shader stage."; + return nullptr; + } + + auto result = std::make_shared( + spv_compiler.CompileGlslToSpv( + reinterpret_cast(sources_->GetMapping()), // source_text + sources_->GetSize(), // source_text_size + shader_kind, // shader_kind + options_.file_name.c_str(), // input_file_name + options_.entry_point_name.c_str(), // entry_point_name + spirv_options // options + )); + if (result->GetCompilationStatus() != + shaderc_compilation_status::shaderc_compilation_status_success) { + COMPILER_ERROR(stream) << SourceLanguageToString(options_.source_language) + << " to SPIRV failed; " + << ShaderCErrorToString( + result->GetCompilationStatus()) + << ". " << result->GetNumErrors() << " error(s) and " + << result->GetNumWarnings() << " warning(s)."; + // It should normally be enough to check that there are errors or warnings, + // but some cases result in no errors or warnings and still have an error + // message. If there's a message we should print it. + if (result->GetNumErrors() > 0 || result->GetNumWarnings() > 0 || + !result->GetErrorMessage().empty()) { + COMPILER_ERROR_NO_PREFIX(stream) << result->GetErrorMessage(); + } + return nullptr; + } + + if (!result) { + COMPILER_ERROR(stream) << "Could not fetch SPIRV from compile job."; + return nullptr; + } + + const auto data_length = (result->cend() - result->cbegin()) * + sizeof(decltype(result)::element_type::element_type); + + return std::make_unique( + reinterpret_cast(result->cbegin()), // + data_length, // + [result](auto, auto) {} // + ); +} + +std::string SPIRVCompiler::GetSourcePrefix() const { + std::stringstream stream; + stream << options_.file_name << ": "; + return stream.str(); +} + +static void SetDefaultLimitations(shaderc::CompileOptions& compiler_opts) { + using Limit = std::pair; + static constexpr std::array limits = { + Limit{shaderc_limit::shaderc_limit_max_lights, 8}, + Limit{shaderc_limit::shaderc_limit_max_clip_planes, 6}, + Limit{shaderc_limit::shaderc_limit_max_texture_units, 2}, + Limit{shaderc_limit::shaderc_limit_max_texture_coords, 8}, + Limit{shaderc_limit::shaderc_limit_max_vertex_attribs, 16}, + Limit{shaderc_limit::shaderc_limit_max_vertex_uniform_components, 4096}, + Limit{shaderc_limit::shaderc_limit_max_varying_floats, 60}, + Limit{shaderc_limit::shaderc_limit_max_vertex_texture_image_units, 16}, + Limit{shaderc_limit::shaderc_limit_max_combined_texture_image_units, 80}, + Limit{shaderc_limit::shaderc_limit_max_texture_image_units, 16}, + Limit{shaderc_limit::shaderc_limit_max_fragment_uniform_components, 1024}, + Limit{shaderc_limit::shaderc_limit_max_draw_buffers, 8}, + Limit{shaderc_limit::shaderc_limit_max_vertex_uniform_vectors, 256}, + Limit{shaderc_limit::shaderc_limit_max_varying_vectors, 15}, + Limit{shaderc_limit::shaderc_limit_max_fragment_uniform_vectors, 256}, + Limit{shaderc_limit::shaderc_limit_max_vertex_output_vectors, 16}, + Limit{shaderc_limit::shaderc_limit_max_fragment_input_vectors, 15}, + Limit{shaderc_limit::shaderc_limit_min_program_texel_offset, -8}, + Limit{shaderc_limit::shaderc_limit_max_program_texel_offset, 7}, + Limit{shaderc_limit::shaderc_limit_max_clip_distances, 8}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_count_x, 65535}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_count_y, 65535}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_count_z, 65535}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_size_x, 1024}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_size_y, 1024}, + Limit{shaderc_limit::shaderc_limit_max_compute_work_group_size_z, 64}, + Limit{shaderc_limit::shaderc_limit_max_compute_uniform_components, 512}, + Limit{shaderc_limit::shaderc_limit_max_compute_texture_image_units, 16}, + Limit{shaderc_limit::shaderc_limit_max_compute_image_uniforms, 8}, + Limit{shaderc_limit::shaderc_limit_max_compute_atomic_counters, 8}, + Limit{shaderc_limit::shaderc_limit_max_compute_atomic_counter_buffers, 1}, + Limit{shaderc_limit::shaderc_limit_max_varying_components, 60}, + Limit{shaderc_limit::shaderc_limit_max_vertex_output_components, 64}, + Limit{shaderc_limit::shaderc_limit_max_geometry_input_components, 64}, + Limit{shaderc_limit::shaderc_limit_max_geometry_output_components, 128}, + Limit{shaderc_limit::shaderc_limit_max_fragment_input_components, 128}, + Limit{shaderc_limit::shaderc_limit_max_image_units, 8}, + Limit{shaderc_limit:: + shaderc_limit_max_combined_image_units_and_fragment_outputs, + 8}, + Limit{shaderc_limit::shaderc_limit_max_combined_shader_output_resources, + 8}, + Limit{shaderc_limit::shaderc_limit_max_image_samples, 0}, + Limit{shaderc_limit::shaderc_limit_max_vertex_image_uniforms, 0}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_image_uniforms, 0}, + Limit{shaderc_limit::shaderc_limit_max_tess_evaluation_image_uniforms, 0}, + Limit{shaderc_limit::shaderc_limit_max_geometry_image_uniforms, 0}, + Limit{shaderc_limit::shaderc_limit_max_fragment_image_uniforms, 8}, + Limit{shaderc_limit::shaderc_limit_max_combined_image_uniforms, 8}, + Limit{shaderc_limit::shaderc_limit_max_geometry_texture_image_units, 16}, + Limit{shaderc_limit::shaderc_limit_max_geometry_output_vertices, 256}, + Limit{shaderc_limit::shaderc_limit_max_geometry_total_output_components, + 1024}, + Limit{shaderc_limit::shaderc_limit_max_geometry_uniform_components, 512}, + Limit{shaderc_limit::shaderc_limit_max_geometry_varying_components, 60}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_input_components, + 128}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_output_components, + 128}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_texture_image_units, + 16}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_uniform_components, + 1024}, + Limit{ + shaderc_limit::shaderc_limit_max_tess_control_total_output_components, + 4096}, + Limit{shaderc_limit::shaderc_limit_max_tess_evaluation_input_components, + 128}, + Limit{shaderc_limit::shaderc_limit_max_tess_evaluation_output_components, + 128}, + Limit{ + shaderc_limit::shaderc_limit_max_tess_evaluation_texture_image_units, + 16}, + Limit{shaderc_limit::shaderc_limit_max_tess_evaluation_uniform_components, + 1024}, + Limit{shaderc_limit::shaderc_limit_max_tess_patch_components, 120}, + Limit{shaderc_limit::shaderc_limit_max_patch_vertices, 32}, + Limit{shaderc_limit::shaderc_limit_max_tess_gen_level, 64}, + Limit{shaderc_limit::shaderc_limit_max_viewports, 16}, + Limit{shaderc_limit::shaderc_limit_max_vertex_atomic_counters, 0}, + Limit{shaderc_limit::shaderc_limit_max_tess_control_atomic_counters, 0}, + Limit{shaderc_limit::shaderc_limit_max_tess_evaluation_atomic_counters, + 0}, + Limit{shaderc_limit::shaderc_limit_max_geometry_atomic_counters, 0}, + Limit{shaderc_limit::shaderc_limit_max_fragment_atomic_counters, 8}, + Limit{shaderc_limit::shaderc_limit_max_combined_atomic_counters, 8}, + Limit{shaderc_limit::shaderc_limit_max_atomic_counter_bindings, 1}, + Limit{shaderc_limit::shaderc_limit_max_vertex_atomic_counter_buffers, 0}, + Limit{ + shaderc_limit::shaderc_limit_max_tess_control_atomic_counter_buffers, + 0}, + Limit{shaderc_limit:: + shaderc_limit_max_tess_evaluation_atomic_counter_buffers, + 0}, + Limit{shaderc_limit::shaderc_limit_max_geometry_atomic_counter_buffers, + 0}, + Limit{shaderc_limit::shaderc_limit_max_fragment_atomic_counter_buffers, + 0}, + Limit{shaderc_limit::shaderc_limit_max_combined_atomic_counter_buffers, + 1}, + Limit{shaderc_limit::shaderc_limit_max_atomic_counter_buffer_size, 32}, + Limit{shaderc_limit::shaderc_limit_max_transform_feedback_buffers, 4}, + Limit{shaderc_limit:: + shaderc_limit_max_transform_feedback_interleaved_components, + 64}, + Limit{shaderc_limit::shaderc_limit_max_cull_distances, 8}, + Limit{shaderc_limit::shaderc_limit_max_combined_clip_and_cull_distances, + 8}, + Limit{shaderc_limit::shaderc_limit_max_samples, 4}, + }; + for (auto& [limit, value] : limits) { + compiler_opts.SetLimit(limit, value); + } +} + +static void SetBindingBaseOffset(shaderc::CompileOptions& options) { + constexpr uint32_t kBindingBaseOffset = 64; + static const shaderc_uniform_kind kUniformKinds[] = { + shaderc_uniform_kind::shaderc_uniform_kind_sampler, + shaderc_uniform_kind::shaderc_uniform_kind_texture, + shaderc_uniform_kind::shaderc_uniform_kind_image, + shaderc_uniform_kind::shaderc_uniform_kind_buffer, // UBOs + shaderc_uniform_kind::shaderc_uniform_kind_storage_buffer, // SSBOs + }; + + for (size_t i = 0u; i < sizeof(kUniformKinds) / sizeof(shaderc_uniform_kind); + i++) { + options.SetBindingBaseForStage( + shaderc_shader_kind::shaderc_fragment_shader, // + kUniformKinds[i], // + kBindingBaseOffset // + ); + } +} + +//------------------------------------------------------------------------------ +/// @brief Wraps a shared includer so unique includers may be created to +/// satisfy the shaderc API. This is a simple proxy object and does +/// nothing. +/// +class UniqueIncluder final : public shaderc::CompileOptions::IncluderInterface { + public: + static std::unique_ptr Make( + std::shared_ptr includer) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return std::unique_ptr( + new UniqueIncluder(std::move(includer))); + } + + // |shaderc::CompileOptions::IncluderInterface| + ~UniqueIncluder() = default; + + // |shaderc::CompileOptions::IncluderInterface| + shaderc_include_result* GetInclude(const char* requested_source, + shaderc_include_type type, + const char* requesting_source, + size_t include_depth) override { + return includer_->GetInclude(requested_source, // + type, // + requesting_source, // + include_depth // + ); + } + + // |shaderc::CompileOptions::IncluderInterface| + void ReleaseInclude(shaderc_include_result* data) override { + return includer_->ReleaseInclude(data); + } + + private: + std::shared_ptr includer_; + + explicit UniqueIncluder(std::shared_ptr includer) + : includer_(std::move(includer)) { + FML_CHECK(includer_); + } + + UniqueIncluder(const UniqueIncluder&) = delete; + + UniqueIncluder& operator=(const UniqueIncluder&) = delete; +}; + +shaderc::CompileOptions SPIRVCompilerOptions::BuildShadercOptions() const { + shaderc::CompileOptions options; + + SetDefaultLimitations(options); + SetBindingBaseOffset(options); + + options.SetAutoBindUniforms(true); + options.SetAutoMapLocations(true); + + options.SetOptimizationLevel(optimization_level); + + if (generate_debug_info) { + options.SetGenerateDebugInfo(); + } + + if (source_langauge.has_value()) { + options.SetSourceLanguage(source_langauge.value()); + } + + if (source_profile.has_value()) { + options.SetForcedVersionProfile(source_profile->version, + source_profile->profile); + } + + if (target.has_value()) { + options.SetTargetEnvironment(target->env, target->version); + options.SetTargetSpirv(target->spirv_version); + } + + for (const auto& macro : macro_definitions) { + options.AddMacroDefinition(macro); + } + + if (includer) { + options.SetIncluder(UniqueIncluder::Make(includer)); + } + + options.SetVulkanRulesRelaxed(relaxed_vulkan_rules); + + return options; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.h b/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..3798b6d53601d4bf2413fa915894a4c602c5c5f7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/spirv_compiler.h @@ -0,0 +1,82 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SPIRV_COMPILER_H_ +#define FLUTTER_IMPELLER_COMPILER_SPIRV_COMPILER_H_ + +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/compiler/includer.h" +#include "impeller/compiler/source_options.h" +#include "shaderc/shaderc.hpp" + +namespace impeller { +namespace compiler { + +struct SPIRVCompilerSourceProfile { + shaderc_profile profile = shaderc_profile_core; + uint32_t version = 460; +}; + +struct SPIRVCompilerTargetEnv { + shaderc_target_env env = shaderc_target_env::shaderc_target_env_vulkan; + shaderc_env_version version = + shaderc_env_version::shaderc_env_version_vulkan_1_1; + shaderc_spirv_version spirv_version = + shaderc_spirv_version::shaderc_spirv_version_1_3; +}; + +struct SPIRVCompilerOptions { + bool generate_debug_info = true; + //---------------------------------------------------------------------------- + // Source Options. + //---------------------------------------------------------------------------- + std::optional source_langauge; + std::optional source_profile; + + shaderc_optimization_level optimization_level = + shaderc_optimization_level::shaderc_optimization_level_performance; + + //---------------------------------------------------------------------------- + // Target Options. + //---------------------------------------------------------------------------- + std::optional target; + + std::vector macro_definitions; + + std::shared_ptr includer; + + bool relaxed_vulkan_rules = false; + + shaderc::CompileOptions BuildShadercOptions() const; +}; + +class SPIRVCompiler { + public: + SPIRVCompiler(const SourceOptions& options, + std::shared_ptr sources); + + ~SPIRVCompiler(); + + std::shared_ptr CompileToSPV( + std::stringstream& error_stream, + const shaderc::CompileOptions& spirv_options) const; + + private: + SourceOptions options_; + const std::shared_ptr sources_; + + std::string GetSourcePrefix() const; + + SPIRVCompiler(const SPIRVCompiler&) = delete; + + SPIRVCompiler& operator=(const SPIRVCompiler&) = delete; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SPIRV_COMPILER_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.cc b/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.cc new file mode 100644 index 0000000000000000000000000000000000000000..b91df96e0e4868219b90767c5c1594453f177441 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.cc @@ -0,0 +1,475 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/spirv_sksl.h" +#include "impeller/compiler/uniform_sorter.h" + +using namespace spv; +using namespace SPIRV_CROSS_NAMESPACE; + +namespace impeller { +namespace compiler { + +// This replaces the SPIRV_CROSS_THROW which aborts and drops the +// error message in non-debug modes. +void report_and_exit(const std::string& msg) { + fprintf(stderr, "There was a compiler error: %s\n", msg.c_str()); + fflush(stderr); + exit(1); +} + +#define FLUTTER_CROSS_THROW(x) report_and_exit(x) + +std::string CompilerSkSL::compile() { + ir.fixup_reserved_names(); + + if (get_execution_model() != ExecutionModelFragment) { + FLUTTER_CROSS_THROW("Only fragment shaders are supported.'"); + return ""; + } + + options.es = false; + options.version = 100; + options.vulkan_semantics = false; + options.enable_420pack_extension = false; + options.flatten_multidimensional_arrays = true; + + backend.allow_precision_qualifiers = false; + backend.basic_int16_type = "short"; + backend.basic_int_type = "int"; + backend.basic_uint16_type = "ushort"; + backend.basic_uint_type = "uint"; + backend.double_literal_suffix = false; + backend.float_literal_suffix = false; + backend.long_long_literal_suffix = false; + backend.needs_row_major_load_workaround = true; + backend.nonuniform_qualifier = ""; + backend.support_precise_qualifier = false; + backend.uint32_t_literal_suffix = false; + backend.use_array_constructor = true; + backend.workgroup_size_is_hidden = true; + + fixup_user_functions(); + + fixup_anonymous_struct_names(); + fixup_type_alias(); + reorder_type_alias(); + build_function_control_flow_graphs_and_analyze(); + fixup_image_load_store_access(); + update_active_builtins(); + analyze_image_and_sampler_usage(); + analyze_interlocked_resource_usage(); + + uint32_t pass_count = 0; + do { + reset(pass_count); + + // Move constructor for this type is broken on GCC 4.9 ... + buffer.reset(); + + emit_header(); + emit_resources(); + + emit_function(get(ir.default_entry_point), Bitset()); + + pass_count++; + } while (is_forcing_recompilation()); + + statement("half4 main(float2 iFragCoord)"); + begin_scope(); + statement(" flutter_FragCoord = float4(iFragCoord, 0, 0);"); + statement(" FLT_main();"); + statement(" return " + output_name_ + ";"); + end_scope(); + + return buffer.str(); +} + +void CompilerSkSL::fixup_user_functions() { + const std::string prefix = "FLT_flutter_local_"; + ir.for_each_typed_id([&](uint32_t, const SPIRFunction& func) { + const auto& original_name = get_name(func.self); + // Just in case. Don't add the prefix a second time. + if (original_name.rfind(prefix, 0) == 0) { + return; + } + std::string new_name = prefix + original_name; + set_name(func.self, new_name); + }); + + ir.for_each_typed_id( + [&](uint32_t, const SPIRFunctionPrototype& func) { + const auto& original_name = get_name(func.self); + // Just in case. Don't add the prefix a second time. + if (original_name.rfind(prefix, 0) == 0) { + return; + } + std::string new_name = prefix + original_name; + set_name(func.self, new_name); + }); +} + +void CompilerSkSL::emit_header() { + statement("// This SkSL shader is autogenerated by spirv-cross."); + statement(""); + statement("float4 flutter_FragCoord;"); + statement(""); +} + +void CompilerSkSL::emit_uniform(const SPIRVariable& var) { + auto& type = get(var.basetype); + if (type.basetype == SPIRType::UInt && is_legacy()) { + FLUTTER_CROSS_THROW("SkSL does not support unsigned integers: '" + + get_name(var.self) + "'"); + } + + add_resource_name(var.self); + statement(variable_decl(var), ";"); + + // The Flutter FragmentProgram implementation passes additional uniforms along + // with shader uniforms that encode the shader width and height. + if (type.basetype == SPIRType::SampledImage) { + std::string name = to_name(var.self); + statement("uniform half2 " + name + "_size;"); + } +} + +bool CompilerSkSL::emit_constant_resources() { + bool emitted = false; + + for (auto& id : ir.ids) { + if (id.get_type() == TypeConstant) { + auto& c = id.get(); + bool needs_declaration = c.specialization || c.is_used_as_lut; + if (needs_declaration) { + if (!options.vulkan_semantics && c.specialization) { + c.specialization_constant_macro_name = constant_value_macro_name( + get_decoration(c.self, DecorationSpecId)); + } + emit_constant(c); + emitted = true; + } + } else if (id.get_type() == TypeConstantOp) { + emit_specialization_constant_op(id.get()); + emitted = true; + } + } + + return emitted; +} + +bool CompilerSkSL::emit_struct_resources() { + bool emitted = false; + + // Output all basic struct types which are not Block or BufferBlock as these + // are declared inplace when such variables are instantiated. + for (auto& id : ir.ids) { + if (id.get_type() == TypeType) { + auto& type = id.get(); + if (type.basetype == SPIRType::Struct && type.array.empty() && + !type.pointer && + (!ir.meta[type.self].decoration.decoration_flags.get( + DecorationBlock) && + !ir.meta[type.self].decoration.decoration_flags.get( + DecorationBufferBlock))) { + emit_struct(type); + emitted = true; + } + } + } + + return emitted; +} + +void CompilerSkSL::detect_unsupported_resources() { + for (auto& id : ir.ids) { + if (id.get_type() == TypeVariable) { + auto& var = id.get(); + auto& type = get(var.basetype); + + // UBOs and SSBOs are not supported. + if (var.storage != StorageClassFunction && type.pointer && + type.storage == StorageClassUniform && !is_hidden_variable(var) && + (ir.meta[type.self].decoration.decoration_flags.get( + DecorationBlock) || + ir.meta[type.self].decoration.decoration_flags.get( + DecorationBufferBlock))) { + FLUTTER_CROSS_THROW("SkSL does not support UBOs or SSBOs: '" + + get_name(var.self) + "'"); + } + + // Push constant blocks are not supported. + if (!is_hidden_variable(var) && var.storage != StorageClassFunction && + type.pointer && type.storage == StorageClassPushConstant) { + FLUTTER_CROSS_THROW("SkSL does not support push constant blocks: '" + + get_name(var.self) + "'"); + } + + // User specified inputs are not supported. + if (!is_hidden_variable(var) && var.storage != StorageClassFunction && + type.pointer && type.storage == StorageClassInput) { + FLUTTER_CROSS_THROW("SkSL does not support inputs: '" + + get_name(var.self) + "'"); + } + } + } +} + +bool CompilerSkSL::emit_uniform_resources() { + bool emitted = false; + + // Output Uniform Constants (values, samplers, images, etc). + std::vector regular_uniforms = + SortUniforms(&ir, this, SPIRType::SampledImage, /*include=*/false); + std::vector shader_uniforms = + SortUniforms(&ir, this, SPIRType::SampledImage); + if (regular_uniforms.size() > 0 || shader_uniforms.size() > 0) { + emitted = true; + } + + for (const auto& id : regular_uniforms) { + auto& var = get(id); + emit_uniform(var); + } + + for (const auto& id : shader_uniforms) { + auto& var = get(id); + emit_uniform(var); + } + + return emitted; +} + +bool CompilerSkSL::emit_output_resources() { + bool emitted = false; + + // Output 'out' variables. These are restricted to the cases handled by + // SkSL in 'emit_interface_block'. + for (auto& id : ir.ids) { + if (id.get_type() == TypeVariable) { + auto& var = id.get(); + auto& type = get(var.basetype); + if (var.storage != StorageClassFunction && !is_hidden_variable(var) && + type.pointer && + (var.storage == StorageClassInput || + var.storage == StorageClassOutput) && + interface_variable_exists_in_entry_point(var.self)) { + emit_interface_block(var); + emitted = true; + } + } + } + + return emitted; +} + +bool CompilerSkSL::emit_global_variable_resources() { + bool emitted = false; + + for (auto global : global_variables) { + auto& var = get(global); + if (is_hidden_variable(var, true)) { + continue; + } + if (var.storage != StorageClassOutput) { + if (!variable_is_lut(var)) { + add_resource_name(var.self); + std::string initializer; + if (options.force_zero_initialized_variables && + var.storage == StorageClassPrivate && !var.initializer && + !var.static_expression && + type_can_zero_initialize(get_variable_data_type(var))) { + initializer = join(" = ", to_zero_initialized_expression( + get_variable_data_type_id(var))); + } + statement(variable_decl(var), initializer, ";"); + emitted = true; + } + } else if (var.initializer && + maybe_get(var.initializer) != nullptr) { + emit_output_variable_initializer(var); + } + } + + return emitted; +} + +bool CompilerSkSL::emit_undefined_values() { + bool emitted = false; + + ir.for_each_typed_id([&](uint32_t, const SPIRUndef& undef) { + auto& type = this->get(undef.basetype); + // OpUndef can be void for some reason ... + if (type.basetype == SPIRType::Void) { + return; + } + + std::string initializer; + if (options.force_zero_initialized_variables && + type_can_zero_initialize(type)) { + initializer = join(" = ", to_zero_initialized_expression(undef.basetype)); + } + + statement(variable_decl(type, to_name(undef.self), undef.self), initializer, + ";"); + emitted = true; + }); + + return emitted; +} + +void CompilerSkSL::emit_resources() { + detect_unsupported_resources(); + + if (emit_constant_resources()) { + statement(""); + } + + if (emit_struct_resources()) { + statement(""); + } + + if (emit_uniform_resources()) { + statement(""); + } + + if (emit_output_resources()) { + statement(""); + } + + if (emit_global_variable_resources()) { + statement(""); + } + + if (emit_undefined_values()) { + statement(""); + } +} + +void CompilerSkSL::emit_interface_block(const SPIRVariable& var) { + auto& type = get(var.basetype); + bool block = + ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock); + if (block) { + FLUTTER_CROSS_THROW("Interface blocks are not supported: '" + + to_name(var.self) + "'"); + } + + // The output is emitted as a global variable, which is returned from the + // wrapper around the 'main' function. Only one output variable is allowed. + add_resource_name(var.self); + statement(variable_decl(type, to_name(var.self), var.self), ";"); + if (output_name_.empty()) { + output_name_ = to_name(var.self); + } else if (to_name(var.self) != output_name_) { + FLUTTER_CROSS_THROW("Only one output variable is supported: '" + + to_name(var.self) + "'"); + } +} + +void CompilerSkSL::emit_function_prototype(SPIRFunction& func, + const Bitset& return_flags) { + // If this is not the entrypoint, then no special processsing for SkSL is + // required. + if (func.self != ir.default_entry_point) { + CompilerGLSL::emit_function_prototype(func, return_flags); + return; + } + + auto& type = get(func.return_type); + if (type.basetype != SPIRType::Void) { + FLUTTER_CROSS_THROW( + "Return type of the entrypoint function must be 'void'"); + } + + if (func.arguments.size() != 0) { + FLUTTER_CROSS_THROW( + "The entry point function should not acept any parameters."); + } + + processing_entry_point = true; + + // If this is the entrypoint of a fragment shader, then GLSL requires the + // prototype to be "void main()", and so it is safe to rewrite as + // "void FLT_main()". + statement("void FLT_main()"); +} + +std::string CompilerSkSL::image_type_glsl(const SPIRType& type, + uint32_t id, + bool member) { + if (type.basetype != SPIRType::SampledImage || type.image.dim != Dim2D) { + FLUTTER_CROSS_THROW("Only sampler2D uniform image types are supported."); + return "???"; + } + return "shader"; +} + +std::string CompilerSkSL::builtin_to_glsl(BuiltIn builtin, + StorageClass storage) { + std::string gl_builtin = CompilerGLSL::builtin_to_glsl(builtin, storage); + switch (builtin) { + case BuiltInFragCoord: + return "flutter_FragCoord"; + default: + FLUTTER_CROSS_THROW("Builtin '" + gl_builtin + "' is not supported."); + break; + } + + return "???"; +} + +std::string CompilerSkSL::to_texture_op( + const Instruction& i, + bool sparse, + bool* forward, + SmallVector& inherited_expressions) { + auto op = static_cast(i.op); + if (op != OpImageSampleImplicitLod) { + FLUTTER_CROSS_THROW("Only simple shader sampling is supported."); + return "???"; + } + return CompilerGLSL::to_texture_op(i, sparse, forward, inherited_expressions); +} + +std::string CompilerSkSL::to_function_name( + const CompilerGLSL::TextureFunctionNameArguments& args) { + std::string name = to_expression(args.base.img); + return name + ".eval"; +} + +std::string CompilerSkSL::to_function_args(const TextureFunctionArguments& args, + bool* p_forward) { + std::string name = to_expression(args.base.img); + + std::string glsl_args = CompilerGLSL::to_function_args(args, p_forward); + // SkSL only supports coordinates. All other arguments to texture are + // unsupported and will generate invalid SkSL. + if (args.grad_x || args.grad_y || args.lod || args.offset || args.sample || + args.min_lod || args.sparse_texel || args.bias || args.component) { + FLUTTER_CROSS_THROW( + "Only sampler and position arguments are supported in texture() " + "calls."); + } + + // GLSL puts the shader as the first argument, but in SkSL the shader is + // implicitly passed as the reciever of the 'eval' method. Therefore, the + // shader is removed from the GLSL argument list. + std::string no_shader; + auto npos = glsl_args.find(", "); // The first ','. + if (npos != std::string::npos) { + no_shader = glsl_args.substr(npos + 1); // The string after the first ','. + } + + if (no_shader.empty()) { + FLUTTER_CROSS_THROW("Unexpected shader sampling arguments: '(" + glsl_args + + ")'"); + return "()"; + } + + return name + "_size * (" + no_shader + ")"; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.h b/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.h new file mode 100644 index 0000000000000000000000000000000000000000..0c21c4ee5ea271968268a35f7725b6ddf8587877 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/spirv_sksl.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_ +#define FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_ + +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "spirv_glsl.hpp" + +namespace impeller { +namespace compiler { + +class CompilerSkSL : public spirv_cross::CompilerGLSL { + public: + explicit CompilerSkSL(std::vector spirv_) + : CompilerGLSL(std::move(spirv_)) {} + + CompilerSkSL(const uint32_t* ir_, size_t word_count) + : CompilerGLSL(ir_, word_count) {} + + explicit CompilerSkSL(const spirv_cross::ParsedIR& ir_) + : spirv_cross::CompilerGLSL(ir_) {} + + explicit CompilerSkSL(spirv_cross::ParsedIR&& ir_) + : spirv_cross::CompilerGLSL(std::move(ir_)) {} + + std::string compile() override; + + private: + std::string output_name_; + + void emit_header() override; + + void emit_uniform(const spirv_cross::SPIRVariable& var) override; + + void fixup_user_functions(); + + void detect_unsupported_resources(); + bool emit_constant_resources(); + bool emit_struct_resources(); + bool emit_uniform_resources(); + bool emit_output_resources(); + bool emit_global_variable_resources(); + bool emit_undefined_values(); + void emit_resources(); + + void emit_interface_block(const spirv_cross::SPIRVariable& var); + + void emit_function_prototype( + spirv_cross::SPIRFunction& func, + const spirv_cross::Bitset& return_flags) override; + + std::string image_type_glsl(const spirv_cross::SPIRType& type, + uint32_t id = 0, + bool member = false) override; + + std::string builtin_to_glsl(spv::BuiltIn builtin, + spv::StorageClass storage) override; + + std::string to_texture_op( + const spirv_cross::Instruction& i, + bool sparse, + bool* forward, + spirv_cross::SmallVector& inherited_expressions) override; + + std::string to_function_name( + const spirv_cross::CompilerGLSL::TextureFunctionNameArguments& args) + override; + + std::string to_function_args( + const spirv_cross::CompilerGLSL::TextureFunctionArguments& args, + bool* p_forward) override; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SPIRV_SKSL_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/switches.cc b/flutter/engine/src/flutter/impeller/compiler/switches.cc new file mode 100644 index 0000000000000000000000000000000000000000..1dba36b211804d0083e83e1c8a1ec889c32d5af4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/switches.cc @@ -0,0 +1,334 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/switches.h" + +#include +#include +#include +#include + +#include "flutter/fml/file.h" +#include "fml/command_line.h" +#include "impeller/compiler/types.h" +#include "impeller/compiler/utilities.h" + +namespace impeller { +namespace compiler { + +static const std::map kKnownPlatforms = { + {"metal-desktop", TargetPlatform::kMetalDesktop}, + {"metal-ios", TargetPlatform::kMetalIOS}, + {"vulkan", TargetPlatform::kVulkan}, + {"opengl-es", TargetPlatform::kOpenGLES}, + {"opengl-desktop", TargetPlatform::kOpenGLDesktop}, +}; + +static const std::map kKnownRuntimeStages = { + {"sksl", TargetPlatform::kSkSL}, + {"runtime-stage-metal", TargetPlatform::kRuntimeStageMetal}, + {"runtime-stage-gles", TargetPlatform::kRuntimeStageGLES}, + {"runtime-stage-gles3", TargetPlatform::kRuntimeStageGLES3}, + {"runtime-stage-vulkan", TargetPlatform::kRuntimeStageVulkan}, +}; + +static const std::map kKnownSourceTypes = { + {"vert", SourceType::kVertexShader}, + {"frag", SourceType::kFragmentShader}, + {"comp", SourceType::kComputeShader}, +}; + +void Switches::PrintHelp(std::ostream& stream) { + // clang-format off + const std::string optional_prefix = "[optional] "; + const std::string optional_multiple_prefix = "[optional,multiple] "; + // clang-format on + + stream << std::endl; + stream << "ImpellerC is an offline shader processor and reflection engine." + << std::endl; + stream << "---------------------------------------------------------------" + << std::endl; + stream << "Expected invocation is:" << std::endl << std::endl; + stream << "./impellerc " + "--input= --sl= " + << std::endl + << std::endl; + + stream << "Valid platforms are:" << std::endl << std::endl; + stream << "One of ["; + for (const auto& platform : kKnownPlatforms) { + stream << " --" << platform.first; + } + stream << " ]" << std::endl << std::endl; + + stream << "Valid runtime stages are:" << std::endl << std::endl; + stream << "At least one of ["; + for (const auto& platform : kKnownRuntimeStages) { + stream << " --" << platform.first; + } + stream << " ]" << std::endl << std::endl; + + stream << "Optional arguments:" << std::endl << std::endl; + stream << optional_prefix + << "--spirv= (ignored for --shader-bundle)" + << std::endl; + stream << optional_prefix << "--input-type={"; + for (const auto& source_type : kKnownSourceTypes) { + stream << source_type.first << ", "; + } + stream << "}" << std::endl; + stream << optional_prefix << "--source-language=glsl|hlsl (default: glsl)" + << std::endl; + stream << optional_prefix + << "--entry-point= (default: main; " + "ignored for glsl)" + << std::endl; + stream << optional_prefix + << "--iplr (causes --sl file to be emitted in " + "iplr format)" + << std::endl; + stream << optional_prefix + << "--shader-bundle= (causes --sl " + "file to be " + "emitted in Flutter GPU's shader bundle format)" + << std::endl; + stream << optional_prefix << "--reflection-json=" + << std::endl; + stream << optional_prefix << "--reflection-header=" + << std::endl; + stream << optional_prefix << "--reflection-cc=" + << std::endl; + stream << optional_multiple_prefix << "--include=" + << std::endl; + stream << optional_multiple_prefix << "--define=" << std::endl; + stream << optional_prefix << "--depfile=" << std::endl; + stream << optional_prefix << "--gles-language-version=" << std::endl; + stream << optional_prefix << "--json" << std::endl; + stream << optional_prefix + << "--use-half-textures (force openGL semantics when " + "targeting metal)" + << std::endl; + stream << optional_prefix << "--require-framebuffer-fetch" << std::endl; +} + +Switches::Switches() = default; + +Switches::~Switches() = default; + +static TargetPlatform TargetPlatformFromCommandLine( + const fml::CommandLine& command_line) { + auto target = TargetPlatform::kUnknown; + for (const auto& platform : kKnownPlatforms) { + if (command_line.HasOption(platform.first)) { + // If the platform has already been determined, the caller may have + // specified multiple platforms. This is an error and only one must be + // selected. + if (target != TargetPlatform::kUnknown) { + return TargetPlatform::kUnknown; + } + target = platform.second; + // Keep going to detect duplicates. + } + } + return target; +} + +static std::vector RuntimeStagesFromCommandLine( + const fml::CommandLine& command_line) { + std::vector stages; + for (const auto& platform : kKnownRuntimeStages) { + if (command_line.HasOption(platform.first)) { + stages.push_back(platform.second); + } + } + return stages; +} + +static SourceType SourceTypeFromCommandLine( + const fml::CommandLine& command_line) { + auto source_type_option = + command_line.GetOptionValueWithDefault("input-type", ""); + auto source_type_search = kKnownSourceTypes.find(source_type_option); + if (source_type_search == kKnownSourceTypes.end()) { + return SourceType::kUnknown; + } + return source_type_search->second; +} + +Switches::Switches(const fml::CommandLine& command_line) + : working_directory(std::make_shared(fml::OpenDirectory( + Utf8FromPath(std::filesystem::current_path()).c_str(), + false, // create if necessary, + fml::FilePermission::kRead))), + source_file_name(command_line.GetOptionValueWithDefault("input", "")), + input_type(SourceTypeFromCommandLine(command_line)), + sl_file_name(command_line.GetOptionValueWithDefault("sl", "")), + iplr(command_line.HasOption("iplr")), + shader_bundle( + command_line.GetOptionValueWithDefault("shader-bundle", "")), + spirv_file_name(command_line.GetOptionValueWithDefault("spirv", "")), + reflection_json_name( + command_line.GetOptionValueWithDefault("reflection-json", "")), + reflection_header_name( + command_line.GetOptionValueWithDefault("reflection-header", "")), + reflection_cc_name( + command_line.GetOptionValueWithDefault("reflection-cc", "")), + depfile_path(command_line.GetOptionValueWithDefault("depfile", "")), + json_format(command_line.HasOption("json")), + gles_language_version( + stoi(command_line.GetOptionValueWithDefault("gles-language-version", + "0"))), + metal_version( + command_line.GetOptionValueWithDefault("metal-version", "1.2")), + entry_point( + command_line.GetOptionValueWithDefault("entry-point", "main")), + use_half_textures(command_line.HasOption("use-half-textures")), + require_framebuffer_fetch( + command_line.HasOption("require-framebuffer-fetch")), + target_platform_(TargetPlatformFromCommandLine(command_line)), + runtime_stages_(RuntimeStagesFromCommandLine(command_line)) { + auto language = ToLowerCase( + command_line.GetOptionValueWithDefault("source-language", "glsl")); + + source_language = ToSourceLanguage(language); + + if (!working_directory || !working_directory->is_valid()) { + return; + } + + for (const auto& include_dir_path : command_line.GetOptionValues("include")) { + if (!include_dir_path.data()) { + continue; + } + + // fml::OpenDirectoryReadOnly for Windows doesn't handle relative paths + // beginning with `../` well, so we build an absolute path. + + // Get the current working directory as a utf8 encoded string. + // Note that the `include_dir_path` is already utf8 encoded, and so we + // mustn't attempt to double-convert it to utf8 lest multi-byte characters + // will become mangled. + std::filesystem::path include_dir_absolute; + if (std::filesystem::path(include_dir_path).is_absolute()) { + include_dir_absolute = std::filesystem::path(include_dir_path); + } else { + auto cwd = Utf8FromPath(std::filesystem::current_path()); + include_dir_absolute = std::filesystem::absolute( + std::filesystem::path(cwd) / include_dir_path); + } + + auto dir = std::make_shared(fml::OpenDirectoryReadOnly( + *working_directory, include_dir_absolute.string().c_str())); + if (!dir || !dir->is_valid()) { + continue; + } + + IncludeDir dir_entry; + dir_entry.name = include_dir_path; + dir_entry.dir = std::move(dir); + + include_directories.emplace_back(std::move(dir_entry)); + } + + for (const auto& define : command_line.GetOptionValues("define")) { + defines.emplace_back(define); + } +} + +bool Switches::AreValid(std::ostream& explain) const { + // When producing a shader bundle, all flags related to single shader inputs + // and outputs such as `--input` and `--spirv-file-name` are ignored. Instead, + // input files are read from the shader bundle spec and a single flatbuffer + // containing all compiled shaders and reflection state is output to `--sl`. + const bool shader_bundle_mode = !shader_bundle.empty(); + + bool valid = true; + if (target_platform_ == TargetPlatform::kUnknown && runtime_stages_.empty() && + !shader_bundle_mode) { + explain << "Either a target platform was not specified, or no runtime " + "stages were specified." + << std::endl; + valid = false; + } + + if (source_language == SourceLanguage::kUnknown && !shader_bundle_mode) { + explain << "Invalid source language type." << std::endl; + valid = false; + } + + if (!working_directory || !working_directory->is_valid()) { + explain << "Could not open the working directory: \"" + << Utf8FromPath(std::filesystem::current_path()).c_str() << "\"" + << std::endl; + valid = false; + } + + if (source_file_name.empty() && !shader_bundle_mode) { + explain << "Input file name was empty." << std::endl; + valid = false; + } + + if (sl_file_name.empty()) { + explain << "Target shading language file name was empty." << std::endl; + valid = false; + } + + if (spirv_file_name.empty() && !shader_bundle_mode) { + explain << "Spirv file name was empty." << std::endl; + valid = false; + } + + if (iplr && shader_bundle_mode) { + explain << "--iplr and --shader-bundle flag cannot be specified at the " + "same time" + << std::endl; + valid = false; + } + + return valid; +} + +std::vector Switches::PlatformsToCompile() const { + if (target_platform_ == TargetPlatform::kUnknown) { + return runtime_stages_; + } + return {target_platform_}; +} + +TargetPlatform Switches::SelectDefaultTargetPlatform() const { + if (target_platform_ == TargetPlatform::kUnknown && + !runtime_stages_.empty()) { + return runtime_stages_.front(); + } + return target_platform_; +} + +SourceOptions Switches::CreateSourceOptions( + std::optional target_platform) const { + SourceOptions options; + options.target_platform = + target_platform.value_or(SelectDefaultTargetPlatform()); + options.source_language = source_language; + if (input_type == SourceType::kUnknown) { + options.type = SourceTypeFromFileName(source_file_name); + } else { + options.type = input_type; + } + options.working_directory = working_directory; + options.file_name = source_file_name; + options.include_dirs = include_directories; + options.defines = defines; + options.entry_point_name = EntryPointFunctionNameFromSourceName( + source_file_name, options.type, options.source_language, entry_point); + options.json_format = json_format; + options.gles_language_version = gles_language_version; + options.metal_version = metal_version; + options.use_half_textures = use_half_textures; + options.require_framebuffer_fetch = require_framebuffer_fetch; + return options; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/switches.h b/flutter/engine/src/flutter/impeller/compiler/switches.h new file mode 100644 index 0000000000000000000000000000000000000000..dd78bcddd7c88d13d28654b9eb0908f1a6a0194a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/switches.h @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_SWITCHES_H_ +#define FLUTTER_IMPELLER_COMPILER_SWITCHES_H_ + +#include +#include +#include + +#include "flutter/fml/command_line.h" +#include "flutter/fml/unique_fd.h" +#include "impeller/compiler/include_dir.h" +#include "impeller/compiler/source_options.h" +#include "impeller/compiler/types.h" + +namespace impeller { +namespace compiler { + +class Switches { + public: + std::shared_ptr working_directory = nullptr; + std::vector include_directories = {}; + std::string source_file_name = ""; + SourceType input_type = SourceType::kUnknown; + /// The raw shader file output by the compiler. For --iplr and + /// --shader-bundle modes, this is used as the filename for the output + /// flatbuffer output. + std::string sl_file_name = ""; + bool iplr = false; + std::string shader_bundle = ""; + std::string spirv_file_name = ""; + std::string reflection_json_name = ""; + std::string reflection_header_name = ""; + std::string reflection_cc_name = ""; + std::string depfile_path = ""; + std::vector defines = {}; + bool json_format = false; + SourceLanguage source_language = SourceLanguage::kUnknown; + uint32_t gles_language_version = 0; + std::string metal_version = ""; + std::string entry_point = ""; + bool use_half_textures = false; + bool require_framebuffer_fetch = false; + + Switches(); + + ~Switches(); + + explicit Switches(const fml::CommandLine& command_line); + + bool AreValid(std::ostream& explain) const; + + /// A vector containing at least one valid platform. + std::vector PlatformsToCompile() const; + TargetPlatform SelectDefaultTargetPlatform() const; + + // Creates source options from these switches for the specified + // TargetPlatform. Uses SelectDefaultTargetPlatform if not specified. + SourceOptions CreateSourceOptions( + std::optional target_platform = std::nullopt) const; + + static void PrintHelp(std::ostream& stream); + + private: + // Use |SelectDefaultTargetPlatform|. + TargetPlatform target_platform_ = TargetPlatform::kUnknown; + // Use |PlatformsToCompile|. + std::vector runtime_stages_; +}; + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_SWITCHES_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/switches_unittests.cc b/flutter/engine/src/flutter/impeller/compiler/switches_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..fd1591e193f0d117e556bbbae74be608e9f3196d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/switches_unittests.cc @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/fml/command_line.h" +#include "flutter/fml/file.h" +#include "flutter/testing/testing.h" +#include "impeller/compiler/switches.h" +#include "impeller/compiler/utilities.h" + +namespace impeller { +namespace compiler { +namespace testing { + +Switches MakeSwitchesDesktopGL( + std::initializer_list additional_options = {}) { + std::vector options = {"--opengl-desktop", "--input=input.vert", + "--sl=output.vert", + "--spirv=output.spirv"}; + options.insert(options.end(), additional_options.begin(), + additional_options.end()); + + auto cl = fml::CommandLineFromIteratorsWithArgv0("impellerc", options.begin(), + options.end()); + return Switches(cl); +} + +TEST(SwitchesTest, DoesntMangleUnicodeIncludes) { + const char* directory_name = "test_shader_include_Ã�"; + fml::CreateDirectory(flutter::testing::OpenFixturesDirectory(), + {directory_name}, fml::FilePermission::kRead); + + auto include_path = + std::string(flutter::testing::GetFixturesPath()) + "/" + directory_name; + auto include_option = "--include=" + include_path; + + Switches switches = MakeSwitchesDesktopGL({include_option.c_str()}); + + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.include_directories.size(), 1u); + ASSERT_NE(switches.include_directories[0].dir, nullptr); + ASSERT_EQ(switches.include_directories[0].name, include_path); +} + +TEST(SwitchesTest, SourceLanguageDefaultsToGLSL) { + Switches switches = MakeSwitchesDesktopGL(); + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.source_language, SourceLanguage::kGLSL); +} + +TEST(SwitchesTest, SourceLanguageCanBeSetToHLSL) { + Switches switches = MakeSwitchesDesktopGL({"--source-language=hLsL"}); + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.source_language, SourceLanguage::kHLSL); +} + +TEST(SwitchesTest, DefaultEntryPointIsMain) { + Switches switches = MakeSwitchesDesktopGL({}); + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.entry_point, "main"); +} + +TEST(SwitchesTest, EntryPointCanBeSetForHLSL) { + Switches switches = MakeSwitchesDesktopGL({"--entry-point=CustomEntryPoint"}); + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.entry_point, "CustomEntryPoint"); +} + +TEST(SwitchesTEst, ConvertToEntrypointName) { + ASSERT_EQ(ConvertToEntrypointName("mandelbrot_unrolled"), + "mandelbrot_unrolled"); + ASSERT_EQ(ConvertToEntrypointName("mandelbrot-unrolled"), + "mandelbrotunrolled"); + ASSERT_EQ(ConvertToEntrypointName("7_"), "i_7_"); + ASSERT_EQ(ConvertToEntrypointName("415"), "i_415"); + ASSERT_EQ(ConvertToEntrypointName("#$%"), "i_"); + ASSERT_EQ(ConvertToEntrypointName(""), ""); +} + +TEST(SwitchesTest, ShaderBundleModeValid) { + // Shader bundles process multiple shaders, and so the single-file input/spirv + // flags are not required. + std::vector options = { + "--shader-bundle={}", "--sl=test.shaderbundle", "--runtime-stage-metal"}; + + auto cl = fml::CommandLineFromIteratorsWithArgv0("impellerc", options.begin(), + options.end()); + Switches switches(cl); + ASSERT_TRUE(switches.AreValid(std::cout)); + ASSERT_EQ(switches.shader_bundle, "{}"); +} + +} // namespace testing +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/types.cc b/flutter/engine/src/flutter/impeller/compiler/types.cc new file mode 100644 index 0000000000000000000000000000000000000000..85e197b99dbe3d3be03c26a07a22f476dbd89201 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/types.cc @@ -0,0 +1,348 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/types.h" + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/compiler/utilities.h" + +namespace impeller { +namespace compiler { + +static bool StringEndWith(const std::string& string, + const std::string& suffix) { + if (suffix.size() > string.size()) { + return false; + } + + if (suffix.empty() || suffix.empty()) { + return false; + } + + return string.rfind(suffix) == (string.size() - suffix.size()); +} + +SourceType SourceTypeFromFileName(const std::string& file_name) { + if (StringEndWith(file_name, ".vert")) { + return SourceType::kVertexShader; + } + + if (StringEndWith(file_name, ".frag")) { + return SourceType::kFragmentShader; + } + + if (StringEndWith(file_name, ".comp")) { + return SourceType::kComputeShader; + } + + return SourceType::kUnknown; +} + +SourceType SourceTypeFromString(std::string name) { + name = ToLowerCase(name); + + if (name == "vertex") { + return SourceType::kVertexShader; + } + + if (name == "fragment") { + return SourceType::kFragmentShader; + } + + if (name == "compute") { + return SourceType::kComputeShader; + } + + return SourceType::kUnknown; +} + +SourceLanguage ToSourceLanguage(const std::string& source_language) { + if (source_language == "glsl") { + return SourceLanguage::kGLSL; + } + if (source_language == "hlsl") { + return SourceLanguage::kHLSL; + } + return SourceLanguage::kUnknown; +} + +std::string TargetPlatformToString(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kUnknown: + return "Unknown"; + case TargetPlatform::kMetalDesktop: + return "MetalDesktop"; + case TargetPlatform::kMetalIOS: + return "MetaliOS"; + case TargetPlatform::kOpenGLES: + return "OpenGLES"; + case TargetPlatform::kOpenGLDesktop: + return "OpenGLDesktop"; + case TargetPlatform::kVulkan: + return "Vulkan"; + case TargetPlatform::kRuntimeStageMetal: + return "RuntimeStageMetal"; + case TargetPlatform::kRuntimeStageGLES: + return "RuntimeStageGLES"; + case TargetPlatform::kRuntimeStageGLES3: + return "RuntimeStageGLES3"; + case TargetPlatform::kRuntimeStageVulkan: + return "RuntimeStageVulkan"; + case TargetPlatform::kSkSL: + return "SkSL"; + } + FML_UNREACHABLE(); +} + +std::string SourceLanguageToString(SourceLanguage source_language) { + switch (source_language) { + case SourceLanguage::kUnknown: + return "Unknown"; + case SourceLanguage::kGLSL: + return "GLSL"; + case SourceLanguage::kHLSL: + return "HLSL"; + } +} + +std::string EntryPointFunctionNameFromSourceName( + const std::string& file_name, + SourceType type, + SourceLanguage source_language, + const std::string& entry_point_name) { + if (source_language == SourceLanguage::kHLSL) { + return entry_point_name; + } + + std::stringstream stream; + std::filesystem::path file_path(file_name); + stream << ConvertToEntrypointName(Utf8FromPath(file_path.stem())) << "_"; + switch (type) { + case SourceType::kUnknown: + stream << "unknown"; + break; + case SourceType::kVertexShader: + stream << "vertex"; + break; + case SourceType::kFragmentShader: + stream << "fragment"; + break; + case SourceType::kComputeShader: + stream << "compute"; + break; + } + stream << "_main"; + return stream.str(); +} + +bool TargetPlatformNeedsReflection(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalIOS: + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kVulkan: + return true; + case TargetPlatform::kUnknown: + case TargetPlatform::kSkSL: + return false; + } + FML_UNREACHABLE(); +} + +std::string ShaderCErrorToString(shaderc_compilation_status status) { + using Status = shaderc_compilation_status; + switch (status) { + case Status::shaderc_compilation_status_success: + return "Success"; + case Status::shaderc_compilation_status_invalid_stage: + return "Invalid shader stage specified"; + case Status::shaderc_compilation_status_compilation_error: + return "Compilation error"; + case Status::shaderc_compilation_status_internal_error: + return "Internal error"; + case Status::shaderc_compilation_status_null_result_object: + return "Internal error. Null result object"; + case Status::shaderc_compilation_status_invalid_assembly: + return "Invalid assembly"; + case Status::shaderc_compilation_status_validation_error: + return "Validation error"; + case Status::shaderc_compilation_status_transformation_error: + return "Transform error"; + case Status::shaderc_compilation_status_configuration_error: + return "Configuration error"; + } + return "Unknown internal error"; +} + +shaderc_shader_kind ToShaderCShaderKind(SourceType type) { + switch (type) { + case SourceType::kVertexShader: + return shaderc_shader_kind::shaderc_vertex_shader; + case SourceType::kFragmentShader: + return shaderc_shader_kind::shaderc_fragment_shader; + case SourceType::kComputeShader: + return shaderc_shader_kind::shaderc_compute_shader; + case SourceType::kUnknown: + break; + } + return shaderc_shader_kind::shaderc_glsl_infer_from_source; +} + +spv::ExecutionModel ToExecutionModel(SourceType type) { + switch (type) { + case SourceType::kVertexShader: + return spv::ExecutionModel::ExecutionModelVertex; + case SourceType::kFragmentShader: + return spv::ExecutionModel::ExecutionModelFragment; + case SourceType::kComputeShader: + return spv::ExecutionModel::ExecutionModelGLCompute; + case SourceType::kUnknown: + break; + } + return spv::ExecutionModel::ExecutionModelMax; +} + +spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform( + TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalIOS: + case TargetPlatform::kRuntimeStageMetal: + return spirv_cross::CompilerMSL::Options::Platform::iOS; + case TargetPlatform::kMetalDesktop: + return spirv_cross::CompilerMSL::Options::Platform::macOS; + case TargetPlatform::kSkSL: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kVulkan: + case TargetPlatform::kUnknown: + return spirv_cross::CompilerMSL::Options::Platform::macOS; + } + FML_UNREACHABLE(); +} + +std::string SourceTypeToString(SourceType type) { + switch (type) { + case SourceType::kUnknown: + return "unknown"; + case SourceType::kVertexShader: + return "vert"; + case SourceType::kFragmentShader: + return "frag"; + case SourceType::kComputeShader: + return "comp"; + } + FML_UNREACHABLE(); +} + +std::string TargetPlatformSLExtension(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kUnknown: + return "unknown"; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kRuntimeStageMetal: + return "metal"; + case TargetPlatform::kSkSL: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + return "glsl"; + case TargetPlatform::kVulkan: + case TargetPlatform::kRuntimeStageVulkan: + return "vk.spirv"; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformIsOpenGL(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + return true; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kUnknown: + case TargetPlatform::kSkSL: + case TargetPlatform::kVulkan: + return false; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformIsMetal(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kRuntimeStageMetal: + return true; + case TargetPlatform::kUnknown: + case TargetPlatform::kSkSL: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kVulkan: + return false; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformIsVulkan(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kRuntimeStageVulkan: + case TargetPlatform::kVulkan: + return true; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kUnknown: + case TargetPlatform::kSkSL: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + return false; + } + FML_UNREACHABLE(); +} + +bool TargetPlatformBundlesSkSL(TargetPlatform platform) { + switch (platform) { + case TargetPlatform::kSkSL: + case TargetPlatform::kRuntimeStageMetal: + case TargetPlatform::kRuntimeStageGLES: + case TargetPlatform::kRuntimeStageGLES3: + case TargetPlatform::kRuntimeStageVulkan: + return true; + case TargetPlatform::kMetalDesktop: + case TargetPlatform::kMetalIOS: + case TargetPlatform::kUnknown: + case TargetPlatform::kOpenGLES: + case TargetPlatform::kOpenGLDesktop: + case TargetPlatform::kVulkan: + return false; + } + FML_UNREACHABLE(); +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/types.h b/flutter/engine/src/flutter/impeller/compiler/types.h new file mode 100644 index 0000000000000000000000000000000000000000..3878d0cef6d5c3c5790eed7b16bdd0e87daaa906 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/types.h @@ -0,0 +1,126 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_TYPES_H_ +#define FLUTTER_IMPELLER_COMPILER_TYPES_H_ + +#include +#include +#include +#include +#include + +#include "shaderc/shaderc.hpp" +#include "spirv_cross.hpp" +#include "spirv_msl.hpp" + +namespace impeller { +namespace compiler { + +enum class SourceType { + kUnknown, + kVertexShader, + kFragmentShader, + kComputeShader, +}; + +enum class TargetPlatform { + kUnknown, + kMetalDesktop, + kMetalIOS, + kOpenGLES, + kOpenGLDesktop, + kVulkan, + kRuntimeStageMetal, + kRuntimeStageGLES, + kRuntimeStageGLES3, + kRuntimeStageVulkan, + kSkSL, +}; + +enum class SourceLanguage { + kUnknown, + kGLSL, + kHLSL, +}; + +struct UniformDescription { + std::string name; + size_t location = 0u; + size_t binding = 0u; + spirv_cross::SPIRType::BaseType type = spirv_cross::SPIRType::BaseType::Float; + size_t rows = 0u; + size_t columns = 0u; + size_t bit_width = 0u; + std::optional array_elements = std::nullopt; + std::vector struct_layout = {}; + size_t struct_float_count = 0u; +}; + +struct InputDescription { + std::string name; + size_t location; + size_t set; + size_t binding; + spirv_cross::SPIRType::BaseType type = + spirv_cross::SPIRType::BaseType::Unknown; + size_t bit_width; + size_t vec_size; + size_t columns; + size_t offset; +}; + +/// A shader config parsed as part of a ShaderBundleConfig. +struct ShaderConfig { + std::string source_file_name; + SourceType type; + SourceLanguage language; + std::string entry_point; +}; + +using ShaderBundleConfig = std::unordered_map; + +bool TargetPlatformIsMetal(TargetPlatform platform); + +bool TargetPlatformIsOpenGL(TargetPlatform platform); + +bool TargetPlatformIsVulkan(TargetPlatform platform); + +SourceType SourceTypeFromFileName(const std::string& file_name); + +SourceType SourceTypeFromString(std::string name); + +std::string SourceTypeToString(SourceType type); + +std::string TargetPlatformToString(TargetPlatform platform); + +SourceLanguage ToSourceLanguage(const std::string& source_language); + +std::string SourceLanguageToString(SourceLanguage source_language); + +std::string TargetPlatformSLExtension(TargetPlatform platform); + +std::string EntryPointFunctionNameFromSourceName( + const std::string& file_name, + SourceType type, + SourceLanguage source_language, + const std::string& entry_point_name); + +bool TargetPlatformNeedsReflection(TargetPlatform platform); + +bool TargetPlatformBundlesSkSL(TargetPlatform platform); + +std::string ShaderCErrorToString(shaderc_compilation_status status); + +shaderc_shader_kind ToShaderCShaderKind(SourceType type); + +spv::ExecutionModel ToExecutionModel(SourceType type); + +spirv_cross::CompilerMSL::Options::Platform TargetPlatformToMSLPlatform( + TargetPlatform platform); + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_TYPES_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.cc b/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.cc new file mode 100644 index 0000000000000000000000000000000000000000..83b8619cef6e5ce3c033a5f0532f50866230d99d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.cc @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/uniform_sorter.h" + +#include + +namespace impeller { + +std::vector SortUniforms( + const spirv_cross::ParsedIR* ir, + const spirv_cross::Compiler* compiler, + std::optional type_filter, + bool include) { + // Sort the IR so that the uniforms are in declaration order. + std::vector uniforms; + ir->for_each_typed_id( + [&](uint32_t, const spirv_cross::SPIRVariable& var) { + if (var.storage != spv::StorageClassUniformConstant) { + return; + } + const auto& type = compiler->get_type(var.basetype); + if (!type_filter.has_value() || + (include && type_filter.value() == type.basetype) || + (!include && type_filter.value() != type.basetype)) { + uniforms.push_back(var.self); + } + }); + + auto compare_locations = [&ir](spirv_cross::ID id1, spirv_cross::ID id2) { + auto& flags1 = ir->get_decoration_bitset(id1); + auto& flags2 = ir->get_decoration_bitset(id2); + // Put the uniforms with no location after the ones that have a location. + if (!flags1.get(spv::Decoration::DecorationLocation)) { + return false; + } + if (!flags2.get(spv::Decoration::DecorationLocation)) { + return true; + } + // Sort in increasing order of location. + return ir->get_decoration(id1, spv::Decoration::DecorationLocation) < + ir->get_decoration(id2, spv::Decoration::DecorationLocation); + }; + std::sort(uniforms.begin(), uniforms.end(), compare_locations); + + return uniforms; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.h b/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.h new file mode 100644 index 0000000000000000000000000000000000000000..3493f60b38b3320e3159ec5bd2257dc1d98f7941 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/uniform_sorter.h @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_UNIFORM_SORTER_H_ +#define FLUTTER_IMPELLER_COMPILER_UNIFORM_SORTER_H_ + +#include + +#include "impeller/compiler/compiler_backend.h" + +#include "spirv_msl.hpp" +#include "spirv_parser.hpp" + +namespace impeller { + +/// @brief Sorts uniform declarations in an IR according to decoration order. +/// +/// The [type_filter] may be optionally supplied to limit which types are +/// returned The [include] value can be set to false change this filter to +/// exclude instead of include. +std::vector SortUniforms( + const spirv_cross::ParsedIR* ir, + const spirv_cross::Compiler* compiler, + std::optional type_filter = std::nullopt, + bool include = true); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_UNIFORM_SORTER_H_ diff --git a/flutter/engine/src/flutter/impeller/compiler/utilities.cc b/flutter/engine/src/flutter/impeller/compiler/utilities.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef24dc1681a5d422a3561fda64ba629fa94cf00e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/utilities.cc @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/compiler/utilities.h" + +#include +#include +#include +#include +#include + +namespace impeller { +namespace compiler { + +bool SetPermissiveAccess(const std::filesystem::path& p) { + auto permissions = + std::filesystem::perms::owner_read | std::filesystem::perms::owner_write | + std::filesystem::perms::group_read | std::filesystem::perms::others_read; + std::error_code error; + std::filesystem::permissions(p, permissions, error); + if (error) { + std::cerr << "Failed to set access on file '" << p + << "': " << error.message() << std::endl; + return false; + } + return true; +} + +std::string Utf8FromPath(const std::filesystem::path& path) { + return reinterpret_cast(path.u8string().c_str()); +} + +std::string InferShaderNameFromPath(std::string_view path) { + auto p = std::filesystem::path{path}.stem(); + return Utf8FromPath(p); +} + +std::string ToCamelCase(std::string_view string) { + if (string.empty()) { + return ""; + } + + std::stringstream stream; + bool next_upper = true; + for (size_t i = 0, count = string.length(); i < count; i++) { + auto ch = string.data()[i]; + if (next_upper) { + next_upper = false; + stream << static_cast(std::toupper(ch)); + continue; + } + if (ch == '_') { + next_upper = true; + continue; + } + stream << ch; + } + return stream.str(); +} + +std::string ToLowerCase(std::string_view string) { + std::string result = std::string(string); + std::transform(result.begin(), result.end(), result.begin(), + [](char x) { return std::tolower(x); }); + return result; +} + +std::string ConvertToEntrypointName(std::string_view string) { + if (string.empty()) { + return ""; + } + std::stringstream stream; + // Append a prefix if the first character is not a letter. + if (!std::isalpha(string.data()[0])) { + stream << "i_"; + } + for (size_t i = 0, count = string.length(); i < count; i++) { + auto ch = string.data()[i]; + if (std::isalnum(ch) || ch == '_') { + stream << ch; + } + } + return stream.str(); +} + +bool StringStartsWith(const std::string& target, const std::string& prefix) { + if (prefix.length() > target.length()) { + return false; + } + for (size_t i = 0; i < prefix.length(); i++) { + if (target[i] != prefix[i]) { + return false; + } + } + return true; +} + +} // namespace compiler +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/compiler/utilities.h b/flutter/engine/src/flutter/impeller/compiler/utilities.h new file mode 100644 index 0000000000000000000000000000000000000000..6da83478ece7961492e11853ce6470d132671fcd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/compiler/utilities.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_COMPILER_UTILITIES_H_ +#define FLUTTER_IMPELLER_COMPILER_UTILITIES_H_ + +#include +#include +#include + +namespace impeller { +namespace compiler { + +/// @brief Sets the file access mode of the file at path 'p' to 0644. +bool SetPermissiveAccess(const std::filesystem::path& p); + +/// @brief Converts a native format path to a utf8 string. +/// +/// This utility uses `path::u8string()` to convert native paths to +/// utf8. If the given path doesn't match the underlying native path +/// format, and the native path format isn't utf8 (i.e. Windows, which +/// has utf16 paths), the path will get mangled. +std::string Utf8FromPath(const std::filesystem::path& path); + +std::string InferShaderNameFromPath(std::string_view path); + +std::string ToCamelCase(std::string_view string); + +std::string ToLowerCase(std::string_view string); + +/// @brief Ensure that the entrypoint name is a valid identifier in the target +/// language. +std::string ConvertToEntrypointName(std::string_view string); + +bool StringStartsWith(const std::string& target, const std::string& prefix); + +} // namespace compiler +} // namespace impeller + +#endif // FLUTTER_IMPELLER_COMPILER_UTILITIES_H_ diff --git a/flutter/engine/src/flutter/impeller/core/BUILD.gn b/flutter/engine/src/flutter/impeller/core/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f88f90c205faa4805814e78de87e6451220c2271 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("core") { + sources = [ + "allocator.cc", + "allocator.h", + "buffer_view.cc", + "buffer_view.h", + "device_buffer.cc", + "device_buffer.h", + "device_buffer_descriptor.cc", + "device_buffer_descriptor.h", + "formats.cc", + "formats.h", + "host_buffer.cc", + "host_buffer.h", + "idle_waiter.h", + "platform.cc", + "platform.h", + "range.cc", + "range.h", + "raw_ptr.cc", + "raw_ptr.h", + "resource_binder.cc", + "resource_binder.h", + "runtime_types.cc", + "runtime_types.h", + "sampler.cc", + "sampler.h", + "sampler_descriptor.cc", + "sampler_descriptor.h", + "shader_types.cc", + "shader_types.h", + "texture.cc", + "texture.h", + "texture_descriptor.cc", + "texture_descriptor.h", + "vertex_buffer.cc", + "vertex_buffer.h", + ] + + deps = [ + "../base", + "../geometry", + "//flutter/fml", + ] +} + +impeller_component("allocator_unittests") { + testonly = true + + sources = [ + "allocator_unittests.cc", + "buffer_view_unittests.cc", + ] + + deps = [ + ":core", + "../geometry", + "//flutter/testing:testing_lib", + ] +} diff --git a/flutter/engine/src/flutter/impeller/core/allocator.cc b/flutter/engine/src/flutter/impeller/core/allocator.cc new file mode 100644 index 0000000000000000000000000000000000000000..19314c5bfcd59a4c4b09b09aad22c22f624ff21e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/allocator.cc @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/allocator.h" + +#include "impeller/base/validation.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/formats.h" +#include "impeller/core/range.h" + +namespace impeller { + +Allocator::Allocator() = default; + +Allocator::~Allocator() = default; + +std::shared_ptr Allocator::CreateBufferWithCopy( + const uint8_t* buffer, + size_t length) { + DeviceBufferDescriptor desc; + desc.size = length; + desc.storage_mode = StorageMode::kHostVisible; + auto new_buffer = CreateBuffer(desc); + + if (!new_buffer) { + return nullptr; + } + + auto entire_range = Range{0, length}; + + if (!new_buffer->CopyHostBuffer(buffer, entire_range)) { + return nullptr; + } + + return new_buffer; +} + +std::shared_ptr Allocator::CreateBufferWithCopy( + const fml::Mapping& mapping) { + return CreateBufferWithCopy(mapping.GetMapping(), mapping.GetSize()); +} + +std::shared_ptr Allocator::CreateBuffer( + const DeviceBufferDescriptor& desc) { + return OnCreateBuffer(desc); +} + +std::shared_ptr Allocator::CreateTexture( + const TextureDescriptor& desc) { + const auto max_size = GetMaxTextureSizeSupported(); + if (desc.size.width > max_size.width || desc.size.height > max_size.height) { + VALIDATION_LOG << "Requested texture size " << desc.size + << " exceeds maximum supported size of " << max_size; + return nullptr; + } + + if (desc.mip_count > desc.size.MipCount()) { + VALIDATION_LOG << "Requested mip_count " << desc.mip_count + << " exceeds maximum supported for size " << desc.size; + TextureDescriptor corrected_desc = desc; + corrected_desc.mip_count = desc.size.MipCount(); + return OnCreateTexture(corrected_desc); + } + + return OnCreateTexture(desc); +} + +uint16_t Allocator::MinimumBytesPerRow(PixelFormat format) const { + return BytesPerPixelForPixelFormat(format); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/allocator.h b/flutter/engine/src/flutter/impeller/core/allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..50da86fe10bf1a8e63563863cc9c818ec2769397 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/allocator.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_ALLOCATOR_H_ +#define FLUTTER_IMPELLER_CORE_ALLOCATOR_H_ + +#include "flutter/fml/mapping.h" +#include "impeller/base/allocation_size.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/idle_waiter.h" +#include "impeller/core/texture.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +class Context; +class DeviceBuffer; + +//------------------------------------------------------------------------------ +/// @brief An object that allocates device memory. +/// +class Allocator { + public: + virtual ~Allocator(); + + bool IsValid() const; + + std::shared_ptr CreateBuffer( + const DeviceBufferDescriptor& desc); + + std::shared_ptr CreateTexture(const TextureDescriptor& desc); + + //------------------------------------------------------------------------------ + /// @brief Minimum value for `row_bytes` on a Texture. The row + /// bytes parameter of that method must be aligned to this value. + /// + virtual uint16_t MinimumBytesPerRow(PixelFormat format) const; + + std::shared_ptr CreateBufferWithCopy(const uint8_t* buffer, + size_t length); + + std::shared_ptr CreateBufferWithCopy( + const fml::Mapping& mapping); + + virtual ISize GetMaxTextureSizeSupported() const = 0; + + /// @brief Write debug memory usage information to the dart timeline in debug + /// and profile modes. + /// + /// This is supported on both the Metal and Vulkan backends. + virtual void DebugTraceMemoryStatistics() const {}; + + // Visible for testing. + virtual Bytes DebugGetHeapUsage() const { return Bytes{0}; } + + protected: + Allocator(); + + virtual std::shared_ptr OnCreateBuffer( + const DeviceBufferDescriptor& desc) = 0; + + virtual std::shared_ptr OnCreateTexture( + const TextureDescriptor& desc) = 0; + + private: + Allocator(const Allocator&) = delete; + + Allocator& operator=(const Allocator&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_ALLOCATOR_H_ diff --git a/flutter/engine/src/flutter/impeller/core/allocator_unittests.cc b/flutter/engine/src/flutter/impeller/core/allocator_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b55140ae3bf7fdd6c7c55aa183b84d05577c606d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/allocator_unittests.cc @@ -0,0 +1,130 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/testing/mocks.h" + +namespace impeller { +namespace testing { + +TEST(AllocatorTest, TextureDescriptorCompatibility) { + // Size. + { + TextureDescriptor desc_a = {.size = ISize(100, 100)}; + TextureDescriptor desc_b = {.size = ISize(100, 100)}; + TextureDescriptor desc_c = {.size = ISize(101, 100)}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Storage Mode. + { + TextureDescriptor desc_a = {.storage_mode = StorageMode::kDevicePrivate}; + TextureDescriptor desc_b = {.storage_mode = StorageMode::kDevicePrivate}; + TextureDescriptor desc_c = {.storage_mode = StorageMode::kHostVisible}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Format. + { + TextureDescriptor desc_a = {.format = PixelFormat::kR8G8B8A8UNormInt}; + TextureDescriptor desc_b = {.format = PixelFormat::kR8G8B8A8UNormInt}; + TextureDescriptor desc_c = {.format = PixelFormat::kB10G10R10A10XR}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Sample Count. + { + TextureDescriptor desc_a = {.sample_count = SampleCount::kCount4}; + TextureDescriptor desc_b = {.sample_count = SampleCount::kCount4}; + TextureDescriptor desc_c = {.sample_count = SampleCount::kCount1}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Sample Count. + { + TextureDescriptor desc_a = {.type = TextureType::kTexture2DMultisample}; + TextureDescriptor desc_b = {.type = TextureType::kTexture2DMultisample}; + TextureDescriptor desc_c = {.type = TextureType::kTexture2D}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Compression. + { + TextureDescriptor desc_a = {.compression_type = CompressionType::kLossless}; + TextureDescriptor desc_b = {.compression_type = CompressionType::kLossless}; + TextureDescriptor desc_c = {.compression_type = CompressionType::kLossy}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } + // Mip Count. + { + TextureDescriptor desc_a = {.mip_count = 1}; + TextureDescriptor desc_b = {.mip_count = 1}; + TextureDescriptor desc_c = {.mip_count = 4}; + + ASSERT_EQ(desc_a, desc_b); + ASSERT_NE(desc_a, desc_c); + } +} + +TEST(AllocatorTest, RangeTest) { + { + Range a = Range{0, 10}; + Range b = Range{10, 20}; + auto merged = a.Merge(b); + + EXPECT_EQ(merged.offset, 0u); + EXPECT_EQ(merged.length, 30u); + } + + { + Range a = Range{0, 10}; + Range b = Range{100, 20}; + auto merged = a.Merge(b); + + EXPECT_EQ(merged.offset, 0u); + EXPECT_EQ(merged.length, 120u); + } + + { + Range a = Range{0, 10}; + Range b = Range{100, 20}; + auto merged = b.Merge(a); + + EXPECT_EQ(merged.offset, 0u); + EXPECT_EQ(merged.length, 120u); + } + + { + Range a = Range{0, 10}; + Range b = Range{100, 0}; + auto merged = b.Merge(a); + + EXPECT_EQ(merged.offset, 0u); + EXPECT_EQ(merged.length, 10u); + } + + { + Range a = Range{0, 10}; + Range b = Range{0, 10}; + auto merged = b.Merge(a); + + EXPECT_EQ(merged.offset, 0u); + EXPECT_EQ(merged.length, 10u); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/buffer_view.cc b/flutter/engine/src/flutter/impeller/core/buffer_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ab3ee01fc8ff0b2f87596bd1cb3e251a9bfb043 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/buffer_view.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/buffer_view.h" + +namespace impeller { + +BufferView::BufferView() : buffer_(nullptr), raw_buffer_(nullptr), range_({}) {} + +BufferView::BufferView(DeviceBuffer* buffer, Range range) + : buffer_(), raw_buffer_(buffer), range_(range) {} + +BufferView::BufferView(std::shared_ptr buffer, Range range) + : buffer_(std::move(buffer)), raw_buffer_(nullptr), range_(range) {} + +const DeviceBuffer* BufferView::GetBuffer() const { + return raw_buffer_ ? raw_buffer_ : buffer_.get(); +} + +std::shared_ptr BufferView::TakeBuffer() { + if (buffer_) { + raw_buffer_ = buffer_.get(); + return std::move(buffer_); + } else { + return nullptr; + } +} + +BufferView::operator bool() const { + return buffer_ || raw_buffer_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/buffer_view.h b/flutter/engine/src/flutter/impeller/core/buffer_view.h new file mode 100644 index 0000000000000000000000000000000000000000..f5a3cf1420a8b47e9061ebaacb577442ebdbe590 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/buffer_view.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_BUFFER_VIEW_H_ +#define FLUTTER_IMPELLER_CORE_BUFFER_VIEW_H_ + +#include +#include "impeller/core/range.h" + +namespace impeller { + +class DeviceBuffer; + +/// A specific range in a DeviceBuffer. +/// +/// BufferView can maintain ownership over the DeviceBuffer or not depending on +/// if it is created with a std::shared_ptr or a raw pointer. +struct BufferView { + public: + BufferView(); + + BufferView(DeviceBuffer* buffer, Range range); + + BufferView(std::shared_ptr buffer, Range range); + + Range GetRange() const { return range_; } + + const DeviceBuffer* GetBuffer() const; + + std::shared_ptr TakeBuffer(); + + explicit operator bool() const; + + private: + std::shared_ptr buffer_; + /// This is a non-owned DeviceBuffer. Steps should be taken to make sure this + /// lives for the duration of the BufferView's life. Usually this is done + /// automatically by the graphics API or in the case of Vulkan the HostBuffer + /// or TrackedObjectsVK keeps it alive. + const DeviceBuffer* raw_buffer_; + Range range_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_BUFFER_VIEW_H_ diff --git a/flutter/engine/src/flutter/impeller/core/buffer_view_unittests.cc b/flutter/engine/src/flutter/impeller/core/buffer_view_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..27c80247a9c480d00f563a2a56935006decd126a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/buffer_view_unittests.cc @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/buffer_view.h" + +namespace impeller { +namespace testing { + +TEST(BufferViewTest, Empty) { + BufferView buffer_view; + EXPECT_FALSE(buffer_view); +} + +TEST(BufferViewTest, TakeRaw) { + DeviceBuffer* buffer = reinterpret_cast(0xcafebabe); + BufferView buffer_view(buffer, {0, 123}); + EXPECT_TRUE(buffer_view); + std::shared_ptr taken = buffer_view.TakeBuffer(); + EXPECT_FALSE(taken); + EXPECT_EQ(buffer_view.GetBuffer(), buffer); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/device_buffer.cc b/flutter/engine/src/flutter/impeller/core/device_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d3f01afff808eef050f7576bf1ffec5f20a76a7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/device_buffer.cc @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/device_buffer.h" + +namespace impeller { + +DeviceBuffer::DeviceBuffer(DeviceBufferDescriptor desc) : desc_(desc) {} + +DeviceBuffer::~DeviceBuffer() = default; + +void DeviceBuffer::Flush(std::optional range) const {} + +void DeviceBuffer::Invalidate(std::optional range) const {} + +// static +BufferView DeviceBuffer::AsBufferView(std::shared_ptr buffer) { + Range range = {0u, buffer->desc_.size}; + return BufferView(std::move(buffer), range); +} + +const DeviceBufferDescriptor& DeviceBuffer::GetDeviceBufferDescriptor() const { + return desc_; +} + +[[nodiscard]] bool DeviceBuffer::CopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) { + if (source_range.length == 0u) { + // Nothing to copy. Bail. + return true; + } + + if (source == nullptr) { + // Attempted to copy data from a null buffer. + return false; + } + + if (desc_.storage_mode != StorageMode::kHostVisible) { + // One of the storage modes where a transfer queue must be used. + return false; + } + + if (offset + source_range.length > desc_.size) { + // Out of bounds of this buffer. + return false; + } + + return OnCopyHostBuffer(source, source_range, offset); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/device_buffer.h b/flutter/engine/src/flutter/impeller/core/device_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..7fa2f3e6329d3470ae98a8bc9f43f984282f3b08 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/device_buffer.h @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_ +#define FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_ + +#include +#include + +#include "impeller/core/allocator.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/range.h" + +namespace impeller { + +class DeviceBuffer { + public: + virtual ~DeviceBuffer(); + + [[nodiscard]] bool CopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset = 0u); + + virtual bool SetLabel(std::string_view label) = 0; + + virtual bool SetLabel(std::string_view label, Range range) = 0; + + /// @brief Create a buffer view of this entire buffer. + static BufferView AsBufferView(std::shared_ptr buffer); + + const DeviceBufferDescriptor& GetDeviceBufferDescriptor() const; + + virtual uint8_t* OnGetContents() const = 0; + + /// Make any pending writes visible to the GPU. + /// + /// This method must be called if the device pointer provided by + /// [OnGetContents] is written to without using [CopyHostBuffer]. On Devices + /// with coherent host memory, this method will not perform extra work. + /// + /// If the range is not provided, the entire buffer is flushed. + virtual void Flush(std::optional range = std::nullopt) const; + + virtual void Invalidate(std::optional range = std::nullopt) const; + + protected: + const DeviceBufferDescriptor desc_; + + explicit DeviceBuffer(DeviceBufferDescriptor desc); + + virtual bool OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) = 0; + + private: + DeviceBuffer(const DeviceBuffer&) = delete; + + DeviceBuffer& operator=(const DeviceBuffer&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_H_ diff --git a/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.cc b/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..9be04ae14fa18cfc16580f3d222dd2cfe212ae76 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/device_buffer_descriptor.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.h b/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..6c7c0ca1d29fc67218f8707220dfbfeb9d58176e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/device_buffer_descriptor.h @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_ +#define FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_ + +#include + +#include "impeller/core/formats.h" + +namespace impeller { + +struct DeviceBufferDescriptor { + StorageMode storage_mode = StorageMode::kDeviceTransient; + size_t size = 0u; + // Perhaps we could combine this with storage mode and create appropriate + // host-write and host-read flags. + bool readback = false; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_DEVICE_BUFFER_DESCRIPTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/core/formats.cc b/flutter/engine/src/flutter/impeller/core/formats.cc new file mode 100644 index 0000000000000000000000000000000000000000..77cbef96ceb0bb80b8151ab656fb07f10f049ca7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/formats.cc @@ -0,0 +1,144 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/formats.h" + +#include + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/texture.h" + +namespace impeller { + +constexpr bool StoreActionNeedsResolveTexture(StoreAction action) { + switch (action) { + case StoreAction::kDontCare: + case StoreAction::kStore: + return false; + case StoreAction::kMultisampleResolve: + case StoreAction::kStoreAndMultisampleResolve: + return true; + } +} + +bool Attachment::IsValid() const { + if (!texture || !texture->IsValid()) { + VALIDATION_LOG << "Attachment has no texture."; + return false; + } + + if (StoreActionNeedsResolveTexture(store_action)) { + if (!resolve_texture || !resolve_texture->IsValid()) { + VALIDATION_LOG << "Store action needs resolve but no valid resolve " + "texture specified."; + return false; + } + } + + if (resolve_texture) { + if (store_action != StoreAction::kMultisampleResolve && + store_action != StoreAction::kStoreAndMultisampleResolve) { + VALIDATION_LOG << "A resolve texture was specified, but the store action " + "doesn't include multisample resolve."; + return false; + } + + if (texture->GetTextureDescriptor().storage_mode == + StorageMode::kDeviceTransient && + store_action == StoreAction::kStoreAndMultisampleResolve) { + VALIDATION_LOG + << "The multisample texture cannot be transient when " + "specifying the StoreAndMultisampleResolve StoreAction."; + } + } + + auto storage_mode = resolve_texture + ? resolve_texture->GetTextureDescriptor().storage_mode + : texture->GetTextureDescriptor().storage_mode; + + if (storage_mode == StorageMode::kDeviceTransient) { + if (load_action == LoadAction::kLoad) { + VALIDATION_LOG << "The LoadAction cannot be Load when attaching a device " + "transient " + + std::string(resolve_texture ? "resolve texture." + : "texture."); + return false; + } + if (store_action != StoreAction::kDontCare) { + VALIDATION_LOG << "The StoreAction must be DontCare when attaching a " + "device transient " + + std::string(resolve_texture ? "resolve texture." + : "texture."); + return false; + } + } + + return true; +} + +std::string TextureUsageMaskToString(TextureUsageMask mask) { + std::vector usages; + if (mask & TextureUsage::kShaderRead) { + usages.push_back(TextureUsage::kShaderRead); + } + if (mask & TextureUsage::kShaderWrite) { + usages.push_back(TextureUsage::kShaderWrite); + } + if (mask & TextureUsage::kRenderTarget) { + usages.push_back(TextureUsage::kRenderTarget); + } + std::stringstream stream; + stream << "{ "; + for (size_t i = 0; i < usages.size(); i++) { + stream << TextureUsageToString(usages[i]); + if (i != usages.size() - 1u) { + stream << ", "; + } + } + stream << " }"; + return stream.str(); +} + +std::string AttachmentToString(const Attachment& attachment) { + std::stringstream stream; + if (attachment.texture) { + stream << "Texture=(" + << TextureDescriptorToString( + attachment.texture->GetTextureDescriptor()) + << "),"; + } + if (attachment.resolve_texture) { + stream << "ResolveTexture=(" + << TextureDescriptorToString( + attachment.resolve_texture->GetTextureDescriptor()) + << "),"; + } + stream << "LoadAction=" << LoadActionToString(attachment.load_action) << ","; + stream << "StoreAction=" << StoreActionToString(attachment.store_action); + return stream.str(); +} + +std::string ColorAttachmentToString(const ColorAttachment& color) { + std::stringstream stream; + stream << AttachmentToString(color) << ","; + stream << "ClearColor=(" << ColorToString(color.clear_color) << ")"; + return stream.str(); +} + +std::string DepthAttachmentToString(const DepthAttachment& depth) { + std::stringstream stream; + stream << AttachmentToString(depth) << ","; + stream << "ClearDepth=" << SPrintF("%.2f", depth.clear_depth); + return stream.str(); +} + +std::string StencilAttachmentToString(const StencilAttachment& stencil) { + std::stringstream stream; + stream << AttachmentToString(stencil) << ","; + stream << "ClearStencil=" << stencil.clear_stencil; + return stream.str(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/formats.h b/flutter/engine/src/flutter/impeller/core/formats.h new file mode 100644 index 0000000000000000000000000000000000000000..e74c88c2ec37ae4149dd2848fcd4b80db1b21926 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/formats.h @@ -0,0 +1,707 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_FORMATS_H_ +#define FLUTTER_IMPELLER_CORE_FORMATS_H_ + +#include +#include +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "flutter/fml/logging.h" +#include "impeller/base/mask.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +enum class WindingOrder { + kClockwise, + kCounterClockwise, +}; + +class Texture; + +//------------------------------------------------------------------------------ +/// @brief Specified where the allocation resides and how it is used. +/// +enum class StorageMode { + //---------------------------------------------------------------------------- + /// Allocations can be mapped onto the hosts address space and also be used by + /// the device. + /// + kHostVisible, + //---------------------------------------------------------------------------- + /// Allocations can only be used by the device. This location is optimal for + /// use by the device. If the host needs to access these allocations, the + /// transfer queue must be used to transfer this allocation onto the a host + /// visible buffer. + /// + kDevicePrivate, + //---------------------------------------------------------------------------- + /// Used by the device for temporary render targets. These allocations cannot + /// be transferred from and to other allocations using the transfer queue. + /// Render pass cannot initialize the contents of these buffers using load and + /// store actions. + /// + /// These allocations reside in tile memory which has higher bandwidth, lower + /// latency and lower power consumption. The total device memory usage is + /// also lower as a separate allocation does not need to be created in + /// device memory. Prefer using these allocations for intermediates like depth + /// and stencil buffers. + /// + kDeviceTransient, +}; + +constexpr const char* StorageModeToString(StorageMode mode) { + switch (mode) { + case StorageMode::kHostVisible: + return "HostVisible"; + case StorageMode::kDevicePrivate: + return "DevicePrivate"; + case StorageMode::kDeviceTransient: + return "DeviceTransient"; + } + FML_UNREACHABLE(); +} + +//------------------------------------------------------------------------------ +/// @brief The Pixel formats supported by Impeller. The naming convention +/// denotes the usage of the component, the bit width of that +/// component, and then one or more qualifiers to its +/// interpretation. +/// +/// For instance, `kR8G8B8A8UNormIntSRGB` is a 32 bits-per-pixel +/// format ordered in RGBA with 8 bits per component with each +/// component expressed as an unsigned normalized integer and a +/// conversion from sRGB to linear color space. +/// +/// Key: +/// R -> Red Component +/// G -> Green Component +/// B -> Blue Component +/// D -> Depth Component +/// S -> Stencil Component +/// U -> Unsigned (Lack of this denotes a signed component) +/// Norm -> Normalized +/// SRGB -> sRGB to linear interpretation +/// +/// While the effective bit width of the pixel can be determined by +/// adding up the widths of each component, only the non-esoteric +/// formats are tightly packed. Do not assume tight packing for the +/// esoteric formats and use blit passes to convert to a +/// non-esoteric pass. +/// +enum class PixelFormat : uint8_t { + kUnknown, + kA8UNormInt, + kR8UNormInt, + kR8G8UNormInt, + kR8G8B8A8UNormInt, + kR8G8B8A8UNormIntSRGB, + kB8G8R8A8UNormInt, + kB8G8R8A8UNormIntSRGB, + kR32G32B32A32Float, + kR16G16B16A16Float, + kB10G10R10XR, + kB10G10R10XRSRGB, + kB10G10R10A10XR, + // Depth and stencil formats. + kS8UInt, + kD24UnormS8Uint, + kD32FloatS8UInt, +}; + +constexpr bool IsDepthWritable(PixelFormat format) { + switch (format) { + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return true; + default: + return false; + } +} + +constexpr bool IsStencilWritable(PixelFormat format) { + switch (format) { + case PixelFormat::kS8UInt: + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return true; + default: + return false; + } +} + +constexpr const char* PixelFormatToString(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + return "Unknown"; + case PixelFormat::kA8UNormInt: + return "A8UNormInt"; + case PixelFormat::kR8UNormInt: + return "R8UNormInt"; + case PixelFormat::kR8G8UNormInt: + return "R8G8UNormInt"; + case PixelFormat::kR8G8B8A8UNormInt: + return "R8G8B8A8UNormInt"; + case PixelFormat::kR8G8B8A8UNormIntSRGB: + return "R8G8B8A8UNormIntSRGB"; + case PixelFormat::kB8G8R8A8UNormInt: + return "B8G8R8A8UNormInt"; + case PixelFormat::kB8G8R8A8UNormIntSRGB: + return "B8G8R8A8UNormIntSRGB"; + case PixelFormat::kR32G32B32A32Float: + return "R32G32B32A32Float"; + case PixelFormat::kR16G16B16A16Float: + return "R16G16B16A16Float"; + case PixelFormat::kB10G10R10XR: + return "B10G10R10XR"; + case PixelFormat::kB10G10R10XRSRGB: + return "B10G10R10XRSRGB"; + case PixelFormat::kB10G10R10A10XR: + return "B10G10R10A10XR"; + case PixelFormat::kS8UInt: + return "S8UInt"; + case PixelFormat::kD24UnormS8Uint: + return "D24UnormS8Uint"; + case PixelFormat::kD32FloatS8UInt: + return "D32FloatS8UInt"; + } + FML_UNREACHABLE(); +} + +enum class BlendFactor { + kZero, + kOne, + kSourceColor, + kOneMinusSourceColor, + kSourceAlpha, + kOneMinusSourceAlpha, + kDestinationColor, + kOneMinusDestinationColor, + kDestinationAlpha, + kOneMinusDestinationAlpha, + kSourceAlphaSaturated, + kBlendColor, + kOneMinusBlendColor, + kBlendAlpha, + kOneMinusBlendAlpha, +}; + +enum class BlendOperation { + kAdd, + kSubtract, + kReverseSubtract, +}; + +enum class LoadAction { + kDontCare, + kLoad, + kClear, +}; + +enum class StoreAction { + kDontCare, + kStore, + kMultisampleResolve, + kStoreAndMultisampleResolve, +}; + +constexpr const char* LoadActionToString(LoadAction action) { + switch (action) { + case LoadAction::kDontCare: + return "DontCare"; + case LoadAction::kLoad: + return "Load"; + case LoadAction::kClear: + return "Clear"; + } +} + +constexpr const char* StoreActionToString(StoreAction action) { + switch (action) { + case StoreAction::kDontCare: + return "DontCare"; + case StoreAction::kStore: + return "Store"; + case StoreAction::kMultisampleResolve: + return "MultisampleResolve"; + case StoreAction::kStoreAndMultisampleResolve: + return "StoreAndMultisampleResolve"; + } +} + +constexpr bool CanClearAttachment(LoadAction action) { + switch (action) { + case LoadAction::kLoad: + return false; + case LoadAction::kDontCare: + case LoadAction::kClear: + return true; + } + FML_UNREACHABLE(); +} + +constexpr bool CanDiscardAttachmentWhenDone(StoreAction action) { + switch (action) { + case StoreAction::kStore: + case StoreAction::kStoreAndMultisampleResolve: + return false; + case StoreAction::kDontCare: + case StoreAction::kMultisampleResolve: + return true; + } + FML_UNREACHABLE(); +} + +enum class TextureType { + kTexture2D, + kTexture2DMultisample, + kTextureCube, + kTextureExternalOES, +}; + +constexpr const char* TextureTypeToString(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + return "Texture2D"; + case TextureType::kTexture2DMultisample: + return "Texture2DMultisample"; + case TextureType::kTextureCube: + return "TextureCube"; + case TextureType::kTextureExternalOES: + return "TextureExternalOES"; + } + FML_UNREACHABLE(); +} + +constexpr bool IsMultisampleCapable(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + case TextureType::kTextureCube: + case TextureType::kTextureExternalOES: + return false; + case TextureType::kTexture2DMultisample: + return true; + } + return false; +} + +enum class SampleCount : uint8_t { + kCount1 = 1, + kCount4 = 4, +}; + +enum class TextureUsage { + kUnknown = 0, + kShaderRead = 1 << 0, + kShaderWrite = 1 << 1, + kRenderTarget = 1 << 2, +}; +IMPELLER_ENUM_IS_MASK(TextureUsage); + +using TextureUsageMask = Mask; + +constexpr const char* TextureUsageToString(TextureUsage usage) { + switch (usage) { + case TextureUsage::kUnknown: + return "Unknown"; + case TextureUsage::kShaderRead: + return "ShaderRead"; + case TextureUsage::kShaderWrite: + return "ShaderWrite"; + case TextureUsage::kRenderTarget: + return "RenderTarget"; + } + FML_UNREACHABLE(); +} + +std::string TextureUsageMaskToString(TextureUsageMask mask); + +// Texture coordinate system. +enum class TextureCoordinateSystem { + // Alternative coordinate system used when uploading texture data from the + // host. + // (0, 0) is the bottom-left of the image with +Y going up. + kUploadFromHost, + // Default coordinate system. + // (0, 0) is the top-left of the image with +Y going down. + kRenderToTexture, +}; + +enum class CullMode { + kNone, + kFrontFace, + kBackFace, +}; + +enum class IndexType { + kUnknown, + k16bit, + k32bit, + /// Does not use the index buffer. + kNone, +}; + +/// Decides how backend draws pixels based on input vertices. +enum class PrimitiveType : uint8_t { + /// Draws a triangle for each separate set of three vertices. + /// + /// Vertices [A, B, C, D, E, F] will produce triangles + /// [ABC, DEF]. + kTriangle, + + /// Draws a triangle for every adjacent three vertices. + /// + /// Vertices [A, B, C, D, E, F] will produce triangles + /// [ABC, BCD, CDE, DEF]. + kTriangleStrip, + + /// Draws a line for each separate set of two vertices. + /// + /// Vertices [A, B, C] will produce discontinued line + /// [AB, BC]. + kLine, + + /// Draws a continuous line that connect every input vertices + /// + /// Vertices [A, B, C] will produce one continuous line + /// [ABC]. + kLineStrip, + + /// Draws a point at each input vertex. + kPoint, + + /// Draws a triangle for every two vertices, after the first. + /// + /// The first vertex acts as the hub, all following vertices connect with + /// this hub to "fan" out from the first vertex. + /// + /// Triangle fans are not supported in Metal and need a capability check. + kTriangleFan, +}; + +enum class PolygonMode { + kFill, + kLine, +}; + +struct DepthRange { + Scalar z_near = 0.0; + Scalar z_far = 1.0; + + constexpr bool operator==(const DepthRange& other) const { + return z_near == other.z_near && z_far == other.z_far; + } +}; + +struct Viewport { + Rect rect; + DepthRange depth_range; + + constexpr bool operator==(const Viewport& other) const { + return rect == other.rect && depth_range == other.depth_range; + } +}; + +/// @brief Describes how the texture should be sampled when the texture +/// is being shrunk (minified) or expanded (magnified) to fit to +/// the sample point. +enum class MinMagFilter : uint8_t { + /// Select nearest to the sample point. Most widely supported. + kNearest, + + /// Select two points and linearly interpolate between them. Some formats + /// may not support this. + kLinear, +}; + +/// @brief Options for selecting and filtering between mipmap levels. +enum class MipFilter : uint8_t { + /// @brief The texture is sampled as if it only had a single mipmap level. + /// + /// All samples are read from level 0. + kBase, + + /// @brief The nearst mipmap level is selected. + kNearest, + + /// @brief Sample from the two nearest mip levels and linearly interpolate. + /// + /// If the filter falls between levels, both levels are sampled, and + /// their results linearly interpolated between levels. + kLinear, +}; + +enum class SamplerAddressMode : uint8_t { + kClampToEdge, + kRepeat, + kMirror, + // More modes are almost always supported but they are usually behind + // extensions checks. The ones current in these structs are safe (always + // supported) defaults. + + /// @brief decal sampling mode is only supported on devices that pass + /// the `Capabilities.SupportsDecalSamplerAddressMode` check. + kDecal, +}; + +enum class ColorWriteMaskBits : uint64_t { + kNone = 0, + kRed = 1 << 0, + kGreen = 1 << 1, + kBlue = 1 << 2, + kAlpha = 1 << 3, + kAll = kRed | kGreen | kBlue | kAlpha, +}; +IMPELLER_ENUM_IS_MASK(ColorWriteMaskBits); + +using ColorWriteMask = Mask; + +constexpr size_t BytesPerPixelForPixelFormat(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + return 0u; + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kS8UInt: + return 1u; + case PixelFormat::kR8G8UNormInt: + return 2u; + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: + return 4u; + case PixelFormat::kD24UnormS8Uint: + return 4u; + case PixelFormat::kD32FloatS8UInt: + return 5u; + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10A10XR: + return 8u; + case PixelFormat::kR32G32B32A32Float: + return 16u; + } + return 0u; +} + +//------------------------------------------------------------------------------ +/// @brief Describe the color attachment that will be used with this +/// pipeline. +/// +/// Blending at specific color attachments follows the pseudo-code: +/// ``` +/// if (blending_enabled) { +/// final_color.rgb = (src_color_blend_factor * new_color.rgb) +/// +/// (dst_color_blend_factor * old_color.rgb); +/// final_color.a = (src_alpha_blend_factor * new_color.a) +/// +/// (dst_alpha_blend_factor * old_color.a); +/// } else { +/// final_color = new_color; +/// } +/// // IMPORTANT: The write mask is applied irrespective of whether +/// // blending_enabled is set. +/// final_color = final_color & write_mask; +/// ``` +/// +/// The default blend mode is 1 - source alpha. +struct ColorAttachmentDescriptor { + PixelFormat format = PixelFormat::kUnknown; + bool blending_enabled = false; + + BlendFactor src_color_blend_factor = BlendFactor::kSourceAlpha; + BlendOperation color_blend_op = BlendOperation::kAdd; + BlendFactor dst_color_blend_factor = BlendFactor::kOneMinusSourceAlpha; + + BlendFactor src_alpha_blend_factor = BlendFactor::kSourceAlpha; + BlendOperation alpha_blend_op = BlendOperation::kAdd; + BlendFactor dst_alpha_blend_factor = BlendFactor::kOneMinusSourceAlpha; + + ColorWriteMask write_mask = ColorWriteMaskBits::kAll; + + constexpr bool operator==(const ColorAttachmentDescriptor& o) const { + return format == o.format && // + blending_enabled == o.blending_enabled && // + src_color_blend_factor == o.src_color_blend_factor && // + color_blend_op == o.color_blend_op && // + dst_color_blend_factor == o.dst_color_blend_factor && // + src_alpha_blend_factor == o.src_alpha_blend_factor && // + alpha_blend_op == o.alpha_blend_op && // + dst_alpha_blend_factor == o.dst_alpha_blend_factor && // + write_mask == o.write_mask; + } + + constexpr size_t Hash() const { + return fml::HashCombine( + format, blending_enabled, src_color_blend_factor, color_blend_op, + dst_color_blend_factor, src_alpha_blend_factor, alpha_blend_op, + dst_alpha_blend_factor, static_cast(write_mask)); + } +}; + +enum class CompareFunction : uint8_t { + /// Comparison test never passes. + kNever, + /// Comparison test passes always passes. + kAlways, + /// Comparison test passes if new_value < current_value. + kLess, + /// Comparison test passes if new_value == current_value. + kEqual, + /// Comparison test passes if new_value <= current_value. + kLessEqual, + /// Comparison test passes if new_value > current_value. + kGreater, + /// Comparison test passes if new_value != current_value. + kNotEqual, + /// Comparison test passes if new_value >= current_value. + kGreaterEqual, +}; + +enum class StencilOperation : uint8_t { + /// Don't modify the current stencil value. + kKeep, + /// Reset the stencil value to zero. + kZero, + /// Reset the stencil value to the reference value. + kSetToReferenceValue, + /// Increment the current stencil value by 1. Clamp it to the maximum. + kIncrementClamp, + /// Decrement the current stencil value by 1. Clamp it to zero. + kDecrementClamp, + /// Perform a logical bitwise invert on the current stencil value. + kInvert, + /// Increment the current stencil value by 1. If at maximum, set to zero. + kIncrementWrap, + /// Decrement the current stencil value by 1. If at zero, set to maximum. + kDecrementWrap, +}; + +struct DepthAttachmentDescriptor { + //---------------------------------------------------------------------------- + /// Indicates how to compare the value with that in the depth buffer. + /// + CompareFunction depth_compare = CompareFunction::kAlways; + //---------------------------------------------------------------------------- + /// Indicates when writes must be performed to the depth buffer. + /// + bool depth_write_enabled = false; + + constexpr bool operator==(const DepthAttachmentDescriptor& o) const { + return depth_compare == o.depth_compare && + depth_write_enabled == o.depth_write_enabled; + } + + constexpr size_t GetHash() const { + return fml::HashCombine(depth_compare, depth_write_enabled); + } +}; + +struct StencilAttachmentDescriptor { + //---------------------------------------------------------------------------- + /// Indicates the operation to perform between the reference value and the + /// value in the stencil buffer. Both values have the read_mask applied to + /// them before performing this operation. + /// + CompareFunction stencil_compare = CompareFunction::kAlways; + //---------------------------------------------------------------------------- + /// Indicates what to do when the stencil test has failed. + /// + StencilOperation stencil_failure = StencilOperation::kKeep; + //---------------------------------------------------------------------------- + /// Indicates what to do when the stencil test passes but the depth test + /// fails. + /// + StencilOperation depth_failure = StencilOperation::kKeep; + //---------------------------------------------------------------------------- + /// Indicates what to do when both the stencil and depth tests pass. + /// + StencilOperation depth_stencil_pass = StencilOperation::kKeep; + + //---------------------------------------------------------------------------- + /// The mask applied to the reference and stencil buffer values before + /// performing the stencil_compare operation. + /// + uint32_t read_mask = ~0; + //---------------------------------------------------------------------------- + /// The mask applied to the new stencil value before it is written into the + /// stencil buffer. + /// + uint32_t write_mask = ~0; + + constexpr bool operator==(const StencilAttachmentDescriptor& o) const { + return stencil_compare == o.stencil_compare && + stencil_failure == o.stencil_failure && + depth_failure == o.depth_failure && + depth_stencil_pass == o.depth_stencil_pass && + read_mask == o.read_mask && write_mask == o.write_mask; + } + + constexpr size_t GetHash() const { + return fml::HashCombine(stencil_compare, stencil_failure, depth_failure, + depth_stencil_pass, read_mask, write_mask); + } +}; + +struct Attachment { + std::shared_ptr texture; + std::shared_ptr resolve_texture; + LoadAction load_action = LoadAction::kDontCare; + StoreAction store_action = StoreAction::kStore; + + bool IsValid() const; +}; + +struct ColorAttachment : public Attachment { + Color clear_color = Color::BlackTransparent(); +}; + +struct DepthAttachment : public Attachment { + double clear_depth = 0.0; +}; + +struct StencilAttachment : public Attachment { + uint32_t clear_stencil = 0; +}; + +std::string AttachmentToString(const Attachment& attachment); + +std::string ColorAttachmentToString(const ColorAttachment& color); + +std::string DepthAttachmentToString(const DepthAttachment& depth); + +std::string StencilAttachmentToString(const StencilAttachment& stencil); + +} // namespace impeller + +namespace std { + +template <> +struct hash { + constexpr std::size_t operator()( + const impeller::DepthAttachmentDescriptor& des) const { + return des.GetHash(); + } +}; + +template <> +struct hash { + constexpr std::size_t operator()( + const impeller::StencilAttachmentDescriptor& des) const { + return des.GetHash(); + } +}; + +} // namespace std + +#endif // FLUTTER_IMPELLER_CORE_FORMATS_H_ diff --git a/flutter/engine/src/flutter/impeller/core/host_buffer.cc b/flutter/engine/src/flutter/impeller/core/host_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..1fef5df595a8b4b38232748f14599f1bbdc83f6b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/host_buffer.cc @@ -0,0 +1,236 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/host_buffer.h" + +#include +#include + +#include "impeller/base/validation.h" +#include "impeller/core/allocator.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" + +namespace impeller { + +constexpr size_t kAllocatorBlockSize = 1024000; // 1024 Kb. + +std::shared_ptr HostBuffer::Create( + const std::shared_ptr& allocator, + const std::shared_ptr& idle_waiter) { + return std::shared_ptr(new HostBuffer(allocator, idle_waiter)); +} + +HostBuffer::HostBuffer(const std::shared_ptr& allocator, + const std::shared_ptr& idle_waiter) + : allocator_(allocator), idle_waiter_(idle_waiter) { + DeviceBufferDescriptor desc; + desc.size = kAllocatorBlockSize; + desc.storage_mode = StorageMode::kHostVisible; + for (auto i = 0u; i < kHostBufferArenaSize; i++) { + std::shared_ptr device_buffer = allocator->CreateBuffer(desc); + FML_CHECK(device_buffer) << "Failed to allocate device buffer."; + device_buffers_[i].push_back(device_buffer); + } +} + +HostBuffer::~HostBuffer() { + if (idle_waiter_) { + // Since we hold on to DeviceBuffers we should make sure they aren't being + // used while we are deleting the HostBuffer. + idle_waiter_->WaitIdle(); + } +}; + +BufferView HostBuffer::Emplace(const void* buffer, + size_t length, + size_t align) { + auto [range, device_buffer, raw_device_buffer] = + EmplaceInternal(buffer, length, align); + if (device_buffer) { + return BufferView(std::move(device_buffer), range); + } else if (raw_device_buffer) { + return BufferView(raw_device_buffer, range); + } else { + return {}; + } +} + +BufferView HostBuffer::Emplace(const void* buffer, size_t length) { + auto [range, device_buffer, raw_device_buffer] = + EmplaceInternal(buffer, length); + if (device_buffer) { + return BufferView(std::move(device_buffer), range); + } else if (raw_device_buffer) { + return BufferView(raw_device_buffer, range); + } else { + return {}; + } +} + +BufferView HostBuffer::Emplace(size_t length, + size_t align, + const EmplaceProc& cb) { + auto [range, device_buffer, raw_device_buffer] = + EmplaceInternal(length, align, cb); + if (device_buffer) { + return BufferView(std::move(device_buffer), range); + } else if (raw_device_buffer) { + return BufferView(raw_device_buffer, range); + } else { + return {}; + } +} + +HostBuffer::TestStateQuery HostBuffer::GetStateForTest() { + return HostBuffer::TestStateQuery{ + .current_frame = frame_index_, + .current_buffer = current_buffer_, + .total_buffer_count = device_buffers_[frame_index_].size(), + }; +} + +bool HostBuffer::MaybeCreateNewBuffer() { + current_buffer_++; + if (current_buffer_ >= device_buffers_[frame_index_].size()) { + DeviceBufferDescriptor desc; + desc.size = kAllocatorBlockSize; + desc.storage_mode = StorageMode::kHostVisible; + std::shared_ptr buffer = allocator_->CreateBuffer(desc); + if (!buffer) { + VALIDATION_LOG << "Failed to allocate host buffer of size " << desc.size; + return false; + } + device_buffers_[frame_index_].push_back(std::move(buffer)); + } + offset_ = 0; + return true; +} + +std::tuple, DeviceBuffer*> +HostBuffer::EmplaceInternal(size_t length, + size_t align, + const EmplaceProc& cb) { + if (!cb) { + return {}; + } + + // If the requested allocation is bigger than the block size, create a one-off + // device buffer and write to that. + if (length > kAllocatorBlockSize) { + DeviceBufferDescriptor desc; + desc.size = length; + desc.storage_mode = StorageMode::kHostVisible; + std::shared_ptr device_buffer = + allocator_->CreateBuffer(desc); + if (!device_buffer) { + return {}; + } + if (cb) { + cb(device_buffer->OnGetContents()); + device_buffer->Flush(Range{0, length}); + } + return std::make_tuple(Range{0, length}, std::move(device_buffer), nullptr); + } + + size_t padding = 0; + if (align > 0 && offset_ % align) { + padding = align - (offset_ % align); + } + if (offset_ + padding + length > kAllocatorBlockSize) { + if (!MaybeCreateNewBuffer()) { + return {}; + } + } else { + offset_ += padding; + } + + const std::shared_ptr& current_buffer = GetCurrentBuffer(); + auto contents = current_buffer->OnGetContents(); + cb(contents + offset_); + Range output_range(offset_, length); + current_buffer->Flush(output_range); + + offset_ += length; + return std::make_tuple(output_range, nullptr, current_buffer.get()); +} + +std::tuple, DeviceBuffer*> +HostBuffer::EmplaceInternal(const void* buffer, size_t length) { + // If the requested allocation is bigger than the block size, create a one-off + // device buffer and write to that. + if (length > kAllocatorBlockSize) { + DeviceBufferDescriptor desc; + desc.size = length; + desc.storage_mode = StorageMode::kHostVisible; + std::shared_ptr device_buffer = + allocator_->CreateBuffer(desc); + if (!device_buffer) { + return {}; + } + if (buffer) { + if (!device_buffer->CopyHostBuffer(static_cast(buffer), + Range{0, length})) { + return {}; + } + } + return std::make_tuple(Range{0, length}, std::move(device_buffer), nullptr); + } + + auto old_length = GetLength(); + if (old_length + length > kAllocatorBlockSize) { + if (!MaybeCreateNewBuffer()) { + return {}; + } + } + old_length = GetLength(); + + const std::shared_ptr& current_buffer = GetCurrentBuffer(); + auto contents = current_buffer->OnGetContents(); + if (buffer) { + ::memmove(contents + old_length, buffer, length); + current_buffer->Flush(Range{old_length, length}); + } + offset_ += length; + return std::make_tuple(Range{old_length, length}, nullptr, + current_buffer.get()); +} + +std::tuple, DeviceBuffer*> +HostBuffer::EmplaceInternal(const void* buffer, size_t length, size_t align) { + if (align == 0 || (GetLength() % align) == 0) { + return EmplaceInternal(buffer, length); + } + + { + auto padding = align - (GetLength() % align); + if (offset_ + padding < kAllocatorBlockSize) { + offset_ += padding; + } else if (!MaybeCreateNewBuffer()) { + return {}; + } + } + + return EmplaceInternal(buffer, length); +} + +const std::shared_ptr& HostBuffer::GetCurrentBuffer() const { + return device_buffers_[frame_index_][current_buffer_]; +} + +void HostBuffer::Reset() { + // When resetting the host buffer state at the end of the frame, check if + // there are any unused buffers and remove them. + while (device_buffers_[frame_index_].size() > current_buffer_ + 1) { + device_buffers_[frame_index_].pop_back(); + } + + offset_ = 0u; + current_buffer_ = 0u; + frame_index_ = (frame_index_ + 1) % kHostBufferArenaSize; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/host_buffer.h b/flutter/engine/src/flutter/impeller/core/host_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..d0c5dbf3f3b5b636bfa932a046a6b99ba2c9177f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/host_buffer.h @@ -0,0 +1,176 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_HOST_BUFFER_H_ +#define FLUTTER_IMPELLER_CORE_HOST_BUFFER_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/core/allocator.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/platform.h" + +namespace impeller { + +/// Approximately the same size as the max frames in flight. +static const constexpr size_t kHostBufferArenaSize = 4u; + +/// The host buffer class manages one more 1024 Kb blocks of device buffer +/// allocations. +/// +/// These are reset per-frame. +class HostBuffer { + public: + static std::shared_ptr Create( + const std::shared_ptr& allocator, + const std::shared_ptr& idle_waiter); + + ~HostBuffer(); + + //---------------------------------------------------------------------------- + /// @brief Emplace uniform data onto the host buffer. Ensure that backend + /// specific uniform alignment requirements are respected. + /// + /// @param[in] uniform The uniform struct to emplace onto the buffer. + /// + /// @tparam UniformType The type of the uniform struct. + /// + /// @return The buffer view. + /// + template >> + [[nodiscard]] BufferView EmplaceUniform(const UniformType& uniform) { + const auto alignment = + std::max(alignof(UniformType), DefaultUniformAlignment()); + return Emplace(reinterpret_cast(&uniform), // buffer + sizeof(UniformType), // size + alignment // alignment + ); + } + + //---------------------------------------------------------------------------- + /// @brief Emplace storage buffer data onto the host buffer. Ensure that + /// backend specific uniform alignment requirements are respected. + /// + /// @param[in] uniform The storage buffer to emplace onto the buffer. + /// + /// @tparam StorageBufferType The type of the shader storage buffer. + /// + /// @return The buffer view. + /// + template < + class StorageBufferType, + class = std::enable_if_t>> + [[nodiscard]] BufferView EmplaceStorageBuffer( + const StorageBufferType& buffer) { + const auto alignment = + std::max(alignof(StorageBufferType), DefaultUniformAlignment()); + return Emplace(&buffer, // buffer + sizeof(StorageBufferType), // size + alignment // alignment + ); + } + + //---------------------------------------------------------------------------- + /// @brief Emplace non-uniform data (like contiguous vertices) onto the + /// host buffer. + /// + /// @param[in] buffer The buffer data. + /// @param[in] alignment Minimum alignment of the data being emplaced. + /// + /// @tparam BufferType The type of the buffer data. + /// + /// @return The buffer view. + /// + template >> + [[nodiscard]] BufferView Emplace(const BufferType& buffer, + size_t alignment = 0) { + return Emplace(reinterpret_cast(&buffer), // buffer + sizeof(BufferType), // size + std::max(alignment, alignof(BufferType)) // alignment + ); + } + + [[nodiscard]] BufferView Emplace(const void* buffer, + size_t length, + size_t align); + + using EmplaceProc = std::function; + + //---------------------------------------------------------------------------- + /// @brief Emplaces undefined data onto the managed buffer and gives the + /// caller a chance to update it using the specified callback. The + /// buffer is guaranteed to have enough space for length bytes. It + /// is the responsibility of the caller to not exceed the bounds + /// of the buffer returned in the EmplaceProc. + /// + /// @param[in] cb A callback that will be passed a ptr to the + /// underlying host buffer. + /// + /// @return The buffer view. + /// + BufferView Emplace(size_t length, size_t align, const EmplaceProc& cb); + + //---------------------------------------------------------------------------- + /// @brief Resets the contents of the HostBuffer to nothing so it can be + /// reused. + void Reset(); + + /// Test only internal state. + struct TestStateQuery { + size_t current_frame; + size_t current_buffer; + size_t total_buffer_count; + }; + + /// @brief Retrieve internal buffer state for test expectations. + TestStateQuery GetStateForTest(); + + private: + [[nodiscard]] std::tuple, DeviceBuffer*> + EmplaceInternal(const void* buffer, size_t length); + + std::tuple, DeviceBuffer*> + EmplaceInternal(size_t length, size_t align, const EmplaceProc& cb); + + std::tuple, DeviceBuffer*> + EmplaceInternal(const void* buffer, size_t length, size_t align); + + size_t GetLength() const { return offset_; } + + /// Attempt to create a new internal buffer if the existing capacity is not + /// sufficient. + /// + /// A false return value indicates an unrecoverable allocation failure. + [[nodiscard]] bool MaybeCreateNewBuffer(); + + const std::shared_ptr& GetCurrentBuffer() const; + + [[nodiscard]] BufferView Emplace(const void* buffer, size_t length); + + explicit HostBuffer(const std::shared_ptr& allocator, + const std::shared_ptr& idle_waiter); + + HostBuffer(const HostBuffer&) = delete; + + HostBuffer& operator=(const HostBuffer&) = delete; + + std::shared_ptr allocator_; + std::shared_ptr idle_waiter_; + std::array>, kHostBufferArenaSize> + device_buffers_; + size_t current_buffer_ = 0u; + size_t offset_ = 0u; + size_t frame_index_ = 0u; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_HOST_BUFFER_H_ diff --git a/flutter/engine/src/flutter/impeller/core/idle_waiter.h b/flutter/engine/src/flutter/impeller/core/idle_waiter.h new file mode 100644 index 0000000000000000000000000000000000000000..f346375b2b0fe154b813f0a277cefa63ce2ad1c3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/idle_waiter.h @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_IDLE_WAITER_H_ +#define FLUTTER_IMPELLER_CORE_IDLE_WAITER_H_ + +namespace impeller { + +/// Abstraction over waiting for the GPU to be idle. +/// +/// This is important for platforms like Vulkan where we need to make sure +/// we aren't deleting resources while the GPU is using them. +class IdleWaiter { + public: + virtual ~IdleWaiter() = default; + + /// Wait for the GPU tasks to finish. + /// This is a noop on some platforms, it's important for Vulkan. + virtual void WaitIdle() const = 0; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_IDLE_WAITER_H_ diff --git a/flutter/engine/src/flutter/impeller/core/platform.cc b/flutter/engine/src/flutter/impeller/core/platform.cc new file mode 100644 index 0000000000000000000000000000000000000000..66a8115092b8941e6ae7a990f82dd155bae8ca61 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/platform.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/platform.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/core/platform.h b/flutter/engine/src/flutter/impeller/core/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..ef63ca38a37dd6c6c14f9b10d2fd2b0641d71ce5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/platform.h @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_CORE_PLATFORM_H_ +#define FLUTTER_IMPELLER_CORE_PLATFORM_H_ + +#include + +#include "flutter/fml/build_config.h" + +namespace impeller { + +constexpr size_t DefaultUniformAlignment() { +#if FML_OS_IOS && !TARGET_OS_SIMULATOR + return 16u; +#else + return 256u; +#endif +} + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_CORE_PLATFORM_H_ diff --git a/flutter/engine/src/flutter/impeller/core/range.cc b/flutter/engine/src/flutter/impeller/core/range.cc new file mode 100644 index 0000000000000000000000000000000000000000..336f08bf3c1832e04f6385bbffe42a4917e1650f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/core/range.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/core/range.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.cc b/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.cc new file mode 100644 index 0000000000000000000000000000000000000000..d6b38635500ed5966cab99694ba9c5b8f595ac6e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.cc @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/display_list/testing/render_text_in_canvas.h" + +#include "flutter/testing/testing.h" +#include "txt/platform.h" + +namespace flutter { +namespace testing { + +bool RenderTextInCanvasSkia(DlCanvas* canvas, + const std::string& text, + const std::string_view& font_fixture, + DlPoint position, + const TextRenderOptions& options) { + auto c_font_fixture = std::string(font_fixture); + auto mapping = flutter::testing::OpenFixtureAsSkData(c_font_fixture.c_str()); + if (!mapping) { + return false; + } + sk_sp font_mgr = txt::GetDefaultFontManager(); + SkFont sk_font(font_mgr->makeFromData(mapping), options.font_size); + if (options.is_subpixel) { + sk_font.setSubpixel(true); + } + auto blob = SkTextBlob::MakeFromString(text.c_str(), sk_font); + if (!blob) { + return false; + } + + auto frame = impeller::MakeTextFrameFromTextBlobSkia(blob); + + DlPaint text_paint; + text_paint.setColor(options.color); + text_paint.setMaskFilter(options.mask_filter); + // text_paint.mask_blur_descriptor = options.mask_blur_descriptor; + // text_paint.stroke_width = 1; + // text_paint.style = + // options.stroke ? Paint::Style::kStroke : Paint::Style::kFill; + canvas->DrawTextFrame(frame, position.x, position.y, text_paint); + return true; +} +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.h b/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.h new file mode 100644 index 0000000000000000000000000000000000000000..e7493564b7bb8e7c02f5dfa2d15e0392d5c42d11 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/display_list/testing/render_text_in_canvas.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RENDER_TEXT_IN_CANVAS_H_ +#define FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RENDER_TEXT_IN_CANVAS_H_ + +#include + +#include "flutter/display_list/dl_canvas.h" +#include "flutter/display_list/dl_color.h" +#include "flutter/display_list/effects/dl_mask_filter.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" + +namespace flutter { +namespace testing { + +struct TextRenderOptions { + bool stroke = false; + SkScalar font_size = 50; + DlColor color = DlColor::kYellow(); + std::shared_ptr mask_filter; + bool is_subpixel = false; +}; + +bool RenderTextInCanvasSkia(DlCanvas* canvas, + const std::string& text, + const std::string_view& font_fixture, + DlPoint position, + const TextRenderOptions& options = {}); + +} // namespace testing +} // namespace flutter + +#endif // FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RENDER_TEXT_IN_CANVAS_H_ diff --git a/flutter/engine/src/flutter/impeller/display_list/testing/rmse.cc b/flutter/engine/src/flutter/impeller/display_list/testing/rmse.cc new file mode 100644 index 0000000000000000000000000000000000000000..be4d7d285a5bd3ea37a248f1140778beb22c0fcf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/display_list/testing/rmse.cc @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/display_list/testing/rmse.h" + +#include +#include "flutter/fml/logging.h" + +namespace flutter { +namespace testing { +namespace { +double CalculateDistance(const uint8_t* left, const uint8_t* right) { + double diff[4] = { + static_cast(left[0]) - right[0], // + static_cast(left[1]) - right[1], // + static_cast(left[2]) - right[2], // + static_cast(left[3]) - right[3] // + }; + return sqrt((diff[0] * diff[0]) + // + (diff[1] * diff[1]) + // + (diff[2] * diff[2]) + // + (diff[3] * diff[3])); +} +} // namespace + +double RMSE(const impeller::testing::Screenshot* left, + const impeller::testing::Screenshot* right) { + FML_CHECK(left); + FML_CHECK(right); + FML_CHECK(left->GetWidth() == right->GetWidth()); + FML_CHECK(left->GetHeight() == right->GetHeight()); + + int64_t samples = left->GetWidth() * left->GetHeight(); + double tally = 0; + + const uint8_t* left_ptr = left->GetBytes(); + const uint8_t* right_ptr = right->GetBytes(); + for (int64_t i = 0; i < samples; ++i, left_ptr += 4, right_ptr += 4) { + double distance = CalculateDistance(left_ptr, right_ptr); + tally += distance * distance; + } + + return sqrt(tally / static_cast(samples)); +} + +} // namespace testing +} // namespace flutter diff --git a/flutter/engine/src/flutter/impeller/display_list/testing/rmse.h b/flutter/engine/src/flutter/impeller/display_list/testing/rmse.h new file mode 100644 index 0000000000000000000000000000000000000000..aadb8302d859071bb6d4221ad1a5a32a11ed378b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/display_list/testing/rmse.h @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RMSE_H_ +#define FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RMSE_H_ + +#include "flutter/impeller/golden_tests/screenshot.h" + +namespace flutter { +namespace testing { +double RMSE(const impeller::testing::Screenshot* left, + const impeller::testing::Screenshot* right); +} +} // namespace flutter +#endif // FLUTTER_IMPELLER_DISPLAY_LIST_TESTING_RMSE_H_ diff --git a/flutter/engine/src/flutter/impeller/docs/assets/README.md b/flutter/engine/src/flutter/impeller/docs/assets/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1bd11fa1c2c7088f845bceec5ae10093feaa4c0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/docs/assets/README.md @@ -0,0 +1 @@ +Assets should be added [here](https://github.com/flutter/assets-for-api-docs/tree/main/assets/engine/impeller) diff --git a/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..f8008f7a8d2675efb842cccdbc99101b1195bf5d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/anonymous_contents.h" + +#include + +namespace impeller { + +std::shared_ptr AnonymousContents::Make(RenderProc render_proc, + CoverageProc coverage_proc) { + return std::shared_ptr( + new AnonymousContents(std::move(render_proc), std::move(coverage_proc))); +} + +AnonymousContents::AnonymousContents(RenderProc render_proc, + CoverageProc coverage_proc) + : render_proc_(std::move(render_proc)), + coverage_proc_(std::move(coverage_proc)) {} + +AnonymousContents::~AnonymousContents() = default; + +bool AnonymousContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + return render_proc_(renderer, entity, pass); +} + +std::optional AnonymousContents::GetCoverage(const Entity& entity) const { + return coverage_proc_(entity); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..97280bbde0e013d5ba7a587eebbd408be6cf074f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/anonymous_contents.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/contents.h" + +namespace impeller { + +class AnonymousContents final : public Contents { + public: + static std::shared_ptr Make(RenderProc render_proc, + CoverageProc coverage_proc); + + // |Contents| + ~AnonymousContents() override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + private: + RenderProc render_proc_; + CoverageProc coverage_proc_; + + AnonymousContents(RenderProc render_proc, CoverageProc coverage_proc); + + AnonymousContents(const AnonymousContents&) = delete; + + AnonymousContents& operator=(const AnonymousContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_ANONYMOUS_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..6bd795a07afd5774ee99eb2a56cc02421d292723 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.cc @@ -0,0 +1,346 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/atlas_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/filters/blend_filter_contents.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/texture_fill.frag.h" +#include "impeller/entity/texture_fill.vert.h" +#include "impeller/geometry/color.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +DrawImageRectAtlasGeometry::DrawImageRectAtlasGeometry( + std::shared_ptr texture, + const Rect& source, + const Rect& destination, + const Color& color, + BlendMode blend_mode, + const SamplerDescriptor& desc) + : texture_(std::move(texture)), + source_(source), + destination_(destination), + color_(color), + blend_mode_(blend_mode), + desc_(desc) {} + +DrawImageRectAtlasGeometry::~DrawImageRectAtlasGeometry() = default; + +bool DrawImageRectAtlasGeometry::ShouldUseBlend() const { + return true; +} + +bool DrawImageRectAtlasGeometry::ShouldSkip() const { + return false; +} + +VertexBuffer DrawImageRectAtlasGeometry::CreateSimpleVertexBuffer( + HostBuffer& host_buffer) const { + using VS = TextureFillVertexShader; + constexpr size_t indices[6] = {0, 1, 2, 1, 2, 3}; + + BufferView buffer_view = host_buffer.Emplace( + sizeof(VS::PerVertexData) * 6, alignof(VS::PerVertexData), + [&](uint8_t* raw_data) { + VS::PerVertexData* data = + reinterpret_cast(raw_data); + int offset = 0; + std::array, 4> destination_points = + destination_.GetPoints(); + std::array, 4> texture_coords = + Rect::MakeSize(texture_->GetSize()).Project(source_).GetPoints(); + for (size_t j = 0; j < 6; j++) { + data[offset].position = destination_points[indices[j]]; + data[offset].texture_coords = texture_coords[indices[j]]; + offset++; + } + }); + + return VertexBuffer{ + .vertex_buffer = buffer_view, + .index_buffer = {}, + .vertex_count = 6, + .index_type = IndexType::kNone, + }; +} + +VertexBuffer DrawImageRectAtlasGeometry::CreateBlendVertexBuffer( + HostBuffer& host_buffer) const { + using VS = PorterDuffBlendVertexShader; + constexpr size_t indices[6] = {0, 1, 2, 1, 2, 3}; + + BufferView buffer_view = host_buffer.Emplace( + sizeof(VS::PerVertexData) * 6, alignof(VS::PerVertexData), + [&](uint8_t* raw_data) { + VS::PerVertexData* data = + reinterpret_cast(raw_data); + int offset = 0; + std::array, 4> texture_coords = + Rect::MakeSize(texture_->GetSize()).Project(source_).GetPoints(); + std::array, 4> destination_points = + destination_.GetPoints(); + for (size_t j = 0; j < 6; j++) { + data[offset].vertices = destination_points[indices[j]]; + data[offset].texture_coords = texture_coords[indices[j]]; + data[offset].color = color_.Premultiply(); + offset++; + } + }); + + return VertexBuffer{ + .vertex_buffer = buffer_view, + .index_buffer = {}, + .vertex_count = 6, + .index_type = IndexType::kNone, + }; +} + +Rect DrawImageRectAtlasGeometry::ComputeBoundingBox() const { + return destination_; +} + +const std::shared_ptr& DrawImageRectAtlasGeometry::GetAtlas() const { + return texture_; +} + +const SamplerDescriptor& DrawImageRectAtlasGeometry::GetSamplerDescriptor() + const { + return desc_; +} + +BlendMode DrawImageRectAtlasGeometry::GetBlendMode() const { + return blend_mode_; +} + +bool DrawImageRectAtlasGeometry::ShouldInvertBlendMode() const { + return false; +} + +//// + +AtlasContents::AtlasContents() = default; + +AtlasContents::~AtlasContents() = default; + +std::optional AtlasContents::GetCoverage(const Entity& entity) const { + if (!geometry_) { + return std::nullopt; + } + return geometry_->ComputeBoundingBox().TransformBounds(entity.GetTransform()); +} + +void AtlasContents::SetGeometry(AtlasGeometry* geometry) { + geometry_ = geometry; +} + +void AtlasContents::SetAlpha(Scalar alpha) { + alpha_ = alpha; +} + +bool AtlasContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (geometry_->ShouldSkip() || alpha_ <= 0.0) { + return true; + } + + const SamplerDescriptor& dst_sampler_descriptor = + geometry_->GetSamplerDescriptor(); + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_sampler_descriptor); + + auto& host_buffer = renderer.GetTransientsBuffer(); + if (!geometry_->ShouldUseBlend()) { + using VS = TextureFillVertexShader; + using FS = TextureFillFragmentShader; + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_sampler_descriptor); + + auto pipeline_options = OptionsFromPassAndEntity(pass, entity); + pipeline_options.primitive_type = PrimitiveType::kTriangle; + pipeline_options.depth_write_enabled = + pipeline_options.blend_mode == BlendMode::kSrc; + + pass.SetPipeline(renderer.GetTexturePipeline(pipeline_options)); + pass.SetVertexBuffer(geometry_->CreateSimpleVertexBuffer(host_buffer)); +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("DrawAtlas"); +#endif // IMPELLER_DEBUG + + VS::FrameInfo frame_info; + frame_info.mvp = entity.GetShaderTransform(pass); + frame_info.texture_sampler_y_coord_scale = + geometry_->GetAtlas()->GetYCoordScale(); + + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + FS::FragInfo frag_info; + frag_info.alpha = alpha_; + FS::BindFragInfo(pass, host_buffer.EmplaceUniform((frag_info))); + FS::BindTextureSampler(pass, geometry_->GetAtlas(), dst_sampler); + return pass.Draw().ok(); + } + + BlendMode blend_mode = geometry_->GetBlendMode(); + + if (blend_mode <= BlendMode::kModulate) { + using VS = PorterDuffBlendPipeline::VertexShader; + using FS = PorterDuffBlendPipeline::FragmentShader; + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("DrawAtlas Blend"); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(geometry_->CreateBlendVertexBuffer(host_buffer)); + BlendMode inverted_blend_mode = + geometry_->ShouldInvertBlendMode() + ? (InvertPorterDuffBlend(blend_mode).value_or(BlendMode::kSrc)) + : blend_mode; + pass.SetPipeline(renderer.GetPorterDuffPipeline( + inverted_blend_mode, OptionsFromPassAndEntity(pass, entity))); + + FS::FragInfo frag_info; + VS::FrameInfo frame_info; + + FS::BindTextureSamplerDst(pass, geometry_->GetAtlas(), dst_sampler); + frame_info.texture_sampler_y_coord_scale = + geometry_->GetAtlas()->GetYCoordScale(); + + frag_info.output_alpha = alpha_; + frag_info.input_alpha = 1.0; + + // These values are ignored on platforms that natively support decal. + frag_info.tmx = static_cast(Entity::TileMode::kDecal); + frag_info.tmy = static_cast(Entity::TileMode::kDecal); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + frame_info.mvp = entity.GetShaderTransform(pass); + + auto uniform_view = host_buffer.EmplaceUniform(frame_info); + VS::BindFrameInfo(pass, uniform_view); + + return pass.Draw().ok(); + } + + using VUS = VerticesUber1Shader::VertexShader; + using FS = VerticesUber1Shader::FragmentShader; + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("DrawAtlas Advanced Blend"); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(geometry_->CreateBlendVertexBuffer(host_buffer)); + + renderer.GetDrawVerticesUberPipeline(blend_mode, + OptionsFromPassAndEntity(pass, entity)); + FS::BindTextureSampler(pass, geometry_->GetAtlas(), dst_sampler); + + VUS::FrameInfo frame_info; + FS::FragInfo frag_info; + + frame_info.texture_sampler_y_coord_scale = + geometry_->GetAtlas()->GetYCoordScale(); + frame_info.mvp = entity.GetShaderTransform(pass); + + frag_info.alpha = alpha_; + frag_info.blend_mode = static_cast(blend_mode); + + // These values are ignored on platforms that natively support decal. + frag_info.tmx = static_cast(Entity::TileMode::kDecal); + frag_info.tmy = static_cast(Entity::TileMode::kDecal); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VUS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); +} + +/////////////// + +ColorFilterAtlasContents::ColorFilterAtlasContents() = default; + +ColorFilterAtlasContents::~ColorFilterAtlasContents() = default; + +std::optional ColorFilterAtlasContents::GetCoverage( + const Entity& entity) const { + if (!geometry_) { + return std::nullopt; + } + return geometry_->ComputeBoundingBox().TransformBounds(entity.GetTransform()); +} + +void ColorFilterAtlasContents::SetGeometry(AtlasGeometry* geometry) { + geometry_ = geometry; +} + +void ColorFilterAtlasContents::SetAlpha(Scalar alpha) { + alpha_ = alpha; +} + +void ColorFilterAtlasContents::SetMatrix(ColorMatrix matrix) { + matrix_ = matrix; +} + +bool ColorFilterAtlasContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (geometry_->ShouldSkip() || alpha_ <= 0.0) { + return true; + } + + const SamplerDescriptor& dst_sampler_descriptor = + geometry_->GetSamplerDescriptor(); + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_sampler_descriptor); + + auto& host_buffer = renderer.GetTransientsBuffer(); + + using VS = ColorMatrixColorFilterPipeline::VertexShader; + using FS = ColorMatrixColorFilterPipeline::FragmentShader; + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("Atlas ColorFilter"); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(geometry_->CreateSimpleVertexBuffer(host_buffer)); + pass.SetPipeline( + renderer.GetColorMatrixColorFilterPipeline(OptionsFromPass(pass))); + + FS::FragInfo frag_info; + VS::FrameInfo frame_info; + + FS::BindInputTexture(pass, geometry_->GetAtlas(), dst_sampler); + frame_info.texture_sampler_y_coord_scale = + geometry_->GetAtlas()->GetYCoordScale(); + + frag_info.input_alpha = 1; + frag_info.output_alpha = alpha_; + const float* matrix = matrix_.array; + frag_info.color_v = Vector4(matrix[4], matrix[9], matrix[14], matrix[19]); + frag_info.color_m = Matrix(matrix[0], matrix[5], matrix[10], matrix[15], // + matrix[1], matrix[6], matrix[11], matrix[16], // + matrix[2], matrix[7], matrix[12], matrix[17], // + matrix[3], matrix[8], matrix[13], matrix[18] // + ); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + frame_info.mvp = entity.GetShaderTransform(pass); + + auto uniform_view = host_buffer.EmplaceUniform(frame_info); + VS::BindFrameInfo(pass, uniform_view); + + return pass.Draw().ok(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..f34c85f407ca39c7314ea6a37229ced97fd712d1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/atlas_contents.h @@ -0,0 +1,145 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_ATLAS_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_ATLAS_CONTENTS_H_ + +#include + +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +// Interface wrapper to allow usage of DL pointer data without copying (or +// circular imports). +class AtlasGeometry { + public: + virtual bool ShouldUseBlend() const = 0; + + virtual bool ShouldSkip() const = 0; + + virtual VertexBuffer CreateSimpleVertexBuffer( + HostBuffer& host_buffer) const = 0; + + virtual VertexBuffer CreateBlendVertexBuffer( + HostBuffer& host_buffer) const = 0; + + virtual Rect ComputeBoundingBox() const = 0; + + virtual const std::shared_ptr& GetAtlas() const = 0; + + virtual const SamplerDescriptor& GetSamplerDescriptor() const = 0; + + virtual BlendMode GetBlendMode() const = 0; + + virtual bool ShouldInvertBlendMode() const { return true; } +}; + +/// @brief An atlas geometry that adapts for drawImageRect. +class DrawImageRectAtlasGeometry : public AtlasGeometry { + public: + DrawImageRectAtlasGeometry(std::shared_ptr texture, + const Rect& source, + const Rect& destination, + const Color& color, + BlendMode blend_mode, + const SamplerDescriptor& desc); + + ~DrawImageRectAtlasGeometry(); + + bool ShouldUseBlend() const override; + + bool ShouldSkip() const override; + + VertexBuffer CreateSimpleVertexBuffer(HostBuffer& host_buffer) const override; + + VertexBuffer CreateBlendVertexBuffer(HostBuffer& host_buffer) const override; + + Rect ComputeBoundingBox() const override; + + const std::shared_ptr& GetAtlas() const override; + + const SamplerDescriptor& GetSamplerDescriptor() const override; + + BlendMode GetBlendMode() const override; + + bool ShouldInvertBlendMode() const override; + + private: + const std::shared_ptr texture_; + const Rect source_; + const Rect destination_; + const Color color_; + const BlendMode blend_mode_; + const SamplerDescriptor desc_; +}; + +class AtlasContents final : public Contents { + public: + explicit AtlasContents(); + + ~AtlasContents() override; + + void SetGeometry(AtlasGeometry* geometry); + + void SetAlpha(Scalar alpha); + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + private: + AtlasGeometry* geometry_ = nullptr; + Scalar alpha_ = 1.0; + + AtlasContents(const AtlasContents&) = delete; + + AtlasContents& operator=(const AtlasContents&) = delete; +}; + +/// A specialized atlas class for applying a color matrix filter to a +/// drawImageRect call. +class ColorFilterAtlasContents final : public Contents { + public: + explicit ColorFilterAtlasContents(); + + ~ColorFilterAtlasContents() override; + + void SetGeometry(AtlasGeometry* geometry); + + void SetAlpha(Scalar alpha); + + void SetMatrix(ColorMatrix matrix); + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + private: + // These contents are created temporarily on the stack and never stored. + // The referenced geometry is also stack allocated and will be de-allocated + // after the contents are. + AtlasGeometry* geometry_ = nullptr; + ColorMatrix matrix_; + Scalar alpha_ = 1.0; + + ColorFilterAtlasContents(const ColorFilterAtlasContents&) = delete; + + ColorFilterAtlasContents& operator=(const ColorFilterAtlasContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_ATLAS_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..c778bec336c7ba47b994d026abf37ab462b2b073 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.cc @@ -0,0 +1,191 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "fml/logging.h" +#include "impeller/core/formats.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/entity.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +static Scalar GetShaderClipDepth(uint32_t clip_depth) { + // Draw the clip at the max of the clip entity's depth slice, so that other + // draw calls with this same depth value will be culled even if they have a + // perspective transform. + return std::nextafterf(Entity::GetShaderClipDepth(clip_depth + 1), 0.0f); +} + +/******************************************************************************* + ******* ClipContents + ******************************************************************************/ + +ClipContents::ClipContents(Rect coverage_rect, bool is_axis_aligned_rect) + : coverage_rect_(coverage_rect), + is_axis_aligned_rect_(is_axis_aligned_rect) {} + +ClipContents::~ClipContents() = default; + +void ClipContents::SetGeometry(GeometryResult clip_geometry) { + clip_geometry_ = std::move(clip_geometry); +} + +void ClipContents::SetClipOperation(Entity::ClipOperation clip_op) { + clip_op_ = clip_op; +} + +ClipCoverage ClipContents::GetClipCoverage( + const std::optional& current_clip_coverage) const { + if (!current_clip_coverage.has_value()) { + return {.coverage = std::nullopt}; + } + switch (clip_op_) { + case Entity::ClipOperation::kDifference: + // This can be optimized further by considering cases when the bounds of + // the current stencil will shrink. + return { + .is_difference_or_non_square = true, // + .coverage = current_clip_coverage // + }; + case Entity::ClipOperation::kIntersect: + if (coverage_rect_.IsEmpty() || !current_clip_coverage.has_value()) { + return {.coverage = std::nullopt}; + } + return { + .is_difference_or_non_square = !is_axis_aligned_rect_, // + .coverage = current_clip_coverage->Intersection(coverage_rect_), // + }; + } + FML_UNREACHABLE(); +} + +bool ClipContents::Render(const ContentContext& renderer, + RenderPass& pass, + uint32_t clip_depth) const { + if (!clip_geometry_.vertex_buffer) { + return true; + } + + using VS = ClipPipeline::VertexShader; + + VS::FrameInfo info; + info.depth = GetShaderClipDepth(clip_depth); + + auto options = OptionsFromPass(pass); + options.blend_mode = BlendMode::kDst; + + pass.SetStencilReference(0); + + /// Stencil preparation draw. + + options.depth_write_enabled = false; + options.primitive_type = clip_geometry_.type; + pass.SetVertexBuffer(clip_geometry_.vertex_buffer); + switch (clip_geometry_.mode) { + case GeometryResult::Mode::kNonZero: + pass.SetCommandLabel("Clip stencil preparation (NonZero)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kStencilNonZeroFill; + break; + case GeometryResult::Mode::kEvenOdd: + pass.SetCommandLabel("Clip stencil preparation (EvenOdd)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kStencilEvenOddFill; + break; + case GeometryResult::Mode::kNormal: + case GeometryResult::Mode::kPreventOverdraw: + pass.SetCommandLabel("Clip stencil preparation (Increment)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kOverdrawPreventionIncrement; + break; + } + pass.SetPipeline(renderer.GetClipPipeline(options)); + + info.mvp = clip_geometry_.transform; + VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info)); + + if (!pass.Draw().ok()) { + return false; + } + + /// Write depth. + + options.depth_write_enabled = true; + options.primitive_type = PrimitiveType::kTriangleStrip; + Rect cover_area; + switch (clip_op_) { + case Entity::ClipOperation::kIntersect: + pass.SetCommandLabel("Intersect Clip"); + options.stencil_mode = + ContentContextOptions::StencilMode::kCoverCompareInverted; + cover_area = Rect::MakeSize(pass.GetRenderTargetSize()); + break; + case Entity::ClipOperation::kDifference: + pass.SetCommandLabel("Difference Clip"); + options.stencil_mode = ContentContextOptions::StencilMode::kCoverCompare; + cover_area = coverage_rect_; + break; + } + auto points = cover_area.GetPoints(); + pass.SetVertexBuffer( + CreateVertexBuffer(points, renderer.GetTransientsBuffer())); + + pass.SetPipeline(renderer.GetClipPipeline(options)); + + info.mvp = pass.GetOrthographicTransform(); + VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info)); + + return pass.Draw().ok(); +} + +/******************************************************************************* + ******* ClipRestoreContents + ******************************************************************************/ + +bool RenderClipRestore(const ContentContext& renderer, + RenderPass& pass, + uint32_t clip_depth, + std::optional restore_coverage) { + using VS = ClipPipeline::VertexShader; + + pass.SetCommandLabel("Restore Clip"); + auto options = OptionsFromPass(pass); + options.blend_mode = BlendMode::kDst; + options.stencil_mode = + ContentContextOptions::StencilMode::kOverdrawPreventionRestore; + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetClipPipeline(options)); + pass.SetStencilReference(0); + + // Create a rect that covers either the given restore area, or the whole + // render target texture. + auto ltrb = + restore_coverage.value_or(Rect::MakeSize(pass.GetRenderTargetSize())) + .GetLTRB(); + + std::array vertices = { + VS::PerVertexData{Point(ltrb[0], ltrb[1])}, + VS::PerVertexData{Point(ltrb[2], ltrb[1])}, + VS::PerVertexData{Point(ltrb[0], ltrb[3])}, + VS::PerVertexData{Point(ltrb[2], ltrb[3])}, + }; + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::FrameInfo info; + info.depth = GetShaderClipDepth(clip_depth); + info.mvp = pass.GetOrthographicTransform(); + VS::BindFrameInfo(pass, renderer.GetTransientsBuffer().EmplaceUniform(info)); + + return pass.Draw().ok(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..8690bcb6571538eaa38b8574567566861170841c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/clip_contents.h @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_ + +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +struct ClipCoverage { + // TODO(jonahwilliams): this should probably use the Entity::ClipOperation + // enum, but that has transitive import errors. + bool is_difference_or_non_square = false; + + /// @brief This coverage is the outer coverage of the clip. + /// + /// For example, if the clip is a circular clip, this is the rectangle that + /// contains the circle and not the rectangle that is contained within the + /// circle. This means that we cannot use the coverage alone to determine if + /// a clip can be culled, and instead also use the somewhat hacky + /// "is_difference_or_non_square" field. + std::optional coverage = std::nullopt; +}; + +class ClipContents { + public: + ClipContents(Rect coverage_rect, bool is_axis_aligned_rect); + + ~ClipContents(); + + /// @brief Set the pre-tessellated clip geometry. + void SetGeometry(GeometryResult geometry); + + void SetClipOperation(Entity::ClipOperation clip_op); + + //---------------------------------------------------------------------------- + /// @brief Given the current pass space bounding rectangle of the clip + /// buffer, return the expected clip coverage after this draw call. + /// This should only be implemented for contents that may write to the + /// clip buffer. + /// + /// During rendering, coverage coordinates count pixels from the top + /// left corner of the framebuffer. + /// + ClipCoverage GetClipCoverage( + const std::optional& current_clip_coverage) const; + + bool Render(const ContentContext& renderer, + RenderPass& pass, + uint32_t clip_depth) const; + + private: + // Pre-tessellated clip geometry. + GeometryResult clip_geometry_; + // Coverage rect of the tessellated geometry. + Rect coverage_rect_; + bool is_axis_aligned_rect_ = false; + Entity::ClipOperation clip_op_ = Entity::ClipOperation::kIntersect; +}; + +/// @brief Render a restore clip. +/// +/// This is is intended to be used for prevent overdraw mechanism. The clip +/// depth should be the depth of the entity that is currently being drawn, and +/// restore_coverage should be its coverage. If restore_coverage is +/// std::nullopt, the render pass coverage is used instead. +bool RenderClipRestore(const ContentContext& renderer, + RenderPass& pass, + uint32_t clip_depth, + std::optional restore_coverage); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CLIP_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..8d42add0a92065e3f700911cb16a326e3e15e2e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.cc @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/color_source_contents.h" + +#include "impeller/entity/entity.h" +#include "impeller/geometry/matrix.h" + +namespace impeller { + +ColorSourceContents::ColorSourceContents() = default; + +ColorSourceContents::~ColorSourceContents() = default; + +void ColorSourceContents::SetGeometry(const Geometry* geometry) { + geometry_ = geometry; +} + +const Geometry* ColorSourceContents::GetGeometry() const { + return geometry_; +} + +void ColorSourceContents::SetOpacityFactor(Scalar alpha) { + opacity_ = alpha; +} + +Scalar ColorSourceContents::GetOpacityFactor() const { + return opacity_ * inherited_opacity_; +} + +void ColorSourceContents::SetEffectTransform(Matrix matrix) { + inverse_matrix_ = matrix.Invert(); +} + +const Matrix& ColorSourceContents::GetInverseEffectTransform() const { + return inverse_matrix_; +} + +bool ColorSourceContents::IsSolidColor() const { + return false; +} + +std::optional ColorSourceContents::GetCoverage( + const Entity& entity) const { + return geometry_->GetCoverage(entity.GetTransform()); +}; + +void ColorSourceContents::SetInheritedOpacity(Scalar opacity) { + inherited_opacity_ = opacity; +} + +bool ColorSourceContents::AppliesAlphaForStrokeCoverage( + const Matrix& transform) const { + return GetGeometry() && GetGeometry()->ComputeAlphaCoverage(transform) < 1.0; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..d43b291a05026cbe25e826487a7578ef73e5b848 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/color_source_contents.h @@ -0,0 +1,307 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_ + +#include "fml/logging.h" +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/entity/geometry/rect_geometry.h" +#include "impeller/geometry/matrix.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// Color sources are geometry-ignostic `Contents` capable of shading any area +/// defined by an `impeller::Geometry`. Conceptually, +/// `impeller::ColorSourceContents` implement a particular color shading +/// behavior. +/// +/// This separation of concerns between geometry and color source output allows +/// Impeller to handle most possible draw combinations in a consistent way. +/// For example: There are color sources for handling solid colors, gradients, +/// textures, custom runtime effects, and even 3D scenes. +/// +/// There are some special rendering exceptions that deviate from this pattern +/// and cross geometry and color source concerns, such as text atlas and image +/// atlas rendering. Special `Contents` exist for rendering these behaviors +/// which don't implement `ColorSourceContents`. +/// +/// @see `impeller::Geometry` +/// +class ColorSourceContents : public Contents { + public: + using BindFragmentCallback = std::function; + using PipelineBuilderCallback = + std::function; + using CreateGeometryCallback = + std::function; + + ColorSourceContents(); + + ~ColorSourceContents() override; + + //---------------------------------------------------------------------------- + /// @brief Set the geometry that this contents will use to render. + /// + void SetGeometry(const Geometry* geometry); + + //---------------------------------------------------------------------------- + /// @brief Get the geometry that this contents will use to render. + /// + const Geometry* GetGeometry() const; + + //---------------------------------------------------------------------------- + /// @brief Set the effect transform for this color source. + /// + /// The effect transform is a transform matrix that is applied to + /// the shaded color output and does not impact geometry in any way. + /// + /// For example: With repeat tiling, any gradient or + /// `TiledTextureContents` could be used with an effect transform to + /// inexpensively draw an infinite scrolling background pattern. + /// + void SetEffectTransform(Matrix matrix); + + //---------------------------------------------------------------------------- + /// @brief Set the inverted effect transform for this color source. + /// + /// When the effect transform is set via `SetEffectTransform`, the + /// value is inverted upon storage. The reason for this is that most + /// color sources internally use the inverted transform. + /// + /// @return The inverse of the transform set by `SetEffectTransform`. + /// + /// @see `SetEffectTransform` + /// + const Matrix& GetInverseEffectTransform() const; + + //---------------------------------------------------------------------------- + /// @brief Set the opacity factor for this color source. + /// + void SetOpacityFactor(Scalar opacity); + + //---------------------------------------------------------------------------- + /// @brief Get the opacity factor for this color source. + /// + /// This value is is factored into the output of the color source in + /// addition to opacity information that may be supplied any other + /// inputs. + /// + /// @note If set, the output of this method factors factors in the inherited + /// opacity of this `Contents`. + Scalar GetOpacityFactor() const; + + virtual bool IsSolidColor() const; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + void SetInheritedOpacity(Scalar opacity) override; + + template + static bool DrawGeometry(const Contents* contents, + const Geometry* geometry, + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass, + const PipelineBuilderCallback& pipeline_callback, + typename VertexShaderT::FrameInfo frame_info, + const BindFragmentCallback& bind_fragment_callback, + bool force_stencil = false, + const CreateGeometryCallback& create_geom_callback = + DefaultCreateGeometryCallback) { + auto options = OptionsFromPassAndEntity(pass, entity); + + GeometryResult::Mode geometry_mode = geometry->GetResultMode(); + bool do_cover_draw = false; + Rect cover_area = {}; + + bool is_stencil_then_cover = + geometry_mode == GeometryResult::Mode::kNonZero || + geometry_mode == GeometryResult::Mode::kEvenOdd; + if (!is_stencil_then_cover && force_stencil) { + geometry_mode = GeometryResult::Mode::kNonZero; + is_stencil_then_cover = true; + } + + if (is_stencil_then_cover) { + pass.SetStencilReference(0); + + /// Stencil preparation draw. + + GeometryResult stencil_geometry_result = + geometry->GetPositionBuffer(renderer, entity, pass); + if (stencil_geometry_result.vertex_buffer.vertex_count == 0u) { + return true; + } + pass.SetVertexBuffer(std::move(stencil_geometry_result.vertex_buffer)); + options.primitive_type = stencil_geometry_result.type; + + options.blend_mode = BlendMode::kDst; + switch (stencil_geometry_result.mode) { + case GeometryResult::Mode::kNonZero: + pass.SetCommandLabel("Stencil preparation (NonZero)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kStencilNonZeroFill; + break; + case GeometryResult::Mode::kEvenOdd: + pass.SetCommandLabel("Stencil preparation (EvenOdd)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kStencilEvenOddFill; + break; + default: + if (force_stencil) { + pass.SetCommandLabel("Stencil preparation (NonZero)"); + options.stencil_mode = + ContentContextOptions::StencilMode::kStencilNonZeroFill; + break; + } + FML_UNREACHABLE(); + } + pass.SetPipeline(renderer.GetClipPipeline(options)); + ClipPipeline::VertexShader::FrameInfo clip_frame_info; + clip_frame_info.depth = entity.GetShaderClipDepth(); + clip_frame_info.mvp = stencil_geometry_result.transform; + ClipPipeline::VertexShader::BindFrameInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(clip_frame_info)); + + if (!pass.Draw().ok()) { + return false; + } + + /// Cover draw. + + options.blend_mode = entity.GetBlendMode(); + options.stencil_mode = ContentContextOptions::StencilMode::kCoverCompare; + std::optional maybe_cover_area = geometry->GetCoverage({}); + if (!maybe_cover_area.has_value()) { + return true; + } + do_cover_draw = true; + cover_area = maybe_cover_area.value(); + } + + GeometryResult geometry_result; + if (do_cover_draw) { + RectGeometry geom(cover_area); + geometry_result = create_geom_callback(renderer, entity, pass, &geom); + } else { + geometry_result = create_geom_callback(renderer, entity, pass, geometry); + } + + if (geometry_result.vertex_buffer.vertex_count == 0u) { + return true; + } + pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer)); + options.primitive_type = geometry_result.type; + + // Enable depth writing for all opaque entities in order to allow + // reordering. Opaque entities are coerced to source blending by + // `EntityPass::AddEntity`. + options.depth_write_enabled = options.blend_mode == BlendMode::kSrc; + + // Take the pre-populated vertex shader uniform struct and set managed + // values. + frame_info.mvp = geometry_result.transform; + + // If overdraw prevention is enabled (like when drawing stroke paths), we + // increment the stencil buffer as we draw, preventing overlapping fragments + // from drawing. Afterwards, we need to append another draw call to clean up + // the stencil buffer (happens below in this method). This can be skipped + // for draws that are fully opaque or use src blend mode. + if (geometry_result.mode == GeometryResult::Mode::kPreventOverdraw && + options.blend_mode != BlendMode::kSrc) { + options.stencil_mode = + ContentContextOptions::StencilMode::kOverdrawPreventionIncrement; + } + pass.SetStencilReference(0); + + VertexShaderT::BindFrameInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); + + // The reason we need to have a callback mechanism here is that this routine + // may insert draw calls before the main draw call below. For example, for + // sufficiently complex paths we may opt to use stencil-then-cover to avoid + // tessellation. + if (!bind_fragment_callback(pass)) { + return false; + } + + pass.SetPipeline(pipeline_callback(options)); + + if (!pass.Draw().ok()) { + return false; + } + + // If we performed overdraw prevention, a subsection of the clip heightmap + // was incremented by 1 in order to self-clip. So simply append a clip + // restore to clean it up. + if (geometry_result.mode == GeometryResult::Mode::kPreventOverdraw && + options.blend_mode != BlendMode::kSrc) { + return RenderClipRestore(renderer, pass, entity.GetClipDepth(), + contents->GetCoverage(entity)); + } + return true; + } + + protected: + static GeometryResult DefaultCreateGeometryCallback( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass, + const Geometry* geom) { + return geom->GetPositionBuffer(renderer, entity, pass); + } + + /// @brief Whether the entity should be treated as non-opaque due to stroke + /// geometry requiring alpha for coverage. + bool AppliesAlphaForStrokeCoverage(const Matrix& transform) const; + + template + bool DrawGeometry(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass, + const PipelineBuilderCallback& pipeline_callback, + typename VertexShaderT::FrameInfo frame_info, + const BindFragmentCallback& bind_fragment_callback, + bool force_stencil = false, + const CreateGeometryCallback& create_geom_callback = + DefaultCreateGeometryCallback) const { + // + return DrawGeometry(this, // + GetGeometry(), // + renderer, // + entity, // + pass, // + pipeline_callback, // + frame_info, // + bind_fragment_callback, // + force_stencil, // + create_geom_callback); + } + + private: + const Geometry* geometry_ = nullptr; + Matrix inverse_matrix_; + Scalar opacity_ = 1.0; + Scalar inherited_opacity_ = 1.0; + + ColorSourceContents(const ColorSourceContents&) = delete; + + ColorSourceContents& operator=(const ColorSourceContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_COLOR_SOURCE_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..c14fe8eabfbc4ae657a008fe86bac3a6af70b4e0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.cc @@ -0,0 +1,259 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "conical_gradient_contents.h" + +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/gradient_generator.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/gradient.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +namespace { +ConicalKind GetConicalKind(Point center, + Scalar radius, + std::optional focus, + Scalar focus_radius) { + ConicalKind kind = ConicalKind::kConical; + if (!focus.has_value() || + center.GetDistance(focus.value()) < kEhCloseEnough) { + kind = ConicalKind::kRadial; + } + if (focus.has_value() && std::fabsf(radius - focus_radius) < kEhCloseEnough) { + if (kind == ConicalKind::kRadial) { + kind = ConicalKind::kStripAndRadial; + } else { + kind = ConicalKind::kStrip; + } + } + return kind; +} + +} // namespace + +ConicalGradientContents::ConicalGradientContents() = default; + +ConicalGradientContents::~ConicalGradientContents() = default; + +void ConicalGradientContents::SetCenterAndRadius(Point center, Scalar radius) { + center_ = center; + radius_ = radius; +} + +void ConicalGradientContents::SetTileMode(Entity::TileMode tile_mode) { + tile_mode_ = tile_mode; +} + +void ConicalGradientContents::SetColors(std::vector colors) { + colors_ = std::move(colors); +} + +void ConicalGradientContents::SetStops(std::vector stops) { + stops_ = std::move(stops); +} + +const std::vector& ConicalGradientContents::GetColors() const { + return colors_; +} + +const std::vector& ConicalGradientContents::GetStops() const { + return stops_; +} + +void ConicalGradientContents::SetFocus(std::optional focus, + Scalar radius) { + focus_ = focus; + focus_radius_ = radius; +} + +#define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0])) +#define UNIFORM_FRAG_INFO(t) \ + t##GradientUniformFillConicalPipeline::FragmentShader::FragInfo +#define UNIFORM_COLOR_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Conical)::colors) +#define UNIFORM_STOP_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Conical)::stop_pairs) +static_assert(UNIFORM_COLOR_SIZE == kMaxUniformGradientStops); +static_assert(UNIFORM_STOP_SIZE == kMaxUniformGradientStops / 2); + +bool ConicalGradientContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (renderer.GetDeviceCapabilities().SupportsSSBO()) { + return RenderSSBO(renderer, entity, pass); + } + if (colors_.size() <= kMaxUniformGradientStops && + stops_.size() <= kMaxUniformGradientStops) { + return RenderUniform(renderer, entity, pass); + } + return RenderTexture(renderer, entity, pass); +} + +bool ConicalGradientContents::RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = ConicalGradientSSBOFillPipeline::VertexShader; + using FS = ConicalGradientSSBOFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + ConicalKind kind = GetConicalKind(center_, radius_, focus_, focus_radius_); + PipelineBuilderCallback pipeline_callback = + [&renderer, kind](ContentContextOptions options) { + return renderer.GetConicalGradientSSBOFillPipeline(options, kind); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + if (focus_) { + frag_info.focus = focus_.value(); + frag_info.focus_radius = focus_radius_; + } else { + frag_info.focus = center_; + frag_info.focus_radius = 0.0; + } + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto colors = CreateGradientColors(colors_, stops_); + + frag_info.colors_length = colors.size(); + auto color_buffer = + host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData), + DefaultUniformAlignment()); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindColorData(pass, color_buffer); + + pass.SetCommandLabel("ConicalGradientSSBOFill"); + return true; + }); +} + +bool ConicalGradientContents::RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = ConicalGradientUniformFillConicalPipeline::VertexShader; + using FS = ConicalGradientUniformFillConicalPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + ConicalKind kind = GetConicalKind(center_, radius_, focus_, focus_radius_); + PipelineBuilderCallback pipeline_callback = + [&renderer, kind](ContentContextOptions options) { + return renderer.GetConicalGradientUniformFillPipeline(options, kind); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + if (focus_) { + frag_info.focus = focus_.value(); + frag_info.focus_radius = focus_radius_; + } else { + frag_info.focus = center_; + frag_info.focus_radius = 0.0; + } + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.colors_length = PopulateUniformGradientColors( + colors_, stops_, frag_info.colors, frag_info.stop_pairs); + frag_info.decal_border_color = decal_border_color_; + + pass.SetCommandLabel("ConicalGradientUniformFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + + return true; + }); +} + +bool ConicalGradientContents::RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = ConicalGradientFillConicalPipeline::VertexShader; + using FS = ConicalGradientFillConicalPipeline::FragmentShader; + + auto gradient_data = CreateGradientBuffer(colors_, stops_); + auto gradient_texture = + CreateGradientTexture(gradient_data, renderer.GetContext()); + if (gradient_texture == nullptr) { + return false; + } + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + ConicalKind kind = GetConicalKind(center_, radius_, focus_, focus_radius_); + PipelineBuilderCallback pipeline_callback = + [&renderer, kind](ContentContextOptions options) { + return renderer.GetConicalGradientFillPipeline(options, kind); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &gradient_texture, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.texture_sampler_y_coord_scale = + gradient_texture->GetYCoordScale(); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.half_texel = + Vector2(0.5 / gradient_texture->GetSize().width, + 0.5 / gradient_texture->GetSize().height); + if (focus_) { + frag_info.focus = focus_.value(); + frag_info.focus_radius = focus_radius_; + } else { + frag_info.focus = center_; + frag_info.focus_radius = 0.0; + } + + pass.SetCommandLabel("ConicalGradientFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + FS::BindTextureSampler( + pass, gradient_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc)); + + return true; + }); +} + +bool ConicalGradientContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + for (Color& color : colors_) { + color = color_filter_proc(color); + } + decal_border_color_ = color_filter_proc(decal_border_color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..1174722385c04866faa20210f4962c6c025d4268 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/conical_gradient_contents.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" + +namespace impeller { + +class ConicalGradientContents final : public ColorSourceContents { + public: + ConicalGradientContents(); + + ~ConicalGradientContents() override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + void SetCenterAndRadius(Point center, Scalar radius); + + void SetColors(std::vector colors); + + void SetStops(std::vector stops); + + const std::vector& GetColors() const; + + const std::vector& GetStops() const; + + void SetTileMode(Entity::TileMode tile_mode); + + void SetFocus(std::optional focus, Scalar radius); + + private: + bool RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + Point center_; + Scalar radius_ = 0.0f; + std::vector colors_; + std::vector stops_; + Entity::TileMode tile_mode_; + Color decal_border_color_ = Color::BlackTransparent(); + std::optional focus_; + Scalar focus_radius_ = 0.0f; + + ConicalGradientContents(const ConicalGradientContents&) = delete; + + ConicalGradientContents& operator=(const ConicalGradientContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CONICAL_GRADIENT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/content_context.cc b/flutter/engine/src/flutter/impeller/entity/contents/content_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..a38c271a5ff03edc14ea57c6c0b62ca585e84451 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/content_context.cc @@ -0,0 +1,1462 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/content_context.h" + +#include +#include + +#include "fml/trace_event.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/entity/contents/framebuffer_blend_contents.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/contents/text_shadow_cache.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/render_target_cache.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/render_target.h" +#include "impeller/renderer/texture_util.h" +#include "impeller/tessellator/tessellator.h" +#include "impeller/typographer/typographer_context.h" + +namespace impeller { + +namespace { + +/// Holds multiple Pipelines associated with the same PipelineHandle types. +/// +/// For example, it may have multiple +/// RenderPipelineHandle +/// instances for different blend modes. From them you can access the +/// Pipeline. +/// +/// See also: +/// - impeller::ContentContextOptions - options from which variants are +/// created. +/// - impeller::Pipeline::CreateVariant +/// - impeller::RenderPipelineHandle<> - The type of objects this typically +/// contains. +template +class Variants { + static_assert( + ShaderStageCompatibilityChecker< + typename PipelineHandleT::VertexShader, + typename PipelineHandleT::FragmentShader>::Check(), + "The output slots for the fragment shader don't have matches in the " + "vertex shader's output slots. This will result in a linker error."); + + public: + Variants() = default; + + void Set(const ContentContextOptions& options, + std::unique_ptr pipeline) { + uint64_t p_key = options.ToKey(); + for (const auto& [key, pipeline] : pipelines_) { + if (key == p_key) { + return; + } + } + pipelines_.push_back(std::make_pair(p_key, std::move(pipeline))); + } + + void SetDefault(const ContentContextOptions& options, + std::unique_ptr pipeline) { + default_options_ = options; + if (pipeline) { + Set(options, std::move(pipeline)); + } + } + + void SetDefaultDescriptor(std::optional desc) { + desc_ = std::move(desc); + } + + void CreateDefault(const Context& context, + const ContentContextOptions& options, + const std::vector& constants = {}) { + auto desc = PipelineHandleT::Builder::MakeDefaultPipelineDescriptor( + context, constants); + if (!desc.has_value()) { + VALIDATION_LOG << "Failed to create default pipeline."; + return; + } + options.ApplyToPipelineDescriptor(*desc); + desc_ = desc; + if (context.GetFlags().lazy_shader_mode) { + SetDefault(options, nullptr); + } else { + SetDefault(options, std::make_unique(context, desc_, + /*async=*/true)); + } + } + + PipelineHandleT* Get(const ContentContextOptions& options) const { + uint64_t p_key = options.ToKey(); + for (const auto& [key, pipeline] : pipelines_) { + if (key == p_key) { + return pipeline.get(); + } + } + return nullptr; + } + + bool IsDefault(const ContentContextOptions& opts) { + return default_options_.has_value() && + opts.ToKey() == default_options_.value().ToKey(); + } + + PipelineHandleT* GetDefault(const Context& context) { + if (!default_options_.has_value()) { + return nullptr; + } + PipelineHandleT* result = Get(default_options_.value()); + if (result != nullptr) { + return result; + } + SetDefault(default_options_.value(), std::make_unique( + context, desc_, /*async=*/false)); + return Get(default_options_.value()); + } + + size_t GetPipelineCount() const { return pipelines_.size(); } + + private: + std::optional desc_; + std::optional default_options_; + std::vector>> pipelines_; + + Variants(const Variants&) = delete; + + Variants& operator=(const Variants&) = delete; +}; + +template +RenderPipelineHandleT* CreateIfNeeded( + const ContentContext* context, + Variants& container, + ContentContextOptions opts) { + if (!context->IsValid()) { + return nullptr; + } + + if (RenderPipelineHandleT* found = container.Get(opts)) { + return found; + } + + RenderPipelineHandleT* default_handle = + container.GetDefault(*context->GetContext()); + if (container.IsDefault(opts)) { + return default_handle; + } + + // The default must always be initialized in the constructor. + FML_CHECK(default_handle != nullptr); + + const std::shared_ptr>& pipeline = + default_handle->WaitAndGet(); + if (!pipeline) { + return nullptr; + } + + auto variant_future = pipeline->CreateVariant( + /*async=*/false, [&opts, variants_count = container.GetPipelineCount()]( + PipelineDescriptor& desc) { + opts.ApplyToPipelineDescriptor(desc); + desc.SetLabel( + SPrintF("%s V#%zu", desc.GetLabel().data(), variants_count)); + }); + std::unique_ptr variant = + std::make_unique(std::move(variant_future)); + container.Set(opts, std::move(variant)); + return container.Get(opts); +} + +template +PipelineRef GetPipeline(const ContentContext* context, + Variants& container, + ContentContextOptions opts) { + TypedPipeline* pipeline = CreateIfNeeded(context, container, opts); + if (!pipeline) { + return raw_ptr>(); + } + return raw_ptr(pipeline->WaitAndGet()); +} + +} // namespace + +struct ContentContext::Pipelines { + // clang-format off + Variants blend_colorburn; + Variants blend_colordodge; + Variants blend_color; + Variants blend_darken; + Variants blend_difference; + Variants blend_exclusion; + Variants blend_hardlight; + Variants blend_hue; + Variants blend_lighten; + Variants blend_luminosity; + Variants blend_multiply; + Variants blend_overlay; + Variants blend_saturation; + Variants blend_screen; + Variants blend_softlight; + Variants border_mask_blur; + Variants clip; + Variants color_matrix_color_filter; + Variants conical_gradient_fill; + Variants conical_gradient_fill_radial; + Variants conical_gradient_fill_strip; + Variants conical_gradient_fill_strip_and_radial; + Variants conical_gradient_ssbo_fill; + Variants conical_gradient_ssbo_fill_radial; + Variants conical_gradient_ssbo_fill_strip_and_radial; + Variants conical_gradient_ssbo_fill_strip; + Variants conical_gradient_uniform_fill; + Variants conical_gradient_uniform_fill_radial; + Variants conical_gradient_uniform_fill_strip; + Variants conical_gradient_uniform_fill_strip_and_radial; + Variants fast_gradient; + Variants framebuffer_blend_colorburn; + Variants framebuffer_blend_colordodge; + Variants framebuffer_blend_color; + Variants framebuffer_blend_darken; + Variants framebuffer_blend_difference; + Variants framebuffer_blend_exclusion; + Variants framebuffer_blend_hardlight; + Variants framebuffer_blend_hue; + Variants framebuffer_blend_lighten; + Variants framebuffer_blend_luminosity; + Variants framebuffer_blend_multiply; + Variants framebuffer_blend_overlay; + Variants framebuffer_blend_saturation; + Variants framebuffer_blend_screen; + Variants framebuffer_blend_softlight; + Variants gaussian_blur; + Variants glyph_atlas; + Variants line; + Variants linear_gradient_fill; + Variants linear_gradient_ssbo_fill; + Variants linear_gradient_uniform_fill; + Variants linear_to_srgb_filter; + Variants morphology_filter; + Variants clear_blend; + Variants destination_a_top_blend; + Variants destination_blend; + Variants destination_in_blend; + Variants destination_out_blend; + Variants destination_over_blend; + Variants modulate_blend; + Variants plus_blend; + Variants screen_blend; + Variants source_a_top_blend; + Variants source_blend; + Variants source_in_blend; + Variants source_out_blend; + Variants source_over_blend; + Variants xor_blend; + Variants radial_gradient_fill; + Variants radial_gradient_ssbo_fill; + Variants radial_gradient_uniform_fill; + Variants rrect_blur; + Variants solid_fill; + Variants srgb_to_linear_filter; + Variants sweep_gradient_fill; + Variants sweep_gradient_ssbo_fill; + Variants sweep_gradient_uniform_fill; + Variants texture_downsample; + Variants texture; + Variants texture_strict_src; + Variants tiled_texture; + Variants vertices_uber_1_; + Variants vertices_uber_2_; + Variants yuv_to_rgb_filter; + +#ifdef IMPELLER_ENABLE_OPENGLES + Variants tiled_texture_external; + Variants texture_downsample_gles; + Variants tiled_texture_uv_external; +#endif // IMPELLER_ENABLE_OPENGLES + // clang-format on +}; + +void ContentContextOptions::ApplyToPipelineDescriptor( + PipelineDescriptor& desc) const { + auto pipeline_blend = blend_mode; + if (blend_mode > Entity::kLastPipelineBlendMode) { + VALIDATION_LOG << "Cannot use blend mode " << static_cast(blend_mode) + << " as a pipeline blend."; + pipeline_blend = BlendMode::kSrcOver; + } + + desc.SetSampleCount(sample_count); + + ColorAttachmentDescriptor color0 = *desc.GetColorAttachmentDescriptor(0u); + color0.format = color_attachment_pixel_format; + color0.alpha_blend_op = BlendOperation::kAdd; + color0.color_blend_op = BlendOperation::kAdd; + color0.write_mask = ColorWriteMaskBits::kAll; + + switch (pipeline_blend) { + case BlendMode::kClear: + if (is_for_rrect_blur_clear) { + color0.alpha_blend_op = BlendOperation::kReverseSubtract; + color0.color_blend_op = BlendOperation::kReverseSubtract; + color0.dst_alpha_blend_factor = BlendFactor::kOne; + color0.dst_color_blend_factor = BlendFactor::kOne; + color0.src_alpha_blend_factor = BlendFactor::kDestinationColor; + color0.src_color_blend_factor = BlendFactor::kDestinationColor; + } else { + color0.dst_alpha_blend_factor = BlendFactor::kZero; + color0.dst_color_blend_factor = BlendFactor::kZero; + color0.src_alpha_blend_factor = BlendFactor::kZero; + color0.src_color_blend_factor = BlendFactor::kZero; + } + break; + case BlendMode::kSrc: + color0.blending_enabled = false; + color0.dst_alpha_blend_factor = BlendFactor::kZero; + color0.dst_color_blend_factor = BlendFactor::kZero; + color0.src_alpha_blend_factor = BlendFactor::kOne; + color0.src_color_blend_factor = BlendFactor::kOne; + break; + case BlendMode::kDst: + color0.dst_alpha_blend_factor = BlendFactor::kOne; + color0.dst_color_blend_factor = BlendFactor::kOne; + color0.src_alpha_blend_factor = BlendFactor::kZero; + color0.src_color_blend_factor = BlendFactor::kZero; + color0.write_mask = ColorWriteMaskBits::kNone; + break; + case BlendMode::kSrcOver: + color0.dst_alpha_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kOne; + color0.src_color_blend_factor = BlendFactor::kOne; + break; + case BlendMode::kDstOver: + color0.dst_alpha_blend_factor = BlendFactor::kOne; + color0.dst_color_blend_factor = BlendFactor::kOne; + color0.src_alpha_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + break; + case BlendMode::kSrcIn: + color0.dst_alpha_blend_factor = BlendFactor::kZero; + color0.dst_color_blend_factor = BlendFactor::kZero; + color0.src_alpha_blend_factor = BlendFactor::kDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kDestinationAlpha; + break; + case BlendMode::kDstIn: + color0.dst_alpha_blend_factor = BlendFactor::kSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kZero; + color0.src_color_blend_factor = BlendFactor::kZero; + break; + case BlendMode::kSrcOut: + color0.dst_alpha_blend_factor = BlendFactor::kZero; + color0.dst_color_blend_factor = BlendFactor::kZero; + color0.src_alpha_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + break; + case BlendMode::kDstOut: + color0.dst_alpha_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kZero; + color0.src_color_blend_factor = BlendFactor::kZero; + break; + case BlendMode::kSrcATop: + color0.dst_alpha_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kDestinationAlpha; + break; + case BlendMode::kDstATop: + color0.dst_alpha_blend_factor = BlendFactor::kSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + break; + case BlendMode::kXor: + color0.dst_alpha_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kOneMinusSourceAlpha; + color0.src_alpha_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + color0.src_color_blend_factor = BlendFactor::kOneMinusDestinationAlpha; + break; + case BlendMode::kPlus: + color0.dst_alpha_blend_factor = BlendFactor::kOne; + color0.dst_color_blend_factor = BlendFactor::kOne; + color0.src_alpha_blend_factor = BlendFactor::kOne; + color0.src_color_blend_factor = BlendFactor::kOne; + break; + case BlendMode::kModulate: + color0.dst_alpha_blend_factor = BlendFactor::kSourceAlpha; + color0.dst_color_blend_factor = BlendFactor::kSourceColor; + color0.src_alpha_blend_factor = BlendFactor::kZero; + color0.src_color_blend_factor = BlendFactor::kZero; + break; + default: + FML_UNREACHABLE(); + } + desc.SetColorAttachmentDescriptor(0u, color0); + + if (!has_depth_stencil_attachments) { + desc.ClearDepthAttachment(); + desc.ClearStencilAttachments(); + } + + auto maybe_stencil = desc.GetFrontStencilAttachmentDescriptor(); + auto maybe_depth = desc.GetDepthStencilAttachmentDescriptor(); + FML_DCHECK(has_depth_stencil_attachments == maybe_depth.has_value()) + << "Depth attachment doesn't match expected pipeline state. " + "has_depth_stencil_attachments=" + << has_depth_stencil_attachments; + FML_DCHECK(has_depth_stencil_attachments == maybe_stencil.has_value()) + << "Stencil attachment doesn't match expected pipeline state. " + "has_depth_stencil_attachments=" + << has_depth_stencil_attachments; + if (maybe_stencil.has_value()) { + StencilAttachmentDescriptor front_stencil = maybe_stencil.value(); + StencilAttachmentDescriptor back_stencil = front_stencil; + + switch (stencil_mode) { + case StencilMode::kIgnore: + front_stencil.stencil_compare = CompareFunction::kAlways; + front_stencil.depth_stencil_pass = StencilOperation::kKeep; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + case StencilMode::kStencilNonZeroFill: + // The stencil ref should be 0 on commands that use this mode. + front_stencil.stencil_compare = CompareFunction::kAlways; + front_stencil.depth_stencil_pass = StencilOperation::kIncrementWrap; + back_stencil.stencil_compare = CompareFunction::kAlways; + back_stencil.depth_stencil_pass = StencilOperation::kDecrementWrap; + desc.SetStencilAttachmentDescriptors(front_stencil, back_stencil); + break; + case StencilMode::kStencilEvenOddFill: + // The stencil ref should be 0 on commands that use this mode. + front_stencil.stencil_compare = CompareFunction::kEqual; + front_stencil.depth_stencil_pass = StencilOperation::kIncrementWrap; + front_stencil.stencil_failure = StencilOperation::kDecrementWrap; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + case StencilMode::kCoverCompare: + // The stencil ref should be 0 on commands that use this mode. + front_stencil.stencil_compare = CompareFunction::kNotEqual; + front_stencil.depth_stencil_pass = + StencilOperation::kSetToReferenceValue; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + case StencilMode::kCoverCompareInverted: + // The stencil ref should be 0 on commands that use this mode. + front_stencil.stencil_compare = CompareFunction::kEqual; + front_stencil.stencil_failure = StencilOperation::kSetToReferenceValue; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + case StencilMode::kOverdrawPreventionIncrement: + front_stencil.stencil_compare = CompareFunction::kEqual; + front_stencil.depth_stencil_pass = StencilOperation::kIncrementClamp; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + case StencilMode::kOverdrawPreventionRestore: + front_stencil.stencil_compare = CompareFunction::kLess; + front_stencil.depth_stencil_pass = + StencilOperation::kSetToReferenceValue; + desc.SetStencilAttachmentDescriptors(front_stencil); + break; + } + } + if (maybe_depth.has_value()) { + DepthAttachmentDescriptor depth = maybe_depth.value(); + depth.depth_write_enabled = depth_write_enabled; + depth.depth_compare = depth_compare; + desc.SetDepthStencilAttachmentDescriptor(depth); + } + + desc.SetPrimitiveType(primitive_type); + desc.SetPolygonMode(PolygonMode::kFill); +} + +std::array, 15> GetPorterDuffSpecConstants( + bool supports_decal) { + Scalar x = supports_decal ? 1 : 0; + return {{ + {x, 0, 0, 0, 0, 0}, // Clear + {x, 1, 0, 0, 0, 0}, // Source + {x, 0, 0, 1, 0, 0}, // Destination + {x, 1, 0, 1, -1, 0}, // SourceOver + {x, 1, -1, 1, 0, 0}, // DestinationOver + {x, 0, 1, 0, 0, 0}, // SourceIn + {x, 0, 0, 0, 1, 0}, // DestinationIn + {x, 1, -1, 0, 0, 0}, // SourceOut + {x, 0, 0, 1, -1, 0}, // DestinationOut + {x, 0, 1, 1, -1, 0}, // SourceATop + {x, 1, -1, 0, 1, 0}, // DestinationATop + {x, 1, -1, 1, -1, 0}, // Xor + {x, 1, 0, 1, 0, 0}, // Plus + {x, 0, 0, 0, 0, 1}, // Modulate + {x, 0, 0, 1, 0, -1}, // Screen + }}; +} + +template +static std::unique_ptr CreateDefaultPipeline( + const Context& context) { + auto desc = PipelineT::Builder::MakeDefaultPipelineDescriptor(context); + if (!desc.has_value()) { + return nullptr; + } + // Apply default ContentContextOptions to the descriptor. + const auto default_color_format = + context.GetCapabilities()->GetDefaultColorFormat(); + ContentContextOptions{.sample_count = SampleCount::kCount4, + .primitive_type = PrimitiveType::kTriangleStrip, + .color_attachment_pixel_format = default_color_format} + .ApplyToPipelineDescriptor(*desc); + return std::make_unique(context, desc); +} + +ContentContext::ContentContext( + std::shared_ptr context, + std::shared_ptr typographer_context, + std::shared_ptr render_target_allocator) + : context_(std::move(context)), + lazy_glyph_atlas_( + std::make_shared(std::move(typographer_context))), + pipelines_(new Pipelines()), + tessellator_(std::make_shared()), + render_target_cache_(render_target_allocator == nullptr + ? std::make_shared( + context_->GetResourceAllocator()) + : std::move(render_target_allocator)), + host_buffer_(HostBuffer::Create(context_->GetResourceAllocator(), + context_->GetIdleWaiter())), + text_shadow_cache_(std::make_unique()) { + if (!context_ || !context_->IsValid()) { + return; + } + + { + TextureDescriptor desc; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.format = PixelFormat::kR8G8B8A8UNormInt; + desc.size = ISize{1, 1}; + empty_texture_ = GetContext()->GetResourceAllocator()->CreateTexture(desc); + + std::array data = Color::BlackTransparent().ToR8G8B8A8(); + std::shared_ptr cmd_buffer = + GetContext()->CreateCommandBuffer(); + std::shared_ptr blit_pass = cmd_buffer->CreateBlitPass(); + HostBuffer& host_buffer = GetTransientsBuffer(); + BufferView buffer_view = host_buffer.Emplace(data); + blit_pass->AddCopy(buffer_view, empty_texture_); + + if (!blit_pass->EncodeCommands() || !GetContext() + ->GetCommandQueue() + ->Submit({std::move(cmd_buffer)}) + .ok()) { + VALIDATION_LOG << "Failed to create empty texture."; + } + } + + auto options = ContentContextOptions{ + .sample_count = SampleCount::kCount4, + .color_attachment_pixel_format = + context_->GetCapabilities()->GetDefaultColorFormat()}; + auto options_trianglestrip = ContentContextOptions{ + .sample_count = SampleCount::kCount4, + .primitive_type = PrimitiveType::kTriangleStrip, + .color_attachment_pixel_format = + context_->GetCapabilities()->GetDefaultColorFormat()}; + auto options_no_msaa_no_depth_stencil = ContentContextOptions{ + .sample_count = SampleCount::kCount1, + .primitive_type = PrimitiveType::kTriangleStrip, + .color_attachment_pixel_format = + context_->GetCapabilities()->GetDefaultColorFormat(), + .has_depth_stencil_attachments = false}; + const auto supports_decal = static_cast( + context_->GetCapabilities()->SupportsDecalSamplerAddressMode()); + + // Futures for the following pipelines may block in case the first frame is + // rendered without the pipelines being ready. Put pipelines that are more + // likely to be used first. + { + pipelines_->glyph_atlas.CreateDefault( + *context_, options, + {static_cast( + GetContext()->GetCapabilities()->GetDefaultGlyphAtlasFormat() == + PixelFormat::kA8UNormInt)}); + pipelines_->solid_fill.CreateDefault(*context_, options); + pipelines_->texture.CreateDefault(*context_, options); + pipelines_->fast_gradient.CreateDefault(*context_, options); + pipelines_->line.CreateDefault(*context_, options); + + if (context_->GetCapabilities()->SupportsSSBO()) { + pipelines_->linear_gradient_ssbo_fill.CreateDefault(*context_, options); + pipelines_->radial_gradient_ssbo_fill.CreateDefault(*context_, options); + pipelines_->conical_gradient_ssbo_fill.CreateDefault(*context_, options, + {3.0}); + pipelines_->conical_gradient_ssbo_fill_radial.CreateDefault( + *context_, options, {1.0}); + pipelines_->conical_gradient_ssbo_fill_strip.CreateDefault( + *context_, options, {2.0}); + pipelines_->conical_gradient_ssbo_fill_strip_and_radial.CreateDefault( + *context_, options, {0.0}); + pipelines_->sweep_gradient_ssbo_fill.CreateDefault(*context_, options); + } else { + pipelines_->linear_gradient_uniform_fill.CreateDefault(*context_, + options); + pipelines_->radial_gradient_uniform_fill.CreateDefault(*context_, + options); + pipelines_->conical_gradient_uniform_fill.CreateDefault(*context_, + options); + pipelines_->conical_gradient_uniform_fill_radial.CreateDefault(*context_, + options); + pipelines_->conical_gradient_uniform_fill_strip.CreateDefault(*context_, + options); + pipelines_->conical_gradient_uniform_fill_strip_and_radial.CreateDefault( + *context_, options); + pipelines_->sweep_gradient_uniform_fill.CreateDefault(*context_, options); + + pipelines_->linear_gradient_fill.CreateDefault(*context_, options); + pipelines_->radial_gradient_fill.CreateDefault(*context_, options); + pipelines_->conical_gradient_fill.CreateDefault(*context_, options); + pipelines_->conical_gradient_fill_radial.CreateDefault(*context_, + options); + pipelines_->conical_gradient_fill_strip.CreateDefault(*context_, options); + pipelines_->conical_gradient_fill_strip_and_radial.CreateDefault( + *context_, options); + pipelines_->sweep_gradient_fill.CreateDefault(*context_, options); + } + + /// Setup default clip pipeline. + auto clip_pipeline_descriptor = + ClipPipeline::Builder::MakeDefaultPipelineDescriptor(*context_); + if (!clip_pipeline_descriptor.has_value()) { + return; + } + ContentContextOptions{ + .sample_count = SampleCount::kCount4, + .color_attachment_pixel_format = + context_->GetCapabilities()->GetDefaultColorFormat()} + .ApplyToPipelineDescriptor(*clip_pipeline_descriptor); + // Disable write to all color attachments. + auto clip_color_attachments = + clip_pipeline_descriptor->GetColorAttachmentDescriptors(); + for (auto& color_attachment : clip_color_attachments) { + color_attachment.second.write_mask = ColorWriteMaskBits::kNone; + } + clip_pipeline_descriptor->SetColorAttachmentDescriptors( + std::move(clip_color_attachments)); + if (GetContext()->GetFlags().lazy_shader_mode) { + pipelines_->clip.SetDefaultDescriptor(clip_pipeline_descriptor); + pipelines_->clip.SetDefault(options, nullptr); + } else { + pipelines_->clip.SetDefault( + options, + std::make_unique(*context_, clip_pipeline_descriptor)); + } + pipelines_->texture_downsample.CreateDefault( + *context_, options_no_msaa_no_depth_stencil); + pipelines_->rrect_blur.CreateDefault(*context_, options_trianglestrip); + pipelines_->texture_strict_src.CreateDefault(*context_, options); + pipelines_->tiled_texture.CreateDefault(*context_, options, + {supports_decal}); + pipelines_->gaussian_blur.CreateDefault( + *context_, options_no_msaa_no_depth_stencil, {supports_decal}); + pipelines_->border_mask_blur.CreateDefault(*context_, + options_trianglestrip); + pipelines_->color_matrix_color_filter.CreateDefault(*context_, + options_trianglestrip); + pipelines_->vertices_uber_1_.CreateDefault(*context_, options, + {supports_decal}); + pipelines_->vertices_uber_2_.CreateDefault(*context_, options, + {supports_decal}); + + const std::array, 15> porter_duff_constants = + GetPorterDuffSpecConstants(supports_decal); + pipelines_->clear_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[0]); + pipelines_->source_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[1]); + pipelines_->destination_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[2]); + pipelines_->source_over_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[3]); + pipelines_->destination_over_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[4]); + pipelines_->source_in_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[5]); + pipelines_->destination_in_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[6]); + pipelines_->source_out_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[7]); + pipelines_->destination_out_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[8]); + pipelines_->source_a_top_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[9]); + pipelines_->destination_a_top_blend.CreateDefault( + *context_, options_trianglestrip, porter_duff_constants[10]); + pipelines_->xor_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[11]); + pipelines_->plus_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[12]); + pipelines_->modulate_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[13]); + pipelines_->screen_blend.CreateDefault(*context_, options_trianglestrip, + porter_duff_constants[14]); + } + + if (context_->GetCapabilities()->SupportsFramebufferFetch()) { + pipelines_->framebuffer_blend_color.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColor), supports_decal}); + pipelines_->framebuffer_blend_colorburn.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColorBurn), supports_decal}); + pipelines_->framebuffer_blend_colordodge.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColorDodge), supports_decal}); + pipelines_->framebuffer_blend_darken.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kDarken), supports_decal}); + pipelines_->framebuffer_blend_difference.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kDifference), supports_decal}); + pipelines_->framebuffer_blend_exclusion.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kExclusion), supports_decal}); + pipelines_->framebuffer_blend_hardlight.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kHardLight), supports_decal}); + pipelines_->framebuffer_blend_hue.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kHue), supports_decal}); + pipelines_->framebuffer_blend_lighten.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kLighten), supports_decal}); + pipelines_->framebuffer_blend_luminosity.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kLuminosity), supports_decal}); + pipelines_->framebuffer_blend_multiply.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kMultiply), supports_decal}); + pipelines_->framebuffer_blend_overlay.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kOverlay), supports_decal}); + pipelines_->framebuffer_blend_saturation.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kSaturation), supports_decal}); + pipelines_->framebuffer_blend_screen.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kScreen), supports_decal}); + pipelines_->framebuffer_blend_softlight.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kSoftLight), supports_decal}); + } else { + pipelines_->blend_color.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColor), supports_decal}); + pipelines_->blend_colorburn.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColorBurn), supports_decal}); + pipelines_->blend_colordodge.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kColorDodge), supports_decal}); + pipelines_->blend_darken.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kDarken), supports_decal}); + pipelines_->blend_difference.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kDifference), supports_decal}); + pipelines_->blend_exclusion.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kExclusion), supports_decal}); + pipelines_->blend_hardlight.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kHardLight), supports_decal}); + pipelines_->blend_hue.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kHue), supports_decal}); + pipelines_->blend_lighten.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kLighten), supports_decal}); + pipelines_->blend_luminosity.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kLuminosity), supports_decal}); + pipelines_->blend_multiply.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kMultiply), supports_decal}); + pipelines_->blend_overlay.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kOverlay), supports_decal}); + pipelines_->blend_saturation.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kSaturation), supports_decal}); + pipelines_->blend_screen.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kScreen), supports_decal}); + pipelines_->blend_softlight.CreateDefault( + *context_, options_trianglestrip, + {static_cast(BlendSelectValues::kSoftLight), supports_decal}); + } + + pipelines_->morphology_filter.CreateDefault(*context_, options_trianglestrip, + {supports_decal}); + pipelines_->linear_to_srgb_filter.CreateDefault(*context_, + options_trianglestrip); + pipelines_->srgb_to_linear_filter.CreateDefault(*context_, + options_trianglestrip); + pipelines_->yuv_to_rgb_filter.CreateDefault(*context_, options_trianglestrip); + +#if defined(IMPELLER_ENABLE_OPENGLES) + if (GetContext()->GetBackendType() == Context::BackendType::kOpenGLES) { +#if !defined(FML_OS_MACOSX) + // GLES only shader that is unsupported on macOS. + pipelines_->tiled_texture_external.CreateDefault(*context_, options); + pipelines_->tiled_texture_uv_external.CreateDefault(*context_, options); +#endif // !defined(FML_OS_MACOSX) + pipelines_->texture_downsample_gles.CreateDefault(*context_, + options_trianglestrip); + } +#endif // IMPELLER_ENABLE_OPENGLES + + is_valid_ = true; + InitializeCommonlyUsedShadersIfNeeded(); +} + +ContentContext::~ContentContext() = default; + +bool ContentContext::IsValid() const { + return is_valid_; +} + +std::shared_ptr ContentContext::GetEmptyTexture() const { + return empty_texture_; +} + +fml::StatusOr ContentContext::MakeSubpass( + std::string_view label, + ISize texture_size, + const std::shared_ptr& command_buffer, + const SubpassCallback& subpass_callback, + bool msaa_enabled, + bool depth_stencil_enabled, + int32_t mip_count) const { + const std::shared_ptr& context = GetContext(); + RenderTarget subpass_target; + + std::optional depth_stencil_config = + depth_stencil_enabled ? RenderTarget::kDefaultStencilAttachmentConfig + : std::optional(); + + if (context->GetCapabilities()->SupportsOffscreenMSAA() && msaa_enabled) { + subpass_target = GetRenderTargetCache()->CreateOffscreenMSAA( + *context, texture_size, + /*mip_count=*/mip_count, label, + RenderTarget::kDefaultColorAttachmentConfigMSAA, depth_stencil_config); + } else { + subpass_target = GetRenderTargetCache()->CreateOffscreen( + *context, texture_size, + /*mip_count=*/mip_count, label, + RenderTarget::kDefaultColorAttachmentConfig, depth_stencil_config); + } + return MakeSubpass(label, subpass_target, command_buffer, subpass_callback); +} + +fml::StatusOr ContentContext::MakeSubpass( + std::string_view label, + const RenderTarget& subpass_target, + const std::shared_ptr& command_buffer, + const SubpassCallback& subpass_callback) const { + const std::shared_ptr& context = GetContext(); + + auto subpass_texture = subpass_target.GetRenderTargetTexture(); + if (!subpass_texture) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + + auto sub_renderpass = command_buffer->CreateRenderPass(subpass_target); + if (!sub_renderpass) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + sub_renderpass->SetLabel(label); + + if (!subpass_callback(*this, *sub_renderpass)) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + + if (!sub_renderpass->EncodeCommands()) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + + const std::shared_ptr& target_texture = + subpass_target.GetRenderTargetTexture(); + if (target_texture->GetMipCount() > 1) { + fml::Status mipmap_status = + AddMipmapGeneration(command_buffer, context, target_texture); + if (!mipmap_status.ok()) { + return mipmap_status; + } + } + + return subpass_target; +} + +Tessellator& ContentContext::GetTessellator() const { + return *tessellator_; +} + +std::shared_ptr ContentContext::GetContext() const { + return context_; +} + +const Capabilities& ContentContext::GetDeviceCapabilities() const { + return *context_->GetCapabilities(); +} + +PipelineRef ContentContext::GetCachedRuntimeEffectPipeline( + const std::string& unique_entrypoint_name, + const ContentContextOptions& options, + const std::function>()>& + create_callback) const { + RuntimeEffectPipelineKey key{unique_entrypoint_name, options}; + auto it = runtime_effect_pipelines_.find(key); + if (it == runtime_effect_pipelines_.end()) { + it = runtime_effect_pipelines_.insert(it, {key, create_callback()}); + } + return raw_ptr(it->second); +} + +void ContentContext::ClearCachedRuntimeEffectPipeline( + const std::string& unique_entrypoint_name) const { + for (auto it = runtime_effect_pipelines_.begin(); + it != runtime_effect_pipelines_.end();) { + if (it->first.unique_entrypoint_name == unique_entrypoint_name) { + it = runtime_effect_pipelines_.erase(it); + } else { + it++; + } + } +} + +void ContentContext::InitializeCommonlyUsedShadersIfNeeded() const { + if (GetContext()->GetFlags().lazy_shader_mode) { + return; + } + GetContext()->InitializeCommonlyUsedShadersIfNeeded(); +} + +PipelineRef ContentContext::GetFastGradientPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->fast_gradient, opts); +} + +PipelineRef ContentContext::GetLinearGradientFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->linear_gradient_fill, opts); +} + +PipelineRef ContentContext::GetLinearGradientUniformFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->linear_gradient_uniform_fill, opts); +} + +PipelineRef ContentContext::GetRadialGradientUniformFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->radial_gradient_uniform_fill, opts); +} + +PipelineRef ContentContext::GetSweepGradientUniformFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->sweep_gradient_uniform_fill, opts); +} + +PipelineRef ContentContext::GetLinearGradientSSBOFillPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsSSBO()); + return GetPipeline(this, pipelines_->linear_gradient_ssbo_fill, opts); +} + +PipelineRef ContentContext::GetRadialGradientSSBOFillPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsSSBO()); + return GetPipeline(this, pipelines_->radial_gradient_ssbo_fill, opts); +} + +PipelineRef ContentContext::GetConicalGradientUniformFillPipeline( + ContentContextOptions opts, + ConicalKind kind) const { + switch (kind) { + case ConicalKind::kConical: + return GetPipeline(this, pipelines_->conical_gradient_uniform_fill, opts); + case ConicalKind::kRadial: + return GetPipeline(this, pipelines_->conical_gradient_uniform_fill_radial, + opts); + case ConicalKind::kStrip: + return GetPipeline(this, pipelines_->conical_gradient_uniform_fill_strip, + opts); + case ConicalKind::kStripAndRadial: + return GetPipeline( + this, pipelines_->conical_gradient_uniform_fill_strip_and_radial, + opts); + } +} + +PipelineRef ContentContext::GetConicalGradientSSBOFillPipeline( + ContentContextOptions opts, + ConicalKind kind) const { + FML_DCHECK(GetDeviceCapabilities().SupportsSSBO()); + switch (kind) { + case ConicalKind::kConical: + return GetPipeline(this, pipelines_->conical_gradient_ssbo_fill, opts); + case ConicalKind::kRadial: + return GetPipeline(this, pipelines_->conical_gradient_ssbo_fill_radial, + opts); + case ConicalKind::kStrip: + return GetPipeline(this, pipelines_->conical_gradient_ssbo_fill_strip, + opts); + case ConicalKind::kStripAndRadial: + return GetPipeline( + this, pipelines_->conical_gradient_ssbo_fill_strip_and_radial, opts); + } +} + +PipelineRef ContentContext::GetSweepGradientSSBOFillPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsSSBO()); + return GetPipeline(this, pipelines_->sweep_gradient_ssbo_fill, opts); +} + +PipelineRef ContentContext::GetRadialGradientFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->radial_gradient_fill, opts); +} + +PipelineRef ContentContext::GetConicalGradientFillPipeline( + ContentContextOptions opts, + ConicalKind kind) const { + switch (kind) { + case ConicalKind::kConical: + return GetPipeline(this, pipelines_->conical_gradient_fill, opts); + case ConicalKind::kRadial: + return GetPipeline(this, pipelines_->conical_gradient_fill_radial, opts); + case ConicalKind::kStrip: + return GetPipeline(this, pipelines_->conical_gradient_fill_strip, opts); + case ConicalKind::kStripAndRadial: + return GetPipeline( + this, pipelines_->conical_gradient_fill_strip_and_radial, opts); + } +} + +PipelineRef ContentContext::GetRRectBlurPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->rrect_blur, opts); +} + +PipelineRef ContentContext::GetSweepGradientFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->sweep_gradient_fill, opts); +} + +PipelineRef ContentContext::GetSolidFillPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->solid_fill, opts); +} + +PipelineRef ContentContext::GetTexturePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->texture, opts); +} + +PipelineRef ContentContext::GetTextureStrictSrcPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->texture_strict_src, opts); +} + +PipelineRef ContentContext::GetTiledTexturePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->tiled_texture, opts); +} + +PipelineRef ContentContext::GetGaussianBlurPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->gaussian_blur, opts); +} + +PipelineRef ContentContext::GetBorderMaskBlurPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->border_mask_blur, opts); +} + +PipelineRef ContentContext::GetMorphologyFilterPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->morphology_filter, opts); +} + +PipelineRef ContentContext::GetColorMatrixColorFilterPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->color_matrix_color_filter, opts); +} + +PipelineRef ContentContext::GetLinearToSrgbFilterPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->linear_to_srgb_filter, opts); +} + +PipelineRef ContentContext::GetSrgbToLinearFilterPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->srgb_to_linear_filter, opts); +} + +PipelineRef ContentContext::GetClipPipeline(ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->clip, opts); +} + +PipelineRef ContentContext::GetGlyphAtlasPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->glyph_atlas, opts); +} + +PipelineRef ContentContext::GetYUVToRGBFilterPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->yuv_to_rgb_filter, opts); +} + +PipelineRef ContentContext::GetPorterDuffPipeline( + BlendMode mode, + ContentContextOptions opts) const { + switch (mode) { + case BlendMode::kClear: + return GetClearBlendPipeline(opts); + case BlendMode::kSrc: + return GetSourceBlendPipeline(opts); + case BlendMode::kDst: + return GetDestinationBlendPipeline(opts); + case BlendMode::kSrcOver: + return GetSourceOverBlendPipeline(opts); + case BlendMode::kDstOver: + return GetDestinationOverBlendPipeline(opts); + case BlendMode::kSrcIn: + return GetSourceInBlendPipeline(opts); + case BlendMode::kDstIn: + return GetDestinationInBlendPipeline(opts); + case BlendMode::kSrcOut: + return GetSourceOutBlendPipeline(opts); + case BlendMode::kDstOut: + return GetDestinationOutBlendPipeline(opts); + case BlendMode::kSrcATop: + return GetSourceATopBlendPipeline(opts); + case BlendMode::kDstATop: + return GetDestinationATopBlendPipeline(opts); + case BlendMode::kXor: + return GetXorBlendPipeline(opts); + case BlendMode::kPlus: + return GetPlusBlendPipeline(opts); + case BlendMode::kModulate: + return GetModulateBlendPipeline(opts); + case BlendMode::kScreen: + return GetScreenBlendPipeline(opts); + case BlendMode::kOverlay: + case BlendMode::kDarken: + case BlendMode::kLighten: + case BlendMode::kColorDodge: + case BlendMode::kColorBurn: + case BlendMode::kHardLight: + case BlendMode::kSoftLight: + case BlendMode::kDifference: + case BlendMode::kExclusion: + case BlendMode::kMultiply: + case BlendMode::kHue: + case BlendMode::kSaturation: + case BlendMode::kColor: + case BlendMode::kLuminosity: + VALIDATION_LOG << "Invalid porter duff blend mode " + << BlendModeToString(mode); + return GetClearBlendPipeline(opts); + break; + } +} + +PipelineRef ContentContext::GetClearBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->clear_blend, opts); +} + +PipelineRef ContentContext::GetSourceBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->source_blend, opts); +} + +PipelineRef ContentContext::GetDestinationBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->destination_blend, opts); +} + +PipelineRef ContentContext::GetSourceOverBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->source_over_blend, opts); +} + +PipelineRef ContentContext::GetDestinationOverBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->destination_over_blend, opts); +} + +PipelineRef ContentContext::GetSourceInBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->source_in_blend, opts); +} + +PipelineRef ContentContext::GetDestinationInBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->destination_in_blend, opts); +} + +PipelineRef ContentContext::GetSourceOutBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->source_out_blend, opts); +} + +PipelineRef ContentContext::GetDestinationOutBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->destination_out_blend, opts); +} + +PipelineRef ContentContext::GetSourceATopBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->source_a_top_blend, opts); +} + +PipelineRef ContentContext::GetDestinationATopBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->destination_a_top_blend, opts); +} + +PipelineRef ContentContext::GetXorBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->xor_blend, opts); +} + +PipelineRef ContentContext::GetPlusBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->plus_blend, opts); +} + +PipelineRef ContentContext::GetModulateBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->modulate_blend, opts); +} + +PipelineRef ContentContext::GetScreenBlendPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->screen_blend, opts); +} + +PipelineRef ContentContext::GetBlendColorPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_color, opts); +} + +PipelineRef ContentContext::GetBlendColorBurnPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_colorburn, opts); +} + +PipelineRef ContentContext::GetBlendColorDodgePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_colordodge, opts); +} + +PipelineRef ContentContext::GetBlendDarkenPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_darken, opts); +} + +PipelineRef ContentContext::GetBlendDifferencePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_difference, opts); +} + +PipelineRef ContentContext::GetBlendExclusionPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_exclusion, opts); +} + +PipelineRef ContentContext::GetBlendHardLightPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_hardlight, opts); +} + +PipelineRef ContentContext::GetBlendHuePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_hue, opts); +} + +PipelineRef ContentContext::GetBlendLightenPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_lighten, opts); +} + +PipelineRef ContentContext::GetBlendLuminosityPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_luminosity, opts); +} + +PipelineRef ContentContext::GetBlendMultiplyPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_multiply, opts); +} + +PipelineRef ContentContext::GetBlendOverlayPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_overlay, opts); +} + +PipelineRef ContentContext::GetBlendSaturationPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_saturation, opts); +} + +PipelineRef ContentContext::GetBlendScreenPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_screen, opts); +} + +PipelineRef ContentContext::GetBlendSoftLightPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->blend_softlight, opts); +} + +PipelineRef ContentContext::GetDownsamplePipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->texture_downsample, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendColorPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_color, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendColorBurnPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_colorburn, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendColorDodgePipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_colordodge, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendDarkenPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_darken, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendDifferencePipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_difference, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendExclusionPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_exclusion, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendHardLightPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_hardlight, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendHuePipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_hue, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendLightenPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_lighten, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendLuminosityPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_luminosity, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendMultiplyPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_multiply, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendOverlayPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_overlay, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendSaturationPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_saturation, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendScreenPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_screen, opts); +} + +PipelineRef ContentContext::GetFramebufferBlendSoftLightPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetDeviceCapabilities().SupportsFramebufferFetch()); + return GetPipeline(this, pipelines_->framebuffer_blend_softlight, opts); +} + +PipelineRef ContentContext::GetDrawVerticesUberPipeline( + BlendMode blend_mode, + ContentContextOptions opts) const { + if (blend_mode <= BlendMode::kHardLight) { + return GetPipeline(this, pipelines_->vertices_uber_1_, opts); + } else { + return GetPipeline(this, pipelines_->vertices_uber_2_, opts); + } +} + +PipelineRef ContentContext::GetLinePipeline(ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->line, opts); +} + +#ifdef IMPELLER_ENABLE_OPENGLES +PipelineRef ContentContext::GetDownsampleTextureGlesPipeline( + ContentContextOptions opts) const { + return GetPipeline(this, pipelines_->texture_downsample_gles, opts); +} + +PipelineRef ContentContext::GetTiledTextureExternalPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetContext()->GetBackendType() == Context::BackendType::kOpenGLES); + return GetPipeline(this, pipelines_->tiled_texture_external, opts); +} + +PipelineRef ContentContext::GetTiledTextureUvExternalPipeline( + ContentContextOptions opts) const { + FML_DCHECK(GetContext()->GetBackendType() == Context::BackendType::kOpenGLES); + return GetPipeline(this, pipelines_->tiled_texture_uv_external, opts); +} +#endif // IMPELLER_ENABLE_OPENGLES + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/content_context.h b/flutter/engine/src/flutter/impeller/entity/contents/content_context.h new file mode 100644 index 0000000000000000000000000000000000000000..da3db495b9db7dc251b2af55a7d6420daa39541a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/content_context.h @@ -0,0 +1,355 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENT_CONTEXT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENT_CONTEXT_H_ + +#include +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/status_or.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/entity/contents/text_shadow_cache.h" +#include "impeller/geometry/color.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/pipeline.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/render_target.h" +#include "impeller/typographer/lazy_glyph_atlas.h" +#include "impeller/typographer/typographer_context.h" + +namespace impeller { +/// Pipeline state configuration. +/// +/// Each unique combination of these options requires a different pipeline state +/// object to be built. This struct is used as a key for the per-pipeline +/// variant cache. +/// +/// When adding fields to this key, reliant features should take care to limit +/// the combinatorical explosion of variations. A sufficiently complicated +/// Flutter application may easily require building hundreds of PSOs in total, +/// but they shouldn't require e.g. 10s of thousands. +struct ContentContextOptions { + enum class StencilMode : uint8_t { + /// Turn the stencil test off. Used when drawing without stencil-then-cover + /// or overdraw prevention. + kIgnore, + + // Operations used for stencil-then-cover. + + /// Draw the stencil for the NonZero fill path rule. + /// + /// The stencil ref should always be 0 on commands using this mode. + kStencilNonZeroFill, + /// Draw the stencil for the EvenOdd fill path rule. + /// + /// The stencil ref should always be 0 on commands using this mode. + kStencilEvenOddFill, + /// Used for draw calls which fill in the stenciled area. Intended to be + /// used after `kStencilNonZeroFill` or `kStencilEvenOddFill` is used to set + /// up the stencil buffer. Also cleans up the stencil buffer by resetting + /// everything to zero. + /// + /// The stencil ref should always be 0 on commands using this mode. + kCoverCompare, + /// The opposite of `kCoverCompare`. Used for draw calls which fill in the + /// non-stenciled area (intersection clips). Intended to be used after + /// `kStencilNonZeroFill` or `kStencilEvenOddFill` is used to set up the + /// stencil buffer. Also cleans up the stencil buffer by resetting + /// everything to zero. + /// + /// The stencil ref should always be 0 on commands using this mode. + kCoverCompareInverted, + + // Operations used for the "overdraw prevention" mechanism. This is used for + // drawing strokes. + + /// For each fragment, increment the stencil value if it's currently zero. + /// Discard fragments when the value is non-zero. This prevents + /// self-overlapping strokes from drawing over themselves. + /// + /// Note that this is done for rendering correctness, not performance. If a + /// stroke is drawn with a backdrop-reliant blend and self-intersects, then + /// the intersected geometry will render incorrectly when overdrawn because + /// we don't adjust the geometry prevent self-intersection. + /// + /// The stencil ref should always be 0 on commands using this mode. + kOverdrawPreventionIncrement, + /// Reset the stencil to a new maximum value specified by the ref (currently + /// always 0). + /// + /// The stencil ref should always be 0 on commands using this mode. + kOverdrawPreventionRestore, + }; + + SampleCount sample_count = SampleCount::kCount1; + BlendMode blend_mode = BlendMode::kSrcOver; + CompareFunction depth_compare = CompareFunction::kAlways; + StencilMode stencil_mode = ContentContextOptions::StencilMode::kIgnore; + PrimitiveType primitive_type = PrimitiveType::kTriangle; + PixelFormat color_attachment_pixel_format = PixelFormat::kUnknown; + bool has_depth_stencil_attachments = true; + bool depth_write_enabled = false; + bool is_for_rrect_blur_clear = false; + + constexpr uint64_t ToKey() const { + static_assert(sizeof(sample_count) == 1); + static_assert(sizeof(blend_mode) == 1); + static_assert(sizeof(sample_count) == 1); + static_assert(sizeof(depth_compare) == 1); + static_assert(sizeof(stencil_mode) == 1); + static_assert(sizeof(primitive_type) == 1); + static_assert(sizeof(color_attachment_pixel_format) == 1); + + return (is_for_rrect_blur_clear ? 1llu : 0llu) << 0 | + (0) << 1 | // // Unused, previously wireframe. + (has_depth_stencil_attachments ? 1llu : 0llu) << 2 | + (depth_write_enabled ? 1llu : 0llu) << 3 | + // enums + static_cast(color_attachment_pixel_format) << 8 | + static_cast(primitive_type) << 16 | + static_cast(stencil_mode) << 24 | + static_cast(depth_compare) << 32 | + static_cast(blend_mode) << 40 | + static_cast(sample_count) << 48; + } + + void ApplyToPipelineDescriptor(PipelineDescriptor& desc) const; +}; + +enum ConicalKind { + kConical, + kRadial, + kStrip, + kStripAndRadial, +}; + +class Tessellator; +class RenderTargetCache; + +class ContentContext { + public: + explicit ContentContext( + std::shared_ptr context, + std::shared_ptr typographer_context, + std::shared_ptr render_target_allocator = nullptr); + + ~ContentContext(); + + bool IsValid() const; + + Tessellator& GetTessellator() const; + + // clang-format off + PipelineRef GetBlendColorBurnPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendColorDodgePipeline(ContentContextOptions opts) const; + PipelineRef GetBlendColorPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendDarkenPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendDifferencePipeline(ContentContextOptions opts) const; + PipelineRef GetBlendExclusionPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendHardLightPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendHuePipeline(ContentContextOptions opts) const; + PipelineRef GetBlendLightenPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendLuminosityPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendMultiplyPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendOverlayPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendSaturationPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendScreenPipeline(ContentContextOptions opts) const; + PipelineRef GetBlendSoftLightPipeline(ContentContextOptions opts) const; + PipelineRef GetBorderMaskBlurPipeline(ContentContextOptions opts) const; + PipelineRef GetClearBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetClipPipeline(ContentContextOptions opts) const; + PipelineRef GetColorMatrixColorFilterPipeline(ContentContextOptions opts) const; + PipelineRef GetConicalGradientFillPipeline(ContentContextOptions opts, ConicalKind kind) const; + PipelineRef GetConicalGradientSSBOFillPipeline(ContentContextOptions opts, ConicalKind kind) const; + PipelineRef GetConicalGradientUniformFillPipeline(ContentContextOptions opts, ConicalKind kind) const; + PipelineRef GetDestinationATopBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetDestinationBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetDestinationInBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetDestinationOutBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetDestinationOverBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetDownsamplePipeline(ContentContextOptions opts) const; + PipelineRef GetDrawVerticesUberPipeline(BlendMode blend_mode, ContentContextOptions opts) const; + PipelineRef GetFastGradientPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendColorBurnPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendColorDodgePipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendColorPipeline( ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendDarkenPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendDifferencePipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendExclusionPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendHardLightPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendHuePipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendLightenPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendLuminosityPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendMultiplyPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendOverlayPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendSaturationPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendScreenPipeline(ContentContextOptions opts) const; + PipelineRef GetFramebufferBlendSoftLightPipeline(ContentContextOptions opts) const; + PipelineRef GetGaussianBlurPipeline(ContentContextOptions opts) const; + PipelineRef GetGlyphAtlasPipeline(ContentContextOptions opts) const; + PipelineRef GetLinePipeline(ContentContextOptions opts) const; + PipelineRef GetLinearGradientFillPipeline(ContentContextOptions opts) const; + PipelineRef GetLinearGradientSSBOFillPipeline(ContentContextOptions opts) const; + PipelineRef GetLinearGradientUniformFillPipeline(ContentContextOptions opts) const; + PipelineRef GetLinearToSrgbFilterPipeline(ContentContextOptions opts) const; + PipelineRef GetModulateBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetMorphologyFilterPipeline(ContentContextOptions opts) const; + PipelineRef GetPlusBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetPorterDuffPipeline(BlendMode mode, ContentContextOptions opts) const; + PipelineRef GetRadialGradientFillPipeline(ContentContextOptions opts) const; + PipelineRef GetRadialGradientSSBOFillPipeline(ContentContextOptions opts) const; + PipelineRef GetRadialGradientUniformFillPipeline(ContentContextOptions opts) const; + PipelineRef GetRRectBlurPipeline(ContentContextOptions opts) const; + PipelineRef GetScreenBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSolidFillPipeline(ContentContextOptions opts) const; + PipelineRef GetSourceATopBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSourceBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSourceInBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSourceOutBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSourceOverBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetSrgbToLinearFilterPipeline(ContentContextOptions opts) const; + PipelineRef GetSweepGradientFillPipeline(ContentContextOptions opts) const; + PipelineRef GetSweepGradientSSBOFillPipeline( ContentContextOptions opts) const; + PipelineRef GetSweepGradientUniformFillPipeline(ContentContextOptions opts) const; + PipelineRef GetTexturePipeline(ContentContextOptions opts) const; + PipelineRef GetTextureStrictSrcPipeline(ContentContextOptions opts) const; + PipelineRef GetTiledTexturePipeline(ContentContextOptions opts) const; + PipelineRef GetXorBlendPipeline(ContentContextOptions opts) const; + PipelineRef GetYUVToRGBFilterPipeline(ContentContextOptions opts) const; +#ifdef IMPELLER_ENABLE_OPENGLES + PipelineRef GetDownsampleTextureGlesPipeline(ContentContextOptions opts) const; + PipelineRef GetTiledTextureExternalPipeline(ContentContextOptions opts) const; + PipelineRef GetTiledTextureUvExternalPipeline(ContentContextOptions opts) const; +#endif // IMPELLER_ENABLE_OPENGLES + // clang-format on + + // An empty 1x1 texture for binding drawVertices/drawAtlas or other cases + // that don't always have a texture (due to blending). + std::shared_ptr GetEmptyTexture() const; + + std::shared_ptr GetContext() const; + + const Capabilities& GetDeviceCapabilities() const; + + using SubpassCallback = + std::function; + + /// @brief Creates a new texture of size `texture_size` and calls + /// `subpass_callback` with a `RenderPass` for drawing to the texture. + fml::StatusOr MakeSubpass( + std::string_view label, + ISize texture_size, + const std::shared_ptr& command_buffer, + const SubpassCallback& subpass_callback, + bool msaa_enabled = true, + bool depth_stencil_enabled = false, + int32_t mip_count = 1) const; + + /// Makes a subpass that will render to `subpass_target`. + fml::StatusOr MakeSubpass( + std::string_view label, + const RenderTarget& subpass_target, + const std::shared_ptr& command_buffer, + const SubpassCallback& subpass_callback) const; + + const std::shared_ptr& GetLazyGlyphAtlas() const { + return lazy_glyph_atlas_; + } + + const std::shared_ptr& GetRenderTargetCache() const { + return render_target_cache_; + } + + /// RuntimeEffect pipelines must be obtained via this method to avoid + /// re-creating them every frame. + /// + /// The unique_entrypoint_name comes from RuntimeEffect::GetEntrypoint. + /// Impellerc generates a unique entrypoint name for runtime effect shaders + /// based on the input file name and shader stage. + /// + /// The create_callback is synchronously invoked exactly once if a cached + /// pipeline is not found. + PipelineRef GetCachedRuntimeEffectPipeline( + const std::string& unique_entrypoint_name, + const ContentContextOptions& options, + const std::function>()>& + create_callback) const; + + /// Used by hot reload/hot restart to clear a cached pipeline from + /// GetCachedRuntimeEffectPipeline. + void ClearCachedRuntimeEffectPipeline( + const std::string& unique_entrypoint_name) const; + + /// @brief Retrieve the currnent host buffer for transient storage. + /// + /// This is only safe to use from the raster threads. Other threads should + /// allocate their own device buffers. + HostBuffer& GetTransientsBuffer() const { return *host_buffer_; } + + TextShadowCache& GetTextShadowCache() const { return *text_shadow_cache_; } + + private: + std::shared_ptr context_; + std::shared_ptr lazy_glyph_atlas_; + + /// Run backend specific additional setup and create common shader variants. + /// + /// This bootstrap is intended to improve the performance of several + /// first frame benchmarks that are tracked in the flutter device lab. + /// The workload includes initializing commonly used but not default + /// shader variants, as well as forcing driver initialization. + void InitializeCommonlyUsedShadersIfNeeded() const; + + struct RuntimeEffectPipelineKey { + std::string unique_entrypoint_name; + ContentContextOptions options; + + struct Hash { + std::size_t operator()(const RuntimeEffectPipelineKey& key) const { + return fml::HashCombine(key.unique_entrypoint_name, + key.options.ToKey()); + } + }; + + struct Equal { + constexpr bool operator()(const RuntimeEffectPipelineKey& lhs, + const RuntimeEffectPipelineKey& rhs) const { + return lhs.unique_entrypoint_name == rhs.unique_entrypoint_name && + lhs.options.ToKey() == rhs.options.ToKey(); + } + }; + }; + + mutable std::unordered_map>, + RuntimeEffectPipelineKey::Hash, + RuntimeEffectPipelineKey::Equal> + runtime_effect_pipelines_; + + struct Pipelines; + std::unique_ptr pipelines_; + + bool is_valid_ = false; + std::shared_ptr tessellator_; + std::shared_ptr render_target_cache_; + std::shared_ptr host_buffer_; + std::shared_ptr empty_texture_; + std::unique_ptr text_shadow_cache_; + + ContentContext(const ContentContext&) = delete; + + ContentContext& operator=(const ContentContext&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENT_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..2d5982dc95dadf2a9fd90fce863aaad0a118651d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/contents.cc @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/contents.h" +#include + +#include "fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +ContentContextOptions OptionsFromPass(const RenderPass& pass) { + ContentContextOptions opts; + opts.sample_count = pass.GetSampleCount(); + opts.color_attachment_pixel_format = pass.GetRenderTargetPixelFormat(); + + bool has_depth_stencil_attachments = + pass.HasDepthAttachment() && pass.HasStencilAttachment(); + FML_DCHECK(pass.HasDepthAttachment() == pass.HasStencilAttachment()); + + opts.has_depth_stencil_attachments = has_depth_stencil_attachments; + opts.depth_compare = CompareFunction::kGreaterEqual; + opts.stencil_mode = ContentContextOptions::StencilMode::kIgnore; + return opts; +} + +ContentContextOptions OptionsFromPassAndEntity(const RenderPass& pass, + const Entity& entity) { + ContentContextOptions opts = OptionsFromPass(pass); + opts.blend_mode = entity.GetBlendMode(); + return opts; +} + +std::shared_ptr Contents::MakeAnonymous( + Contents::RenderProc render_proc, + Contents::CoverageProc coverage_proc) { + return AnonymousContents::Make(std::move(render_proc), + std::move(coverage_proc)); +} + +Contents::Contents() = default; + +Contents::~Contents() = default; + +bool Contents::IsOpaque(const Matrix& transform) const { + return false; +} + +std::optional Contents::RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + const std::optional& sampler_descriptor, + bool msaa_enabled, + int32_t mip_count, + std::string_view label) const { + auto coverage = GetCoverage(entity); + if (!coverage.has_value()) { + return std::nullopt; + } + + std::shared_ptr command_buffer = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return std::nullopt; + } + + // Pad Contents snapshots with 1 pixel borders to ensure correct sampling + // behavior. Not doing so results in a coverage leak for filters that support + // customizing the input sampling mode. Snapshots of contents should be + // theoretically treated as infinite size just like layers. + coverage = coverage->Expand(1); + + if (coverage_limit.has_value()) { + coverage = coverage->Intersection(*coverage_limit); + if (!coverage.has_value()) { + return std::nullopt; + } + } + + ISize subpass_size = ISize::Ceil(coverage->GetSize()); + fml::StatusOr render_target = renderer.MakeSubpass( + label, subpass_size, command_buffer, + [&contents = *this, &entity, &coverage](const ContentContext& renderer, + RenderPass& pass) -> bool { + Entity sub_entity; + sub_entity.SetBlendMode(BlendMode::kSrcOver); + sub_entity.SetTransform( + Matrix::MakeTranslation(Vector3(-coverage->GetOrigin())) * + entity.GetTransform()); + return contents.Render(renderer, sub_entity, pass); + }, + msaa_enabled, /*depth_stencil_enabled=*/true, + std::min(mip_count, static_cast(subpass_size.MipCount()))); + + if (!render_target.ok()) { + return std::nullopt; + } + if (!renderer.GetContext()->EnqueueCommandBuffer(std::move(command_buffer))) { + return std::nullopt; + } + + auto snapshot = Snapshot{ + .texture = render_target.value().GetRenderTargetTexture(), + .transform = Matrix::MakeTranslation(coverage->GetOrigin()), + }; + if (sampler_descriptor.has_value()) { + snapshot.sampler_descriptor = sampler_descriptor.value(); + } + + return snapshot; +} + +void Contents::SetInheritedOpacity(Scalar opacity) { + VALIDATION_LOG << "Contents::SetInheritedOpacity should never be called when " + "Contents::CanAcceptOpacity returns false."; +} + +std::optional Contents::AsBackgroundColor(const Entity& entity, + ISize target_size) const { + return {}; +} + +bool Contents::ApplyColorFilter( + const Contents::ColorFilterProc& color_filter_proc) { + return false; +} + +void Contents::SetCoverageHint(std::optional coverage_hint) { + coverage_hint_ = coverage_hint; +} + +const std::optional& Contents::GetCoverageHint() const { + return coverage_hint_; +} + +std::optional Contents::GetColorSourceSize() const { + return color_source_size_; +}; + +void Contents::SetColorSourceSize(Size size) { + color_source_size_ = size; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/contents.h b/flutter/engine/src/flutter/impeller/entity/contents/contents.h new file mode 100644 index 0000000000000000000000000000000000000000..2672136c52d70e27ea98b3abf23259d5a345dfe6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/contents.h @@ -0,0 +1,159 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENTS_H_ + +#include +#include + +#include "impeller/core/sampler_descriptor.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/rect.h" +#include "impeller/renderer/snapshot.h" +#include "impeller/typographer/lazy_glyph_atlas.h" + +namespace impeller { + +class ContentContext; +struct ContentContextOptions; +class Entity; +class Surface; +class RenderPass; +class FilterContents; + +ContentContextOptions OptionsFromPass(const RenderPass& pass); + +ContentContextOptions OptionsFromPassAndEntity(const RenderPass& pass, + const Entity& entity); + +class Contents { + public: + /// A procedure that filters a given unpremultiplied color to produce a new + /// unpremultiplied color. + using ColorFilterProc = std::function; + + using RenderProc = std::function; + using CoverageProc = std::function(const Entity& entity)>; + + static std::shared_ptr MakeAnonymous(RenderProc render_proc, + CoverageProc coverage_proc); + + Contents(); + + virtual ~Contents(); + + virtual bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const = 0; + + //---------------------------------------------------------------------------- + /// @brief Get the area of the render pass that will be affected when this + /// contents is rendered. + /// + /// During rendering, coverage coordinates count pixels from the top + /// left corner of the framebuffer. + /// + /// @return The coverage rectangle. An `std::nullopt` result means that + /// rendering this contents has no effect on the output color. + /// + virtual std::optional GetCoverage(const Entity& entity) const = 0; + + //---------------------------------------------------------------------------- + /// @brief Hint that specifies the coverage area of this Contents that will + /// actually be used during rendering. This is for optimization + /// purposes only and can not be relied on as a clip. May optionally + /// affect the result of `GetCoverage()`. + /// + void SetCoverageHint(std::optional coverage_hint); + + const std::optional& GetCoverageHint() const; + + //---------------------------------------------------------------------------- + /// @brief Whether this Contents only emits opaque source colors from the + /// fragment stage. This value does not account for any entity + /// properties (e.g. the blend mode), clips/visibility culling, or + /// inherited opacity. + /// + /// @param transform The current transform matrix of the entity that will + /// render this contents. + virtual bool IsOpaque(const Matrix& transform) const; + + //---------------------------------------------------------------------------- + /// @brief Render this contents to a snapshot, respecting the entity's + /// transform, path, clip depth, and blend mode. + /// The result texture size is always the size of + /// `GetCoverage(entity)`. + /// + virtual std::optional RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit = std::nullopt, + const std::optional& sampler_descriptor = std::nullopt, + bool msaa_enabled = true, + int32_t mip_count = 1, + std::string_view label = "Snapshot") const; + + //---------------------------------------------------------------------------- + /// @brief Return the color source's intrinsic size, if available. + /// + /// For example, a gradient has a size based on its end and beginning + /// points, ignoring any tiling. Solid colors and runtime effects have + /// no size. + /// + std::optional GetColorSourceSize() const; + + void SetColorSourceSize(Size size); + + //---------------------------------------------------------------------------- + /// @brief Inherit the provided opacity. + /// + /// Use of this method is invalid if CanAcceptOpacity returns false. + /// + virtual void SetInheritedOpacity(Scalar opacity); + + //---------------------------------------------------------------------------- + /// @brief Returns a color if this Contents will flood the given `target_size` + /// with a color. This output color is the "Source" color that will be + /// used for the Entity's blend operation. + /// + /// This is useful for absorbing full screen solid color draws into + /// subpass clear colors. + /// + virtual std::optional AsBackgroundColor(const Entity& entity, + ISize target_size) const; + + //---------------------------------------------------------------------------- + /// @brief If possible, applies a color filter to this contents inputs on + /// the CPU. + /// + /// This method will either fully apply the color filter or + /// perform no action. Partial/incorrect application of the color + /// filter will never occur. + /// + /// @param[in] color_filter_proc A function that filters a given + /// unpremultiplied color to produce a new + /// unpremultiplied color. + /// + /// @return True if the color filter was able to be fully applied to all + /// all relevant inputs. Otherwise, this operation is a no-op and + /// false is returned. + /// + [[nodiscard]] virtual bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc); + + private: + std::optional coverage_hint_; + std::optional color_source_size_; + + Contents(const Contents&) = delete; + + Contents& operator=(const Contents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..0b71044a731127568679c837aaf87b303b696b63 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.cc @@ -0,0 +1,993 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/blend_filter_contents.h" + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/base/strings.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" +#include "impeller/entity/contents/solid_color_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/rect_geometry.h" +#include "impeller/entity/texture_fill.frag.h" +#include "impeller/entity/texture_fill.vert.h" +#include "impeller/geometry/color.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/snapshot.h" + +namespace impeller { + +namespace { + +#ifdef IMPELLER_DEBUG + +#define _IMPELLER_BLEND_MODE_FILTER_NAME_LIST(blend_mode) \ + "Blend Filter " #blend_mode, + +static constexpr const char* kBlendModeFilterNames[] = { + IMPELLER_FOR_EACH_BLEND_MODE(_IMPELLER_BLEND_MODE_FILTER_NAME_LIST)}; + +const std::string_view BlendModeToFilterString(BlendMode blend_mode) { + return kBlendModeFilterNames[static_cast>( + blend_mode)]; +} +#endif // IMPELLER_DEBUG + +} // namespace + +std::optional InvertPorterDuffBlend(BlendMode blend_mode) { + switch (blend_mode) { + case BlendMode::kClear: + return BlendMode::kClear; + case BlendMode::kSrc: + return BlendMode::kDst; + case BlendMode::kDst: + return BlendMode::kSrc; + case BlendMode::kSrcOver: + return BlendMode::kDstOver; + case BlendMode::kDstOver: + return BlendMode::kSrcOver; + case BlendMode::kSrcIn: + return BlendMode::kDstIn; + case BlendMode::kDstIn: + return BlendMode::kSrcIn; + case BlendMode::kSrcOut: + return BlendMode::kDstOut; + case BlendMode::kDstOut: + return BlendMode::kSrcOut; + case BlendMode::kSrcATop: + return BlendMode::kDstATop; + case BlendMode::kDstATop: + return BlendMode::kSrcATop; + case BlendMode::kXor: + return BlendMode::kXor; + case BlendMode::kPlus: + return BlendMode::kPlus; + case BlendMode::kModulate: + return BlendMode::kModulate; + default: + return std::nullopt; + } +} + +BlendFilterContents::BlendFilterContents() { + SetBlendMode(BlendMode::kSrcOver); +} + +BlendFilterContents::~BlendFilterContents() = default; + +using PipelineProc = + PipelineRef (ContentContext::*)(ContentContextOptions) const; + +template +static std::optional AdvancedBlend( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + BlendMode blend_mode, + std::optional foreground_color, + ColorFilterContents::AbsorbOpacity absorb_opacity, + PipelineProc pipeline_proc, + std::optional alpha) { + using VS = typename TPipeline::VertexShader; + using FS = typename TPipeline::FragmentShader; + + //---------------------------------------------------------------------------- + /// Handle inputs. + /// + + const size_t total_inputs = + inputs.size() + (foreground_color.has_value() ? 1 : 0); + if (total_inputs < 2) { + return std::nullopt; + } + + auto dst_snapshot = + inputs[0]->GetSnapshot("AdvancedBlend(Dst)", renderer, entity); + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + auto maybe_dst_uvs = dst_snapshot->GetCoverageUVs(coverage); + if (!maybe_dst_uvs.has_value()) { + return std::nullopt; + } + auto dst_uvs = maybe_dst_uvs.value(); + + std::optional src_snapshot; + std::array src_uvs; + if (!foreground_color.has_value()) { + src_snapshot = + inputs[1]->GetSnapshot("AdvancedBlend(Src)", renderer, entity); + if (!src_snapshot.has_value()) { + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + return Entity::FromSnapshot(dst_snapshot.value(), entity.GetBlendMode()); + } + auto maybe_src_uvs = src_snapshot->GetCoverageUVs(coverage); + if (!maybe_src_uvs.has_value()) { + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + return Entity::FromSnapshot(dst_snapshot.value(), entity.GetBlendMode()); + } + src_uvs = maybe_src_uvs.value(); + } + + Rect subpass_coverage = coverage; + if (entity.GetContents()) { + auto coverage_hint = entity.GetContents()->GetCoverageHint(); + + if (coverage_hint.has_value()) { + auto maybe_subpass_coverage = + subpass_coverage.Intersection(*coverage_hint); + if (!maybe_subpass_coverage.has_value()) { + return std::nullopt; // Nothing to render. + } + + subpass_coverage = *maybe_subpass_coverage; + } + } + + //---------------------------------------------------------------------------- + /// Render to texture. + /// + + ContentContext::SubpassCallback callback = [&](const ContentContext& renderer, + RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); + + auto size = pass.GetRenderTargetSize(); + + std::array vertices = { + typename VS::PerVertexData{Point(0, 0), dst_uvs[0], src_uvs[0]}, + typename VS::PerVertexData{Point(size.width, 0), dst_uvs[1], + src_uvs[1]}, + typename VS::PerVertexData{Point(0, size.height), dst_uvs[2], + src_uvs[2]}, + typename VS::PerVertexData{Point(size.width, size.height), dst_uvs[3], + src_uvs[3]}, + }; + auto vtx_buffer = + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer()); + + auto options = OptionsFromPass(pass); + options.primitive_type = PrimitiveType::kTriangleStrip; + options.blend_mode = BlendMode::kSrc; + PipelineRef pipeline = std::invoke(pipeline_proc, renderer, options); + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(BlendModeToFilterString(blend_mode)); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(std::move(vtx_buffer)); + pass.SetPipeline(pipeline); + + typename FS::BlendInfo blend_info; + typename VS::FrameInfo frame_info; + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_snapshot->sampler_descriptor); + FS::BindTextureSamplerDst(pass, dst_snapshot->texture, dst_sampler); + frame_info.dst_y_coord_scale = dst_snapshot->texture->GetYCoordScale(); + blend_info.dst_input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? dst_snapshot->opacity + : 1.0; + + if (foreground_color.has_value()) { + blend_info.color_factor = 1; + blend_info.color = foreground_color.value(); + // This texture will not be sampled from due to the color factor. But + // this is present so that validation doesn't trip on a missing + // binding. + FS::BindTextureSamplerSrc(pass, dst_snapshot->texture, dst_sampler); + } else { + raw_ptr src_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + src_snapshot->sampler_descriptor); + blend_info.color_factor = 0; + blend_info.src_input_alpha = src_snapshot->opacity; + FS::BindTextureSamplerSrc(pass, src_snapshot->texture, src_sampler); + frame_info.src_y_coord_scale = src_snapshot->texture->GetYCoordScale(); + } + auto blend_uniform = host_buffer.EmplaceUniform(blend_info); + FS::BindBlendInfo(pass, blend_uniform); + + frame_info.mvp = pass.GetOrthographicTransform() * + Matrix::MakeTranslation(coverage.GetOrigin() - + subpass_coverage.GetOrigin()); + + auto uniform_view = host_buffer.EmplaceUniform(frame_info); + VS::BindFrameInfo(pass, uniform_view); + + return pass.Draw().ok(); + }; + + std::shared_ptr command_buffer = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return std::nullopt; + } + fml::StatusOr render_target = renderer.MakeSubpass( + "Advanced Blend Filter", ISize(subpass_coverage.GetSize()), + command_buffer, callback); + if (!render_target.ok()) { + return std::nullopt; + } + if (!renderer.GetContext()->EnqueueCommandBuffer(std::move(command_buffer))) { + return std::nullopt; + } + + return Entity::FromSnapshot( + Snapshot{ + .texture = render_target.value().GetRenderTargetTexture(), + .transform = Matrix::MakeTranslation(subpass_coverage.GetOrigin()), + // Since we absorbed the transform of the inputs and used the + // respective snapshot sampling modes when blending, pass on + // the default NN clamp sampler. + .sampler_descriptor = {}, + .opacity = (absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? 1.0f + : dst_snapshot->opacity) * + alpha.value_or(1.0)}, + entity.GetBlendMode()); +} + +std::optional BlendFilterContents::CreateForegroundAdvancedBlend( + const std::shared_ptr& input, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + Color foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const { + auto dst_snapshot = + input->GetSnapshot("ForegroundAdvancedBlend", renderer, entity); + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + + RenderProc render_proc = [foreground_color, dst_snapshot, blend_mode, alpha, + absorb_opacity](const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) -> bool { + using VS = BlendScreenPipeline::VertexShader; + using FS = BlendScreenPipeline::FragmentShader; + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto size = dst_snapshot->texture->GetSize(); + + std::array vertices = { + VS::PerVertexData{{0, 0}, {0, 0}, {0, 0}}, + VS::PerVertexData{Point(size.width, 0), {1, 0}, {1, 0}}, + VS::PerVertexData{Point(0, size.height), {0, 1}, {0, 1}}, + VS::PerVertexData{Point(size.width, size.height), {1, 1}, {1, 1}}, + }; + auto vtx_buffer = + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer()); + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(BlendModeToFilterString(blend_mode)); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(std::move(vtx_buffer)); + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + + switch (blend_mode) { + case BlendMode::kScreen: + pass.SetPipeline(renderer.GetBlendScreenPipeline(options)); + break; + case BlendMode::kOverlay: + pass.SetPipeline(renderer.GetBlendOverlayPipeline(options)); + break; + case BlendMode::kDarken: + pass.SetPipeline(renderer.GetBlendDarkenPipeline(options)); + break; + case BlendMode::kLighten: + pass.SetPipeline(renderer.GetBlendLightenPipeline(options)); + break; + case BlendMode::kColorDodge: + pass.SetPipeline(renderer.GetBlendColorDodgePipeline(options)); + break; + case BlendMode::kColorBurn: + pass.SetPipeline(renderer.GetBlendColorBurnPipeline(options)); + break; + case BlendMode::kHardLight: + pass.SetPipeline(renderer.GetBlendHardLightPipeline(options)); + break; + case BlendMode::kSoftLight: + pass.SetPipeline(renderer.GetBlendSoftLightPipeline(options)); + break; + case BlendMode::kDifference: + pass.SetPipeline(renderer.GetBlendDifferencePipeline(options)); + break; + case BlendMode::kExclusion: + pass.SetPipeline(renderer.GetBlendExclusionPipeline(options)); + break; + case BlendMode::kMultiply: + pass.SetPipeline(renderer.GetBlendMultiplyPipeline(options)); + break; + case BlendMode::kHue: + pass.SetPipeline(renderer.GetBlendHuePipeline(options)); + break; + case BlendMode::kSaturation: + pass.SetPipeline(renderer.GetBlendSaturationPipeline(options)); + break; + case BlendMode::kColor: + pass.SetPipeline(renderer.GetBlendColorPipeline(options)); + break; + case BlendMode::kLuminosity: + pass.SetPipeline(renderer.GetBlendLuminosityPipeline(options)); + break; + default: + return false; + } + + FS::BlendInfo blend_info; + VS::FrameInfo frame_info; + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_snapshot->sampler_descriptor); + FS::BindTextureSamplerDst(pass, dst_snapshot->texture, dst_sampler); + frame_info.dst_y_coord_scale = dst_snapshot->texture->GetYCoordScale(); + + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * dst_snapshot->transform); + + blend_info.dst_input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? dst_snapshot->opacity * alpha.value_or(1.0) + : 1.0; + + blend_info.color_factor = 1; + blend_info.color = foreground_color; + // This texture will not be sampled from due to the color factor. But + // this is present so that validation doesn't trip on a missing + // binding. + FS::BindTextureSamplerSrc(pass, dst_snapshot->texture, dst_sampler); + + auto blend_uniform = host_buffer.EmplaceUniform(blend_info); + FS::BindBlendInfo(pass, blend_uniform); + + auto uniform_view = host_buffer.EmplaceUniform(frame_info); + VS::BindFrameInfo(pass, uniform_view); + + return pass.Draw().ok(); + }; + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + + return sub_entity; +} + +std::optional BlendFilterContents::CreateForegroundPorterDuffBlend( + const std::shared_ptr& input, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + Color foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const { + if (blend_mode == BlendMode::kClear) { + return std::nullopt; + } + + auto dst_snapshot = + input->GetSnapshot("ForegroundPorterDuffBlend", renderer, entity); + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + + if (blend_mode == BlendMode::kDst) { + return Entity::FromSnapshot(dst_snapshot.value(), entity.GetBlendMode()); + } + + RenderProc render_proc = [foreground_color, dst_snapshot, blend_mode, + absorb_opacity, alpha]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + using VS = PorterDuffBlendPipeline::VertexShader; + using FS = PorterDuffBlendPipeline::FragmentShader; + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto size = dst_snapshot->texture->GetSize(); + auto color = foreground_color.Premultiply(); + + std::array vertices = { + VS::PerVertexData{{0, 0}, {0, 0}, color}, + VS::PerVertexData{Point(size.width, 0), {1, 0}, color}, + VS::PerVertexData{Point(0, size.height), {0, 1}, color}, + VS::PerVertexData{Point(size.width, size.height), {1, 1}, color}, + }; + auto vtx_buffer = + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer()); + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(BlendModeToFilterString(blend_mode)); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(std::move(vtx_buffer)); + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetPorterDuffPipeline(blend_mode, options)); + + FS::FragInfo frag_info; + VS::FrameInfo frame_info; + + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * dst_snapshot->transform); + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_snapshot->sampler_descriptor); + FS::BindTextureSamplerDst(pass, dst_snapshot->texture, dst_sampler); + frame_info.texture_sampler_y_coord_scale = + dst_snapshot->texture->GetYCoordScale(); + + frag_info.input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? dst_snapshot->opacity * alpha.value_or(1.0) + : 1.0; + frag_info.output_alpha = 1.0; + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + + return sub_entity; +} + +static std::optional PipelineBlend( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + BlendMode blend_mode, + std::optional foreground_color, + ColorFilterContents::AbsorbOpacity absorb_opacity, + std::optional alpha) { + using VS = TexturePipeline::VertexShader; + using FS = TexturePipeline::FragmentShader; + + auto dst_snapshot = + inputs[0]->GetSnapshot("PipelineBlend(Dst)", renderer, entity); + if (!dst_snapshot.has_value()) { + return std::nullopt; // Nothing to render. + } + + Rect subpass_coverage = coverage; + if (entity.GetContents()) { + auto coverage_hint = entity.GetContents()->GetCoverageHint(); + + if (coverage_hint.has_value()) { + auto maybe_subpass_coverage = + subpass_coverage.Intersection(*coverage_hint); + if (!maybe_subpass_coverage.has_value()) { + return std::nullopt; // Nothing to render. + } + + subpass_coverage = *maybe_subpass_coverage; + } + } + + ContentContext::SubpassCallback callback = [&](const ContentContext& renderer, + RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(BlendModeToFilterString(blend_mode)); +#endif // IMPELLER_DEBUG + auto options = OptionsFromPass(pass); + options.primitive_type = PrimitiveType::kTriangleStrip; + + auto add_blend_command = [&](std::optional input) { + if (!input.has_value()) { + return false; + } + auto input_coverage = input->GetCoverage(); + if (!input_coverage.has_value()) { + return false; + } + + raw_ptr sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + input->sampler_descriptor); + FS::BindTextureSampler(pass, input->texture, sampler); + + auto size = input->texture->GetSize(); + std::array vertices = { + VS::PerVertexData{Point(0, 0), Point(0, 0)}, + VS::PerVertexData{Point(size.width, 0), Point(1, 0)}, + VS::PerVertexData{Point(0, size.height), Point(0, 1)}, + VS::PerVertexData{Point(size.width, size.height), Point(1, 1)}, + }; + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::FrameInfo frame_info; + frame_info.mvp = pass.GetOrthographicTransform() * + Matrix::MakeTranslation(-subpass_coverage.GetOrigin()) * + input->transform; + frame_info.texture_sampler_y_coord_scale = + input->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + frag_info.alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? input->opacity + : 1.0; + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + // Draw the first texture using kSource. + options.blend_mode = BlendMode::kSrc; + pass.SetPipeline(renderer.GetTexturePipeline(options)); + if (!add_blend_command(dst_snapshot)) { + return true; + } + + // Write subsequent textures using the selected blend mode. + + if (inputs.size() >= 2) { + options.blend_mode = blend_mode; + pass.SetPipeline(renderer.GetTexturePipeline(options)); + + for (auto texture_i = inputs.begin() + 1; texture_i < inputs.end(); + texture_i++) { + auto src_input = texture_i->get()->GetSnapshot("PipelineBlend(Src)", + renderer, entity); + if (!add_blend_command(src_input)) { + return true; + } + } + } + + // If a foreground color is set, blend it in. + + if (foreground_color.has_value()) { + auto contents = std::make_shared(); + RectGeometry geom(Rect::MakeSize(pass.GetRenderTargetSize())); + contents->SetGeometry(&geom); + contents->SetColor(foreground_color.value()); + + Entity foreground_entity; + foreground_entity.SetBlendMode(blend_mode); + foreground_entity.SetContents(contents); + if (!foreground_entity.Render(renderer, pass)) { + return false; + } + } + + return true; + }; + + std::shared_ptr command_buffer = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return std::nullopt; + } + + fml::StatusOr render_target = renderer.MakeSubpass( + "Pipeline Blend Filter", ISize(subpass_coverage.GetSize()), + command_buffer, callback); + + if (!render_target.ok()) { + return std::nullopt; + } + if (!renderer.GetContext()->EnqueueCommandBuffer(std::move(command_buffer))) { + return std::nullopt; + } + + return Entity::FromSnapshot( + Snapshot{ + .texture = render_target.value().GetRenderTargetTexture(), + .transform = Matrix::MakeTranslation(subpass_coverage.GetOrigin()), + // Since we absorbed the transform of the inputs and used the + // respective snapshot sampling modes when blending, pass on + // the default NN clamp sampler. + .sampler_descriptor = {}, + .opacity = (absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? 1.0f + : dst_snapshot->opacity) * + alpha.value_or(1.0)}, + entity.GetBlendMode()); +} + +std::optional BlendFilterContents::CreateFramebufferAdvancedBlend( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + std::optional foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const { + // This works with either 2 contents or 1 contents and a foreground color. + FML_DCHECK(inputs.size() == 2u || + (inputs.size() == 1u && foreground_color.has_value())); + + auto dst_snapshot = + inputs[0]->GetSnapshot("ForegroundAdvancedBlend", renderer, entity); + if (!dst_snapshot.has_value()) { + return std::nullopt; + } + + std::shared_ptr foreground_texture; + + ContentContext::SubpassCallback subpass_callback = [&](const ContentContext& + renderer, + RenderPass& pass) { + // First, we create a new render pass and populate it with the contents + // of the first (dst) input. + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + + { + using FS = TextureFillFragmentShader; + using VS = TextureFillVertexShader; + + pass.SetCommandLabel("Framebuffer Advanced Blend"); + auto pipeline_options = OptionsFromPass(pass); + pipeline_options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetTexturePipeline(pipeline_options)); + + VS::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); + frame_info.texture_sampler_y_coord_scale = 1.0; + + FS::FragInfo frag_info; + frag_info.alpha = 1.0; + + std::array vertices = { + VS::PerVertexData{{0, 0}, {0, 0}}, + VS::PerVertexData{Point(1, 0), {1, 0}}, + VS::PerVertexData{Point(0, 1), {0, 1}}, + VS::PerVertexData{Point(1, 1), {1, 1}}, + }; + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + FS::BindTextureSampler( + pass, dst_snapshot->texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler({})); + + if (!pass.Draw().ok()) { + return false; + } + } + + { + using VS = FramebufferBlendScreenPipeline::VertexShader; + using FS = FramebufferBlendScreenPipeline::FragmentShader; + + // Next, we render the second contents to a snapshot, or create a 1x1 + // texture for the foreground color. + std::shared_ptr src_texture; + SamplerDescriptor src_sampler_descriptor = SamplerDescriptor{}; + if (foreground_color.has_value()) { + src_texture = foreground_texture; + } else { + auto src_snapshot = + inputs[0]->GetSnapshot("ForegroundAdvancedBlend", renderer, entity); + if (!src_snapshot.has_value()) { + return false; + } + // This doesn't really handle the case where the transforms are wildly + // different, but we only need to support blending two contents together + // in limited circumstances (mask blur). + src_texture = src_snapshot->texture; + src_sampler_descriptor = src_snapshot->sampler_descriptor; + } + + std::array vertices = { + VS::PerVertexData{Point(0, 0), Point(0, 0)}, + VS::PerVertexData{Point(1, 0), Point(1, 0)}, + VS::PerVertexData{Point(0, 1), Point(0, 1)}, + VS::PerVertexData{Point(1, 1), Point(1, 1)}, + }; + + auto options = OptionsFromPass(pass); + options.blend_mode = BlendMode::kSrc; + options.primitive_type = PrimitiveType::kTriangleStrip; + + pass.SetCommandLabel("Framebuffer Advanced Blend Filter"); + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + switch (blend_mode) { + case BlendMode::kScreen: + pass.SetPipeline(renderer.GetFramebufferBlendScreenPipeline(options)); + break; + case BlendMode::kOverlay: + pass.SetPipeline( + renderer.GetFramebufferBlendOverlayPipeline(options)); + break; + case BlendMode::kDarken: + pass.SetPipeline(renderer.GetFramebufferBlendDarkenPipeline(options)); + break; + case BlendMode::kLighten: + pass.SetPipeline( + renderer.GetFramebufferBlendLightenPipeline(options)); + break; + case BlendMode::kColorDodge: + pass.SetPipeline( + renderer.GetFramebufferBlendColorDodgePipeline(options)); + break; + case BlendMode::kColorBurn: + pass.SetPipeline( + renderer.GetFramebufferBlendColorBurnPipeline(options)); + break; + case BlendMode::kHardLight: + pass.SetPipeline( + renderer.GetFramebufferBlendHardLightPipeline(options)); + break; + case BlendMode::kSoftLight: + pass.SetPipeline( + renderer.GetFramebufferBlendSoftLightPipeline(options)); + break; + case BlendMode::kDifference: + pass.SetPipeline( + renderer.GetFramebufferBlendDifferencePipeline(options)); + break; + case BlendMode::kExclusion: + pass.SetPipeline( + renderer.GetFramebufferBlendExclusionPipeline(options)); + break; + case BlendMode::kMultiply: + pass.SetPipeline( + renderer.GetFramebufferBlendMultiplyPipeline(options)); + break; + case BlendMode::kHue: + pass.SetPipeline(renderer.GetFramebufferBlendHuePipeline(options)); + break; + case BlendMode::kSaturation: + pass.SetPipeline( + renderer.GetFramebufferBlendSaturationPipeline(options)); + break; + case BlendMode::kColor: + pass.SetPipeline(renderer.GetFramebufferBlendColorPipeline(options)); + break; + case BlendMode::kLuminosity: + pass.SetPipeline( + renderer.GetFramebufferBlendLuminosityPipeline(options)); + break; + default: + return false; + } + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + + raw_ptr src_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + src_sampler_descriptor); + FS::BindTextureSamplerSrc(pass, src_texture, src_sampler); + + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); + frame_info.src_y_coord_scale = src_texture->GetYCoordScale(); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + frag_info.src_input_alpha = 1.0; + frag_info.dst_input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? dst_snapshot->opacity + : 1.0; + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + return pass.Draw().ok(); + } + }; + + std::shared_ptr cmd_buffer = + renderer.GetContext()->CreateCommandBuffer(); + + // Generate a 1x1 texture to implement foreground color blending. + if (foreground_color.has_value()) { + TextureDescriptor desc; + desc.size = {1, 1}; + desc.format = PixelFormat::kR8G8B8A8UNormInt; + desc.storage_mode = StorageMode::kDevicePrivate; + foreground_texture = + renderer.GetContext()->GetResourceAllocator()->CreateTexture(desc); + if (!foreground_texture) { + return std::nullopt; + } + auto blit_pass = cmd_buffer->CreateBlitPass(); + auto buffer_view = renderer.GetTransientsBuffer().Emplace( + foreground_color->Premultiply().ToR8G8B8A8(), /*alignment=*/4); + + blit_pass->AddCopy(std::move(buffer_view), foreground_texture); + if (!blit_pass->EncodeCommands()) { + return std::nullopt; + } + } + + auto render_target = + renderer.MakeSubpass("FramebufferBlend", dst_snapshot->texture->GetSize(), + cmd_buffer, subpass_callback); + + if (!render_target.ok()) { + return std::nullopt; + } + if (!renderer.GetContext()->EnqueueCommandBuffer(std::move(cmd_buffer))) { + return std::nullopt; + } + + return Entity::FromSnapshot( + Snapshot{ + .texture = render_target.value().GetRenderTargetTexture(), + .transform = dst_snapshot->transform, + // Since we absorbed the transform of the inputs and used the + // respective snapshot sampling modes when blending, pass on + // the default NN clamp sampler. + .sampler_descriptor = {}, + .opacity = (absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? 1.0f + : dst_snapshot->opacity) * + alpha.value_or(1.0)}, + entity.GetBlendMode()); +} + +#define BLEND_CASE(mode) \ + case BlendMode::k##mode: \ + advanced_blend_proc_ = \ + [](const FilterInput::Vector& inputs, const ContentContext& renderer, \ + const Entity& entity, const Rect& coverage, BlendMode blend_mode, \ + std::optional fg_color, \ + ColorFilterContents::AbsorbOpacity absorb_opacity, \ + std::optional alpha) { \ + PipelineProc p = &ContentContext::GetBlend##mode##Pipeline; \ + return AdvancedBlend( \ + inputs, renderer, entity, coverage, blend_mode, fg_color, \ + absorb_opacity, p, alpha); \ + }; \ + break; + +void BlendFilterContents::SetBlendMode(BlendMode blend_mode) { + if (blend_mode > Entity::kLastAdvancedBlendMode) { + VALIDATION_LOG << "Invalid blend mode " << static_cast(blend_mode) + << " assigned to BlendFilterContents."; + } + + blend_mode_ = blend_mode; + + if (blend_mode > Entity::kLastPipelineBlendMode) { + switch (blend_mode) { + BLEND_CASE(Screen) + BLEND_CASE(Overlay) + BLEND_CASE(Darken) + BLEND_CASE(Lighten) + BLEND_CASE(ColorDodge) + BLEND_CASE(ColorBurn) + BLEND_CASE(HardLight) + BLEND_CASE(SoftLight) + BLEND_CASE(Difference) + BLEND_CASE(Exclusion) + BLEND_CASE(Multiply) + BLEND_CASE(Hue) + BLEND_CASE(Saturation) + BLEND_CASE(Color) + BLEND_CASE(Luminosity) + default: + FML_UNREACHABLE(); + } + } +} + +void BlendFilterContents::SetForegroundColor(std::optional color) { + foreground_color_ = color; +} + +std::optional BlendFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.empty()) { + return std::nullopt; + } + + if (inputs.size() == 1 && !foreground_color_.has_value()) { + // Nothing to blend. + return PipelineBlend(inputs, renderer, entity, coverage, BlendMode::kSrc, + std::nullopt, GetAbsorbOpacity(), GetAlpha()); + } + + if (blend_mode_ <= Entity::kLastPipelineBlendMode) { + if (inputs.size() == 1 && foreground_color_.has_value() && + GetAbsorbOpacity() == ColorFilterContents::AbsorbOpacity::kYes) { + return CreateForegroundPorterDuffBlend( + inputs[0], renderer, entity, coverage, foreground_color_.value(), + blend_mode_, GetAlpha(), GetAbsorbOpacity()); + } + return PipelineBlend(inputs, renderer, entity, coverage, blend_mode_, + foreground_color_, GetAbsorbOpacity(), GetAlpha()); + } + + if (blend_mode_ <= Entity::kLastAdvancedBlendMode) { + if (renderer.GetDeviceCapabilities().SupportsFramebufferFetch()) { + return CreateFramebufferAdvancedBlend(inputs, renderer, entity, coverage, + foreground_color_, blend_mode_, + GetAlpha(), GetAbsorbOpacity()); + } + if (inputs.size() == 1 && foreground_color_.has_value() && + GetAbsorbOpacity() == ColorFilterContents::AbsorbOpacity::kYes) { + return CreateForegroundAdvancedBlend( + inputs[0], renderer, entity, coverage, foreground_color_.value(), + blend_mode_, GetAlpha(), GetAbsorbOpacity()); + } + return advanced_blend_proc_(inputs, renderer, entity, coverage, blend_mode_, + foreground_color_, GetAbsorbOpacity(), + GetAlpha()); + } + + FML_UNREACHABLE(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..9d4fcee8209245a7466ad4b3a3e20fe41a7d6085 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents.h @@ -0,0 +1,123 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BLEND_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BLEND_FILTER_CONTENTS_H_ + +#include +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +constexpr std::array, 15> kPorterDuffCoefficients = {{ + {0, 0, 0, 0, 0}, // Clear + {1, 0, 0, 0, 0}, // Source + {0, 0, 1, 0, 0}, // Destination + {1, 0, 1, -1, 0}, // SourceOver + {1, -1, 1, 0, 0}, // DestinationOver + {0, 1, 0, 0, 0}, // SourceIn + {0, 0, 0, 1, 0}, // DestinationIn + {1, -1, 0, 0, 0}, // SourceOut + {0, 0, 1, -1, 0}, // DestinationOut + {0, 1, 1, -1, 0}, // SourceATop + {1, -1, 0, 1, 0}, // DestinationATop + {1, -1, 1, -1, 0}, // Xor + {1, 0, 1, 0, 0}, // Plus + {0, 0, 0, 0, 1}, // Modulate + {0, 0, 1, 0, -1}, // Screen +}}; + +std::optional InvertPorterDuffBlend(BlendMode blend_mode); + +class BlendFilterContents : public ColorFilterContents { + public: + using AdvancedBlendProc = std::function( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + BlendMode blend_mode, + std::optional foreground_color, + ColorFilterContents::AbsorbOpacity absorb_opacity, + std::optional alpha)>; + + BlendFilterContents(); + + ~BlendFilterContents() override; + + void SetBlendMode(BlendMode blend_mode); + + /// @brief Sets a source color which is blended after all of the inputs have + /// been blended. + void SetForegroundColor(std::optional color); + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + /// @brief Optimized advanced blend that avoids a second subpass when there is + /// only a single input and a foreground color. + /// + /// These contents cannot absorb opacity. + std::optional CreateForegroundAdvancedBlend( + const std::shared_ptr& input, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + Color foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const; + + /// @brief Implements the advanced blends filters in terms of the framebuffer + /// blend filters. + /// + /// This requires device support for frameuffer fetch, + /// `Capabilities::SupportsFramebufferFetch` must be true + /// This allows a substantial reduction in the number of bootstrapped + /// shaders. + std::optional CreateFramebufferAdvancedBlend( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + std::optional foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const; + + /// @brief Optimized porter-duff blend that avoids a second subpass when there + /// is only a single input and a foreground color. + /// + /// These contents cannot absorb opacity. + std::optional CreateForegroundPorterDuffBlend( + const std::shared_ptr& input, + const ContentContext& renderer, + const Entity& entity, + const Rect& coverage, + Color foreground_color, + BlendMode blend_mode, + std::optional alpha, + ColorFilterContents::AbsorbOpacity absorb_opacity) const; + + BlendMode blend_mode_ = BlendMode::kSrcOver; + AdvancedBlendProc advanced_blend_proc_; + std::optional foreground_color_; + + BlendFilterContents(const BlendFilterContents&) = delete; + + BlendFilterContents& operator=(const BlendFilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BLEND_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc8176679e4046d6e03b25935367882b9d21725a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/blend_filter_contents_unittests.cc @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/filters/blend_filter_contents.h" +#include "impeller/entity/entity_playground.h" + +namespace impeller { +namespace testing { + +class BlendFilterContentsTest : public EntityPlayground { + public: + /// Create a texture that has been cleared to transparent black. + std::shared_ptr MakeTexture(ISize size) { + std::shared_ptr command_buffer = + GetContentContext()->GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return nullptr; + } + + auto render_target = GetContentContext()->MakeSubpass( + "Clear Subpass", size, command_buffer, + [](const ContentContext&, RenderPass&) { return true; }); + + if (!GetContentContext() + ->GetContext() + ->GetCommandQueue() + ->Submit(/*buffers=*/{command_buffer}) + .ok()) { + return nullptr; + } + + if (render_target.ok()) { + return render_target.value().GetRenderTargetTexture(); + } + return nullptr; + } +}; +INSTANTIATE_PLAYGROUND_SUITE(BlendFilterContentsTest); + +// https://github.com/flutter/flutter/issues/149216 +TEST_P(BlendFilterContentsTest, AdvancedBlendColorAlignsColorTo4) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + BlendFilterContents filter_contents; + filter_contents.SetInputs({FilterInput::Make(texture)}); + filter_contents.SetForegroundColor(Color(1.0, 0.0, 0.0, 1.0)); + filter_contents.SetBlendMode(BlendMode::kColorDodge); + + std::shared_ptr renderer = GetContentContext(); + // Add random byte to get the HostBuffer in a bad alignment. + uint8_t byte = 0xff; + BufferView buffer_view = + renderer->GetTransientsBuffer().Emplace(&byte, /*length=*/1, /*align=*/1); + EXPECT_EQ(buffer_view.GetRange().offset, 4u); + EXPECT_EQ(buffer_view.GetRange().length, 1u); + Entity entity; + + std::optional result = filter_contents.GetEntity( + *renderer, entity, /*coverage_hint=*/std::nullopt); + + EXPECT_TRUE(result.has_value()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..2e89685e19e468056bdbe1404f9f9b308a6dbb80 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.cc @@ -0,0 +1,175 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/border_mask_blur_filter_contents.h" +#include "impeller/entity/contents/content_context.h" + +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +BorderMaskBlurFilterContents::BorderMaskBlurFilterContents() = default; + +BorderMaskBlurFilterContents::~BorderMaskBlurFilterContents() = default; + +void BorderMaskBlurFilterContents::SetSigma(Sigma sigma_x, Sigma sigma_y) { + sigma_x_ = sigma_x; + sigma_y_ = sigma_y; +} + +void BorderMaskBlurFilterContents::SetBlurStyle(BlurStyle blur_style) { + blur_style_ = blur_style; + + switch (blur_style) { + case FilterContents::BlurStyle::kNormal: + src_color_factor_ = false; + inner_blur_factor_ = true; + outer_blur_factor_ = true; + break; + case FilterContents::BlurStyle::kSolid: + src_color_factor_ = true; + inner_blur_factor_ = false; + outer_blur_factor_ = true; + break; + case FilterContents::BlurStyle::kOuter: + src_color_factor_ = false; + inner_blur_factor_ = false; + outer_blur_factor_ = true; + break; + case FilterContents::BlurStyle::kInner: + src_color_factor_ = false; + inner_blur_factor_ = true; + outer_blur_factor_ = false; + break; + } +} + +std::optional BorderMaskBlurFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + using VS = BorderMaskBlurPipeline::VertexShader; + using FS = BorderMaskBlurPipeline::FragmentShader; + + //---------------------------------------------------------------------------- + /// Handle inputs. + /// + + if (inputs.empty()) { + return std::nullopt; + } + + auto input_snapshot = + inputs[0]->GetSnapshot("BorderMaskBlur", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + auto maybe_input_uvs = input_snapshot->GetCoverageUVs(coverage); + if (!maybe_input_uvs.has_value()) { + return std::nullopt; + } + auto input_uvs = maybe_input_uvs.value(); + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + + auto sigma = effect_transform * Vector2(sigma_x_.sigma, sigma_y_.sigma); + RenderProc render_proc = [coverage, input_snapshot, input_uvs = input_uvs, + src_color_factor = src_color_factor_, + inner_blur_factor = inner_blur_factor_, + outer_blur_factor = outer_blur_factor_, sigma]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + auto& host_buffer = renderer.GetTransientsBuffer(); + + auto origin = coverage.GetOrigin(); + auto size = coverage.GetSize(); + std::array vertices = { + VS::PerVertexData{origin, input_uvs[0]}, + VS::PerVertexData{{origin.x + size.width, origin.y}, input_uvs[1]}, + VS::PerVertexData{{origin.x, origin.y + size.height}, input_uvs[2]}, + VS::PerVertexData{{origin.x + size.width, origin.y + size.height}, + input_uvs[3]}, + }; + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + + VS::FrameInfo frame_info; + frame_info.mvp = entity.GetShaderTransform(pass); + frame_info.texture_sampler_y_coord_scale = + input_snapshot->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + frag_info.sigma_uv = sigma.Abs() / input_snapshot->texture->GetSize(); + frag_info.src_factor = src_color_factor; + frag_info.inner_blur_factor = inner_blur_factor; + frag_info.outer_blur_factor = outer_blur_factor; + + pass.SetCommandLabel("Border Mask Blur Filter"); + pass.SetPipeline(renderer.GetBorderMaskBlurPipeline(options)); + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + raw_ptr sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler({}); + FS::BindTextureSampler(pass, input_snapshot->texture, sampler); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + return sub_entity; +} + +std::optional BorderMaskBlurFilterContents::GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const { + if (inputs.empty()) { + return std::nullopt; + } + + auto coverage = inputs[0]->GetCoverage(entity); + if (!coverage.has_value()) { + return std::nullopt; + } + auto transform = inputs[0]->GetTransform(entity) * effect_transform; + auto transformed_blur_vector = + transform.TransformDirection(Vector2(Radius{sigma_x_}.radius, 0)).Abs() + + transform.TransformDirection(Vector2(0, Radius{sigma_y_}.radius)).Abs(); + return coverage->Expand(transformed_blur_vector); +} + +std::optional BorderMaskBlurFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + auto transformed_blur_vector = + effect_transform.TransformDirection(Vector2(Radius{sigma_x_}.radius, 0)) + .Abs() + + effect_transform.TransformDirection(Vector2(0, Radius{sigma_y_}.radius)) + .Abs(); + return output_limit.Expand(transformed_blur_vector); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..10be38dbb72edc8900e0de5f6c762caa5abc7e36 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/border_mask_blur_filter_contents.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BORDER_MASK_BLUR_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BORDER_MASK_BLUR_FILTER_CONTENTS_H_ + +#include +#include +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class BorderMaskBlurFilterContents final : public FilterContents { + public: + BorderMaskBlurFilterContents(); + + ~BorderMaskBlurFilterContents() override; + + void SetSigma(Sigma sigma_x, Sigma sigma_y); + + void SetBlurStyle(BlurStyle blur_style); + + // |FilterContents| + std::optional GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + Sigma sigma_x_; + Sigma sigma_y_; + BlurStyle blur_style_ = BlurStyle::kNormal; + bool src_color_factor_ = false; + bool inner_blur_factor_ = true; + bool outer_blur_factor_ = true; + + BorderMaskBlurFilterContents(const BorderMaskBlurFilterContents&) = delete; + + BorderMaskBlurFilterContents& operator=(const BorderMaskBlurFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_BORDER_MASK_BLUR_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..6c88925be3e14306c0951db3db3034fcead93599 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.cc @@ -0,0 +1,112 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/color_filter_contents.h" + +#include + +#include "impeller/base/validation.h" +#include "impeller/entity/contents/filters/blend_filter_contents.h" +#include "impeller/entity/contents/filters/color_matrix_filter_contents.h" +#include "impeller/entity/contents/filters/linear_to_srgb_filter_contents.h" +#include "impeller/entity/contents/filters/srgb_to_linear_filter_contents.h" + +namespace impeller { + +std::shared_ptr ColorFilterContents::MakeBlend( + BlendMode blend_mode, + FilterInput::Vector inputs, + std::optional foreground_color) { + if (blend_mode > Entity::kLastAdvancedBlendMode) { + VALIDATION_LOG << "Invalid blend mode " << static_cast(blend_mode) + << " passed to ColorFilterContents::MakeBlend."; + return nullptr; + } + + size_t total_inputs = inputs.size() + (foreground_color.has_value() ? 1 : 0); + if (total_inputs < 2 || blend_mode <= Entity::kLastPipelineBlendMode) { + auto blend = std::make_shared(); + blend->SetInputs(inputs); + blend->SetBlendMode(blend_mode); + blend->SetForegroundColor(foreground_color); + return blend; + } + + auto blend_input = inputs[0]; + std::shared_ptr new_blend; + for (auto in_i = inputs.begin() + 1; in_i < inputs.end(); in_i++) { + new_blend = std::make_shared(); + new_blend->SetInputs({blend_input, *in_i}); + new_blend->SetBlendMode(blend_mode); + if (in_i < inputs.end() - 1 || foreground_color.has_value()) { + blend_input = FilterInput::Make( + std::static_pointer_cast(new_blend)); + } + } + + if (foreground_color.has_value()) { + new_blend = std::make_shared(); + new_blend->SetInputs({blend_input}); + new_blend->SetBlendMode(blend_mode); + new_blend->SetForegroundColor(foreground_color); + } + + return new_blend; +} + +std::shared_ptr ColorFilterContents::MakeColorMatrix( + FilterInput::Ref input, + const ColorMatrix& color_matrix) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetMatrix(color_matrix); + return filter; +} + +std::shared_ptr +ColorFilterContents::MakeLinearToSrgbFilter(FilterInput::Ref input) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + return filter; +} + +std::shared_ptr +ColorFilterContents::MakeSrgbToLinearFilter(FilterInput::Ref input) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + return filter; +} + +ColorFilterContents::ColorFilterContents() = default; + +ColorFilterContents::~ColorFilterContents() = default; + +void ColorFilterContents::SetAbsorbOpacity(AbsorbOpacity absorb_opacity) { + absorb_opacity_ = absorb_opacity; +} + +ColorFilterContents::AbsorbOpacity ColorFilterContents::GetAbsorbOpacity() + const { + return absorb_opacity_; +} + +void ColorFilterContents::SetAlpha(Scalar alpha) { + alpha_ = alpha; +} + +std::optional ColorFilterContents::GetAlpha() const { + return alpha_.value_or(1.0) * inherited_opacity_; +} + +void ColorFilterContents::SetInheritedOpacity(Scalar opacity) { + inherited_opacity_ = opacity; +} + +std::optional ColorFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + return output_limit; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..9acaec6b436797784da810ca4dfc765f0d916c07 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_filter_contents.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/filter_contents.h" + +namespace impeller { + +class ColorFilterContents : public FilterContents { + public: + enum class AbsorbOpacity { + kYes, + kNo, + }; + + /// @brief the [inputs] are expected to be in the order of dst, src. + static std::shared_ptr MakeBlend( + BlendMode blend_mode, + FilterInput::Vector inputs, + std::optional foreground_color = std::nullopt); + + static std::shared_ptr MakeColorMatrix( + FilterInput::Ref input, + const ColorMatrix& color_matrix); + + static std::shared_ptr MakeLinearToSrgbFilter( + FilterInput::Ref input); + + static std::shared_ptr MakeSrgbToLinearFilter( + FilterInput::Ref input); + + ColorFilterContents(); + + ~ColorFilterContents() override; + + void SetAbsorbOpacity(AbsorbOpacity absorb_opacity); + + AbsorbOpacity GetAbsorbOpacity() const; + + /// @brief Sets an alpha that is applied to the final blended result. + void SetAlpha(Scalar alpha); + + std::optional GetAlpha() const; + + // |Contents| + void SetInheritedOpacity(Scalar opacity) override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + private: + AbsorbOpacity absorb_opacity_ = AbsorbOpacity::kNo; + std::optional alpha_; + Scalar inherited_opacity_ = 1.0; + + ColorFilterContents(const ColorFilterContents&) = delete; + + ColorFilterContents& operator=(const ColorFilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..337512f9a4ff501bf84bf7b6dd8c0dd4ac9cecd3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.cc @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/color_matrix_filter_contents.h" + +#include + +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/vector.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +ColorMatrixFilterContents::ColorMatrixFilterContents() = default; + +ColorMatrixFilterContents::~ColorMatrixFilterContents() = default; + +void ColorMatrixFilterContents::SetMatrix(const ColorMatrix& matrix) { + matrix_ = matrix; +} + +std::optional ColorMatrixFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + using VS = ColorMatrixColorFilterPipeline::VertexShader; + using FS = ColorMatrixColorFilterPipeline::FragmentShader; + + //---------------------------------------------------------------------------- + /// Handle inputs. + /// + + if (inputs.empty()) { + return std::nullopt; + } + + auto input_snapshot = inputs[0]->GetSnapshot("ColorMatrix", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + RenderProc render_proc = [input_snapshot, color_matrix = matrix_, + absorb_opacity = GetAbsorbOpacity()]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + pass.SetCommandLabel("Color Matrix Filter"); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetColorMatrixColorFilterPipeline(options)); + + auto size = input_snapshot->texture->GetSize(); + + std::array vertices = { + VS::PerVertexData{Point(0, 0), Point(0, 0)}, + VS::PerVertexData{Point(1, 0), Point(1, 0)}, + VS::PerVertexData{Point(0, 1), Point(0, 1)}, + VS::PerVertexData{Point(1, 1), Point(1, 1)}, + }; + auto& host_buffer = renderer.GetTransientsBuffer(); + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::FrameInfo frame_info; + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * input_snapshot->transform * + Matrix::MakeScale(Vector2(size))); + frame_info.texture_sampler_y_coord_scale = + input_snapshot->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + const float* matrix = color_matrix.array; + frag_info.color_v = Vector4(matrix[4], matrix[9], matrix[14], matrix[19]); + frag_info.color_m = Matrix(matrix[0], matrix[5], matrix[10], matrix[15], // + matrix[1], matrix[6], matrix[11], matrix[16], // + matrix[2], matrix[7], matrix[12], matrix[17], // + matrix[3], matrix[8], matrix[13], matrix[18] // + ); + frag_info.input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? input_snapshot->opacity + : 1.0f; + frag_info.output_alpha = 1; + + raw_ptr sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler({}); + FS::BindInputTexture(pass, input_snapshot->texture, sampler); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + return sub_entity; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..e394125f79b9a083b4b29b26337f9215858383a3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/color_matrix_filter_contents.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_ + +#include +#include + +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +// Look at example at: https://github.com/flutter/impeller/pull/132 + +class ColorMatrixFilterContents final : public ColorFilterContents { + public: + ColorMatrixFilterContents(); + + ~ColorMatrixFilterContents() override; + + void SetMatrix(const ColorMatrix& matrix); + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + ColorMatrix matrix_; + + ColorMatrixFilterContents(const ColorMatrixFilterContents&) = delete; + + ColorMatrixFilterContents& operator=(const ColorMatrixFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_COLOR_MATRIX_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d42ad104dff25b55cca17d185888c2c936af7b7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.cc @@ -0,0 +1,290 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/filter_contents.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/filters/border_mask_blur_filter_contents.h" +#include "impeller/entity/contents/filters/gaussian_blur_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" +#include "impeller/entity/contents/filters/local_matrix_filter_contents.h" +#include "impeller/entity/contents/filters/matrix_filter_contents.h" +#include "impeller/entity/contents/filters/morphology_filter_contents.h" +#include "impeller/entity/contents/filters/runtime_effect_filter_contents.h" +#include "impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h" +#include "impeller/entity/contents/texture_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace impeller { + +const int32_t FilterContents::kBlurFilterRequiredMipCount = + GaussianBlurFilterContents::kBlurFilterRequiredMipCount; + +std::shared_ptr FilterContents::MakeGaussianBlur( + const FilterInput::Ref& input, + Sigma sigma_x, + Sigma sigma_y, + Entity::TileMode tile_mode, + FilterContents::BlurStyle mask_blur_style, + const Geometry* mask_geometry) { + auto blur = std::make_shared( + sigma_x.sigma, sigma_y.sigma, tile_mode, mask_blur_style, mask_geometry); + blur->SetInputs({input}); + return blur; +} + +std::shared_ptr FilterContents::MakeBorderMaskBlur( + FilterInput::Ref input, + Sigma sigma_x, + Sigma sigma_y, + BlurStyle blur_style) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetSigma(sigma_x, sigma_y); + filter->SetBlurStyle(blur_style); + return filter; +} + +std::shared_ptr FilterContents::MakeDirectionalMorphology( + FilterInput::Ref input, + Radius radius, + Vector2 direction, + MorphType morph_type) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetRadius(radius); + filter->SetDirection(direction); + filter->SetMorphType(morph_type); + return filter; +} + +std::shared_ptr FilterContents::MakeMorphology( + FilterInput::Ref input, + Radius radius_x, + Radius radius_y, + MorphType morph_type) { + auto x_morphology = MakeDirectionalMorphology(std::move(input), radius_x, + Point(1, 0), morph_type); + auto y_morphology = MakeDirectionalMorphology( + FilterInput::Make(x_morphology), radius_y, Point(0, 1), morph_type); + return y_morphology; +} + +std::shared_ptr FilterContents::MakeMatrixFilter( + FilterInput::Ref input, + const Matrix& matrix, + const SamplerDescriptor& desc) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetMatrix(matrix); + filter->SetSamplerDescriptor(desc); + return filter; +} + +std::shared_ptr FilterContents::MakeLocalMatrixFilter( + FilterInput::Ref input, + const Matrix& matrix) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetMatrix(matrix); + return filter; +} + +std::shared_ptr FilterContents::MakeYUVToRGBFilter( + std::shared_ptr y_texture, + std::shared_ptr uv_texture, + YUVColorSpace yuv_color_space) { + auto filter = std::make_shared(); + filter->SetInputs({impeller::FilterInput::Make(y_texture), + impeller::FilterInput::Make(uv_texture)}); + filter->SetYUVColorSpace(yuv_color_space); + return filter; +} + +std::shared_ptr FilterContents::MakeRuntimeEffect( + FilterInput::Ref input, + std::shared_ptr runtime_stage, + std::shared_ptr> uniforms, + std::vector texture_inputs) { + auto filter = std::make_shared(); + filter->SetInputs({std::move(input)}); + filter->SetRuntimeStage(std::move(runtime_stage)); + filter->SetUniforms(std::move(uniforms)); + filter->SetTextureInputs(std::move(texture_inputs)); + return filter; +} + +FilterContents::FilterContents() = default; + +FilterContents::~FilterContents() = default; + +void FilterContents::SetInputs(FilterInput::Vector inputs) { + inputs_ = std::move(inputs); +} + +void FilterContents::SetEffectTransform(const Matrix& effect_transform) { + effect_transform_ = effect_transform; + + for (auto& input : inputs_) { + input->SetEffectTransform(effect_transform); + } +} + +bool FilterContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto filter_coverage = GetCoverage(entity); + if (!filter_coverage.has_value()) { + return true; + } + + // Run the filter. + + auto maybe_entity = GetEntity(renderer, entity, GetCoverageHint()); + if (!maybe_entity.has_value()) { + return true; + } + maybe_entity->SetClipDepth(entity.GetClipDepth()); + return maybe_entity->Render(renderer, pass); +} + +std::optional FilterContents::GetLocalCoverage( + const Entity& local_entity) const { + auto coverage = GetFilterCoverage(inputs_, local_entity, effect_transform_); + auto coverage_hint = GetCoverageHint(); + if (coverage_hint.has_value() && coverage.has_value()) { + coverage = coverage->Intersection(coverage_hint.value()); + } + + return coverage; +} + +std::optional FilterContents::GetCoverage(const Entity& entity) const { + Entity entity_with_local_transform = entity.Clone(); + entity_with_local_transform.SetTransform(GetTransform(entity.GetTransform())); + + return GetLocalCoverage(entity_with_local_transform); +} + +std::optional FilterContents::GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const { + // The default coverage of FilterContents is just the union of its inputs' + // coverage. FilterContents implementations may choose to adjust this + // coverage depending on the use case. + + if (inputs_.empty()) { + return std::nullopt; + } + + std::optional result; + for (const auto& input : inputs) { + auto coverage = input->GetCoverage(entity); + if (!coverage.has_value()) { + continue; + } + if (!result.has_value()) { + result = coverage; + continue; + } + result = result->Union(coverage.value()); + } + return result; +} + +std::optional FilterContents::GetSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + auto filter_input_coverage = + GetFilterSourceCoverage(effect_transform_, output_limit); + + if (!filter_input_coverage.has_value()) { + return std::nullopt; + } + + std::optional inputs_coverage; + for (const auto& input : inputs_) { + auto input_coverage = input->GetSourceCoverage( + effect_transform, filter_input_coverage.value()); + if (!input_coverage.has_value()) { + return std::nullopt; + } + inputs_coverage = Rect::Union(inputs_coverage, input_coverage.value()); + } + return inputs_coverage; +} + +std::optional FilterContents::GetEntity( + const ContentContext& renderer, + const Entity& entity, + const std::optional& coverage_hint) const { + Entity entity_with_local_transform = entity.Clone(); + entity_with_local_transform.SetTransform(GetTransform(entity.GetTransform())); + + auto coverage = GetLocalCoverage(entity_with_local_transform); + if (!coverage.has_value() || coverage->IsEmpty()) { + return std::nullopt; + } + + return RenderFilter(inputs_, renderer, entity_with_local_transform, + effect_transform_, coverage.value(), coverage_hint); +} + +std::optional FilterContents::RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + const std::optional& sampler_descriptor, + bool msaa_enabled, + int32_t mip_count, + std::string_view label) const { + // Resolve the render instruction (entity) from the filter and render it to a + // snapshot. + if (std::optional result = + GetEntity(renderer, entity, coverage_limit); + result.has_value()) { + return result->GetContents()->RenderToSnapshot( + renderer, // renderer + result.value(), // entity + coverage_limit, // coverage_limit + std::nullopt, // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/mip_count, + label // label + ); + } + + return std::nullopt; +} + +Matrix FilterContents::GetLocalTransform(const Matrix& parent_transform) const { + return Matrix(); +} + +Matrix FilterContents::GetTransform(const Matrix& parent_transform) const { + return parent_transform * GetLocalTransform(parent_transform); +} + +void FilterContents::SetRenderingMode(Entity::RenderingMode rendering_mode) { + for (auto& input : inputs_) { + input->SetRenderingMode(rendering_mode); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..baa168f16719bdbfea2dbef21b43353f83c231b7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/filter_contents.h @@ -0,0 +1,219 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_FILTER_CONTENTS_H_ + +#include +#include +#include +#include + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" +#include "impeller/entity/contents/runtime_effect_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/sigma.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace impeller { + +class FilterContents : public Contents { + public: + static const int32_t kBlurFilterRequiredMipCount; + + enum class BlurStyle { + /// Blurred inside and outside. + kNormal, + /// Solid inside, blurred outside. + kSolid, + /// Nothing inside, blurred outside. + kOuter, + /// Blurred inside, nothing outside. + kInner, + }; + + enum class MorphType { kDilate, kErode }; + + /// Creates a gaussian blur that operates in 2 dimensions. + /// See also: `MakeDirectionalGaussianBlur` + static std::shared_ptr MakeGaussianBlur( + const FilterInput::Ref& input, + Sigma sigma_x, + Sigma sigma_y, + Entity::TileMode tile_mode = Entity::TileMode::kDecal, + BlurStyle mask_blur_style = BlurStyle::kNormal, + const Geometry* mask_geometry = nullptr); + + static std::shared_ptr MakeBorderMaskBlur( + FilterInput::Ref input, + Sigma sigma_x, + Sigma sigma_y, + BlurStyle blur_style = BlurStyle::kNormal); + + static std::shared_ptr MakeDirectionalMorphology( + FilterInput::Ref input, + Radius radius, + Vector2 direction, + MorphType morph_type); + + static std::shared_ptr MakeMorphology(FilterInput::Ref input, + Radius radius_x, + Radius radius_y, + MorphType morph_type); + + static std::shared_ptr MakeMatrixFilter( + FilterInput::Ref input, + const Matrix& matrix, + const SamplerDescriptor& desc); + + static std::shared_ptr MakeLocalMatrixFilter( + FilterInput::Ref input, + const Matrix& matrix); + + static std::shared_ptr MakeYUVToRGBFilter( + std::shared_ptr y_texture, + std::shared_ptr uv_texture, + YUVColorSpace yuv_color_space); + + static std::shared_ptr MakeRuntimeEffect( + FilterInput::Ref input, + std::shared_ptr runtime_stage, + std::shared_ptr> uniforms, + std::vector texture_inputs); + + FilterContents(); + + ~FilterContents() override; + + /// @brief The input texture sources for this filter. Each input's emitted + /// texture is expected to have premultiplied alpha colors. + /// + /// The number of required or optional textures depends on the + /// particular filter's implementation. + void SetInputs(FilterInput::Vector inputs); + + /// @brief Sets the transform which gets appended to the effect of this + /// filter. Note that this is in addition to the entity's transform. + /// + /// This is useful for subpass rendering scenarios where it's + /// difficult to encode the current transform of the layer into the + /// Entity being rendered. + void SetEffectTransform(const Matrix& effect_transform); + + /// @brief Create an Entity that renders this filter's output. + std::optional GetEntity( + const ContentContext& renderer, + const Entity& entity, + const std::optional& coverage_hint) const; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + std::optional RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit = std::nullopt, + const std::optional& sampler_descriptor = std::nullopt, + bool msaa_enabled = true, + int32_t mip_count = 1, + std::string_view label = "Filter Snapshot") const override; + + /// @brief Determines the coverage of source pixels that will be needed + /// to produce results for the specified |output_limit| under the + /// specified |effect_transform|. This is essentially a reverse of + /// the |GetCoverage| method computing a source coverage from + /// an intended |output_limit| coverage. + /// + /// Both the |output_limit| and the return value are in the + /// transformed coordinate space, and so do not need to be + /// transformed or inverse transformed by the |effect_transform| + /// but individual parameters on the filter might be in the + /// untransformed space and should be transformed by the + /// |effect_transform| before applying them to the coverages. + /// + /// The method computes a result such that if the filter is applied + /// to a set of pixels filling the computed source coverage, it + /// should produce an output that covers the entire specified + /// |output_limit|. + /// + /// This is useful for subpass rendering scenarios where a filter + /// will be applied to the output of the subpass and we need to + /// determine how large of a render target to allocate in order + /// to collect all pixels that might affect the supplied output + /// coverage limit. While we might end up clipping the rendering + /// of the subpass to its destination, we want to avoid clipping + /// out any pixels that contribute to the output limit via the + /// filtering operation. + /// + /// @return The coverage bounds in the transformed space of any source pixel + /// that may be needed to produce output for the indicated filter + /// that covers the indicated |output_limit|. + std::optional GetSourceCoverage(const Matrix& effect_transform, + const Rect& output_limit) const; + + virtual Matrix GetLocalTransform(const Matrix& parent_transform) const; + + Matrix GetTransform(const Matrix& parent_transform) const; + + /// @brief Marks this filter chain as applying in a subpass scenario. + /// + /// Subpasses render in screenspace, and this setting informs filters + /// that the current transform matrix of the entity is not stored + /// in the Entity transform matrix. Instead, the effect transform + /// is used in this case. + virtual void SetRenderingMode(Entity::RenderingMode rendering_mode); + + private: + /// @brief Internal utility method for |GetLocalCoverage| that computes + /// the output coverage of this filter across the specified inputs, + /// ignoring the coverage hint. + virtual std::optional GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const; + + /// @brief Internal utility method for |GetSourceCoverage| that computes + /// the inverse effect of this transform on the specified output + /// coverage, ignoring the inputs which will be accommodated by + /// the caller. + virtual std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const = 0; + + /// @brief Converts zero or more filter inputs into a render instruction. + virtual std::optional RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const = 0; + + /// @brief Internal utility method to compute the coverage of this + /// filter across its internally specified inputs and subject + /// to the coverage hint. + /// + /// Uses |GetFilterCoverage|. + std::optional GetLocalCoverage(const Entity& local_entity) const; + + FilterInput::Vector inputs_; + Matrix effect_transform_ = Matrix(); + + FilterContents(const FilterContents&) = delete; + + FilterContents& operator=(const FilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d85fc66943e68de1e1a267ebdd4e278a097e353 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.cc @@ -0,0 +1,993 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/gaussian_blur_filter_contents.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/texture_downsample.frag.h" +#include "impeller/entity/texture_fill.frag.h" +#include "impeller/entity/texture_fill.vert.h" +#include "impeller/geometry/color.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +using GaussianBlurVertexShader = GaussianBlurPipeline::VertexShader; +using GaussianBlurFragmentShader = GaussianBlurPipeline::FragmentShader; + +namespace { + +constexpr Scalar kMaxSigma = 500.0f; + +SamplerDescriptor MakeSamplerDescriptor(MinMagFilter filter, + SamplerAddressMode address_mode) { + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = filter; + sampler_desc.mag_filter = filter; + sampler_desc.width_address_mode = address_mode; + sampler_desc.height_address_mode = address_mode; + return sampler_desc; +} + +void SetTileMode(SamplerDescriptor* descriptor, + const ContentContext& renderer, + Entity::TileMode tile_mode) { + switch (tile_mode) { + case Entity::TileMode::kDecal: + if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { + descriptor->width_address_mode = SamplerAddressMode::kDecal; + descriptor->height_address_mode = SamplerAddressMode::kDecal; + } + break; + case Entity::TileMode::kClamp: + descriptor->width_address_mode = SamplerAddressMode::kClampToEdge; + descriptor->height_address_mode = SamplerAddressMode::kClampToEdge; + break; + case Entity::TileMode::kMirror: + descriptor->width_address_mode = SamplerAddressMode::kMirror; + descriptor->height_address_mode = SamplerAddressMode::kMirror; + break; + case Entity::TileMode::kRepeat: + descriptor->width_address_mode = SamplerAddressMode::kRepeat; + descriptor->height_address_mode = SamplerAddressMode::kRepeat; + break; + } +} + +Vector2 Clamp(Vector2 vec2, Scalar min, Scalar max) { + return Vector2(std::clamp(vec2.x, /*lo=*/min, /*hi=*/max), + std::clamp(vec2.y, /*lo=*/min, /*hi=*/max)); +} + +Vector2 ExtractScale(const Matrix& matrix) { + Vector2 entity_scale_x = matrix * Vector2(1.0, 0.0); + Vector2 entity_scale_y = matrix * Vector2(0.0, 1.0); + return Vector2(entity_scale_x.GetLength(), entity_scale_y.GetLength()); +} + +struct BlurInfo { + /// The scalar that is used to get from source space to unrotated local space. + Vector2 source_space_scalar; + /// The translation that is used to get from source space to unrotated local + /// space. + Vector2 source_space_offset; + /// Sigma when considering an entity's scale and the effect transform. + Vector2 scaled_sigma; + /// Blur radius in source pixels based on scaled_sigma. + Vector2 blur_radius; + /// The halo padding in source space. + Vector2 padding; + /// Padding in unrotated local space. + Vector2 local_padding; +}; + +/// Calculates sigma derivatives necessary for rendering or calculating +/// coverage. +BlurInfo CalculateBlurInfo(const Entity& entity, + const Matrix& effect_transform, + Vector2 sigma) { + // Source space here is scaled by the entity's transform. This is a + // requirement for text to be rendered correctly. You can think of this as + // "scaled source space" or "un-rotated local space". The entity's rotation is + // applied to the result of the blur as part of the result's transform. + const Vector2 source_space_scalar = + ExtractScale(entity.GetTransform().Basis()); + const Vector2 source_space_offset = + Vector2(entity.GetTransform().m[12], entity.GetTransform().m[13]); + + Vector2 scaled_sigma = + (effect_transform.Basis() * Matrix::MakeScale(source_space_scalar) * // + Vector2(GaussianBlurFilterContents::ScaleSigma(sigma.x), + GaussianBlurFilterContents::ScaleSigma(sigma.y))) + .Abs(); + scaled_sigma = Clamp(scaled_sigma, 0, kMaxSigma); + Vector2 blur_radius = + Vector2(GaussianBlurFilterContents::CalculateBlurRadius(scaled_sigma.x), + GaussianBlurFilterContents::CalculateBlurRadius(scaled_sigma.y)); + Vector2 padding(ceil(blur_radius.x), ceil(blur_radius.y)); + Vector2 local_padding = + (Matrix::MakeScale(source_space_scalar) * padding).Abs(); + return { + .source_space_scalar = source_space_scalar, + .source_space_offset = source_space_offset, + .scaled_sigma = scaled_sigma, + .blur_radius = blur_radius, + .padding = padding, + .local_padding = local_padding, + }; +} + +/// Perform FilterInput::GetSnapshot with safety checks. +std::optional GetSnapshot(const std::shared_ptr& input, + const ContentContext& renderer, + const Entity& entity, + const std::optional& coverage_hint) { + std::optional input_snapshot = + input->GetSnapshot("GaussianBlur", renderer, entity, + /*coverage_limit=*/coverage_hint); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + return input_snapshot; +} + +/// Returns `rect` relative to `reference`, where Rect::MakeXYWH(0,0,1,1) will +/// be returned when `rect` == `reference`. +Rect MakeReferenceUVs(const Rect& reference, const Rect& rect) { + Rect result = Rect::MakeOriginSize(rect.GetOrigin() - reference.GetOrigin(), + rect.GetSize()); + return result.Scale(1.0f / Vector2(reference.GetSize())); +} + +Quad CalculateSnapshotUVs( + const Snapshot& input_snapshot, + const std::optional& source_expanded_coverage_hint) { + std::optional input_snapshot_coverage = input_snapshot.GetCoverage(); + Quad blur_uvs = {Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)}; + FML_DCHECK(input_snapshot.transform.IsTranslationScaleOnly()); + if (source_expanded_coverage_hint.has_value() && + input_snapshot_coverage.has_value()) { + // Only process the uvs where the blur is happening, not the whole texture. + std::optional uvs = + MakeReferenceUVs(input_snapshot_coverage.value(), + source_expanded_coverage_hint.value()) + .Intersection(Rect::MakeSize(Size(1, 1))); + FML_DCHECK(uvs.has_value()); + if (uvs.has_value()) { + blur_uvs[0] = uvs->GetLeftTop(); + blur_uvs[1] = uvs->GetRightTop(); + blur_uvs[2] = uvs->GetLeftBottom(); + blur_uvs[3] = uvs->GetRightBottom(); + } + } + return blur_uvs; +} + +Scalar CeilToDivisible(Scalar val, Scalar divisor) { + if (divisor == 0.0f) { + return val; + } + + Scalar remainder = fmod(val, divisor); + if (remainder != 0.0f) { + return val + (divisor - remainder); + } else { + return val; + } +} + +Scalar FloorToDivisible(Scalar val, Scalar divisor) { + if (divisor == 0.0f) { + return val; + } + + Scalar remainder = fmod(val, divisor); + if (remainder != 0.0f) { + return val - remainder; + } else { + return val; + } +} + +struct DownsamplePassArgs { + /// The output size of the down-sampling pass. + ISize subpass_size; + /// The UVs that will be used for drawing to the down-sampling pass. + /// This effectively is chopping out a region of the input. + Quad uvs; + /// The effective scalar of the down-sample pass. + /// This isn't usually exactly as we'd calculate because it has to be rounded + /// to integer boundaries for generating the texture for the output. + Vector2 effective_scalar; + /// Transforms from unrotated local space to position the output from the + /// down-sample pass. + /// This can differ if we request a coverage hint but it is rejected, as is + /// the case with backdrop filters. + Matrix transform; +}; + +/// Calculates info required for the down-sampling pass. +DownsamplePassArgs CalculateDownsamplePassArgs( + Vector2 scaled_sigma, + Vector2 padding, + const Snapshot& input_snapshot, + const std::optional& source_expanded_coverage_hint, + const std::shared_ptr& input, + const Entity& snapshot_entity) { + Scalar desired_scalar = + std::min(GaussianBlurFilterContents::CalculateScale(scaled_sigma.x), + GaussianBlurFilterContents::CalculateScale(scaled_sigma.y)); + + // TODO(jonahwilliams): If desired_scalar is 1.0 and we fully acquired the + // gutter from the expanded_coverage_hint, we can skip the downsample pass. + // pass. + Vector2 downsample_scalar(desired_scalar, desired_scalar); + // TODO(gaaclarke): The padding could be removed if we know it's not needed or + // resized to account for the expanded_clip_coverage. There doesn't appear + // to be the math to make those calculations though. The following + // optimization works, but causes a shimmer as a result of + // https://github.com/flutter/flutter/issues/140193 so it isn't applied. + // + // !input_snapshot->GetCoverage()->Expand(-local_padding) + // .Contains(coverage_hint.value())) + + std::optional snapshot_coverage = input_snapshot.GetCoverage(); + if (input_snapshot.transform.Equals(snapshot_entity.GetTransform()) && + source_expanded_coverage_hint.has_value() && + snapshot_coverage.has_value() && + snapshot_coverage->Contains(source_expanded_coverage_hint.value())) { + // If the snapshot's transform is the identity transform and we have + // coverage hint that fits inside of the snapshots coverage that means the + // coverage hint was ignored so we will trim out the area we are interested + // in the down-sample pass. This usually means we have a backdrop image + // filter. + // + // The region we cut out will be aligned with the down-sample divisor to + // avoid pixel alignment problems that create shimmering. + int32_t divisor = std::round(1.0f / desired_scalar); + Rect aligned_coverage_hint = Rect::MakeLTRB( + FloorToDivisible(source_expanded_coverage_hint->GetLeft(), divisor), + FloorToDivisible(source_expanded_coverage_hint->GetTop(), divisor), + source_expanded_coverage_hint->GetRight(), + source_expanded_coverage_hint->GetBottom()); + aligned_coverage_hint = Rect::MakeXYWH( + aligned_coverage_hint.GetX(), aligned_coverage_hint.GetY(), + CeilToDivisible(aligned_coverage_hint.GetWidth(), divisor), + CeilToDivisible(aligned_coverage_hint.GetHeight(), divisor)); + ISize source_size = ISize(aligned_coverage_hint.GetSize().width, + aligned_coverage_hint.GetSize().height); + Vector2 downsampled_size = source_size * downsample_scalar; + Scalar int_part; + FML_DCHECK(std::modf(downsampled_size.x, &int_part) == 0.0f); + FML_DCHECK(std::modf(downsampled_size.y, &int_part) == 0.0f); + (void)int_part; + ISize subpass_size = ISize(downsampled_size.x, downsampled_size.y); + Vector2 effective_scalar = Vector2(subpass_size) / source_size; + FML_DCHECK(effective_scalar == downsample_scalar); + + Quad uvs = CalculateSnapshotUVs(input_snapshot, aligned_coverage_hint); + return { + .subpass_size = subpass_size, + .uvs = uvs, + .effective_scalar = effective_scalar, + .transform = Matrix::MakeTranslation( + {aligned_coverage_hint.GetX(), aligned_coverage_hint.GetY(), 0})}; + } else { + ////////////////////////////////////////////////////////////////////////////// + auto input_snapshot_size = input_snapshot.texture->GetSize(); + Rect source_rect = Rect::MakeSize(input_snapshot_size); + Rect source_rect_padded = source_rect.Expand(padding); + Vector2 downsampled_size = source_rect_padded.GetSize() * downsample_scalar; + ISize subpass_size = + ISize(ceil(downsampled_size.x), ceil(downsampled_size.y)); + Vector2 divisible_size(CeilToDivisible(source_rect_padded.GetSize().width, + 1.0 / downsample_scalar.x), + CeilToDivisible(source_rect_padded.GetSize().height, + 1.0 / downsample_scalar.y)); + // Only make the padding divisible if we already have padding. If we don't + // have padding adding more can add artifacts to hard blur edges. + Vector2 divisible_padding( + padding.x > 0 + ? padding.x + + (divisible_size.x - source_rect_padded.GetSize().width) / 2.0 + : 0.f, + padding.y > 0 + ? padding.y + + (divisible_size.y - source_rect_padded.GetSize().height) / 2.0 + : 0.f); + source_rect_padded = source_rect.Expand(divisible_padding); + + Vector2 effective_scalar = + Vector2(subpass_size) / source_rect_padded.GetSize(); + Quad uvs = GaussianBlurFilterContents::CalculateUVs( + input, snapshot_entity, source_rect_padded, input_snapshot_size); + return { + .subpass_size = subpass_size, + .uvs = uvs, + .effective_scalar = effective_scalar, + .transform = input_snapshot.transform * + Matrix::MakeTranslation(-divisible_padding), + }; + } +} + +/// Makes a subpass that will render the scaled down input and add the +/// transparent gutter required for the blur halo. +fml::StatusOr MakeDownsampleSubpass( + const ContentContext& renderer, + const std::shared_ptr& command_buffer, + const std::shared_ptr& input_texture, + const SamplerDescriptor& sampler_descriptor, + const DownsamplePassArgs& pass_args, + Entity::TileMode tile_mode) { + using VS = TextureFillVertexShader; + + // If the texture already had mip levels generated, then we can use the + // original downsample shader. + if (pass_args.effective_scalar.x >= 0.5f || + (!input_texture->NeedsMipmapGeneration() && + input_texture->GetTextureDescriptor().mip_count > 1)) { + ContentContext::SubpassCallback subpass_callback = + [&](const ContentContext& renderer, RenderPass& pass) { + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + + pass.SetCommandLabel("Gaussian blur downsample"); + auto pipeline_options = OptionsFromPass(pass); + pipeline_options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetTexturePipeline(pipeline_options)); + + TextureFillVertexShader::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); + frame_info.texture_sampler_y_coord_scale = + input_texture->GetYCoordScale(); + + TextureFillFragmentShader::FragInfo frag_info; + frag_info.alpha = 1.0; + + const Quad& uvs = pass_args.uvs; + std::array vertices = { + VS::PerVertexData{Point(0, 0), uvs[0]}, + VS::PerVertexData{Point(1, 0), uvs[1]}, + VS::PerVertexData{Point(0, 1), uvs[2]}, + VS::PerVertexData{Point(1, 1), uvs[3]}, + }; + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + SamplerDescriptor linear_sampler_descriptor = sampler_descriptor; + SetTileMode(&linear_sampler_descriptor, renderer, tile_mode); + linear_sampler_descriptor.mag_filter = MinMagFilter::kLinear; + linear_sampler_descriptor.min_filter = MinMagFilter::kLinear; + TextureFillVertexShader::BindFrameInfo( + pass, host_buffer.EmplaceUniform(frame_info)); + TextureFillFragmentShader::BindFragInfo( + pass, host_buffer.EmplaceUniform(frag_info)); + TextureFillFragmentShader::BindTextureSampler( + pass, input_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + linear_sampler_descriptor)); + + return pass.Draw().ok(); + }; + return renderer.MakeSubpass("Gaussian Blur Filter", pass_args.subpass_size, + command_buffer, subpass_callback, + /*msaa_enabled=*/false, + /*depth_stencil_enabled=*/false); + } else { + // This assumes we don't scale below 1/16. + Scalar edge = 1.0; + Scalar ratio = 0.25; + if (pass_args.effective_scalar.x <= 0.0625f) { + edge = 7.0; + ratio = 1.0f / 64.0f; + } else if (pass_args.effective_scalar.x <= 0.125f) { + edge = 3.0; + ratio = 1.0f / 16.0f; + } + ContentContext::SubpassCallback subpass_callback = + [&](const ContentContext& renderer, RenderPass& pass) { + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + + pass.SetCommandLabel("Gaussian blur downsample"); + auto pipeline_options = OptionsFromPass(pass); + pipeline_options.primitive_type = PrimitiveType::kTriangleStrip; +#ifdef IMPELLER_ENABLE_OPENGLES + // The GLES backend conditionally supports decal tile mode, while + // decal is always supported for Vulkan and Metal. + if (renderer.GetDeviceCapabilities() + .SupportsDecalSamplerAddressMode() || + tile_mode != Entity::TileMode::kDecal) { + pass.SetPipeline(renderer.GetDownsamplePipeline(pipeline_options)); + } else { + pass.SetPipeline( + renderer.GetDownsampleTextureGlesPipeline(pipeline_options)); + } +#else + pass.SetPipeline(renderer.GetDownsamplePipeline(pipeline_options)); +#endif // IMPELLER_ENABLE_OPENGLES + + TextureFillVertexShader::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); + frame_info.texture_sampler_y_coord_scale = + input_texture->GetYCoordScale(); + + TextureDownsampleFragmentShader::FragInfo frag_info; + frag_info.edge = edge; + frag_info.ratio = ratio; + frag_info.pixel_size = Vector2(1.0f / Size(input_texture->GetSize())); + + const Quad& uvs = pass_args.uvs; + std::array vertices = { + VS::PerVertexData{Point(0, 0), uvs[0]}, + VS::PerVertexData{Point(1, 0), uvs[1]}, + VS::PerVertexData{Point(0, 1), uvs[2]}, + VS::PerVertexData{Point(1, 1), uvs[3]}, + }; + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + SamplerDescriptor linear_sampler_descriptor = sampler_descriptor; + SetTileMode(&linear_sampler_descriptor, renderer, tile_mode); + linear_sampler_descriptor.mag_filter = MinMagFilter::kLinear; + linear_sampler_descriptor.min_filter = MinMagFilter::kLinear; + TextureFillVertexShader::BindFrameInfo( + pass, host_buffer.EmplaceUniform(frame_info)); + TextureDownsampleFragmentShader::BindFragInfo( + pass, host_buffer.EmplaceUniform(frag_info)); + TextureDownsampleFragmentShader::BindTextureSampler( + pass, input_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + linear_sampler_descriptor)); + + return pass.Draw().ok(); + }; + return renderer.MakeSubpass("Gaussian Blur Filter", pass_args.subpass_size, + command_buffer, subpass_callback, + /*msaa_enabled=*/false, + /*depth_stencil_enabled=*/false); + } +} + +fml::StatusOr MakeBlurSubpass( + const ContentContext& renderer, + const std::shared_ptr& command_buffer, + const RenderTarget& input_pass, + const SamplerDescriptor& sampler_descriptor, + Entity::TileMode tile_mode, + const BlurParameters& blur_info, + std::optional destination_target, + const Quad& blur_uvs) { + using VS = GaussianBlurVertexShader; + + if (blur_info.blur_sigma < kEhCloseEnough) { + return input_pass; + } + + const std::shared_ptr& input_texture = + input_pass.GetRenderTargetTexture(); + + // TODO(gaaclarke): This blurs the whole image, but because we know the clip + // region we could focus on just blurring that. + ISize subpass_size = input_texture->GetSize(); + ContentContext::SubpassCallback subpass_callback = + [&](const ContentContext& renderer, RenderPass& pass) { + GaussianBlurVertexShader::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)), + frame_info.texture_sampler_y_coord_scale = + input_texture->GetYCoordScale(); + + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + + ContentContextOptions options = OptionsFromPass(pass); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetGaussianBlurPipeline(options)); + + std::array vertices = { + VS::PerVertexData{blur_uvs[0], blur_uvs[0]}, + VS::PerVertexData{blur_uvs[1], blur_uvs[1]}, + VS::PerVertexData{blur_uvs[2], blur_uvs[2]}, + VS::PerVertexData{blur_uvs[3], blur_uvs[3]}, + }; + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + SamplerDescriptor linear_sampler_descriptor = sampler_descriptor; + linear_sampler_descriptor.mag_filter = MinMagFilter::kLinear; + linear_sampler_descriptor.min_filter = MinMagFilter::kLinear; + GaussianBlurFragmentShader::BindTextureSampler( + pass, input_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + linear_sampler_descriptor)); + GaussianBlurVertexShader::BindFrameInfo( + pass, host_buffer.EmplaceUniform(frame_info)); + GaussianBlurFragmentShader::BindKernelSamples( + pass, host_buffer.EmplaceUniform( + LerpHackKernelSamples(GenerateBlurInfo(blur_info)))); + return pass.Draw().ok(); + }; + if (destination_target.has_value()) { + return renderer.MakeSubpass("Gaussian Blur Filter", + destination_target.value(), command_buffer, + subpass_callback); + } else { + return renderer.MakeSubpass( + "Gaussian Blur Filter", subpass_size, command_buffer, subpass_callback, + /*msaa_enabled=*/false, /*depth_stencil_enabled=*/false); + } +} + +int ScaleBlurRadius(Scalar radius, Scalar scalar) { + return static_cast(std::round(radius * scalar)); +} + +Entity ApplyClippedBlurStyle(Entity::ClipOperation clip_operation, + const Entity& entity, + const std::shared_ptr& input, + const Snapshot& input_snapshot, + Entity blur_entity, + const Geometry* geometry) { + Matrix entity_transform = entity.GetTransform(); + Matrix blur_transform = blur_entity.GetTransform(); + + auto renderer = + fml::MakeCopyable([blur_entity = blur_entity.Clone(), clip_operation, + entity_transform, blur_transform, geometry]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) mutable { + Entity clipper; + clipper.SetClipDepth(entity.GetClipDepth()); + clipper.SetTransform(entity.GetTransform() * entity_transform); + + auto geom_result = geometry->GetPositionBuffer(renderer, clipper, pass); + + ClipContents clip_contents(geometry->GetCoverage(clipper.GetTransform()) + .value_or(Rect::MakeLTRB(0, 0, 0, 0)), + /*is_axis_aligned_rect=*/false); + clip_contents.SetClipOperation(clip_operation); + clip_contents.SetGeometry(std::move(geom_result)); + + if (!clip_contents.Render(renderer, pass, entity.GetClipDepth())) { + return false; + } + blur_entity.SetClipDepth(entity.GetClipDepth()); + blur_entity.SetTransform(entity.GetTransform() * blur_transform); + + return blur_entity.Render(renderer, pass); + }); + auto coverage = + fml::MakeCopyable([blur_entity = std::move(blur_entity), + blur_transform](const Entity& entity) mutable { + blur_entity.SetTransform(entity.GetTransform() * blur_transform); + return blur_entity.GetCoverage(); + }); + Entity result; + result.SetContents(Contents::MakeAnonymous(renderer, coverage)); + return result; +} + +Entity ApplyBlurStyle(FilterContents::BlurStyle blur_style, + const Entity& entity, + const std::shared_ptr& input, + const Snapshot& input_snapshot, + Entity blur_entity, + const Geometry* geometry, + Vector2 source_space_scalar, + Vector2 source_space_offset) { + switch (blur_style) { + case FilterContents::BlurStyle::kNormal: + return blur_entity; + case FilterContents::BlurStyle::kInner: + return ApplyClippedBlurStyle(Entity::ClipOperation::kIntersect, entity, + input, input_snapshot, + std::move(blur_entity), geometry); + break; + case FilterContents::BlurStyle::kOuter: + return ApplyClippedBlurStyle(Entity::ClipOperation::kDifference, entity, + input, input_snapshot, + std::move(blur_entity), geometry); + case FilterContents::BlurStyle::kSolid: { + Entity snapshot_entity = + Entity::FromSnapshot(input_snapshot, entity.GetBlendMode()); + Entity result; + Matrix blurred_transform = blur_entity.GetTransform(); + Matrix snapshot_transform = + entity.GetTransform() * // + Matrix::MakeScale(1.f / source_space_scalar) * + Matrix::MakeTranslation(-1 * source_space_offset) * + input_snapshot.transform; + result.SetContents(Contents::MakeAnonymous( + fml::MakeCopyable([blur_entity = blur_entity.Clone(), + blurred_transform, snapshot_transform, + snapshot_entity = std::move(snapshot_entity)]( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) mutable { + snapshot_entity.SetTransform(entity.GetTransform() * + snapshot_transform); + snapshot_entity.SetClipDepth(entity.GetClipDepth()); + if (!snapshot_entity.Render(renderer, pass)) { + return false; + } + blur_entity.SetClipDepth(entity.GetClipDepth()); + blur_entity.SetTransform(entity.GetTransform() * blurred_transform); + return blur_entity.Render(renderer, pass); + }), + fml::MakeCopyable([blur_entity = blur_entity.Clone(), + blurred_transform](const Entity& entity) mutable { + blur_entity.SetTransform(entity.GetTransform() * blurred_transform); + return blur_entity.GetCoverage(); + }))); + return result; + } + } +} +} // namespace + +GaussianBlurFilterContents::GaussianBlurFilterContents( + Scalar sigma_x, + Scalar sigma_y, + Entity::TileMode tile_mode, + BlurStyle mask_blur_style, + const Geometry* mask_geometry) + : sigma_(sigma_x, sigma_y), + tile_mode_(tile_mode), + mask_blur_style_(mask_blur_style), + mask_geometry_(mask_geometry) { + // This is supposed to be enforced at a higher level. + FML_DCHECK(mask_blur_style == BlurStyle::kNormal || mask_geometry); +} + +// This value was extracted from Skia, see: +// * https://github.com/google/skia/blob/d29cc3fe182f6e8a8539004a6a4ee8251677a6fd/src/gpu/ganesh/GrBlurUtils.cpp#L2561-L2576 +// * https://github.com/google/skia/blob/d29cc3fe182f6e8a8539004a6a4ee8251677a6fd/src/gpu/BlurUtils.h#L57 +Scalar GaussianBlurFilterContents::CalculateScale(Scalar sigma) { + if (sigma <= 4) { + return 1.0; + } + Scalar raw_result = 4.0 / sigma; + // Round to the nearest 1/(2^n) to get the best quality down scaling. + Scalar exponent = round(log2f(raw_result)); + // Don't scale down below 1/16th to preserve signal. + exponent = std::max(-4.0f, exponent); + Scalar rounded = powf(2.0f, exponent); + Scalar result = rounded; + // Extend the range of the 1/8th downsample based on the effective kernel size + // for the blur. + if (rounded < 0.125f) { + Scalar rounded_plus = powf(2.0f, exponent + 1); + Scalar blur_radius = CalculateBlurRadius(sigma); + int kernel_size_plus = (ScaleBlurRadius(blur_radius, rounded_plus) * 2) + 1; + // This constant was picked by looking at the results to make sure no + // shimmering was introduced at the highest sigma values that downscale to + // 1/16th. + static constexpr int32_t kEighthDownsampleKernalWidthMax = 41; + result = kernel_size_plus <= kEighthDownsampleKernalWidthMax ? rounded_plus + : rounded; + } + return result; +}; + +std::optional GaussianBlurFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + Vector2 scaled_sigma = {ScaleSigma(sigma_.x), ScaleSigma(sigma_.y)}; + Vector2 blur_radius = {CalculateBlurRadius(scaled_sigma.x), + CalculateBlurRadius(scaled_sigma.y)}; + Vector3 blur_radii = + effect_transform.Basis() * Vector3{blur_radius.x, blur_radius.y, 0.0}; + return output_limit.Expand(Point(blur_radii.x, blur_radii.y)); +} + +std::optional GaussianBlurFilterContents::GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const { + if (inputs.empty()) { + return {}; + } + std::optional input_coverage = inputs[0]->GetCoverage(entity); + if (!input_coverage.has_value()) { + return {}; + } + + BlurInfo blur_info = CalculateBlurInfo(entity, effect_transform, sigma_); + return input_coverage.value().Expand( + Point(blur_info.local_padding.x, blur_info.local_padding.y)); +} + +// A brief overview how this works: +// 1) Snapshot the filter input. +// 2) Perform downsample pass. This also inserts the gutter around the input +// snapshot since the blur can render outside the bounds of the snapshot. +// 3) Perform 1D horizontal blur pass. +// 4) Perform 1D vertical blur pass. +// 5) Apply the blur style to the blur result. This may just mask the output or +// draw the original snapshot over the result. +std::optional GaussianBlurFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.empty()) { + return std::nullopt; + } + + BlurInfo blur_info = CalculateBlurInfo(entity, effect_transform, sigma_); + + // Apply as much of the desired padding as possible from the source. This may + // be ignored so must be accounted for in the downsample pass by adding a + // transparent gutter. + std::optional expanded_coverage_hint; + if (coverage_hint.has_value()) { + expanded_coverage_hint = coverage_hint->Expand(blur_info.local_padding); + } + + Entity snapshot_entity = entity.Clone(); + snapshot_entity.SetTransform( + Matrix::MakeTranslation(blur_info.source_space_offset) * + Matrix::MakeScale(blur_info.source_space_scalar)); + + std::optional source_expanded_coverage_hint; + if (expanded_coverage_hint.has_value()) { + source_expanded_coverage_hint = expanded_coverage_hint->TransformBounds( + Matrix::MakeTranslation(blur_info.source_space_offset) * + Matrix::MakeScale(blur_info.source_space_scalar) * + entity.GetTransform().Invert()); + } + + std::optional input_snapshot = GetSnapshot( + inputs[0], renderer, snapshot_entity, source_expanded_coverage_hint); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + if (blur_info.scaled_sigma.x < kEhCloseEnough && + blur_info.scaled_sigma.y < kEhCloseEnough) { + Entity result = + Entity::FromSnapshot(input_snapshot.value(), + entity.GetBlendMode()); // No blur to render. + result.SetTransform( + entity.GetTransform() * + Matrix::MakeScale(1.f / blur_info.source_space_scalar) * + Matrix::MakeTranslation(-1 * blur_info.source_space_offset) * + input_snapshot->transform); + return result; + } + + // Note: The code below uses three different command buffers when it would be + // possible to combine the operations into a single buffer. From testing and + // user bug reports (see https://github.com/flutter/flutter/issues/154046 ), + // this sometimes causes deviceLost errors on older Adreno devices. Breaking + // the work up into three different command buffers seems to prevent this + // crash. + std::shared_ptr command_buffer_1 = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer_1) { + return std::nullopt; + } + + DownsamplePassArgs downsample_pass_args = CalculateDownsamplePassArgs( + blur_info.scaled_sigma, blur_info.padding, input_snapshot.value(), + source_expanded_coverage_hint, inputs[0], snapshot_entity); + + fml::StatusOr pass1_out = MakeDownsampleSubpass( + renderer, command_buffer_1, input_snapshot->texture, + input_snapshot->sampler_descriptor, downsample_pass_args, tile_mode_); + + if (!pass1_out.ok()) { + return std::nullopt; + } + + Vector2 pass1_pixel_size = + 1.0 / Vector2(pass1_out.value().GetRenderTargetTexture()->GetSize()); + + Quad blur_uvs = {Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)}; + + std::shared_ptr command_buffer_2 = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer_2) { + return std::nullopt; + } + + fml::StatusOr pass2_out = MakeBlurSubpass( + renderer, command_buffer_2, /*input_pass=*/pass1_out.value(), + input_snapshot->sampler_descriptor, tile_mode_, + BlurParameters{ + .blur_uv_offset = Point(0.0, pass1_pixel_size.y), + .blur_sigma = blur_info.scaled_sigma.y * + downsample_pass_args.effective_scalar.y, + .blur_radius = ScaleBlurRadius( + blur_info.blur_radius.y, downsample_pass_args.effective_scalar.y), + .step_size = 1, + }, + /*destination_target=*/std::nullopt, blur_uvs); + + if (!pass2_out.ok()) { + return std::nullopt; + } + + std::shared_ptr command_buffer_3 = + renderer.GetContext()->CreateCommandBuffer(); + if (!command_buffer_3) { + return std::nullopt; + } + + // Only ping pong if the first pass actually created a render target. + auto pass3_destination = pass2_out.value().GetRenderTargetTexture() != + pass1_out.value().GetRenderTargetTexture() + ? std::optional(pass1_out.value()) + : std::optional(std::nullopt); + + fml::StatusOr pass3_out = MakeBlurSubpass( + renderer, command_buffer_3, /*input_pass=*/pass2_out.value(), + input_snapshot->sampler_descriptor, tile_mode_, + BlurParameters{ + .blur_uv_offset = Point(pass1_pixel_size.x, 0.0), + .blur_sigma = blur_info.scaled_sigma.x * + downsample_pass_args.effective_scalar.x, + .blur_radius = ScaleBlurRadius( + blur_info.blur_radius.x, downsample_pass_args.effective_scalar.x), + .step_size = 1, + }, + pass3_destination, blur_uvs); + + if (!pass3_out.ok()) { + return std::nullopt; + } + + if (!(renderer.GetContext()->EnqueueCommandBuffer( + std::move(command_buffer_1)) && + renderer.GetContext()->EnqueueCommandBuffer( + std::move(command_buffer_2)) && + renderer.GetContext()->EnqueueCommandBuffer( + std::move(command_buffer_3)))) { + return std::nullopt; + } + + // The ping-pong approach requires that each render pass output has the same + // size. + FML_DCHECK((pass1_out.value().GetRenderTargetSize() == + pass2_out.value().GetRenderTargetSize()) && + (pass2_out.value().GetRenderTargetSize() == + pass3_out.value().GetRenderTargetSize())); + + SamplerDescriptor sampler_desc = MakeSamplerDescriptor( + MinMagFilter::kLinear, SamplerAddressMode::kClampToEdge); + + Entity blur_output_entity = Entity::FromSnapshot( + Snapshot{.texture = pass3_out.value().GetRenderTargetTexture(), + .transform = + entity.GetTransform() * // + Matrix::MakeScale(1.f / blur_info.source_space_scalar) * // + Matrix::MakeTranslation(-1 * blur_info.source_space_offset) * + downsample_pass_args.transform * // + Matrix::MakeScale(1 / downsample_pass_args.effective_scalar), + .sampler_descriptor = sampler_desc, + .opacity = input_snapshot->opacity}, + entity.GetBlendMode()); + + return ApplyBlurStyle(mask_blur_style_, entity, inputs[0], + input_snapshot.value(), std::move(blur_output_entity), + mask_geometry_, blur_info.source_space_scalar, + blur_info.source_space_offset); +} + +Scalar GaussianBlurFilterContents::CalculateBlurRadius(Scalar sigma) { + return static_cast(Sigma(sigma)).radius; +} + +Quad GaussianBlurFilterContents::CalculateUVs( + const std::shared_ptr& filter_input, + const Entity& entity, + const Rect& source_rect, + const ISize& texture_size) { + Matrix input_transform = filter_input->GetLocalTransform(entity); + Quad coverage_quad = source_rect.GetTransformedPoints(input_transform); + + Matrix uv_transform = Matrix::MakeScale( + {1.0f / texture_size.width, 1.0f / texture_size.height, 1.0f}); + return uv_transform.Transform(coverage_quad); +} + +// This function was calculated by observing Skia's behavior. Its blur at 500 +// seemed to be 0.15. Since we clamp at 500 I solved the quadratic equation +// that puts the minima there and a f(0)=1. +Scalar GaussianBlurFilterContents::ScaleSigma(Scalar sigma) { + // Limit the kernel size to 1000x1000 pixels, like Skia does. + Scalar clamped = std::min(sigma, kMaxSigma); + constexpr Scalar a = 3.4e-06; + constexpr Scalar b = -3.4e-3; + constexpr Scalar c = 1.f; + Scalar scalar = c + b * clamped + a * clamped * clamped; + return clamped * scalar; +} + +KernelSamples GenerateBlurInfo(BlurParameters parameters) { + KernelSamples result; + result.sample_count = + ((2 * parameters.blur_radius) / parameters.step_size) + 1; + + // Chop off the last samples if the radius >= 3 where they account for < 1.56% + // of the result. + int x_offset = 0; + if (parameters.blur_radius >= 3) { + result.sample_count -= 2; + x_offset = 1; + } + + // This is a safe-guard to make sure we don't overflow the fragment shader. + // The kernel size is multiplied by 2 since we'll use the lerp hack on the + // result. In practice this isn't throwing away much data since the blur radii + // are around 53 before the down-sampling and max sigma of 500 kick in. + // + // TODO(https://github.com/flutter/flutter/issues/150462): Come up with a more + // wholistic remedy for this. A proper downsample size should not make this + // required. Or we can increase the kernel size. + if (result.sample_count > KernelSamples::kMaxKernelSize) { + result.sample_count = KernelSamples::kMaxKernelSize; + } + + Scalar tally = 0.0f; + for (int i = 0; i < result.sample_count; ++i) { + int x = x_offset + (i * parameters.step_size) - parameters.blur_radius; + result.samples[i] = KernelSample{ + .uv_offset = parameters.blur_uv_offset * x, + .coefficient = expf(-0.5f * (x * x) / + (parameters.blur_sigma * parameters.blur_sigma)) / + (sqrtf(2.0f * M_PI) * parameters.blur_sigma), + }; + tally += result.samples[i].coefficient; + } + + // Make sure everything adds up to 1. + for (auto& sample : result.samples) { + sample.coefficient /= tally; + } + + return result; +} + +// This works by shrinking the kernel size by 2 and relying on lerp to read +// between the samples. +GaussianBlurPipeline::FragmentShader::KernelSamples LerpHackKernelSamples( + KernelSamples parameters) { + GaussianBlurPipeline::FragmentShader::KernelSamples result = {}; + result.sample_count = ((parameters.sample_count - 1) / 2) + 1; + int32_t middle = result.sample_count / 2; + int32_t j = 0; + FML_DCHECK(result.sample_count <= kGaussianBlurMaxKernelSize); + static_assert(sizeof(result.sample_data) == + sizeof(std::array)); + + for (int i = 0; i < result.sample_count; i++) { + if (i == middle) { + result.sample_data[i].x = parameters.samples[j].uv_offset.x; + result.sample_data[i].y = parameters.samples[j].uv_offset.y; + result.sample_data[i].z = parameters.samples[j].coefficient; + j++; + } else { + KernelSample left = parameters.samples[j]; + KernelSample right = parameters.samples[j + 1]; + + result.sample_data[i].z = left.coefficient + right.coefficient; + + Point uv = (left.uv_offset * left.coefficient + + right.uv_offset * right.coefficient) / + (left.coefficient + right.coefficient); + result.sample_data[i].x = uv.x; + result.sample_data[i].y = uv.y; + j += 2; + } + } + + return result; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..1cc43cfaf5c5af4bd57a3e5d1e875c2c73f2ee30 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents.h @@ -0,0 +1,124 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_GAUSSIAN_BLUR_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_GAUSSIAN_BLUR_FILTER_CONTENTS_H_ + +#include +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +// Comes from gaussian.frag. +static constexpr int32_t kGaussianBlurMaxKernelSize = 50; + +static_assert(sizeof(GaussianBlurPipeline::FragmentShader::KernelSamples) == + sizeof(Vector4) * kGaussianBlurMaxKernelSize + sizeof(Vector4)); + +struct BlurParameters { + Point blur_uv_offset; + Scalar blur_sigma; + int blur_radius; + int step_size; +}; + +struct KernelSample { + Vector2 uv_offset; + float coefficient; +}; + +/// A larger mirror of GaussianBlurPipeline::FragmentShader::KernelSamples. +/// +/// This is a mirror of GaussianBlurPipeline::FragmentShader::KernelSamples that +/// can hold 2x the max kernel size since it will get reduced with the lerp +/// hack. +struct KernelSamples { + static constexpr int kMaxKernelSize = kGaussianBlurMaxKernelSize * 2; + int sample_count; + KernelSample samples[kMaxKernelSize]; +}; + +KernelSamples GenerateBlurInfo(BlurParameters parameters); + +/// This will shrink the size of a kernel by roughly half by sampling between +/// samples and relying on linear interpolation between the samples. +GaussianBlurPipeline::FragmentShader::KernelSamples LerpHackKernelSamples( + KernelSamples samples); + +/// Performs a bidirectional Gaussian blur. +/// +/// This is accomplished by rendering multiple passes in multiple directions. +/// Note: This will replace `DirectionalGaussianBlurFilterContents`. +class GaussianBlurFilterContents final : public FilterContents { + public: + explicit GaussianBlurFilterContents(Scalar sigma_x, + Scalar sigma_y, + Entity::TileMode tile_mode, + BlurStyle mask_blur_style, + const Geometry* mask_geometry = nullptr); + + Scalar GetSigmaX() const { return sigma_.x; } + Scalar GetSigmaY() const { return sigma_.y; } + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + // |FilterContents| + std::optional GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const override; + + /// Given a sigma (standard deviation) calculate the blur radius (1/2 the + /// kernel size). + static Scalar CalculateBlurRadius(Scalar sigma); + + /// Calculate the UV coordinates for rendering the filter_input. + /// @param filter_input The FilterInput that should be rendered. + /// @param entity The associated entity for the filter_input. + /// @param source_rect The rect in source coordinates to convert to uvs. + /// @param texture_size The rect to convert in source coordinates. + static Quad CalculateUVs(const std::shared_ptr& filter_input, + const Entity& entity, + const Rect& source_rect, + const ISize& texture_size); + + /// Calculate the scale factor for the downsample pass given a sigma value. + /// + /// Visible for testing. + static Scalar CalculateScale(Scalar sigma); + + /// Scales down the sigma value to match Skia's behavior. + /// + /// effective_blur_radius = CalculateBlurRadius(ScaleSigma(sigma_)); + /// + /// This function was calculated by observing Skia's behavior. Its blur at + /// 500 seemed to be 0.15. Since we clamp at 500 I solved the quadratic + /// equation that puts the minima there and a f(0)=1. + static Scalar ScaleSigma(Scalar sigma); + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + const Vector2 sigma_ = Vector2(0.0, 0.0); + const Entity::TileMode tile_mode_; + const BlurStyle mask_blur_style_; + const Geometry* mask_geometry_ = nullptr; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_GAUSSIAN_BLUR_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..84f3c00aa46e734e47e62dab25bdd6c090dbb1e4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/gaussian_blur_filter_contents_unittests.cc @@ -0,0 +1,636 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "fml/status_or.h" +#include "gmock/gmock.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/filters/gaussian_blur_filter_contents.h" +#include "impeller/entity/contents/texture_contents.h" +#include "impeller/entity/entity_playground.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/geometry_asserts.h" +#include "impeller/renderer/testing/mocks.h" + +#if FML_OS_MACOSX +#define IMPELLER_RAND arc4random +#else +#define IMPELLER_RAND rand +#endif + +namespace impeller { +namespace testing { + +namespace { + +// Use newtonian method to give the closest answer to target where +// f(x) is less than the target. We do this because the value is `ceil`'d to +// grab fractional pixels. +fml::StatusOr LowerBoundNewtonianMethod( + const std::function& func, + float target, + float guess, + float tolerance) { + const double delta = 1e-6; + double x = guess; + double fx; + static const int kMaxIterations = 1000; + int count = 0; + + do { + fx = func(x) - target; + double derivative = (func(x + delta) - func(x)) / delta; + x = x - fx / derivative; + if (++count > kMaxIterations) { + return fml::Status(fml::StatusCode::kDeadlineExceeded, + "Did not converge on answer."); + } + } while (std::abs(fx) > tolerance || + fx < 0.0); // fx < 0.0 makes this lower bound. + + return x; +} + +Scalar GetCoefficient(const Vector4& vec) { + return vec.z; +} + +Vector2 GetUVOffset(const Vector4& vec) { + return vec.xy(); +} + +fml::StatusOr CalculateSigmaForBlurRadius( + Scalar radius, + const Matrix& effect_transform) { + auto f = [effect_transform](Scalar x) -> Scalar { + Vector2 scaled_sigma = (effect_transform.Basis() * + Vector2(GaussianBlurFilterContents::ScaleSigma(x), + GaussianBlurFilterContents::ScaleSigma(x))) + .Abs(); + Vector2 blur_radius = Vector2( + GaussianBlurFilterContents::CalculateBlurRadius(scaled_sigma.x), + GaussianBlurFilterContents::CalculateBlurRadius(scaled_sigma.y)); + return std::max(blur_radius.x, blur_radius.y); + }; + // The newtonian method is used here since inverting the function is + // non-trivial because of conditional logic and would be fragile to changes. + return LowerBoundNewtonianMethod(f, radius, 2.f, 0.001f); +} + +} // namespace + +class GaussianBlurFilterContentsTest : public EntityPlayground { + public: + /// Create a texture that has been cleared to transparent black. + std::shared_ptr MakeTexture(ISize size) { + std::shared_ptr command_buffer = + GetContentContext()->GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return nullptr; + } + + auto render_target = GetContentContext()->MakeSubpass( + "Clear Subpass", size, command_buffer, + [](const ContentContext&, RenderPass&) { return true; }); + + if (!GetContentContext() + ->GetContext() + ->GetCommandQueue() + ->Submit(/*buffers=*/{command_buffer}) + .ok()) { + return nullptr; + } + + if (render_target.ok()) { + return render_target.value().GetRenderTargetTexture(); + } + return nullptr; + } +}; +INSTANTIATE_PLAYGROUND_SUITE(GaussianBlurFilterContentsTest); + +TEST(GaussianBlurFilterContentsTest, Create) { + GaussianBlurFilterContents contents( + /*sigma_x=*/0.0, /*sigma_y=*/0.0, Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + EXPECT_EQ(contents.GetSigmaX(), 0.0); + EXPECT_EQ(contents.GetSigmaY(), 0.0); +} + +TEST(GaussianBlurFilterContentsTest, CoverageEmpty) { + GaussianBlurFilterContents contents( + /*sigma_x=*/0.0, /*sigma_y=*/0.0, Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + FilterInput::Vector inputs = {}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + ASSERT_FALSE(coverage.has_value()); +} + +TEST(GaussianBlurFilterContentsTest, CoverageSimple) { + GaussianBlurFilterContents contents( + /*sigma_x=*/0.0, /*sigma_y=*/0.0, Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + FilterInput::Vector inputs = { + FilterInput::Make(Rect::MakeLTRB(10, 10, 110, 110))}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + + ASSERT_EQ(coverage, Rect::MakeLTRB(10, 10, 110, 110)); +} + +TEST(GaussianBlurFilterContentsTest, CoverageWithSigma) { + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + ASSERT_TRUE(sigma_radius_1.ok()); + GaussianBlurFilterContents contents( + /*sigma_x=*/sigma_radius_1.value(), + /*sigma_y=*/sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + FilterInput::Vector inputs = { + FilterInput::Make(Rect::MakeLTRB(100, 100, 200, 200))}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + + EXPECT_TRUE(coverage.has_value()); + if (coverage.has_value()) { + EXPECT_RECT_NEAR(coverage.value(), Rect::MakeLTRB(99, 99, 201, 201)); + } +} + +TEST_P(GaussianBlurFilterContentsTest, CoverageWithTexture) { + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + ASSERT_TRUE(sigma_radius_1.ok()); + GaussianBlurFilterContents contents( + /*sigma_X=*/sigma_radius_1.value(), + /*sigma_y=*/sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + FilterInput::Vector inputs = {FilterInput::Make(texture)}; + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 100, 0})); + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + + EXPECT_TRUE(coverage.has_value()); + if (coverage.has_value()) { + EXPECT_RECT_NEAR(coverage.value(), Rect::MakeLTRB(99, 99, 201, 201)); + } +} + +TEST_P(GaussianBlurFilterContentsTest, CoverageWithEffectTransform) { + Matrix effect_transform = Matrix::MakeScale({2.0, 2.0, 1.0}); + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, effect_transform); + ASSERT_TRUE(sigma_radius_1.ok()); + GaussianBlurFilterContents contents( + /*sigma_x=*/sigma_radius_1.value(), + /*sigma_y=*/sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + FilterInput::Vector inputs = {FilterInput::Make(texture)}; + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 100, 0})); + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, effect_transform); + EXPECT_TRUE(coverage.has_value()); + if (coverage.has_value()) { + EXPECT_RECT_NEAR(coverage.value(), + Rect::MakeLTRB(100 - 1, 100 - 1, 200 + 1, 200 + 1)); + } +} + +TEST(GaussianBlurFilterContentsTest, FilterSourceCoverage) { + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + ASSERT_TRUE(sigma_radius_1.ok()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + std::optional coverage = contents->GetFilterSourceCoverage( + /*effect_transform=*/Matrix::MakeScale({2.0, 2.0, 1.0}), + /*output_limit=*/Rect::MakeLTRB(100, 100, 200, 200)); + EXPECT_TRUE(coverage.has_value()); + if (coverage.has_value()) { + EXPECT_RECT_NEAR(coverage.value(), + Rect::MakeLTRB(100 - 2, 100 - 2, 200 + 2, 200 + 2)); + } +} + +TEST(GaussianBlurFilterContentsTest, CalculateSigmaValues) { + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(1.0f), 1); + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(2.0f), 1); + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(3.0f), 1); + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(4.0f), 1); + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(16.0f), 0.25); + // Hang on to 1/8 as long as possible. + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(95.0f), 0.125); + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(96.0f), 0.0625); + // Downsample clamped to 1/16th. + EXPECT_EQ(GaussianBlurFilterContents::CalculateScale(1024.0f), 0.0625); +} + +TEST_P(GaussianBlurFilterContentsTest, RenderCoverageMatchesGetCoverage) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + ASSERT_TRUE(sigma_radius_1.ok()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture)}); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(contents_coverage.value(), + Rect::MakeLTRB(-1, -1, 101, 101))); + EXPECT_TRUE( + RectNear(result_coverage.value(), Rect::MakeLTRB(-1, -1, 101, 101))); + } + } +} + +TEST_P(GaussianBlurFilterContentsTest, + RenderCoverageMatchesGetCoverageTranslate) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + ASSERT_TRUE(sigma_radius_1.ok()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture)}); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(contents_coverage.value(), + Rect::MakeLTRB(99, 199, 201, 301))); + EXPECT_TRUE( + RectNear(result_coverage.value(), Rect::MakeLTRB(99, 199, 201, 301))); + } + } +} + +TEST_P(GaussianBlurFilterContentsTest, + RenderCoverageMatchesGetCoverageRotated) { + std::shared_ptr texture = MakeTexture(ISize(400, 300)); + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture)}); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + // Rotate around the top left corner, then push it over to (100, 100). + entity.SetTransform(Matrix::MakeTranslation({400, 100, 0}) * + Matrix::MakeRotationZ(Degrees(90.0))); + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(contents_coverage.value(), + Rect::MakeLTRB(99, 99, 401, 501))); + EXPECT_TRUE( + RectNear(result_coverage.value(), Rect::MakeLTRB(99, 99, 401, 501))); + } + } +} + +TEST_P(GaussianBlurFilterContentsTest, CalculateUVsSimple) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + auto filter_input = FilterInput::Make(texture); + Entity entity; + Quad uvs = GaussianBlurFilterContents::CalculateUVs( + filter_input, entity, Rect::MakeSize(ISize(100, 100)), ISize(100, 100)); + std::optional uvs_bounds = Rect::MakePointBounds(uvs); + EXPECT_TRUE(uvs_bounds.has_value()); + if (uvs_bounds.has_value()) { + EXPECT_TRUE(RectNear(uvs_bounds.value(), Rect::MakeXYWH(0, 0, 1, 1))); + } +} + +TEST_P(GaussianBlurFilterContentsTest, TextureContentsWithDestinationRect) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + auto texture_contents = std::make_shared(); + texture_contents->SetSourceRect(Rect::MakeSize(texture->GetSize())); + texture_contents->SetTexture(texture); + texture_contents->SetDestinationRect(Rect::MakeXYWH( + 50, 40, texture->GetSize().width, texture->GetSize().height)); + + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture_contents)}); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(result_coverage.value(), contents_coverage.value())); + EXPECT_TRUE(RectNear(result_coverage.value(), + Rect::MakeLTRB(49.f, 39.f, 151.f, 141.f))); + } + } +} + +TEST_P(GaussianBlurFilterContentsTest, + TextureContentsWithDestinationRectScaled) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + auto texture_contents = std::make_shared(); + texture_contents->SetSourceRect(Rect::MakeSize(texture->GetSize())); + texture_contents->SetTexture(texture); + texture_contents->SetDestinationRect(Rect::MakeXYWH( + 50, 40, texture->GetSize().width, texture->GetSize().height)); + + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, Matrix()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, + /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture_contents)}); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + entity.SetTransform(Matrix::MakeScale({2.0, 2.0, 1.0})); + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(result_coverage.value(), contents_coverage.value())); + // Scaling a blurred entity doesn't seem to scale the blur radius linearly + // when comparing results with rrect_blur. That's why this is not + // Rect::MakeXYWH(98.f, 78.f, 204.0f, 204.f). + EXPECT_TRUE(RectNear(contents_coverage.value(), + Rect::MakeXYWH(94.f, 74.f, 212.0f, 212.f))); + } + } +} + +TEST_P(GaussianBlurFilterContentsTest, TextureContentsWithEffectTransform) { + Matrix effect_transform = Matrix::MakeScale({2.0, 2.0, 1.0}); + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + auto texture_contents = std::make_shared(); + texture_contents->SetSourceRect(Rect::MakeSize(texture->GetSize())); + texture_contents->SetTexture(texture); + texture_contents->SetDestinationRect(Rect::MakeXYWH( + 50, 40, texture->GetSize().width, texture->GetSize().height)); + + fml::StatusOr sigma_radius_1 = + CalculateSigmaForBlurRadius(1.0, effect_transform); + ASSERT_TRUE(sigma_radius_1.ok()); + auto contents = std::make_unique( + sigma_radius_1.value(), sigma_radius_1.value(), Entity::TileMode::kDecal, + FilterContents::BlurStyle::kNormal, /*mask_geometry=*/nullptr); + contents->SetInputs({FilterInput::Make(texture_contents)}); + contents->SetEffectTransform(effect_transform); + std::shared_ptr renderer = GetContentContext(); + + Entity entity; + std::optional result = + contents->GetEntity(*renderer, entity, /*coverage_hint=*/{}); + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + std::optional contents_coverage = contents->GetCoverage(entity); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(result_coverage.value(), contents_coverage.value())); + EXPECT_TRUE(RectNear(contents_coverage.value(), + Rect::MakeXYWH(49.f, 39.f, 102.f, 102.f))); + } + } +} + +TEST(GaussianBlurFilterContentsTest, CalculateSigmaForBlurRadius) { + Scalar sigma = 1.0; + Scalar radius = GaussianBlurFilterContents::CalculateBlurRadius( + GaussianBlurFilterContents::ScaleSigma(sigma)); + fml::StatusOr derived_sigma = + CalculateSigmaForBlurRadius(radius, Matrix()); + ASSERT_TRUE(derived_sigma.ok()); + EXPECT_NEAR(sigma, derived_sigma.value(), 0.01f); +} + +TEST(GaussianBlurFilterContentsTest, Coefficients) { + BlurParameters parameters = {.blur_uv_offset = Point(1, 0), + .blur_sigma = 1, + .blur_radius = 5, + .step_size = 1}; + KernelSamples samples = GenerateBlurInfo(parameters); + EXPECT_EQ(samples.sample_count, 9); + + // Coefficients should add up to 1. + Scalar tally = 0; + for (int i = 0; i < samples.sample_count; ++i) { + tally += samples.samples[i].coefficient; + } + EXPECT_FLOAT_EQ(tally, 1.0f); + + // Verify the shape of the curve. + for (int i = 0; i < 4; ++i) { + EXPECT_FLOAT_EQ(samples.samples[i].coefficient, + samples.samples[8 - i].coefficient); + EXPECT_TRUE(samples.samples[i + 1].coefficient > + samples.samples[i].coefficient); + } +} + +TEST(GaussianBlurFilterContentsTest, LerpHackKernelSamplesSimple) { + KernelSamples kernel_samples = { + .sample_count = 5, + .samples = + { + { + .uv_offset = Vector2(-2, 0), + .coefficient = 0.1f, + }, + { + .uv_offset = Vector2(-1, 0), + .coefficient = 0.2f, + }, + { + .uv_offset = Vector2(0, 0), + .coefficient = 0.4f, + }, + { + .uv_offset = Vector2(1, 0), + .coefficient = 0.2f, + }, + { + .uv_offset = Vector2(2, 0), + .coefficient = 0.1f, + }, + }, + }; + + GaussianBlurPipeline::FragmentShader::KernelSamples blur_info = + LerpHackKernelSamples(kernel_samples); + EXPECT_EQ(blur_info.sample_count, 3); + + KernelSample* samples = kernel_samples.samples; + + ////////////////////////////////////////////////////////////////////////////// + // Check output kernel. + + EXPECT_POINT_NEAR(GetUVOffset(blur_info.sample_data[0]), + Point(-1.3333333, 0)); + EXPECT_FLOAT_EQ(GetCoefficient(blur_info.sample_data[0]), 0.3); + + EXPECT_POINT_NEAR(GetUVOffset(blur_info.sample_data[1]), Point(0, 0)); + EXPECT_FLOAT_EQ(GetCoefficient(blur_info.sample_data[1]), 0.4); + + EXPECT_POINT_NEAR(GetUVOffset(blur_info.sample_data[2]), Point(1.333333, 0)); + EXPECT_FLOAT_EQ(GetCoefficient(blur_info.sample_data[2]), 0.3); + + ////////////////////////////////////////////////////////////////////////////// + // Check output of fast kernel versus original kernel. + + Scalar data[5] = {0.25, 0.5, 0.5, 1.0, 0.2}; + Scalar original_output = + samples[0].coefficient * data[0] + samples[1].coefficient * data[1] + + samples[2].coefficient * data[2] + samples[3].coefficient * data[3] + + samples[4].coefficient * data[4]; + + auto lerp = [](const Point& point, Scalar left, Scalar right) { + Scalar int_part; + Scalar fract = fabsf(modf(point.x, &int_part)); + if (point.x < 0) { + return left * fract + right * (1.0 - fract); + } else { + return left * (1.0 - fract) + right * fract; + } + }; + Scalar fast_output = + /*1st*/ lerp(GetUVOffset(blur_info.sample_data[0]), data[0], data[1]) * + GetCoefficient(blur_info.sample_data[0]) + + /*2nd*/ data[2] * GetCoefficient(blur_info.sample_data[1]) + + /*3rd*/ lerp(GetUVOffset(blur_info.sample_data[2]), data[3], data[4]) * + GetCoefficient(blur_info.sample_data[2]); + + EXPECT_NEAR(original_output, fast_output, 0.01); +} + +TEST(GaussianBlurFilterContentsTest, LerpHackKernelSamplesComplex) { + Scalar sigma = 10.0f; + int32_t blur_radius = static_cast( + std::ceil(GaussianBlurFilterContents::CalculateBlurRadius(sigma))); + BlurParameters parameters = {.blur_uv_offset = Point(1, 0), + .blur_sigma = sigma, + .blur_radius = blur_radius, + .step_size = 1}; + KernelSamples kernel_samples = GenerateBlurInfo(parameters); + EXPECT_EQ(kernel_samples.sample_count, 33); + GaussianBlurPipeline::FragmentShader::KernelSamples fast_kernel_samples = + LerpHackKernelSamples(kernel_samples); + EXPECT_EQ(fast_kernel_samples.sample_count, 17); + float data[33]; + srand(0); + for (int i = 0; i < 33; i++) { + data[i] = 255.0 * static_cast(IMPELLER_RAND()) / RAND_MAX; + } + + auto sampler = [data](Point point) -> Scalar { + FML_CHECK(point.y == 0.0f); + FML_CHECK(point.x >= -16); + FML_CHECK(point.x <= 16); + Scalar fint_part; + Scalar fract = fabsf(modf(point.x, &fint_part)); + if (fract == 0) { + int32_t int_part = static_cast(fint_part) + 16; + return data[int_part]; + } else { + int32_t left = static_cast(floor(point.x)) + 16; + int32_t right = static_cast(ceil(point.x)) + 16; + if (point.x < 0) { + return fract * data[left] + (1.0 - fract) * data[right]; + } else { + return (1.0 - fract) * data[left] + fract * data[right]; + } + } + }; + + Scalar output = 0.0; + for (int i = 0; i < kernel_samples.sample_count; ++i) { + auto sample = kernel_samples.samples[i]; + output += sample.coefficient * sampler(sample.uv_offset); + } + + Scalar fast_output = 0.0; + for (int i = 0; i < fast_kernel_samples.sample_count; i++) { + fast_output += GetCoefficient(fast_kernel_samples.sample_data[i]) * + sampler(GetUVOffset(fast_kernel_samples.sample_data[i])); + } + + EXPECT_NEAR(output, fast_output, 0.1); +} + +TEST(GaussianBlurFilterContentsTest, ChopHugeBlurs) { + Scalar sigma = 30.5f; + int32_t blur_radius = static_cast( + std::ceil(GaussianBlurFilterContents::CalculateBlurRadius(sigma))); + BlurParameters parameters = {.blur_uv_offset = Point(1, 0), + .blur_sigma = sigma, + .blur_radius = blur_radius, + .step_size = 1}; + KernelSamples kernel_samples = GenerateBlurInfo(parameters); + GaussianBlurPipeline::FragmentShader::KernelSamples frag_kernel_samples = + LerpHackKernelSamples(kernel_samples); + EXPECT_TRUE(frag_kernel_samples.sample_count <= kGaussianBlurMaxKernelSize); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.cc new file mode 100644 index 0000000000000000000000000000000000000000..9be12186d4baac47315ab7d4dc9b8c790c165ad3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.cc @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/inputs/contents_filter_input.h" + +#include +#include + +namespace impeller { + +ContentsFilterInput::ContentsFilterInput(std::shared_ptr contents, + bool msaa_enabled) + : contents_(std::move(contents)), msaa_enabled_(msaa_enabled) {} + +ContentsFilterInput::~ContentsFilterInput() = default; + +std::optional ContentsFilterInput::GetSnapshot( + std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const { + if (!coverage_limit.has_value() && entity.GetContents()) { + coverage_limit = entity.GetContents()->GetCoverageHint(); + } + if (!snapshot_.has_value()) { + snapshot_ = contents_->RenderToSnapshot(renderer, // renderer + entity, // entity + coverage_limit, // coverage_limit + std::nullopt, // sampler_descriptor + msaa_enabled_, // msaa_enabled + /*mip_count=*/mip_count, // + label // + ); + } + return snapshot_; +} + +std::optional ContentsFilterInput::GetCoverage( + const Entity& entity) const { + return contents_->GetCoverage(entity); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.h new file mode 100644 index 0000000000000000000000000000000000000000..42258f3d3a8a629d905260282fd43419d125a23c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/contents_filter_input.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_ + +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class ContentsFilterInput final : public FilterInput { + public: + ~ContentsFilterInput() override; + + // |FilterInput| + std::optional GetSnapshot(std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const override; + + // |FilterInput| + std::optional GetCoverage(const Entity& entity) const override; + + private: + ContentsFilterInput(std::shared_ptr contents, bool msaa_enabled); + + std::shared_ptr contents_; + mutable std::optional snapshot_; + bool msaa_enabled_; + + friend FilterInput; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_CONTENTS_FILTER_INPUT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.cc new file mode 100644 index 0000000000000000000000000000000000000000..10000909a7da8aee4f20671fdd1497350c328339 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.cc @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/inputs/filter_contents_filter_input.h" + +#include + +#include "impeller/base/strings.h" +#include "impeller/entity/contents/filters/filter_contents.h" + +namespace impeller { + +FilterContentsFilterInput::FilterContentsFilterInput( + std::shared_ptr filter) + : filter_(std::move(filter)) {} + +FilterContentsFilterInput::~FilterContentsFilterInput() = default; + +std::optional FilterContentsFilterInput::GetSnapshot( + std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const { + if (!snapshot_.has_value()) { + snapshot_ = filter_->RenderToSnapshot(renderer, // renderer + entity, // entity + coverage_limit, // coverage_limit + std::nullopt, // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/mip_count, // + label); // label + } + return snapshot_; +} + +std::optional FilterContentsFilterInput::GetCoverage( + const Entity& entity) const { + return filter_->GetCoverage(entity); +} + +std::optional FilterContentsFilterInput::GetSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + return filter_->GetSourceCoverage(effect_transform, output_limit); +} + +Matrix FilterContentsFilterInput::GetLocalTransform( + const Entity& entity) const { + return filter_->GetLocalTransform(entity.GetTransform()); +} + +Matrix FilterContentsFilterInput::GetTransform(const Entity& entity) const { + return filter_->GetTransform(entity.GetTransform()); +} + +void FilterContentsFilterInput::SetEffectTransform(const Matrix& matrix) { + filter_->SetEffectTransform(matrix); +} + +void FilterContentsFilterInput::SetRenderingMode( + Entity::RenderingMode rendering_mode) { + filter_->SetRenderingMode(rendering_mode); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.h new file mode 100644 index 0000000000000000000000000000000000000000..9bcac002b6207bf642888ad12134bc727f9b1de4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_contents_filter_input.h @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_CONTENTS_FILTER_INPUT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_CONTENTS_FILTER_INPUT_H_ + +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class FilterContentsFilterInput final : public FilterInput { + public: + ~FilterContentsFilterInput() override; + + // |FilterInput| + std::optional GetSnapshot(std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const override; + + // |FilterInput| + std::optional GetCoverage(const Entity& entity) const override; + + // |FilterInput| + std::optional GetSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + // |FilterInput| + Matrix GetLocalTransform(const Entity& entity) const override; + + // |FilterInput| + Matrix GetTransform(const Entity& entity) const override; + + // |FilterInput| + virtual void SetEffectTransform(const Matrix& matrix) override; + + // |FilterInput| + virtual void SetRenderingMode(Entity::RenderingMode rendering_mode) override; + + private: + explicit FilterContentsFilterInput(std::shared_ptr filter); + + std::shared_ptr filter_; + mutable std::optional snapshot_; + + friend FilterInput; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_CONTENTS_FILTER_INPUT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.cc new file mode 100644 index 0000000000000000000000000000000000000000..8963dbf8726baa646c4bbc68720aeacb1c046efa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/contents/filters/inputs/contents_filter_input.h" +#include "impeller/entity/contents/filters/inputs/filter_contents_filter_input.h" +#include "impeller/entity/contents/filters/inputs/placeholder_filter_input.h" +#include "impeller/entity/contents/filters/inputs/texture_filter_input.h" + +namespace impeller { + +FilterInput::Ref FilterInput::Make(Variant input, bool msaa_enabled) { + if (auto filter = std::get_if>(&input)) { + return std::static_pointer_cast( + std::shared_ptr( + new FilterContentsFilterInput(*filter))); + } + + if (auto contents = std::get_if>(&input)) { + return std::static_pointer_cast( + std::shared_ptr( + new ContentsFilterInput(*contents, msaa_enabled))); + } + + if (auto texture = std::get_if>(&input)) { + return Make(*texture, Matrix()); + } + + if (auto rect = std::get_if(&input)) { + return std::shared_ptr( + new PlaceholderFilterInput(*rect)); + } + + FML_UNREACHABLE(); +} + +FilterInput::Ref FilterInput::Make(std::shared_ptr texture, + Matrix local_transform) { + return std::shared_ptr( + new TextureFilterInput(std::move(texture), local_transform)); +} + +FilterInput::Vector FilterInput::Make(std::initializer_list inputs) { + FilterInput::Vector result; + result.reserve(inputs.size()); + for (const auto& input : inputs) { + result.push_back(Make(input)); + } + return result; +} + +Matrix FilterInput::GetLocalTransform(const Entity& entity) const { + return Matrix(); +} + +std::optional FilterInput::GetLocalCoverage(const Entity& entity) const { + Entity local_entity = entity.Clone(); + local_entity.SetTransform(GetLocalTransform(entity)); + return GetCoverage(local_entity); +} + +std::optional FilterInput::GetSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + return output_limit; +} + +Matrix FilterInput::GetTransform(const Entity& entity) const { + return entity.GetTransform() * GetLocalTransform(entity); +} + +FilterInput::~FilterInput() = default; + +void FilterInput::SetEffectTransform(const Matrix& matrix) {} + +void FilterInput::SetRenderingMode(Entity::RenderingMode rendering_mode) {} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.h new file mode 100644 index 0000000000000000000000000000000000000000..7888ac6ef9ec14b1a4ef91099a983fd40c966334 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input.h @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_ + +#include +#include +#include +#include + +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +class ContentContext; +class FilterContents; + +/// `FilterInput` is a lazy/single eval `Snapshot` which may be shared across +/// filter parameters and used to evaluate input coverage. +/// +/// A `FilterInput` can be re-used for any filter inputs across an entity's +/// filter graph without repeating subpasses unnecessarily. +/// +/// Filters may decide to not evaluate inputs in situations where they won't +/// contribute to the filter's output texture. +class FilterInput { + public: + using Ref = std::shared_ptr; + using Vector = std::vector; + using Variant = std::variant, + std::shared_ptr, + std::shared_ptr, + Rect>; + + virtual ~FilterInput(); + + static FilterInput::Ref Make(Variant input, bool msaa_enabled = true); + + static FilterInput::Ref Make(std::shared_ptr input, + Matrix local_transform); + + static FilterInput::Vector Make(std::initializer_list inputs); + + virtual std::optional GetSnapshot( + std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit = std::nullopt, + int32_t mip_count = 1) const = 0; + + std::optional GetLocalCoverage(const Entity& entity) const; + + virtual std::optional GetCoverage(const Entity& entity) const = 0; + + virtual std::optional GetSourceCoverage(const Matrix& effect_transform, + const Rect& output_limit) const; + + /// @brief Get the local transform of this filter input. This transform is + /// relative to the `Entity` transform space. + virtual Matrix GetLocalTransform(const Entity& entity) const; + + /// @brief Get the transform of this `FilterInput`. This is equivalent to + /// calling `entity.GetTransform() * GetLocalTransform()`. + virtual Matrix GetTransform(const Entity& entity) const; + + /// @brief Sets the effect transform of filter inputs. + virtual void SetEffectTransform(const Matrix& matrix); + + /// @brief Turns on subpass mode for filter inputs. + virtual void SetRenderingMode(Entity::RenderingMode rendering_mode); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_INPUT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b52d4a399fd04c4025a5ae7e52b74ecad22a4268 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/filter_input_unittests.cc @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +TEST(FilterInputTest, CanSetLocalTransformForTexture) { + std::shared_ptr texture = nullptr; + auto input = + FilterInput::Make(texture, Matrix::MakeTranslation({1.0, 0.0, 0.0})); + Entity e; + e.SetTransform(Matrix::MakeTranslation({0.0, 2.0, 0.0})); + + ASSERT_MATRIX_NEAR(input->GetLocalTransform(e), + Matrix::MakeTranslation({1.0, 0.0, 0.0})); + ASSERT_MATRIX_NEAR(input->GetTransform(e), + Matrix::MakeTranslation({1.0, 2.0, 0.0})); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.cc new file mode 100644 index 0000000000000000000000000000000000000000..0201645f40817fd8ca0825197e6932f1fa4d0f35 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.cc @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/inputs/placeholder_filter_input.h" + +#include + +namespace impeller { + +PlaceholderFilterInput::PlaceholderFilterInput(Rect coverage_rect) + : coverage_rect_(coverage_rect) {} + +PlaceholderFilterInput::~PlaceholderFilterInput() = default; + +std::optional PlaceholderFilterInput::GetSnapshot( + std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const { + return std::nullopt; +} + +std::optional PlaceholderFilterInput::GetCoverage( + const Entity& entity) const { + return coverage_rect_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.h new file mode 100644 index 0000000000000000000000000000000000000000..e64688c03016f06a5d65017a1685732954600888 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/placeholder_filter_input.h @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_ + +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class PlaceholderFilterInput final : public FilterInput { + public: + explicit PlaceholderFilterInput(Rect coverage); + + ~PlaceholderFilterInput() override; + + // |FilterInput| + std::optional GetSnapshot(std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count = 1) const override; + + // |FilterInput| + std::optional GetCoverage(const Entity& entity) const override; + + private: + Rect coverage_rect_; + + friend FilterInput; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_PLACEHOLDER_FILTER_INPUT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.cc new file mode 100644 index 0000000000000000000000000000000000000000..38ee99a5b78d37570a3686e11219b6f3c0c7ded8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.cc @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/inputs/texture_filter_input.h" + +#include + +#include "impeller/core/formats.h" + +namespace impeller { + +TextureFilterInput::TextureFilterInput(std::shared_ptr texture, + Matrix local_transform) + : texture_(std::move(texture)), local_transform_(local_transform) {} + +TextureFilterInput::~TextureFilterInput() = default; + +std::optional TextureFilterInput::GetSnapshot( + std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const { + auto snapshot = + Snapshot{.texture = texture_, .transform = GetTransform(entity)}; + if (texture_->GetMipCount() > 1) { + snapshot.sampler_descriptor.label = "TextureFilterInput Trilinear Sampler"; + snapshot.sampler_descriptor.mip_filter = MipFilter::kLinear; + } + return snapshot; +} + +std::optional TextureFilterInput::GetCoverage( + const Entity& entity) const { + return Rect::MakeSize(texture_->GetSize()) + .TransformBounds(GetTransform(entity)); +} + +Matrix TextureFilterInput::GetLocalTransform(const Entity& entity) const { + return local_transform_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.h new file mode 100644 index 0000000000000000000000000000000000000000..817dcb3077e259c9938b4d8a1939a202ecf61097 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/inputs/texture_filter_input.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_ + +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +#include "impeller/geometry/matrix.h" + +namespace impeller { + +class TextureFilterInput final : public FilterInput { + public: + ~TextureFilterInput() override; + + // |FilterInput| + std::optional GetSnapshot(std::string_view label, + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + int32_t mip_count) const override; + + // |FilterInput| + std::optional GetCoverage(const Entity& entity) const override; + + // |FilterInput| + Matrix GetLocalTransform(const Entity& entity) const override; + + private: + explicit TextureFilterInput(std::shared_ptr texture, + Matrix local_transform = Matrix()); + + std::shared_ptr texture_; + Matrix local_transform_; + + friend FilterInput; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_TEXTURE_FILTER_INPUT_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac8debca592d63fece5bf7bd4219a24f25ac98bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.cc @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/linear_to_srgb_filter_contents.h" + +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/geometry/point.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +LinearToSrgbFilterContents::LinearToSrgbFilterContents() = default; + +LinearToSrgbFilterContents::~LinearToSrgbFilterContents() = default; + +std::optional LinearToSrgbFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.empty()) { + return std::nullopt; + } + + using VS = LinearToSrgbFilterPipeline::VertexShader; + using FS = LinearToSrgbFilterPipeline::FragmentShader; + + auto input_snapshot = + inputs[0]->GetSnapshot("LinearToSrgb", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + RenderProc render_proc = [input_snapshot, + absorb_opacity = GetAbsorbOpacity()]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + pass.SetCommandLabel("Linear to sRGB Filter"); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetLinearToSrgbFilterPipeline(options)); + + auto size = input_snapshot->texture->GetSize(); + std::array vertices = { + VS::PerVertexData{Point(0, 0)}, + VS::PerVertexData{Point(1, 0)}, + VS::PerVertexData{Point(0, 1)}, + VS::PerVertexData{Point(1, 1)}, + }; + + auto& host_buffer = renderer.GetTransientsBuffer(); + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + VS::FrameInfo frame_info; + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * input_snapshot->transform * + Matrix::MakeScale(Vector2(size))); + frame_info.texture_sampler_y_coord_scale = + input_snapshot->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + frag_info.input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? input_snapshot->opacity + : 1.0f; + + FS::BindInputTexture( + pass, input_snapshot->texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler({})); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + return sub_entity; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..d43703896aacf4acb5889878ebcd7ffc78695d70 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/linear_to_srgb_filter_contents.h @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LINEAR_TO_SRGB_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LINEAR_TO_SRGB_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class LinearToSrgbFilterContents final : public ColorFilterContents { + public: + LinearToSrgbFilterContents(); + + ~LinearToSrgbFilterContents() override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + LinearToSrgbFilterContents(const LinearToSrgbFilterContents&) = delete; + + LinearToSrgbFilterContents& operator=(const LinearToSrgbFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LINEAR_TO_SRGB_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..de06e4f953a24e2189eb20cda2aa1dbf41500fce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.cc @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/local_matrix_filter_contents.h" + +namespace impeller { + +LocalMatrixFilterContents::LocalMatrixFilterContents() = default; + +LocalMatrixFilterContents::~LocalMatrixFilterContents() = default; + +void LocalMatrixFilterContents::SetMatrix(Matrix matrix) { + matrix_ = matrix; +} + +Matrix LocalMatrixFilterContents::GetLocalTransform( + const Matrix& parent_transform) const { + return matrix_; +} + +std::optional LocalMatrixFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + auto matrix = matrix_.Basis(); + if (!matrix.IsInvertible()) { + return std::nullopt; + } + auto inverse = matrix.Invert(); + return output_limit.TransformBounds(inverse); +} + +std::optional LocalMatrixFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + std::optional snapshot = + inputs[0]->GetSnapshot("LocalMatrix", renderer, entity); + if (!snapshot.has_value()) { + return std::nullopt; + } + return Entity::FromSnapshot(snapshot.value(), entity.GetBlendMode()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..0340058a021bca8878dbde023425aa3767d0f47b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/local_matrix_filter_contents.h @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LOCAL_MATRIX_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LOCAL_MATRIX_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class LocalMatrixFilterContents final : public FilterContents { + public: + LocalMatrixFilterContents(); + + ~LocalMatrixFilterContents() override; + + void SetMatrix(Matrix matrix); + + // |FilterContents| + Matrix GetLocalTransform(const Matrix& parent_transform) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + Matrix matrix_; + + LocalMatrixFilterContents(const LocalMatrixFilterContents&) = delete; + + LocalMatrixFilterContents& operator=(const LocalMatrixFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_LOCAL_MATRIX_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..743716d4f4cb8a5941dc8fe2258c2336cc89b7cb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.cc @@ -0,0 +1,150 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/matrix_filter_contents.h" + +namespace impeller { + +MatrixFilterContents::MatrixFilterContents() = default; + +MatrixFilterContents::~MatrixFilterContents() = default; + +void MatrixFilterContents::SetMatrix(Matrix matrix) { + matrix_ = matrix; +} + +void MatrixFilterContents::SetRenderingMode( + Entity::RenderingMode rendering_mode) { + rendering_mode_ = rendering_mode; + FilterContents::SetRenderingMode(rendering_mode); +} + +void MatrixFilterContents::SetSamplerDescriptor(const SamplerDescriptor& desc) { + sampler_descriptor_ = desc; +} + +namespace { +Matrix CalculateSubpassTransform(const Matrix& snapshot_transform, + const Matrix& effect_transform, + const Matrix& matrix, + Entity::RenderingMode rendering_mode) { + if (rendering_mode == + Entity::RenderingMode::kSubpassAppendSnapshotTransform) { + return snapshot_transform * // + effect_transform * // + matrix * // + effect_transform.Invert(); + } else { + FML_DCHECK(rendering_mode == + Entity::RenderingMode::kSubpassPrependSnapshotTransform); + return effect_transform * // + matrix * // + effect_transform.Invert() * // + snapshot_transform; + } +} +} // namespace + +std::optional MatrixFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + auto snapshot = inputs[0]->GetSnapshot("Matrix", renderer, entity); + if (!snapshot.has_value()) { + return std::nullopt; + } + + if (rendering_mode_ == + Entity::RenderingMode::kSubpassPrependSnapshotTransform || + rendering_mode_ == + Entity::RenderingMode::kSubpassAppendSnapshotTransform) { + // There are two special quirks with how Matrix filters behave when used as + // subpass backdrop filters: + // + // 1. For subpass backdrop filters, the snapshot transform is always just a + // translation that positions the parent pass texture correctly relative + // to the subpass texture. However, this translation always needs to be + // applied in screen space. + // + // Since we know the snapshot transform will always have an identity + // basis in this case, we safely reverse the order and apply the filter's + // matrix within the snapshot transform space. + // + // 2. The filter's matrix needs to be applied within the space defined by + // the scene's current transformation matrix (CTM). For example: If the + // CTM is scaled up, then translations applied by the matrix should be + // magnified accordingly. + // + // To accomplish this, we sandwitch the filter's matrix within the CTM in + // both cases. But notice that for the subpass backdrop filter case, we + // use the "effect transform" instead of the Entity's transform! + // + // That's because in the subpass backdrop filter case, the Entity's + // transform isn't actually the captured CTM of the scene like it usually + // is; instead, it's just a screen space translation that offsets the + // backdrop texture (as mentioned above). And so we sneak the subpass's + // captured CTM in through the effect transform. + // + snapshot->transform = CalculateSubpassTransform( + snapshot->transform, effect_transform, matrix_, rendering_mode_); + } else { + snapshot->transform = entity.GetTransform() * // + matrix_ * // + entity.GetTransform().Invert() * // + snapshot->transform; + } + snapshot->sampler_descriptor = sampler_descriptor_; + if (!snapshot.has_value()) { + return std::nullopt; + } + return Entity::FromSnapshot(snapshot.value(), entity.GetBlendMode()); +} + +std::optional MatrixFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + auto transform = effect_transform * // + matrix_ * // + effect_transform.Invert(); // + if (!transform.IsInvertible()) { + return std::nullopt; + } + auto inverse = transform.Invert(); + return output_limit.TransformBounds(inverse); +} + +std::optional MatrixFilterContents::GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const { + if (inputs.empty()) { + return std::nullopt; + } + + std::optional coverage = inputs[0]->GetCoverage(entity); + if (!coverage.has_value()) { + return std::nullopt; + } + + Matrix input_transform = inputs[0]->GetTransform(entity); + if (rendering_mode_ == + Entity::RenderingMode::kSubpassPrependSnapshotTransform || + rendering_mode_ == + Entity::RenderingMode::kSubpassAppendSnapshotTransform) { + Rect coverage_bounds = coverage->TransformBounds(input_transform.Invert()); + Matrix transform = CalculateSubpassTransform( + input_transform, effect_transform, matrix_, rendering_mode_); + return coverage_bounds.TransformBounds(transform); + } else { + Matrix transform = input_transform * // + matrix_ * // + input_transform.Invert(); // + return coverage->TransformBounds(transform); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..f853243d84cd0028b620c236273b7f5af5af3e67 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MATRIX_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MATRIX_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class MatrixFilterContents final : public FilterContents { + public: + MatrixFilterContents(); + + ~MatrixFilterContents() override; + + void SetMatrix(Matrix matrix); + + // |FilterContents| + void SetRenderingMode(Entity::RenderingMode rendering_mode) override; + + void SetSamplerDescriptor(const SamplerDescriptor& desc); + + // |FilterContents| + std::optional GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + Matrix matrix_; + SamplerDescriptor sampler_descriptor_ = {}; + Entity::RenderingMode rendering_mode_ = Entity::RenderingMode::kDirect; + + MatrixFilterContents(const MatrixFilterContents&) = delete; + + MatrixFilterContents& operator=(const MatrixFilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MATRIX_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c33ed379a7454d56f87be58ff3a99813a454f17 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/matrix_filter_contents_unittests.cc @@ -0,0 +1,215 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "impeller/entity/contents/filters/matrix_filter_contents.h" +#include "impeller/entity/entity_playground.h" +#include "impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +class MatrixFilterContentsTest : public EntityPlayground { + public: + /// Create a texture that has been cleared to transparent black. + std::shared_ptr MakeTexture(ISize size) { + std::shared_ptr command_buffer = + GetContentContext()->GetContext()->CreateCommandBuffer(); + if (!command_buffer) { + return nullptr; + } + + auto render_target = GetContentContext()->MakeSubpass( + "Clear Subpass", size, command_buffer, + [](const ContentContext&, RenderPass&) { return true; }); + + if (!GetContentContext() + ->GetContext() + ->GetCommandQueue() + ->Submit(/*buffers=*/{command_buffer}) + .ok()) { + return nullptr; + } + + if (render_target.ok()) { + return render_target.value().GetRenderTargetTexture(); + } + return nullptr; + } +}; + +INSTANTIATE_PLAYGROUND_SUITE(MatrixFilterContentsTest); + +TEST(MatrixFilterContentsTest, CoverageEmpty) { + MatrixFilterContents contents; + FilterInput::Vector inputs = {}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + ASSERT_FALSE(coverage.has_value()); +} + +TEST(MatrixFilterContentsTest, CoverageSimple) { + MatrixFilterContents contents; + FilterInput::Vector inputs = { + FilterInput::Make(Rect::MakeLTRB(10, 10, 110, 110))}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + + ASSERT_EQ(coverage, Rect::MakeLTRB(10, 10, 110, 110)); +} + +TEST(MatrixFilterContentsTest, Coverage2x) { + MatrixFilterContents contents; + contents.SetMatrix(Matrix::MakeScale({2.0, 2.0, 1.0})); + FilterInput::Vector inputs = { + FilterInput::Make(Rect::MakeXYWH(10, 10, 100, 100))}; + Entity entity; + std::optional coverage = + contents.GetFilterCoverage(inputs, entity, /*effect_transform=*/Matrix()); + + ASSERT_EQ(coverage, Rect::MakeXYWH(20, 20, 200, 200)); +} + +TEST(MatrixFilterContentsTest, Coverage2xEffect) { + MatrixFilterContents contents; + FilterInput::Vector inputs = { + FilterInput::Make(Rect::MakeXYWH(10, 10, 100, 100))}; + Entity entity; + std::optional coverage = contents.GetFilterCoverage( + inputs, entity, /*effect_transform=*/Matrix::MakeScale({2.0, 2.0, 1.0})); + + ASSERT_EQ(coverage, Rect::MakeXYWH(10, 10, 100, 100)); +} + +namespace { +void expectRenderCoverageEqual(const std::optional& result, + const std::optional contents_coverage, + const Rect& expected) { + EXPECT_TRUE(result.has_value()); + if (result.has_value()) { + EXPECT_EQ(result.value().GetBlendMode(), BlendMode::kSrcOver); + std::optional result_coverage = result.value().GetCoverage(); + EXPECT_TRUE(result_coverage.has_value()); + EXPECT_TRUE(contents_coverage.has_value()); + if (result_coverage.has_value() && contents_coverage.has_value()) { + EXPECT_TRUE(RectNear(contents_coverage.value(), expected)); + EXPECT_TRUE(RectNear(result_coverage.value(), expected)); + } + } +} +} // namespace + +TEST_P(MatrixFilterContentsTest, RenderCoverageMatchesGetCoverageIdentity) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(100, 200, 100, 100)); +} + +TEST_P(MatrixFilterContentsTest, RenderCoverageMatchesGetCoverageTranslate) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + contents.SetMatrix(Matrix::MakeTranslation({50, 100, 0})); + contents.SetEffectTransform(Matrix::MakeScale({2, 2, 1})); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(150, 300, 100, 100)); +} + +TEST_P(MatrixFilterContentsTest, + RenderCoverageMatchesGetCoverageClippedSubpassTranslate) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + contents.SetMatrix(Matrix::MakeTranslation({50, 100, 0})); + contents.SetEffectTransform(Matrix::MakeScale({2, 2, 1})); + contents.SetRenderingMode( + Entity::RenderingMode::kSubpassAppendSnapshotTransform); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(200, 400, 100, 100)); +} + +TEST_P(MatrixFilterContentsTest, RenderCoverageMatchesGetCoverageScale) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + contents.SetMatrix(Matrix::MakeScale({3, 3, 1})); + contents.SetEffectTransform(Matrix::MakeScale({2, 2, 1})); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(100, 200, 300, 300)); +} + +TEST_P(MatrixFilterContentsTest, + RenderCoverageMatchesGetCoverageClippedSubpassScale) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + contents.SetMatrix(Matrix::MakeScale({3, 3, 1})); + contents.SetEffectTransform(Matrix::MakeScale({2, 2, 1})); + contents.SetRenderingMode( + Entity::RenderingMode::kSubpassAppendSnapshotTransform); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(100, 200, 300, 300)); +} + +TEST_P(MatrixFilterContentsTest, RenderCoverageMatchesGetCoverageSubpassScale) { + std::shared_ptr texture = MakeTexture(ISize(100, 100)); + MatrixFilterContents contents; + contents.SetInputs({FilterInput::Make(texture)}); + contents.SetMatrix(Matrix::MakeScale({3, 3, 1})); + contents.SetEffectTransform(Matrix::MakeScale({2, 2, 1})); + contents.SetRenderingMode( + Entity::RenderingMode::kSubpassPrependSnapshotTransform); + + Entity entity; + entity.SetTransform(Matrix::MakeTranslation({100, 200, 0})); + + std::shared_ptr renderer = GetContentContext(); + std::optional result = + contents.GetEntity(*renderer, entity, /*coverage_hint=*/{}); + expectRenderCoverageEqual(result, contents.GetCoverage(entity), + Rect::MakeXYWH(300, 600, 300, 300)); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..a87d5298c6c871fb9dc12b18e7d35cac9ab0e330 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.cc @@ -0,0 +1,212 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/morphology_filter_contents.h" + +#include + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +DirectionalMorphologyFilterContents::DirectionalMorphologyFilterContents() = + default; + +DirectionalMorphologyFilterContents::~DirectionalMorphologyFilterContents() = + default; + +void DirectionalMorphologyFilterContents::SetRadius(Radius radius) { + radius_ = radius; +} + +void DirectionalMorphologyFilterContents::SetDirection(Vector2 direction) { + direction_ = direction.Normalize(); + if (direction_.IsZero()) { + direction_ = Vector2(0, 1); + } +} + +void DirectionalMorphologyFilterContents::SetMorphType(MorphType morph_type) { + morph_type_ = morph_type; +} + +std::optional DirectionalMorphologyFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + using VS = MorphologyFilterPipeline::VertexShader; + using FS = MorphologyFilterPipeline::FragmentShader; + + //---------------------------------------------------------------------------- + /// Handle inputs. + /// + + if (inputs.empty()) { + return std::nullopt; + } + + auto input_snapshot = inputs[0]->GetSnapshot("Morphology", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + if (radius_.radius < kEhCloseEnough) { + return Entity::FromSnapshot(input_snapshot.value(), entity.GetBlendMode()); + } + + auto maybe_input_uvs = input_snapshot->GetCoverageUVs(coverage); + if (!maybe_input_uvs.has_value()) { + return std::nullopt; + } + auto input_uvs = maybe_input_uvs.value(); + + //---------------------------------------------------------------------------- + /// Render to texture. + /// + + ContentContext::SubpassCallback callback = [&](const ContentContext& renderer, + RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); + + std::array vertices = { + VS::PerVertexData{Point(0, 0), input_uvs[0]}, + VS::PerVertexData{Point(1, 0), input_uvs[1]}, + VS::PerVertexData{Point(0, 1), input_uvs[2]}, + VS::PerVertexData{Point(1, 1), input_uvs[3]}, + }; + + VS::FrameInfo frame_info; + frame_info.mvp = Matrix::MakeOrthographic(ISize(1, 1)); + frame_info.texture_sampler_y_coord_scale = + input_snapshot->texture->GetYCoordScale(); + + auto transform = entity.GetTransform() * effect_transform.Basis(); + auto transformed_radius = + transform.TransformDirection(direction_ * radius_.radius); + auto transformed_texture_vertices = + Rect::MakeSize(input_snapshot->texture->GetSize()) + .GetTransformedPoints(input_snapshot->transform); + auto transformed_texture_width = + transformed_texture_vertices[0].GetDistance( + transformed_texture_vertices[1]); + auto transformed_texture_height = + transformed_texture_vertices[0].GetDistance( + transformed_texture_vertices[2]); + + FS::FragInfo frag_info; + frag_info.radius = std::round(transformed_radius.GetLength()); + frag_info.morph_type = static_cast(morph_type_); + frag_info.uv_offset = + input_snapshot->transform.Invert() + .TransformDirection(transformed_radius) + .Normalize() / + Point(transformed_texture_width, transformed_texture_height); + + pass.SetCommandLabel("Morphology Filter"); + auto options = OptionsFromPass(pass); + options.primitive_type = PrimitiveType::kTriangleStrip; + options.blend_mode = BlendMode::kSrc; + pass.SetPipeline(renderer.GetMorphologyFilterPipeline(options)); + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + auto sampler_descriptor = input_snapshot->sampler_descriptor; + if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { + sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; + sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; + } + + FS::BindTextureSampler( + pass, input_snapshot->texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_descriptor)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + return pass.Draw().ok(); + }; + std::shared_ptr command_buffer = + renderer.GetContext()->CreateCommandBuffer(); + if (command_buffer == nullptr) { + return std::nullopt; + } + + fml::StatusOr render_target = + renderer.MakeSubpass("Directional Morphology Filter", + ISize(coverage.GetSize()), command_buffer, callback); + if (!render_target.ok()) { + return std::nullopt; + } + + if (!renderer.GetContext()->EnqueueCommandBuffer(std::move(command_buffer))) { + return std::nullopt; + } + + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + + return Entity::FromSnapshot( + Snapshot{.texture = render_target.value().GetRenderTargetTexture(), + .transform = Matrix::MakeTranslation(coverage.GetOrigin()), + .sampler_descriptor = sampler_desc, + .opacity = input_snapshot->opacity}, + entity.GetBlendMode()); +} + +std::optional DirectionalMorphologyFilterContents::GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const { + if (inputs.empty()) { + return std::nullopt; + } + + auto coverage = inputs[0]->GetCoverage(entity); + if (!coverage.has_value()) { + return std::nullopt; + } + auto transform = inputs[0]->GetTransform(entity) * effect_transform.Basis(); + auto transformed_vector = + transform.TransformDirection(direction_ * radius_.radius).Abs(); + + auto origin = coverage->GetOrigin(); + auto size = Vector2(coverage->GetSize()); + switch (morph_type_) { + case FilterContents::MorphType::kDilate: + origin -= transformed_vector; + size += transformed_vector * 2; + break; + case FilterContents::MorphType::kErode: + origin += transformed_vector; + size -= transformed_vector * 2; + break; + } + if (size.x < 0 || size.y < 0) { + return Rect::MakeSize(Size(0, 0)); + } + return Rect::MakeOriginSize(origin, Size(size.x, size.y)); +} + +std::optional +DirectionalMorphologyFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + auto transformed_vector = + effect_transform.TransformDirection(direction_ * radius_.radius).Abs(); + switch (morph_type_) { + case FilterContents::MorphType::kDilate: + return output_limit.Expand(-transformed_vector); + case FilterContents::MorphType::kErode: + return output_limit.Expand(transformed_vector); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..db3c23071ce0906529a3bd69e738964f81239ab0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/morphology_filter_contents.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_ + +#include +#include +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class DirectionalMorphologyFilterContents final : public FilterContents { + public: + DirectionalMorphologyFilterContents(); + + ~DirectionalMorphologyFilterContents() override; + + void SetRadius(Radius radius); + + void SetDirection(Vector2 direction); + + void SetMorphType(MorphType morph_type); + + // |FilterContents| + std::optional GetFilterCoverage( + const FilterInput::Vector& inputs, + const Entity& entity, + const Matrix& effect_transform) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + Radius radius_; + Vector2 direction_; + MorphType morph_type_; + + DirectionalMorphologyFilterContents( + const DirectionalMorphologyFilterContents&) = delete; + + DirectionalMorphologyFilterContents& operator=( + const DirectionalMorphologyFilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_MORPHOLOGY_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..4bc87c443efd95dd6dec5848030d324fbd423cd1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.cc @@ -0,0 +1,111 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/runtime_effect_filter_contents.h" + +#include +#include + +#include "impeller/base/validation.h" +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/runtime_effect_contents.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +void RuntimeEffectFilterContents::SetRuntimeStage( + std::shared_ptr runtime_stage) { + runtime_stage_ = std::move(runtime_stage); +} + +void RuntimeEffectFilterContents::SetUniforms( + std::shared_ptr> uniforms) { + uniforms_ = std::move(uniforms); +} + +void RuntimeEffectFilterContents::SetTextureInputs( + std::vector texture_inputs) { + texture_inputs_ = std::move(texture_inputs); +} + +// |FilterContents| +std::optional RuntimeEffectFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.empty()) { + return std::nullopt; + } + + auto input_snapshot = + inputs[0]->GetSnapshot("RuntimeEffectContents", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + std::optional maybe_input_coverage = input_snapshot->GetCoverage(); + if (!maybe_input_coverage.has_value()) { + return std::nullopt; + } + Rect input_coverage = maybe_input_coverage.value(); + // The shader is required to have at least one sampler, the first of + // which is treated as the input and a vec2 size uniform to compute the + // offsets. These are validated at the dart:ui layer, but to avoid crashes we + // check here too. + if (texture_inputs_.size() < 1 || uniforms_->size() < 8) { + VALIDATION_LOG + << "Invalid fragment shader in RuntimeEffectFilterContents. " + << "Shader must have at least one sampler and a vec2 size uniform."; + return std::nullopt; + } + + // Update uniform values. + std::vector texture_input_copy = + texture_inputs_; + texture_input_copy[0].texture = input_snapshot->texture; + + Size size = Size(input_snapshot->texture->GetSize()); + memcpy(uniforms_->data(), &size, sizeof(Size)); + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + RenderProc render_proc = + [input_snapshot, runtime_stage = runtime_stage_, uniforms = uniforms_, + texture_inputs = texture_input_copy, + input_coverage](const ContentContext& renderer, const Entity& entity, + RenderPass& pass) -> bool { + RuntimeEffectContents contents; + RectGeometry geom(Rect::MakeSize(input_coverage.GetSize())); + contents.SetRuntimeStage(runtime_stage); + contents.SetUniformData(uniforms); + contents.SetTextureInputs(texture_inputs); + contents.SetGeometry(&geom); + return contents.Render(renderer, entity, pass); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + sub_entity.SetTransform(input_snapshot->transform); + return sub_entity; +} + +// |FilterContents| +std::optional RuntimeEffectFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + return output_limit; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..3a68ecd67ab1577a2cb42749e54b89150f097cf3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/runtime_effect_filter_contents.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_RUNTIME_EFFECT_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_RUNTIME_EFFECT_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/filter_contents.h" + +namespace impeller { + +/// A filter that applies a runtime effect shader +class RuntimeEffectFilterContents final : public FilterContents { + public: + RuntimeEffectFilterContents() {} + + ~RuntimeEffectFilterContents() = default; + + void SetRuntimeStage(std::shared_ptr runtime_stage); + + void SetUniforms(std::shared_ptr> uniforms); + + void SetTextureInputs( + std::vector texture_inputs); + + private: + std::shared_ptr runtime_stage_; + std::shared_ptr> uniforms_; + std::vector texture_inputs_; + + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + RuntimeEffectFilterContents(const RuntimeEffectFilterContents&) = delete; + + RuntimeEffectFilterContents& operator=(const RuntimeEffectFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_RUNTIME_EFFECT_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..59b918bd9a26f3a8b43171e866d40b19b98712a8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/srgb_to_linear_filter_contents.h" + +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/geometry/point.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +SrgbToLinearFilterContents::SrgbToLinearFilterContents() = default; + +SrgbToLinearFilterContents::~SrgbToLinearFilterContents() = default; + +std::optional SrgbToLinearFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.empty()) { + return std::nullopt; + } + + using VS = SrgbToLinearFilterPipeline::VertexShader; + using FS = SrgbToLinearFilterPipeline::FragmentShader; + + auto input_snapshot = + inputs[0]->GetSnapshot("SrgbToLinear", renderer, entity); + if (!input_snapshot.has_value()) { + return std::nullopt; + } + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + RenderProc render_proc = [input_snapshot, + absorb_opacity = GetAbsorbOpacity()]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + pass.SetCommandLabel("sRGB to Linear Filter"); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetSrgbToLinearFilterPipeline(options)); + + auto size = input_snapshot->texture->GetSize(); + + std::array vertices = { + VS::PerVertexData{Point(0, 0)}, + VS::PerVertexData{Point(1, 0)}, + VS::PerVertexData{Point(0, 1)}, + VS::PerVertexData{Point(1, 1)}, + }; + + auto& host_buffer = renderer.GetTransientsBuffer(); + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::FrameInfo frame_info; + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * input_snapshot->transform * + Matrix::MakeScale(Vector2(size))); + frame_info.texture_sampler_y_coord_scale = + input_snapshot->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + frag_info.input_alpha = + absorb_opacity == ColorFilterContents::AbsorbOpacity::kYes + ? input_snapshot->opacity + : 1.0f; + + raw_ptr sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler({}); + FS::BindInputTexture(pass, input_snapshot->texture, sampler); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + return sub_entity; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..dfadcffbf0c42955816046413b4cb8837e491a52 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/srgb_to_linear_filter_contents.h @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_SRGB_TO_LINEAR_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_SRGB_TO_LINEAR_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/contents/filters/inputs/filter_input.h" + +namespace impeller { + +class SrgbToLinearFilterContents final : public ColorFilterContents { + public: + SrgbToLinearFilterContents(); + + ~SrgbToLinearFilterContents() override; + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + SrgbToLinearFilterContents(const SrgbToLinearFilterContents&) = delete; + + SrgbToLinearFilterContents& operator=(const SrgbToLinearFilterContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_SRGB_TO_LINEAR_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ba820bfb6446e08f45353fcd5e69938fdc2f47f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.cc @@ -0,0 +1,144 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h" + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/anonymous_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/geometry/matrix.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +// clang-format off +constexpr Matrix kMatrixBT601LimitedRange = { + 1.164, 1.164, 1.164, 0.0, + 0.0, -0.392, 2.017, 0.0, + 1.596, -0.813, 0.0, 0.0, + 0.0, 0.0, 0.0, 1.0 +}; + +constexpr Matrix kMatrixBT601FullRange = { + 1.0, 1.0, 1.0, 0.0, + 0.0, -0.344, 1.772, 0.0, + 1.402, -0.714, 0.0, 0.0, + 0.0, 0.0, 0.0, 1.0 +}; +// clang-format on + +YUVToRGBFilterContents::YUVToRGBFilterContents() = default; + +YUVToRGBFilterContents::~YUVToRGBFilterContents() = default; + +void YUVToRGBFilterContents::SetYUVColorSpace(YUVColorSpace yuv_color_space) { + yuv_color_space_ = yuv_color_space; +} + +std::optional YUVToRGBFilterContents::RenderFilter( + const FilterInput::Vector& inputs, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const { + if (inputs.size() < 2) { + return std::nullopt; + } + + using VS = YUVToRGBFilterPipeline::VertexShader; + using FS = YUVToRGBFilterPipeline::FragmentShader; + + auto y_input_snapshot = + inputs[0]->GetSnapshot("YUVToRGB(Y)", renderer, entity); + auto uv_input_snapshot = + inputs[1]->GetSnapshot("YUVToRGB(UV)", renderer, entity); + if (!y_input_snapshot.has_value() || !uv_input_snapshot.has_value()) { + return std::nullopt; + } + + if (y_input_snapshot->texture->GetTextureDescriptor().format != + PixelFormat::kR8UNormInt || + uv_input_snapshot->texture->GetTextureDescriptor().format != + PixelFormat::kR8G8UNormInt) { + return std::nullopt; + } + + //---------------------------------------------------------------------------- + /// Create AnonymousContents for rendering. + /// + RenderProc render_proc = [y_input_snapshot, uv_input_snapshot, + yuv_color_space = yuv_color_space_]( + const ContentContext& renderer, + const Entity& entity, RenderPass& pass) -> bool { + pass.SetCommandLabel("YUV to RGB Filter"); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = PrimitiveType::kTriangleStrip; + pass.SetPipeline(renderer.GetYUVToRGBFilterPipeline(options)); + + auto size = y_input_snapshot->texture->GetSize(); + + std::array vertices = { + VS::PerVertexData{Point(0, 0)}, + VS::PerVertexData{Point(1, 0)}, + VS::PerVertexData{Point(0, 1)}, + VS::PerVertexData{Point(1, 1)}, + }; + + auto& host_buffer = renderer.GetTransientsBuffer(); + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + VS::FrameInfo frame_info; + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * y_input_snapshot->transform * + Matrix::MakeScale(Vector2(size))); + frame_info.texture_sampler_y_coord_scale = + y_input_snapshot->texture->GetYCoordScale(); + + FS::FragInfo frag_info; + frag_info.yuv_color_space = static_cast(yuv_color_space); + switch (yuv_color_space) { + case YUVColorSpace::kBT601LimitedRange: + frag_info.matrix = kMatrixBT601LimitedRange; + break; + case YUVColorSpace::kBT601FullRange: + frag_info.matrix = kMatrixBT601FullRange; + break; + } + + raw_ptr sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler({}); + FS::BindYTexture(pass, y_input_snapshot->texture, sampler); + FS::BindUvTexture(pass, uv_input_snapshot->texture, sampler); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + }; + + CoverageProc coverage_proc = + [coverage](const Entity& entity) -> std::optional { + return coverage.TransformBounds(entity.GetTransform()); + }; + + auto contents = AnonymousContents::Make(render_proc, coverage_proc); + + Entity sub_entity; + sub_entity.SetContents(std::move(contents)); + sub_entity.SetBlendMode(entity.GetBlendMode()); + return sub_entity; +} + +std::optional YUVToRGBFilterContents::GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const { + return output_limit; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..efa903f0d9d350adc8d74e2d04214df452559f1b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/filters/yuv_to_rgb_filter_contents.h @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_YUV_TO_RGB_FILTER_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_YUV_TO_RGB_FILTER_CONTENTS_H_ + +#include "impeller/entity/contents/filters/filter_contents.h" + +namespace impeller { + +class YUVToRGBFilterContents final : public FilterContents { + public: + YUVToRGBFilterContents(); + + ~YUVToRGBFilterContents() override; + + void SetYUVColorSpace(YUVColorSpace yuv_color_space); + + private: + // |FilterContents| + std::optional RenderFilter( + const FilterInput::Vector& input_textures, + const ContentContext& renderer, + const Entity& entity, + const Matrix& effect_transform, + const Rect& coverage, + const std::optional& coverage_hint) const override; + + // |FilterContents| + std::optional GetFilterSourceCoverage( + const Matrix& effect_transform, + const Rect& output_limit) const override; + + YUVColorSpace yuv_color_space_ = YUVColorSpace::kBT601LimitedRange; + + YUVToRGBFilterContents(const YUVToRGBFilterContents&) = delete; + + YUVToRGBFilterContents& operator=(const YUVToRGBFilterContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_YUV_TO_RGB_FILTER_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..3d8e4cca85d35baf3f72deade74c66debb949a65 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.cc @@ -0,0 +1,148 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "framebuffer_blend_contents.h" + +#include "impeller/entity/contents/content_context.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +FramebufferBlendContents::FramebufferBlendContents() = default; + +FramebufferBlendContents::~FramebufferBlendContents() = default; + +void FramebufferBlendContents::SetBlendMode(BlendMode blend_mode) { + blend_mode_ = blend_mode; +} + +void FramebufferBlendContents::SetChildContents( + std::shared_ptr child_contents) { + child_contents_ = std::move(child_contents); +} + +// |Contents| +std::optional FramebufferBlendContents::GetCoverage( + const Entity& entity) const { + return child_contents_->GetCoverage(entity); +} + +bool FramebufferBlendContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (!renderer.GetDeviceCapabilities().SupportsFramebufferFetch()) { + return false; + } + + using VS = FramebufferBlendScreenPipeline::VertexShader; + using FS = FramebufferBlendScreenPipeline::FragmentShader; + + auto& host_buffer = renderer.GetTransientsBuffer(); + + auto src_snapshot = child_contents_->RenderToSnapshot( + renderer, // renderer + entity, // entity + Rect::MakeSize(pass.GetRenderTargetSize()), // coverage_limit + std::nullopt, // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/1, + "FramebufferBlendContents Snapshot"); // label + + if (!src_snapshot.has_value()) { + return true; + } + + auto size = src_snapshot->texture->GetSize(); + + std::array vertices = { + VS::PerVertexData{Point(0, 0), Point(0, 0)}, + VS::PerVertexData{Point(size.width, 0), Point(1, 0)}, + VS::PerVertexData{Point(0, size.height), Point(0, 1)}, + VS::PerVertexData{Point(size.width, size.height), Point(1, 1)}, + }; + + auto options = OptionsFromPass(pass); + options.blend_mode = BlendMode::kSrc; + options.primitive_type = PrimitiveType::kTriangleStrip; + + pass.SetCommandLabel("Framebuffer Advanced Blend Filter"); + pass.SetVertexBuffer( + CreateVertexBuffer(vertices, renderer.GetTransientsBuffer())); + + switch (blend_mode_) { + case BlendMode::kScreen: + pass.SetPipeline(renderer.GetFramebufferBlendScreenPipeline(options)); + break; + case BlendMode::kOverlay: + pass.SetPipeline(renderer.GetFramebufferBlendOverlayPipeline(options)); + break; + case BlendMode::kDarken: + pass.SetPipeline(renderer.GetFramebufferBlendDarkenPipeline(options)); + break; + case BlendMode::kLighten: + pass.SetPipeline(renderer.GetFramebufferBlendLightenPipeline(options)); + break; + case BlendMode::kColorDodge: + pass.SetPipeline(renderer.GetFramebufferBlendColorDodgePipeline(options)); + break; + case BlendMode::kColorBurn: + pass.SetPipeline(renderer.GetFramebufferBlendColorBurnPipeline(options)); + break; + case BlendMode::kHardLight: + pass.SetPipeline(renderer.GetFramebufferBlendHardLightPipeline(options)); + break; + case BlendMode::kSoftLight: + pass.SetPipeline(renderer.GetFramebufferBlendSoftLightPipeline(options)); + break; + case BlendMode::kDifference: + pass.SetPipeline(renderer.GetFramebufferBlendDifferencePipeline(options)); + break; + case BlendMode::kExclusion: + pass.SetPipeline(renderer.GetFramebufferBlendExclusionPipeline(options)); + break; + case BlendMode::kMultiply: + pass.SetPipeline(renderer.GetFramebufferBlendMultiplyPipeline(options)); + break; + case BlendMode::kHue: + pass.SetPipeline(renderer.GetFramebufferBlendHuePipeline(options)); + break; + case BlendMode::kSaturation: + pass.SetPipeline(renderer.GetFramebufferBlendSaturationPipeline(options)); + break; + case BlendMode::kColor: + pass.SetPipeline(renderer.GetFramebufferBlendColorPipeline(options)); + break; + case BlendMode::kLuminosity: + pass.SetPipeline(renderer.GetFramebufferBlendLuminosityPipeline(options)); + break; + default: + return false; + } + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + + auto src_sampler_descriptor = src_snapshot->sampler_descriptor; + if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { + src_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; + src_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; + } + raw_ptr src_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + src_sampler_descriptor); + FS::BindTextureSamplerSrc(pass, src_snapshot->texture, src_sampler); + + frame_info.mvp = Entity::GetShaderTransform(entity.GetShaderClipDepth(), pass, + src_snapshot->transform); + frame_info.src_y_coord_scale = src_snapshot->texture->GetYCoordScale(); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + frag_info.src_input_alpha = src_snapshot->opacity; + frag_info.dst_input_alpha = 1.0; + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + return pass.Draw().ok(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..5335055bd3f612422cd68f450561b977becebef6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/framebuffer_blend_contents.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/entity.h" + +namespace impeller { + +enum class BlendSelectValues { + kScreen = 0, + kOverlay, + kDarken, + kLighten, + kColorDodge, + kColorBurn, + kHardLight, + kSoftLight, + kDifference, + kExclusion, + kMultiply, + kHue, + kSaturation, + kColor, + kLuminosity, +}; + +class FramebufferBlendContents final : public ColorSourceContents { + public: + FramebufferBlendContents(); + + ~FramebufferBlendContents() override; + + void SetBlendMode(BlendMode blend_mode); + + void SetChildContents(std::shared_ptr child_contents); + + private: + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + BlendMode blend_mode_; + std::shared_ptr child_contents_; + + FramebufferBlendContents(const FramebufferBlendContents&) = delete; + + FramebufferBlendContents& operator=(const FramebufferBlendContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FRAMEBUFFER_BLEND_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.cc b/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.cc new file mode 100644 index 0000000000000000000000000000000000000000..f83c1424d9c2ec15106c6326b55517384ff8dc70 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.cc @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/gradient_generator.h" + +#include "flutter/fml/logging.h" +#include "impeller/base/strings.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/texture_util.h" + +namespace impeller { + +std::shared_ptr CreateGradientTexture( + const GradientData& gradient_data, + const std::shared_ptr& context) { + if (gradient_data.texture_size == 0) { + FML_DLOG(ERROR) << "Invalid gradient data."; + return nullptr; + } + + impeller::TextureDescriptor texture_descriptor; + texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; + texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt; + texture_descriptor.size = {gradient_data.texture_size, 1}; + + return CreateTexture(texture_descriptor, gradient_data.color_bytes, context, + "Gradient"); +} + +std::vector CreateGradientColors(const std::vector& colors, + const std::vector& stops) { + FML_DCHECK(stops.size() == colors.size()); + + std::vector result; + result.reserve(stops.size()); + Scalar last_stop = 0; + for (auto i = 0u; i < stops.size(); i++) { + Scalar delta = stops[i] - last_stop; + Scalar inverse_delta = delta == 0.0f ? 0.0 : 1.0 / delta; + result.emplace_back(StopData{ + .color = colors[i], .stop = stops[i], .inverse_delta = inverse_delta}); + last_stop = stops[i]; + } + return result; +} + +int PopulateUniformGradientColors( + const std::vector& colors, + const std::vector& stops, + Vector4 frag_info_colors[kMaxUniformGradientStops], + Vector4 frag_info_stop_pairs[kMaxUniformGradientStops / 2]) { + FML_DCHECK(stops.size() == colors.size()); + + Scalar last_stop = 0; + int index = 0; + for (auto i = 0u; i < stops.size() && i < kMaxUniformGradientStops; i++) { + Scalar cur_stop = stops[i]; + Scalar delta = cur_stop - last_stop; + Scalar inverse_delta = delta == 0.0f ? 0.0 : 1.0 / delta; + frag_info_colors[index] = colors[i]; + if ((i & 1) == 0) { + frag_info_stop_pairs[index / 2].x = cur_stop; + frag_info_stop_pairs[index / 2].y = inverse_delta; + } else { + frag_info_stop_pairs[index / 2].z = cur_stop; + frag_info_stop_pairs[index / 2].w = inverse_delta; + } + last_stop = cur_stop; + index++; + } + return index; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.h b/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..fa6dab716f94a0b361e3551bf51d34da34afad4b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/gradient_generator.h @@ -0,0 +1,71 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_ + +#include +#include + +#include "flutter/impeller/core/texture.h" +#include "impeller/core/shader_types.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/gradient.h" + +namespace impeller { + +class Context; + +/** + * @brief Create a host visible texture that contains the gradient defined + * by the provided gradient data. + */ +std::shared_ptr CreateGradientTexture( + const GradientData& gradient_data, + const std::shared_ptr& context); + +struct StopData { + Color color; + Scalar stop; + Scalar inverse_delta; + Padding<8> _padding_; +}; + +static_assert(sizeof(StopData) == 32); + +/** + * @brief Populate a vector with the color and stop data for a gradient + * + * @param colors + * @param stops + * @return StopData + */ +std::vector CreateGradientColors(const std::vector& colors, + const std::vector& stops); + +static constexpr uint32_t kMaxUniformGradientStops = 256u; + +/** + * @brief Populate 2 arrays with the colors and stop data for a gradient + * + * The color data is simply converted to a vec4 format, but the stop data + * is both turned into pairs of {t, inverse_delta} information and also + * stops are themselves paired up into a vec4 format for efficient packing + * in the uniform data. + * + * @param colors colors from gradient + * @param stops stops from gradient + * @param frag_info_colors colors for fragment shader in vec4 format + * @param frag_info_stop_pairs pairs of stop data for shader in vec4 format + * @return count of colors stored + */ +int PopulateUniformGradientColors( + const std::vector& colors, + const std::vector& stops, + Vector4 frag_info_colors[kMaxUniformGradientStops], + Vector4 frag_info_stop_pairs[kMaxUniformGradientStops / 2]); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_GRADIENT_GENERATOR_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/host_buffer_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/host_buffer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ffac9c806adaab4eebee1efa532852cc3a6543eb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/host_buffer_unittests.cc @@ -0,0 +1,235 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "impeller/base/validation.h" +#include "impeller/core/allocator.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/idle_waiter.h" +#include "impeller/entity/entity_playground.h" + +namespace impeller { +namespace testing { + +class MockIdleWaiter : public IdleWaiter { + public: + MOCK_METHOD(void, WaitIdle, (), (const, override)); +}; + +using HostBufferTest = EntityPlayground; +INSTANTIATE_PLAYGROUND_SUITE(HostBufferTest); + +TEST_P(HostBufferTest, IdleWaiter) { + auto mock_idle_waiter = std::make_shared(); + { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + mock_idle_waiter); + EXPECT_CALL(*mock_idle_waiter, WaitIdle()); + } +} + +TEST_P(HostBufferTest, CanEmplace) { + struct Length2 { + uint8_t pad[2]; + }; + static_assert(sizeof(Length2) == 2u); + + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + for (size_t i = 0; i < 12500; i++) { + auto view = buffer->Emplace(Length2{}); + ASSERT_TRUE(view); + ASSERT_EQ(view.GetRange(), Range(i * sizeof(Length2), 2u)); + } +} + +TEST_P(HostBufferTest, CanEmplaceWithAlignment) { + struct Length2 { + uint8_t pad[2]; + }; + static_assert(sizeof(Length2) == 2); + struct alignas(16) Align16 { + uint8_t pad[2]; + }; + static_assert(alignof(Align16) == 16); + static_assert(sizeof(Align16) == 16); + + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + ASSERT_TRUE(buffer); + + { + auto view = buffer->Emplace(Length2{}); + ASSERT_TRUE(view); + ASSERT_EQ(view.GetRange(), Range(0u, 2u)); + } + + { + auto view = buffer->Emplace(Align16{}); + ASSERT_TRUE(view); + ASSERT_EQ(view.GetRange().offset, 16u); + ASSERT_EQ(view.GetRange().length, 16u); + } + { + auto view = buffer->Emplace(Length2{}); + ASSERT_TRUE(view); + ASSERT_EQ(view.GetRange(), Range(32u, 2u)); + } + + { + auto view = buffer->Emplace(Align16{}); + ASSERT_TRUE(view); + ASSERT_EQ(view.GetRange().offset, 48u); + ASSERT_EQ(view.GetRange().length, 16u); + } +} + +TEST_P(HostBufferTest, HostBufferInitialState) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u); +} + +TEST_P(HostBufferTest, ResetIncrementsFrameCounter) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + + buffer->Reset(); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 1u); + + buffer->Reset(); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 2u); + + buffer->Reset(); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 3u); + + buffer->Reset(); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); +} + +TEST_P(HostBufferTest, + EmplacingLargerThanBlockSizeCreatesOneOffBufferCallback) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + // Emplace an amount larger than the block size, to verify that the host + // buffer does not create a buffer. + auto buffer_view = buffer->Emplace(1024000 + 10, 0, [](uint8_t* data) {}); + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u); +} + +TEST_P(HostBufferTest, EmplacingLargerThanBlockSizeCreatesOneOffBuffer) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + // Emplace an amount larger than the block size, to verify that the host + // buffer does not create a buffer. + auto buffer_view = buffer->Emplace(nullptr, 1024000 + 10, 0); + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u); +} + +TEST_P(HostBufferTest, UnusedBuffersAreDiscardedWhenResetting) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + // Emplace two large allocations to force the allocation of a second buffer. + auto buffer_view_a = buffer->Emplace(1020000, 0, [](uint8_t* data) {}); + auto buffer_view_b = buffer->Emplace(1020000, 0, [](uint8_t* data) {}); + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 1u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 2u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + + // Reset until we get back to this frame. + for (auto i = 0; i < 4; i++) { + buffer->Reset(); + } + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 2u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); + + // Now when we reset, the buffer should get dropped. + // Reset until we get back to this frame. + for (auto i = 0; i < 4; i++) { + buffer->Reset(); + } + + EXPECT_EQ(buffer->GetStateForTest().current_buffer, 0u); + EXPECT_EQ(buffer->GetStateForTest().total_buffer_count, 1u); + EXPECT_EQ(buffer->GetStateForTest().current_frame, 0u); +} + +TEST_P(HostBufferTest, EmplaceWithProcIsAligned) { + auto buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + BufferView view = buffer->Emplace(std::array()); + EXPECT_EQ(view.GetRange(), Range(0, 21)); + + view = buffer->Emplace(64, 16, [](uint8_t*) {}); + EXPECT_EQ(view.GetRange(), Range(32, 64)); +} + +static constexpr const size_t kMagicFailingAllocation = 1024000 * 2; + +class FailingAllocator : public Allocator { + public: + explicit FailingAllocator(std::shared_ptr delegate) + : Allocator(), delegate_(std::move(delegate)) {} + + ~FailingAllocator() = default; + + std::shared_ptr OnCreateBuffer( + const DeviceBufferDescriptor& desc) { + // Magic number used in test below to trigger failure. + if (desc.size == kMagicFailingAllocation) { + return nullptr; + } + return delegate_->CreateBuffer(desc); + } + + std::shared_ptr OnCreateTexture(const TextureDescriptor& desc) { + return delegate_->CreateTexture(desc); + } + + ISize GetMaxTextureSizeSupported() const override { + return delegate_->GetMaxTextureSizeSupported(); + } + + private: + std::shared_ptr delegate_; +}; + +TEST_P(HostBufferTest, EmplaceWithFailingAllocationDoesntCrash) { + ScopedValidationDisable disable; + std::shared_ptr allocator = + std::make_shared(GetContext()->GetResourceAllocator()); + auto buffer = HostBuffer::Create(allocator, GetContext()->GetIdleWaiter()); + + auto view = buffer->Emplace(nullptr, kMagicFailingAllocation, 0); + + EXPECT_EQ(view.GetBuffer(), nullptr); + EXPECT_EQ(view.GetRange().offset, 0u); + EXPECT_EQ(view.GetRange().length, 0u); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/line_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/line_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..949ad1eed39dbb58dcd50028c41d1cc61c1b99d6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/line_contents.cc @@ -0,0 +1,269 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/line_contents.h" +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/geometry/rect_geometry.h" +#include "impeller/renderer/texture_util.h" + +namespace impeller { + +using VS = LinePipeline::VertexShader; +using FS = LinePipeline::FragmentShader; + +namespace { +using BindFragmentCallback = std::function; +using PipelineBuilderCallback = + std::function; +using CreateGeometryCallback = + std::function; + +const int32_t kCurveResolution = 32; + +uint8_t DoubleToUint8(double x) { + return static_cast(std::clamp(std::round(x * 255.0), 0.0, 255.0)); +} + +/// See also: CreateGradientTexture +std::shared_ptr CreateCurveTexture( + Scalar width, + Scalar radius, + Scalar scale, + const std::shared_ptr& context) { + // + impeller::TextureDescriptor texture_descriptor; + texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; + texture_descriptor.format = PixelFormat::kR8UNormInt; + texture_descriptor.size = {kCurveResolution, 1}; + + std::vector curve_data = + LineContents::CreateCurveData(width, radius, scale); + + return CreateTexture(texture_descriptor, curve_data, context, "LineCurve"); +} + +std::pair CreateGeometry( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass, + const Geometry* geometry) { + using PerVertexData = LineVertexShader::PerVertexData; + const LineGeometry* line_geometry = + static_cast(geometry); + + auto& transform = entity.GetTransform(); + auto& host_buffer = renderer.GetTransientsBuffer(); + + size_t count = 4; + fml::StatusOr calculate_status = + LineContents::EffectiveLineParameters{.width = 0, .radius = 0}; + BufferView vertex_buffer = host_buffer.Emplace( + count * sizeof(PerVertexData), alignof(PerVertexData), + [line_geometry, &transform, &calculate_status](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + calculate_status = LineContents::CalculatePerVertex( + vertices, line_geometry, transform); + }); + if (!calculate_status.ok()) { + return std::make_pair( + LineContents::EffectiveLineParameters{ + .width = line_geometry->GetWidth(), + .radius = LineContents::kSampleRadius}, + kEmptyResult); + } + + // We do the math in CalculatePerVertex in unrotated space. This then applies + // the rotation to the line. + Point diff = line_geometry->GetP1() - line_geometry->GetP0(); + Scalar angle = std::atan2(diff.y, diff.x); + Entity rotated_entity = entity.Clone(); + Matrix matrix = entity.GetTransform(); + matrix = matrix * Matrix::MakeTranslation(line_geometry->GetP0()) * + Matrix::MakeRotationZ(Radians(angle)) * + Matrix::MakeTranslation(-1 * line_geometry->GetP0()); + rotated_entity.SetTransform(matrix); + + return std::make_pair( + calculate_status.value(), + GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = vertex_buffer, + .vertex_count = count, + .index_type = IndexType::kNone, + }, + .transform = rotated_entity.GetShaderTransform(pass), + }); +} + +struct LineInfo { + Vector3 e0; + Vector3 e1; + Vector3 e2; + Vector3 e3; +}; + +LineInfo CalculateLineInfo(Point p0, Point p1, Scalar width, Scalar radius) { + Vector2 diff = p0 - p1; + float k = 2.0 / ((2.0 * radius + width) * sqrt(diff.Dot(diff))); + + return LineInfo{ + .e0 = Vector3(k * (p0.y - p1.y), // + k * (p1.x - p0.x), // + 1.0 + k * (p0.x * p1.y - p1.x * p0.y)), + .e1 = Vector3( + k * (p1.x - p0.x), // + k * (p1.y - p0.y), // + 1.0 + k * (p0.x * p0.x + p0.y * p0.y - p0.x * p1.x - p0.y * p1.y)), + .e2 = Vector3(k * (p1.y - p0.y), // + k * (p0.x - p1.x), // + 1.0 + k * (p1.x * p0.y - p0.x * p1.y)), + .e3 = Vector3( + k * (p0.x - p1.x), // + k * (p0.y - p1.y), // + 1.0 + k * (p1.x * p1.x + p1.y * p1.y - p0.x * p1.x - p0.y * p1.y)), + }; +} +} // namespace + +const Scalar LineContents::kSampleRadius = 1.f; + +std::unique_ptr LineContents::Make( + std::unique_ptr geometry, + Color color) { + return std::unique_ptr( + new LineContents(std::move(geometry), color)); +} + +LineContents::LineContents(std::unique_ptr geometry, Color color) + : geometry_(std::move(geometry)), color_(color) {} + +bool LineContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& host_buffer = renderer.GetTransientsBuffer(); + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + frag_info.color = color_; + + Scalar scale = entity.GetTransform().GetMaxBasisLengthXY(); + + auto geometry_result = + CreateGeometry(renderer, entity, pass, geometry_.get()); + + std::shared_ptr curve_texture = CreateCurveTexture( + geometry_->GetWidth(), kSampleRadius, scale, renderer.GetContext()); + + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + + FS::BindCurve( + pass, curve_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler(sampler_desc)); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetLinePipeline(options); + }; + + return ColorSourceContents::DrawGeometry( + this, geometry_.get(), renderer, entity, pass, pipeline_callback, + frame_info, + /*bind_fragment_callback=*/ + [&frag_info, &host_buffer](RenderPass& pass) { + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + pass.SetCommandLabel("Line"); + return true; + }, + /*force_stencil=*/false, + /*create_geom_callback=*/ + [geometry_result = std::move(geometry_result)]( + const ContentContext& renderer, const Entity& entity, + RenderPass& pass, + const Geometry* geometry) { return geometry_result.second; }); +} + +std::optional LineContents::GetCoverage(const Entity& entity) const { + return geometry_->GetCoverage(entity.GetTransform()); +} + +std::vector LineContents::CreateCurveData(Scalar width, + Scalar radius, + Scalar scale) { + std::vector curve_data; + curve_data.reserve(kCurveResolution); + // More simply written as rise / run: + // double slope = 1.0 / ((radius * 2) / (scale * width + radius)); + double slope = (scale * width + radius) / (radius * 2); + for (int i = 0; i < kCurveResolution; ++i) { + double norm = + (static_cast(i)) / static_cast(kCurveResolution - 1); + double scaled = slope * norm; + curve_data.push_back(DoubleToUint8(scaled)); + } + return curve_data; +} + +namespace { +void ExpandLine(std::array& corners, Point expansion) { + Point along = (corners[1] - corners[0]).Normalize(); + Point across = (corners[2] - corners[0]).Normalize(); + corners[0] += -1 * (across * expansion.x) + -1 * (along * expansion.y); + corners[1] += -1 * (across * expansion.x) + (along * expansion.y); + corners[2] += (across * expansion.x) + -1 * (along * expansion.y); + corners[3] += (across * expansion.x) + (along * expansion.y); +} +} // namespace + +fml::StatusOr +LineContents::CalculatePerVertex(LineVertexShader::PerVertexData* per_vertex, + const LineGeometry* geometry, + const Matrix& entity_transform) { + Scalar scale = entity_transform.GetMaxBasisLengthXY(); + + // Transform the line into unrotated space by rotating p1 to be horizontal + // with p0. We do this because there seems to be a flaw in the eN calculations + // where they create thinner lines for diagonal lines. + Point diff = geometry->GetP1() - geometry->GetP0(); + Scalar magnitude = diff.GetLength(); + Point p1_prime = Point(geometry->GetP0().x + magnitude, geometry->GetP0().y); + + std::array corners; + // Make sure we get kSampleRadius pixels to sample from. + Scalar expand_size = std::max(kSampleRadius / scale, kSampleRadius); + if (!LineGeometry::ComputeCorners( + corners.data(), entity_transform, + /*extend_endpoints=*/geometry->GetCap() != Cap::kButt, + geometry->GetP0(), p1_prime, geometry->GetWidth())) { + return fml::Status(fml::StatusCode::kAborted, "No valid corners"); + } + Scalar effective_line_width = std::fabsf((corners[2] - corners[0]).y); + ExpandLine(corners, Point(expand_size, expand_size)); + Scalar padded_line_width = std::fabsf((corners[2] - corners[0]).y); + Scalar effective_sample_radius = + (padded_line_width - effective_line_width) / 2.f; + LineInfo line_info = + CalculateLineInfo(geometry->GetP0(), p1_prime, effective_line_width, + effective_sample_radius); + for (auto& corner : corners) { + *per_vertex++ = { + .position = corner, + .e0 = line_info.e0, + .e1 = line_info.e1, + .e2 = line_info.e2, + .e3 = line_info.e3, + }; + } + + return EffectiveLineParameters{.width = effective_line_width, + .radius = effective_sample_radius}; +} +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/line_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/line_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..6f5fa02df46ea2aa54e87111437e95e8377d9b78 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/line_contents.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_LINE_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_LINE_CONTENTS_H_ + +#include + +#include "flutter/impeller/entity/contents/contents.h" +#include "flutter/impeller/entity/geometry/line_geometry.h" +#include "impeller/entity/line.vert.h" + +namespace impeller { +class LineContents : public Contents { + public: + static const Scalar kSampleRadius; + static std::vector CreateCurveData(Scalar width, + Scalar radius, + Scalar scale); + + struct EffectiveLineParameters { + Scalar width; + Scalar radius; + }; + + /// Calculates the values needed for the vertex shader, per vertex. + /// Returns the effective line parameters that are used. These differ from the + /// ones provided by `geometry` when the line gets clamped for being too thin. + static fml::StatusOr CalculatePerVertex( + LineVertexShader::PerVertexData* per_vertex, + const LineGeometry* geometry, + const Matrix& entity_transform); + + static std::unique_ptr Make( + std::unique_ptr geometry, + Color color); + + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + std::optional GetCoverage(const Entity& entity) const override; + + private: + explicit LineContents(std::unique_ptr geometry, Color color); + + std::unique_ptr geometry_; + Color color_; +}; +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_LINE_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/line_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/line_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..da2797df853b63c37a0fb001c00059ec1db0a6a3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/line_contents_unittests.cc @@ -0,0 +1,162 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/line_contents.h" + +#include + +#include "impeller/geometry/geometry_asserts.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +namespace impeller { +namespace testing { + +namespace { +float lookup(Scalar x) { + return std::clamp(x, /*lo=*/0.f, /*hi=*/1.f); +} + +// This mirrors the function in line.frag. +float CalculateLine(const LineVertexShader::PerVertexData& per_vertex, + Point position) { + Vector3 pos = Vector3(position.x, position.y, 1.0); + Scalar d[4] = {pos.Dot(per_vertex.e0), pos.Dot(per_vertex.e1), + pos.Dot(per_vertex.e2), pos.Dot(per_vertex.e3)}; + + for (int i = 0; i < 4; ++i) { + if (d[i] < 0.f) { + return 0.0; + } + } + + return lookup(std::min(d[0], d[2])) * lookup(std::min(d[1], d[3])); +} +} // namespace + +TEST(LineContents, Create) { + Path path; + Scalar width = 5.0f; + auto geometry = std::make_unique( + /*p0=*/Point{0, 0}, // + /*p1=*/Point{100, 100}, // + /*width=*/width, // + /*cap=*/Cap::kSquare); + std::unique_ptr contents = + LineContents::Make(std::move(geometry), Color(1.f, 0.f, 0.f, 1.f)); + EXPECT_TRUE(contents); + Entity entity; + std::optional coverage = contents->GetCoverage(entity); + EXPECT_TRUE(coverage.has_value()); + if (coverage.has_value()) { + Scalar lip = sqrt((width * width) / 2.f); + EXPECT_EQ(*coverage, + Rect::MakeXYWH(-lip, -lip, 100 + 2 * lip, 100 + 2 * lip)); + } +} + +TEST(LineContents, CalculatePerVertex) { + LineVertexShader::PerVertexData per_vertex[4]; + auto geometry = std::make_unique( + /*p0=*/Point{100, 100}, // + /*p1=*/Point{200, 100}, // + /*width=*/5.f, // + /*cap=*/Cap::kButt); + Matrix transform; + + fml::StatusOr status = + LineContents::CalculatePerVertex(per_vertex, geometry.get(), transform); + Scalar offset = + (LineContents::kSampleRadius * 2.0 + geometry->GetWidth()) / 2.f; + ASSERT_TRUE(status.ok()); + EXPECT_EQ(status.value().width, 5.f); + EXPECT_EQ(status.value().radius, LineContents::kSampleRadius); + EXPECT_POINT_NEAR(per_vertex[0].position, + Point(100 - LineContents::kSampleRadius, 100 + offset)); + EXPECT_POINT_NEAR(per_vertex[1].position, + Point(200 + LineContents::kSampleRadius, 100 + offset)); + EXPECT_POINT_NEAR(per_vertex[2].position, + Point(100 - LineContents::kSampleRadius, 100 - offset)); + EXPECT_POINT_NEAR(per_vertex[3].position, + Point(200 + LineContents::kSampleRadius, 100 - offset)); + + for (int i = 1; i < 4; ++i) { + EXPECT_VECTOR3_NEAR(per_vertex[0].e0, per_vertex[i].e0) << i; + EXPECT_VECTOR3_NEAR(per_vertex[0].e1, per_vertex[i].e1) << i; + EXPECT_VECTOR3_NEAR(per_vertex[0].e2, per_vertex[i].e2) << i; + EXPECT_VECTOR3_NEAR(per_vertex[0].e3, per_vertex[i].e3) << i; + } + + EXPECT_EQ(CalculateLine(per_vertex[0], Point(0, 0)), 0.f); + EXPECT_NEAR(CalculateLine(per_vertex[0], Point(150, 100 + offset)), 0.f, + kEhCloseEnough); + EXPECT_NEAR(CalculateLine(per_vertex[0], Point(150, 100 + offset * 0.5)), + 0.5f, kEhCloseEnough); + EXPECT_NEAR(CalculateLine(per_vertex[0], Point(150, 100)), 1.f, + kEhCloseEnough); +} + +TEST(LineContents, CreateCurveData) { + std::vector data = LineContents::CreateCurveData(/*width=*/31, + /*radius=*/1, + /*scale=*/1); + EXPECT_EQ(data.size(), 32u); + EXPECT_NEAR(data[0] / 255.f, 0.f, kEhCloseEnough); + EXPECT_NEAR(data[1] / 255.f, 0.5f, 0.02); + EXPECT_NEAR(data[2] / 255.f, 1.f, kEhCloseEnough); + EXPECT_NEAR(data[3] / 255.f, 1.f, kEhCloseEnough); +} + +TEST(LineContents, CreateCurveDataScaled) { + std::vector data = LineContents::CreateCurveData(/*width=*/15.5, + /*radius=*/1, + /*scale=*/2); + EXPECT_EQ(data.size(), 32u); + EXPECT_NEAR(data[0] / 255.f, 0.f, kEhCloseEnough); + EXPECT_NEAR(data[1] / 255.f, 0.5f, 0.02); + EXPECT_NEAR(data[2] / 255.f, 1.f, kEhCloseEnough); + EXPECT_NEAR(data[3] / 255.f, 1.f, kEhCloseEnough); +} + +// This scales the line to be less than 1 pixel. +TEST(LineContents, CalculatePerVertexLimit) { + LineVertexShader::PerVertexData per_vertex[4]; + Scalar scale = 0.05; + auto geometry = std::make_unique( + /*p0=*/Point{100, 100}, // + /*p1=*/Point{200, 100}, // + /*width=*/10.f, // + /*cap=*/Cap::kButt); + Matrix transform = Matrix::MakeTranslation({100, 100, 1.0}) * + Matrix::MakeScale({scale, scale, 1.0}) * + Matrix::MakeTranslation({-100, -100, 1.0}); + + fml::StatusOr status = + LineContents::CalculatePerVertex(per_vertex, geometry.get(), transform); + + Scalar one_radius_size = std::max(LineContents::kSampleRadius / scale, + LineContents::kSampleRadius); + Scalar one_px_size = 1.f / scale; + Scalar offset = one_px_size / 2.f + one_radius_size; + ASSERT_TRUE(status.ok()); + EXPECT_NEAR(status.value().width, 20.f, kEhCloseEnough); + EXPECT_NEAR(status.value().radius, one_px_size * LineContents::kSampleRadius, + kEhCloseEnough); + EXPECT_POINT_NEAR(per_vertex[0].position, + Point(100 - one_radius_size, 100 + offset)); + EXPECT_POINT_NEAR(per_vertex[1].position, + Point(200 + one_radius_size, 100 + offset)); + EXPECT_POINT_NEAR(per_vertex[2].position, + Point(100 - one_radius_size, 100 - offset)); + EXPECT_POINT_NEAR(per_vertex[3].position, + Point(200 + one_radius_size, 100 - offset)); + + EXPECT_NEAR(CalculateLine(per_vertex[0], Point(150, 100)), 1.f, + kEhCloseEnough); + // EXPECT_NEAR(CalculateLine(per_vertex[0], Point(150, 100 + + // one_px_size)), 1.f, + // kEhCloseEnough); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..7eef8b78fbbbba5d2fc88db7772e12d115f73cc5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.cc @@ -0,0 +1,372 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "linear_gradient_contents.h" + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/gradient_generator.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/scalar.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +LinearGradientContents::LinearGradientContents() = default; + +LinearGradientContents::~LinearGradientContents() = default; + +void LinearGradientContents::SetEndPoints(Point start_point, Point end_point) { + start_point_ = start_point; + end_point_ = end_point; +} + +void LinearGradientContents::SetColors(std::vector colors) { + colors_ = std::move(colors); +} + +void LinearGradientContents::SetStops(std::vector stops) { + stops_ = std::move(stops); +} + +const std::vector& LinearGradientContents::GetColors() const { + return colors_; +} + +const std::vector& LinearGradientContents::GetStops() const { + return stops_; +} + +void LinearGradientContents::SetTileMode(Entity::TileMode tile_mode) { + tile_mode_ = tile_mode; +} + +bool LinearGradientContents::IsOpaque(const Matrix& transform) const { + if (GetOpacityFactor() < 1 || tile_mode_ == Entity::TileMode::kDecal) { + return false; + } + for (auto color : colors_) { + if (!color.IsOpaque()) { + return false; + } + } + return !AppliesAlphaForStrokeCoverage(transform); +} + +bool LinearGradientContents::CanApplyFastGradient() const { + if (!GetInverseEffectTransform().IsIdentity()) { + return false; + } + std::optional maybe_rect = GetGeometry()->GetCoverage(Matrix()); + if (!maybe_rect.has_value()) { + return false; + } + Rect rect = maybe_rect.value(); + + if (ScalarNearlyEqual(start_point_.x, end_point_.x)) { + // Sort start and end to make on-rect comparisons easier. + Point start = (start_point_.y < end_point_.y) ? start_point_ : end_point_; + Point end = (start_point_.y < end_point_.y) ? end_point_ : start_point_; + // The exact x positon doesn't matter for a vertical gradient, but the y + // position must be nearly on the rectangle. + if (ScalarNearlyEqual(start.y, rect.GetTop()) && + ScalarNearlyEqual(end.y, rect.GetBottom())) { + return true; + } + return false; + } + + if (ScalarNearlyEqual(start_point_.y, end_point_.y)) { + // Sort start and end to make on-rect comparisons easier. + Point start = (start_point_.x < end_point_.x) ? start_point_ : end_point_; + Point end = (start_point_.x < end_point_.x) ? end_point_ : start_point_; + // The exact y positon doesn't matter for a horizontal gradient, but the x + // position must be nearly on the rectangle. + if (ScalarNearlyEqual(start.x, rect.GetLeft()) && + ScalarNearlyEqual(end.x, rect.GetRight())) { + return true; + } + return false; + } + + return false; +} + +// A much faster (in terms of ALU) linear gradient that uses vertex +// interpolation to perform all color computation. Requires that the geometry of +// the gradient is divided into regions based on the stop values. +// Currently restricted to rect geometry where the start and end points are +// perfectly horizontal/vertical, but could easily be expanded to StC cases +// provided that the start/end are on or outside of the coverage rect. +bool LinearGradientContents::FastLinearGradient(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = FastGradientPipeline::VertexShader; + using FS = FastGradientPipeline::FragmentShader; + + const Geometry* geometry = GetGeometry(); + bool force_stencil = !geometry->IsAxisAlignedRect(); + + auto geom_callback = [&](const ContentContext& renderer, const Entity& entity, + RenderPass& pass, + const Geometry* geometry) -> GeometryResult { + // We already know this is an axis aligned rectangle, so the coverage will + // be approximately the same as the geometry. For non axis-algined + // rectangles, we can force stencil then cover (not done here). We give an + // identity transform to avoid double transforming the gradient. + std::optional maybe_rect = geometry->GetCoverage(Matrix()); + if (!maybe_rect.has_value()) { + return {}; + } + Rect rect = maybe_rect.value(); + bool horizontal_axis = start_point_.y == end_point_.y; + + // Compute the locations of each breakpoint along the primary axis, then + // create a rectangle that joins each segment. There will be two triangles + // between each pair of points. + VertexBufferBuilder vtx_builder; + vtx_builder.Reserve(6 * (stops_.size() - 1)); + Point prev = start_point_; + for (auto i = 1u; i < stops_.size(); i++) { + Scalar t = stops_[i]; + Point current = (1.0 - t) * start_point_ + t * end_point_; + Rect section = horizontal_axis + ? Rect::MakeXYWH(prev.x, rect.GetY(), + current.x - prev.x, rect.GetHeight()) + + : Rect::MakeXYWH(rect.GetX(), prev.y, rect.GetWidth(), + current.y - prev.y); + vtx_builder.AddVertices({ + {section.GetLeftTop(), colors_[i - 1]}, + {section.GetRightTop(), + horizontal_axis ? colors_[i] : colors_[i - 1]}, + {section.GetLeftBottom(), + horizontal_axis ? colors_[i - 1] : colors_[i]}, + {section.GetRightTop(), + horizontal_axis ? colors_[i] : colors_[i - 1]}, + {section.GetLeftBottom(), + horizontal_axis ? colors_[i - 1] : colors_[i]}, + {section.GetRightBottom(), colors_[i]}, + }); + prev = current; + } + return GeometryResult{ + .type = PrimitiveType::kTriangle, + .vertex_buffer = + vtx_builder.CreateVertexBuffer(renderer.GetTransientsBuffer()), + .transform = entity.GetShaderTransform(pass), + }; + }; + + pass.SetLabel("LinearGradient"); + + VS::FrameInfo frame_info; + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetFastGradientPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); + + FS::FragInfo frag_info; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + return true; + }, + /*force_stencil=*/force_stencil, geom_callback); +} + +#define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0])) +#define UNIFORM_FRAG_INFO(t) \ + t##GradientUniformFillPipeline::FragmentShader::FragInfo +#define UNIFORM_COLOR_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Linear)::colors) +#define UNIFORM_STOP_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Linear)::stop_pairs) +static_assert(UNIFORM_COLOR_SIZE == kMaxUniformGradientStops); +static_assert(UNIFORM_STOP_SIZE == kMaxUniformGradientStops / 2); + +bool LinearGradientContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + // TODO(148651): The fast path is overly restrictive, following the design in + // https://github.com/flutter/flutter/issues/148651 support for more cases can + // be gradually added. + if (CanApplyFastGradient()) { + return FastLinearGradient(renderer, entity, pass); + } + if (renderer.GetDeviceCapabilities().SupportsSSBO()) { + return RenderSSBO(renderer, entity, pass); + } + if (colors_.size() <= kMaxUniformGradientStops && + stops_.size() <= kMaxUniformGradientStops) { + return RenderUniform(renderer, entity, pass); + } + return RenderTexture(renderer, entity, pass); +} + +bool LinearGradientContents::RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = LinearGradientFillPipeline::VertexShader; + using FS = LinearGradientFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetLinearGradientFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + auto gradient_data = CreateGradientBuffer(colors_, stops_); + auto gradient_texture = + CreateGradientTexture(gradient_data, renderer.GetContext()); + if (gradient_texture == nullptr) { + return false; + } + + FS::FragInfo frag_info; + frag_info.start_point = start_point_; + frag_info.end_point = end_point_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.texture_sampler_y_coord_scale = + gradient_texture->GetYCoordScale(); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + ; + frag_info.half_texel = + Vector2(0.5 / gradient_texture->GetSize().width, + 0.5 / gradient_texture->GetSize().height); + + pass.SetCommandLabel("LinearGradientFill"); + + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + + FS::BindTextureSampler( + pass, std::move(gradient_texture), + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc)); + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + return true; + }); +} + +namespace { +Scalar CalculateInverseDotStartToEnd(Point start_point, Point end_point) { + Point start_to_end = end_point - start_point; + Scalar dot = + (start_to_end.x * start_to_end.x + start_to_end.y * start_to_end.y); + return dot == 0.0f ? 0.0f : 1.0f / dot; +} +} // namespace + +bool LinearGradientContents::RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = LinearGradientSSBOFillPipeline::VertexShader; + using FS = LinearGradientSSBOFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetLinearGradientSSBOFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.start_point = start_point_; + frag_info.end_point = end_point_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.start_to_end = end_point_ - start_point_; + frag_info.inverse_dot_start_to_end = + CalculateInverseDotStartToEnd(start_point_, end_point_); + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto colors = CreateGradientColors(colors_, stops_); + + frag_info.colors_length = colors.size(); + auto color_buffer = + host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData), + DefaultUniformAlignment()); + + pass.SetCommandLabel("LinearGradientSSBOFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindColorData(pass, color_buffer); + + return true; + }); +} + +bool LinearGradientContents::RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = LinearGradientUniformFillPipeline::VertexShader; + using FS = LinearGradientUniformFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetLinearGradientUniformFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.start_point = start_point_; + frag_info.start_to_end = end_point_ - start_point_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.colors_length = PopulateUniformGradientColors( + colors_, stops_, frag_info.colors, frag_info.stop_pairs); + frag_info.inverse_dot_start_to_end = + CalculateInverseDotStartToEnd(start_point_, end_point_); + frag_info.decal_border_color = decal_border_color_; + + pass.SetCommandLabel("LinearGradientUniformFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + + return true; + }); +} + +bool LinearGradientContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + for (Color& color : colors_) { + color = color_filter_proc(color); + } + decal_border_color_ = color_filter_proc(decal_border_color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..1aaccb1e439212dfeee52c58f04f67f4843bc95c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/linear_gradient_contents.h @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" + +namespace impeller { + +class LinearGradientContents final : public ColorSourceContents { + public: + LinearGradientContents(); + + ~LinearGradientContents() override; + + // |Contents| + bool IsOpaque(const Matrix& transform) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + void SetEndPoints(Point start_point, Point end_point); + + void SetColors(std::vector colors); + + void SetStops(std::vector stops); + + const std::vector& GetColors() const; + + const std::vector& GetStops() const; + + void SetTileMode(Entity::TileMode tile_mode); + + private: + bool RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool FastLinearGradient(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool CanApplyFastGradient() const; + + Point start_point_; + Point end_point_; + std::vector colors_; + std::vector stops_; + Entity::TileMode tile_mode_; + Color decal_border_color_ = Color::BlackTransparent(); + + LinearGradientContents(const LinearGradientContents&) = delete; + + LinearGradientContents& operator=(const LinearGradientContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_LINEAR_GRADIENT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/pipelines.h b/flutter/engine/src/flutter/impeller/entity/contents/pipelines.h new file mode 100644 index 0000000000000000000000000000000000000000..f3998a779ead30735b4a980052fec8123768a804 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/pipelines.h @@ -0,0 +1,168 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_PIPELINES_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_PIPELINES_H_ + +#include "impeller/entity/advanced_blend.frag.h" +#include "impeller/entity/advanced_blend.vert.h" +#include "impeller/entity/border_mask_blur.frag.h" +#include "impeller/entity/clip.frag.h" +#include "impeller/entity/clip.vert.h" +#include "impeller/entity/color_matrix_color_filter.frag.h" +#include "impeller/entity/conical_gradient_fill_conical.frag.h" +#include "impeller/entity/conical_gradient_fill_radial.frag.h" +#include "impeller/entity/conical_gradient_fill_strip.frag.h" +#include "impeller/entity/conical_gradient_fill_strip_radial.frag.h" +#include "impeller/entity/conical_gradient_ssbo_fill.frag.h" +#include "impeller/entity/conical_gradient_uniform_fill_conical.frag.h" +#include "impeller/entity/conical_gradient_uniform_fill_radial.frag.h" +#include "impeller/entity/conical_gradient_uniform_fill_strip.frag.h" +#include "impeller/entity/conical_gradient_uniform_fill_strip_radial.frag.h" +#include "impeller/entity/fast_gradient.frag.h" +#include "impeller/entity/fast_gradient.vert.h" +#include "impeller/entity/filter_position.vert.h" +#include "impeller/entity/filter_position_uv.vert.h" +#include "impeller/entity/framebuffer_blend.frag.h" +#include "impeller/entity/framebuffer_blend.vert.h" +#include "impeller/entity/gaussian.frag.h" +#include "impeller/entity/glyph_atlas.frag.h" +#include "impeller/entity/glyph_atlas.vert.h" +#include "impeller/entity/gradient_fill.vert.h" +#include "impeller/entity/line.frag.h" +#include "impeller/entity/line.vert.h" +#include "impeller/entity/linear_gradient_fill.frag.h" +#include "impeller/entity/linear_gradient_ssbo_fill.frag.h" +#include "impeller/entity/linear_gradient_uniform_fill.frag.h" +#include "impeller/entity/linear_to_srgb_filter.frag.h" +#include "impeller/entity/morphology_filter.frag.h" +#include "impeller/entity/porter_duff_blend.frag.h" +#include "impeller/entity/porter_duff_blend.vert.h" +#include "impeller/entity/radial_gradient_fill.frag.h" +#include "impeller/entity/radial_gradient_ssbo_fill.frag.h" +#include "impeller/entity/radial_gradient_uniform_fill.frag.h" +#include "impeller/entity/rrect_blur.frag.h" +#include "impeller/entity/rrect_blur.vert.h" +#include "impeller/entity/solid_fill.frag.h" +#include "impeller/entity/solid_fill.vert.h" +#include "impeller/entity/srgb_to_linear_filter.frag.h" +#include "impeller/entity/sweep_gradient_fill.frag.h" +#include "impeller/entity/sweep_gradient_ssbo_fill.frag.h" +#include "impeller/entity/sweep_gradient_uniform_fill.frag.h" +#include "impeller/entity/texture_downsample.frag.h" +#include "impeller/entity/texture_fill.frag.h" +#include "impeller/entity/texture_fill.vert.h" +#include "impeller/entity/texture_fill_strict_src.frag.h" +#include "impeller/entity/texture_uv_fill.vert.h" +#include "impeller/entity/tiled_texture_fill.frag.h" +#include "impeller/entity/vertices_uber_1.frag.h" +#include "impeller/entity/vertices_uber_2.frag.h" +#include "impeller/entity/yuv_to_rgb_filter.frag.h" +#include "impeller/renderer/pipeline.h" + +#ifdef IMPELLER_ENABLE_OPENGLES +#include "impeller/entity/texture_downsample_gles.frag.h" +#include "impeller/entity/tiled_texture_fill_external.frag.h" +#endif // IMPELLER_ENABLE_OPENGLES + +// TODO(gaaclarke): These should be split up into different files. +namespace impeller { + +template +using GradientPipelineHandle = + RenderPipelineHandle; + +using AdvancedBlendPipelineHandle = + RenderPipelineHandle; + +using FramebufferBlendPipelineHandle = + RenderPipelineHandle; + +// clang-format off +using BlendColorBurnPipeline = AdvancedBlendPipelineHandle; +using BlendColorDodgePipeline = AdvancedBlendPipelineHandle; +using BlendColorPipeline = AdvancedBlendPipelineHandle; +using BlendDarkenPipeline = AdvancedBlendPipelineHandle; +using BlendDifferencePipeline = AdvancedBlendPipelineHandle; +using BlendExclusionPipeline = AdvancedBlendPipelineHandle; +using BlendHardLightPipeline = AdvancedBlendPipelineHandle; +using BlendHuePipeline = AdvancedBlendPipelineHandle; +using BlendLightenPipeline = AdvancedBlendPipelineHandle; +using BlendLuminosityPipeline = AdvancedBlendPipelineHandle; +using BlendMultiplyPipeline = AdvancedBlendPipelineHandle; +using BlendOverlayPipeline = AdvancedBlendPipelineHandle; +using BlendSaturationPipeline = AdvancedBlendPipelineHandle; +using BlendScreenPipeline = AdvancedBlendPipelineHandle; +using BlendSoftLightPipeline = AdvancedBlendPipelineHandle; +using BorderMaskBlurPipeline = RenderPipelineHandle; +using ClipPipeline = RenderPipelineHandle; +using ColorMatrixColorFilterPipeline = RenderPipelineHandle; +using ConicalGradientFillConicalPipeline = GradientPipelineHandle; +using ConicalGradientFillRadialPipeline = GradientPipelineHandle; +using ConicalGradientFillStripPipeline = GradientPipelineHandle; +using ConicalGradientFillStripRadialPipeline = GradientPipelineHandle; +using ConicalGradientSSBOFillPipeline = GradientPipelineHandle; +using ConicalGradientUniformFillConicalPipeline = GradientPipelineHandle; +using ConicalGradientUniformFillRadialPipeline = GradientPipelineHandle; +using ConicalGradientUniformFillStripPipeline = GradientPipelineHandle; +using ConicalGradientUniformFillStripRadialPipeline = GradientPipelineHandle; +using FastGradientPipeline = RenderPipelineHandle; +using FramebufferBlendColorBurnPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendColorDodgePipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendColorPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendDarkenPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendDifferencePipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendExclusionPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendHardLightPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendHuePipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendLightenPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendLuminosityPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendMultiplyPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendOverlayPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendSaturationPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendScreenPipeline = FramebufferBlendPipelineHandle; +using FramebufferBlendSoftLightPipeline = FramebufferBlendPipelineHandle; +using GaussianBlurPipeline = RenderPipelineHandle; +using GlyphAtlasPipeline = RenderPipelineHandle; +using LinePipeline = RenderPipelineHandle; +using LinearGradientFillPipeline = GradientPipelineHandle; +using LinearGradientSSBOFillPipeline = GradientPipelineHandle; +using LinearGradientUniformFillPipeline = GradientPipelineHandle; +using LinearToSrgbFilterPipeline = RenderPipelineHandle; +using MorphologyFilterPipeline = RenderPipelineHandle; +using PorterDuffBlendPipeline = RenderPipelineHandle; +using RadialGradientFillPipeline = GradientPipelineHandle; +using RadialGradientSSBOFillPipeline = GradientPipelineHandle; +using RadialGradientUniformFillPipeline = GradientPipelineHandle; +using RRectBlurPipeline = RenderPipelineHandle; +using SolidFillPipeline = RenderPipelineHandle; +using SrgbToLinearFilterPipeline = RenderPipelineHandle; +using SweepGradientFillPipeline = GradientPipelineHandle; +using SweepGradientSSBOFillPipeline = GradientPipelineHandle; +using SweepGradientUniformFillPipeline = GradientPipelineHandle; +using TextureDownsamplePipeline = RenderPipelineHandle; +using TexturePipeline = RenderPipelineHandle; +using TextureStrictSrcPipeline = RenderPipelineHandle; +using TiledTexturePipeline = RenderPipelineHandle; +using VerticesUber1Shader = RenderPipelineHandle; +using VerticesUber2Shader = RenderPipelineHandle; +using YUVToRGBFilterPipeline = RenderPipelineHandle; +// clang-format on + +#ifdef IMPELLER_ENABLE_OPENGLES +using TiledTextureExternalPipeline = + RenderPipelineHandle; +using TiledTextureUvExternalPipeline = + RenderPipelineHandle; +using TextureDownsampleGlesPipeline = + RenderPipelineHandle; +#endif // IMPELLER_ENABLE_OPENGLES +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_PIPELINES_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..8fad640b1b6070664b139cbfe0d7f4def154d5bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.cc @@ -0,0 +1,220 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "radial_gradient_contents.h" + +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/gradient_generator.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/gradient.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +RadialGradientContents::RadialGradientContents() = default; + +RadialGradientContents::~RadialGradientContents() = default; + +void RadialGradientContents::SetCenterAndRadius(Point center, Scalar radius) { + center_ = center; + radius_ = radius; +} + +void RadialGradientContents::SetTileMode(Entity::TileMode tile_mode) { + tile_mode_ = tile_mode; +} + +void RadialGradientContents::SetColors(std::vector colors) { + colors_ = std::move(colors); +} + +void RadialGradientContents::SetStops(std::vector stops) { + stops_ = std::move(stops); +} + +const std::vector& RadialGradientContents::GetColors() const { + return colors_; +} + +const std::vector& RadialGradientContents::GetStops() const { + return stops_; +} + +bool RadialGradientContents::IsOpaque(const Matrix& transform) const { + if (GetOpacityFactor() < 1 || tile_mode_ == Entity::TileMode::kDecal) { + return false; + } + for (auto color : colors_) { + if (!color.IsOpaque()) { + return false; + } + } + return !AppliesAlphaForStrokeCoverage(transform); +} + +#define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0])) +#define UNIFORM_FRAG_INFO(t) \ + t##GradientUniformFillPipeline::FragmentShader::FragInfo +#define UNIFORM_COLOR_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Radial)::colors) +#define UNIFORM_STOP_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Radial)::stop_pairs) +static_assert(UNIFORM_COLOR_SIZE == kMaxUniformGradientStops); +static_assert(UNIFORM_STOP_SIZE == kMaxUniformGradientStops / 2); + +bool RadialGradientContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (renderer.GetDeviceCapabilities().SupportsSSBO()) { + return RenderSSBO(renderer, entity, pass); + } + if (colors_.size() <= kMaxUniformGradientStops && + stops_.size() <= kMaxUniformGradientStops) { + return RenderUniform(renderer, entity, pass); + } + return RenderTexture(renderer, entity, pass); +} + +bool RadialGradientContents::RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = RadialGradientSSBOFillPipeline::VertexShader; + using FS = RadialGradientSSBOFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetRadialGradientSSBOFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto colors = CreateGradientColors(colors_, stops_); + + frag_info.colors_length = colors.size(); + auto color_buffer = + host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData), + DefaultUniformAlignment()); + + pass.SetCommandLabel("RadialGradientSSBOFill"); + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindColorData(pass, color_buffer); + + return true; + }); +} + +bool RadialGradientContents::RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = RadialGradientUniformFillPipeline::VertexShader; + using FS = RadialGradientUniformFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetRadialGradientUniformFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.colors_length = PopulateUniformGradientColors( + colors_, stops_, frag_info.colors, frag_info.stop_pairs); + frag_info.decal_border_color = decal_border_color_; + + pass.SetCommandLabel("RadialGradientUniformFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + + return true; + }); +} + +bool RadialGradientContents::RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = RadialGradientFillPipeline::VertexShader; + using FS = RadialGradientFillPipeline::FragmentShader; + + auto gradient_data = CreateGradientBuffer(colors_, stops_); + auto gradient_texture = + CreateGradientTexture(gradient_data, renderer.GetContext()); + if (gradient_texture == nullptr) { + return false; + } + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetRadialGradientFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &gradient_texture, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.radius = radius_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.texture_sampler_y_coord_scale = + gradient_texture->GetYCoordScale(); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.half_texel = + Vector2(0.5 / gradient_texture->GetSize().width, + 0.5 / gradient_texture->GetSize().height); + + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + + pass.SetCommandLabel("RadialGradientFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindTextureSampler( + pass, gradient_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc)); + + return true; + }); +} + +bool RadialGradientContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + for (Color& color : colors_) { + color = color_filter_proc(color); + } + decal_border_color_ = color_filter_proc(decal_border_color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..f1cff5813c3f8cb788c18bb039cdb6c231f2db2e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/radial_gradient_contents.h @@ -0,0 +1,74 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_RADIAL_GRADIENT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_RADIAL_GRADIENT_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" + +namespace impeller { + +class RadialGradientContents final : public ColorSourceContents { + public: + RadialGradientContents(); + + ~RadialGradientContents() override; + + // |Contents| + bool IsOpaque(const Matrix& transform) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + void SetCenterAndRadius(Point center, Scalar radius); + + void SetColors(std::vector colors); + + void SetStops(std::vector stops); + + const std::vector& GetColors() const; + + const std::vector& GetStops() const; + + void SetTileMode(Entity::TileMode tile_mode); + + private: + bool RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + Point center_; + Scalar radius_; + std::vector colors_; + std::vector stops_; + Entity::TileMode tile_mode_; + Color decal_border_color_ = Color::BlackTransparent(); + + RadialGradientContents(const RadialGradientContents&) = delete; + + RadialGradientContents& operator=(const RadialGradientContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_RADIAL_GRADIENT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..920efba84e2bb13e80e55383b1323430aa3ee56e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.cc @@ -0,0 +1,329 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/runtime_effect_contents.h" + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/make_copyable.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/shader_types.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/runtime_effect.vert.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/shader_function.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +namespace { +constexpr char kPaddingType = 0; +constexpr char kFloatType = 1; +} // namespace + +// static +BufferView RuntimeEffectContents::EmplaceVulkanUniform( + const std::shared_ptr>& input_data, + HostBuffer& host_buffer, + const RuntimeUniformDescription& uniform) { + // TODO(jonahwilliams): rewrite this to emplace directly into + // HostBuffer. + std::vector uniform_buffer; + uniform_buffer.reserve(uniform.struct_layout.size()); + size_t uniform_byte_index = 0u; + for (char byte_type : uniform.struct_layout) { + if (byte_type == kPaddingType) { + uniform_buffer.push_back(0.f); + } else { + FML_DCHECK(byte_type == kFloatType); + uniform_buffer.push_back(reinterpret_cast( + input_data->data())[uniform_byte_index++]); + } + } + size_t alignment = std::max(sizeof(float) * uniform_buffer.size(), + DefaultUniformAlignment()); + + return host_buffer.Emplace( + reinterpret_cast(uniform_buffer.data()), + sizeof(float) * uniform_buffer.size(), alignment); +} + +void RuntimeEffectContents::SetRuntimeStage( + std::shared_ptr runtime_stage) { + runtime_stage_ = std::move(runtime_stage); +} + +void RuntimeEffectContents::SetUniformData( + std::shared_ptr> uniform_data) { + uniform_data_ = std::move(uniform_data); +} + +void RuntimeEffectContents::SetTextureInputs( + std::vector texture_inputs) { + texture_inputs_ = std::move(texture_inputs); +} + +static ShaderType GetShaderType(RuntimeUniformType type) { + switch (type) { + case kSampledImage: + return ShaderType::kSampledImage; + case kFloat: + return ShaderType::kFloat; + case kStruct: + return ShaderType::kStruct; + } +} + +static std::unique_ptr MakeShaderMetadata( + const RuntimeUniformDescription& uniform) { + std::unique_ptr metadata = std::make_unique(); + metadata->name = uniform.name; + metadata->members.emplace_back(ShaderStructMemberMetadata{ + .type = GetShaderType(uniform.type), + .size = uniform.GetSize(), + .byte_length = uniform.bit_width / 8, + }); + + return metadata; +} + +bool RuntimeEffectContents::BootstrapShader( + const ContentContext& renderer) const { + if (!RegisterShader(renderer)) { + return false; + } + ContentContextOptions options; + options.color_attachment_pixel_format = + renderer.GetContext()->GetCapabilities()->GetDefaultColorFormat(); + CreatePipeline(renderer, options, /*async=*/true); + return true; +} + +bool RuntimeEffectContents::RegisterShader( + const ContentContext& renderer) const { + const std::shared_ptr& context = renderer.GetContext(); + const std::shared_ptr& library = context->GetShaderLibrary(); + + std::shared_ptr function = library->GetFunction( + runtime_stage_->GetEntrypoint(), ShaderStage::kFragment); + + //-------------------------------------------------------------------------- + /// Resolve runtime stage function. + /// + + if (function && runtime_stage_->IsDirty()) { + renderer.ClearCachedRuntimeEffectPipeline(runtime_stage_->GetEntrypoint()); + context->GetPipelineLibrary()->RemovePipelinesWithEntryPoint(function); + library->UnregisterFunction(runtime_stage_->GetEntrypoint(), + ShaderStage::kFragment); + + function = nullptr; + } + + if (!function) { + std::promise promise; + auto future = promise.get_future(); + + library->RegisterFunction( + runtime_stage_->GetEntrypoint(), + ToShaderStage(runtime_stage_->GetShaderStage()), + runtime_stage_->GetCodeMapping(), + fml::MakeCopyable([promise = std::move(promise)](bool result) mutable { + promise.set_value(result); + })); + + if (!future.get()) { + VALIDATION_LOG << "Failed to build runtime effect (entry point: " + << runtime_stage_->GetEntrypoint() << ")"; + return false; + } + + function = library->GetFunction(runtime_stage_->GetEntrypoint(), + ShaderStage::kFragment); + if (!function) { + VALIDATION_LOG + << "Failed to fetch runtime effect function immediately after " + "registering it (entry point: " + << runtime_stage_->GetEntrypoint() << ")"; + return false; + } + + runtime_stage_->SetClean(); + } + return true; +} + +std::shared_ptr> +RuntimeEffectContents::CreatePipeline(const ContentContext& renderer, + ContentContextOptions options, + bool async) const { + const std::shared_ptr& context = renderer.GetContext(); + const std::shared_ptr& library = context->GetShaderLibrary(); + const std::shared_ptr& caps = context->GetCapabilities(); + const PixelFormat color_attachment_format = caps->GetDefaultColorFormat(); + const PixelFormat stencil_attachment_format = + caps->GetDefaultDepthStencilFormat(); + + using VS = RuntimeEffectVertexShader; + + PipelineDescriptor desc; + desc.SetLabel("Runtime Stage"); + desc.AddStageEntrypoint( + library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex)); + desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(), + ShaderStage::kFragment)); + + std::shared_ptr vertex_descriptor = + std::make_shared(); + vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs, + VS::kInterleavedBufferLayout); + vertex_descriptor->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts); + vertex_descriptor->RegisterDescriptorSetLayouts( + runtime_stage_->GetDescriptorSetLayouts().data(), + runtime_stage_->GetDescriptorSetLayouts().size()); + desc.SetVertexDescriptor(std::move(vertex_descriptor)); + desc.SetColorAttachmentDescriptor( + 0u, {.format = color_attachment_format, .blending_enabled = true}); + + desc.SetStencilAttachmentDescriptors(StencilAttachmentDescriptor{}); + desc.SetStencilPixelFormat(stencil_attachment_format); + + desc.SetDepthStencilAttachmentDescriptor(DepthAttachmentDescriptor{}); + desc.SetDepthPixelFormat(stencil_attachment_format); + + options.ApplyToPipelineDescriptor(desc); + if (async) { + context->GetPipelineLibrary()->GetPipeline(desc, async); + return nullptr; + } + + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc, async).Get(); + if (!pipeline) { + VALIDATION_LOG << "Failed to get or create runtime effect pipeline."; + return nullptr; + } + + return pipeline; +} + +bool RuntimeEffectContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + const std::shared_ptr& context = renderer.GetContext(); + const std::shared_ptr& library = context->GetShaderLibrary(); + + //-------------------------------------------------------------------------- + /// Get or register shader. Flutter will do this when the runtime effect + /// is first loaded, but this check is added to supporting testing of the + /// Aiks API and non-flutter usage of Impeller. + /// + if (!RegisterShader(renderer)) { + return false; + } + + //-------------------------------------------------------------------------- + /// Fragment stage uniforms. + /// + BindFragmentCallback bind_callback = [this, &renderer, + &context](RenderPass& pass) { + size_t buffer_index = 0; + size_t buffer_offset = 0; + size_t sampler_location = 0; + size_t buffer_location = 0; + + // Uniforms are ordered in the IPLR according to their + // declaration and the uniform location reflects the correct offset to + // be mapped to - except that it may include all proceeding + // uniforms of a different type. For example, a texture sampler that comes + // after 4 float uniforms may have a location of 4. Since we know that + // the declarations are already ordered, we can track the uniform location + // ourselves. + for (const auto& uniform : runtime_stage_->GetUniforms()) { + std::unique_ptr metadata = MakeShaderMetadata(uniform); + switch (uniform.type) { + case kSampledImage: { + FML_DCHECK(sampler_location < texture_inputs_.size()); + auto& input = texture_inputs_[sampler_location]; + + raw_ptr sampler = + context->GetSamplerLibrary()->GetSampler( + input.sampler_descriptor); + + SampledImageSlot image_slot; + image_slot.name = uniform.name.c_str(); + image_slot.binding = uniform.binding; + image_slot.texture_index = sampler_location; + pass.BindDynamicResource(ShaderStage::kFragment, + DescriptorType::kSampledImage, image_slot, + std::move(metadata), input.texture, sampler); + sampler_location++; + break; + } + case kFloat: { + FML_DCHECK(renderer.GetContext()->GetBackendType() != + Context::BackendType::kVulkan) + << "Uniform " << uniform.name + << " had unexpected type kFloat for Vulkan backend."; + + size_t alignment = + std::max(uniform.bit_width / 8, DefaultUniformAlignment()); + BufferView buffer_view = renderer.GetTransientsBuffer().Emplace( + uniform_data_->data() + buffer_offset, uniform.GetSize(), + alignment); + + ShaderUniformSlot uniform_slot; + uniform_slot.name = uniform.name.c_str(); + uniform_slot.ext_res_0 = buffer_location; + pass.BindDynamicResource(ShaderStage::kFragment, + DescriptorType::kUniformBuffer, uniform_slot, + std::move(metadata), std::move(buffer_view)); + buffer_index++; + buffer_offset += uniform.GetSize(); + buffer_location++; + break; + } + case kStruct: { + FML_DCHECK(renderer.GetContext()->GetBackendType() == + Context::BackendType::kVulkan); + ShaderUniformSlot uniform_slot; + uniform_slot.binding = uniform.location; + uniform_slot.name = uniform.name.c_str(); + + pass.BindResource( + ShaderStage::kFragment, DescriptorType::kUniformBuffer, + uniform_slot, nullptr, + EmplaceVulkanUniform(uniform_data_, + renderer.GetTransientsBuffer(), uniform)); + } + } + } + + return true; + }; + + /// Now that the descriptor set layouts are known, get the pipeline. + using VS = RuntimeEffectVertexShader; + + PipelineBuilderCallback pipeline_callback = + [&](ContentContextOptions options) { + // Pipeline creation callback for the cache handler to call. + return renderer.GetCachedRuntimeEffectPipeline( + runtime_stage_->GetEntrypoint(), options, [&]() { + return CreatePipeline(renderer, options, /*async=*/false); + }); + }; + + return ColorSourceContents::DrawGeometry(renderer, entity, pass, + pipeline_callback, + VS::FrameInfo{}, bind_callback); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..dd62059f221fcc8f366204eaf170f603cca08556 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/runtime_effect_contents.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_ + +#include +#include + +#include "impeller/core/host_buffer.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace impeller { + +class RuntimeEffectContents final : public ColorSourceContents { + public: + struct TextureInput { + SamplerDescriptor sampler_descriptor; + std::shared_ptr texture; + }; + + void SetRuntimeStage(std::shared_ptr runtime_stage); + + void SetUniformData(std::shared_ptr> uniform_data); + + void SetTextureInputs(std::vector texture_inputs); + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + /// Load the runtime effect and ensure a default PSO is initialized. + bool BootstrapShader(const ContentContext& renderer) const; + + // Visible for testing + static BufferView EmplaceVulkanUniform( + const std::shared_ptr>& input_data, + HostBuffer& host_buffer, + const RuntimeUniformDescription& uniform); + + private: + bool RegisterShader(const ContentContext& renderer) const; + + // If async is true, this will always return nullptr as pipeline creation + // is not blocked on. + std::shared_ptr> CreatePipeline( + const ContentContext& renderer, + ContentContextOptions options, + bool async) const; + + std::shared_ptr runtime_stage_; + std::shared_ptr> uniform_data_; + std::vector texture_inputs_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_RUNTIME_EFFECT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..9284f01cd604d20957d3729c886bab18513524a4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.cc @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "solid_color_contents.h" + +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +SolidColorContents::SolidColorContents() = default; + +SolidColorContents::~SolidColorContents() = default; + +void SolidColorContents::SetColor(Color color) { + color_ = color; +} + +Color SolidColorContents::GetColor() const { + return color_.WithAlpha(color_.alpha * GetOpacityFactor()); +} + +bool SolidColorContents::IsSolidColor() const { + return true; +} + +bool SolidColorContents::IsOpaque(const Matrix& transform) const { + return GetColor().IsOpaque() && !AppliesAlphaForStrokeCoverage(transform); +} + +std::optional SolidColorContents::GetCoverage( + const Entity& entity) const { + if (GetColor().IsTransparent()) { + return std::nullopt; + } + + const Geometry* geometry = GetGeometry(); + if (geometry == nullptr) { + return std::nullopt; + } + return geometry->GetCoverage(entity.GetTransform()); +}; + +bool SolidColorContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = SolidFillPipeline::VertexShader; + using FS = SolidFillPipeline::FragmentShader; + auto& host_buffer = renderer.GetTransientsBuffer(); + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + frag_info.color = GetColor().Premultiply() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetSolidFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [&frag_info, &host_buffer](RenderPass& pass) { + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + pass.SetCommandLabel("Solid Fill"); + return true; + }); +} + +std::optional SolidColorContents::AsBackgroundColor( + const Entity& entity, + ISize target_size) const { + Rect target_rect = Rect::MakeSize(target_size); + return GetGeometry()->CoversArea(entity.GetTransform(), target_rect) + ? GetColor() + : std::optional(); +} + +bool SolidColorContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + color_ = color_filter_proc(color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..c6982206f21a9f9e9766069bd60e06779862e747 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/solid_color_contents.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_ + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +class SolidColorContents final : public ColorSourceContents { + public: + SolidColorContents(); + + ~SolidColorContents() override; + + void SetColor(Color color); + + Color GetColor() const; + + // |ColorSourceContents| + bool IsSolidColor() const override; + + // |Contents| + bool IsOpaque(const Matrix& transform) const override; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + std::optional AsBackgroundColor(const Entity& entity, + ISize target_size) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + private: + Color color_; + + SolidColorContents(const SolidColorContents&) = delete; + + SolidColorContents& operator=(const SolidColorContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_COLOR_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..c38f553469fc66ba9a2e1fd581ab9b3554c585f6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.cc @@ -0,0 +1,202 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/solid_rrect_blur_contents.h" +#include + +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/constants.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +namespace { +// Generous padding to make sure blurs with large sigmas are fully visible. Used +// to expand the geometry around the rrect. Larger sigmas have more subtle +// gradients so they need larger padding to avoid hard cutoffs. Sigma is +// maximized to 3.5 since that should cover 99.95% of all samples. 3.0 should +// cover 99.7% but that was seen to be not enough for large sigmas. +Scalar PadForSigma(Scalar sigma) { + Scalar scalar = std::min((1.0f / 47.6f) * sigma + 2.5f, 3.5f); + return sigma * scalar; +} +} // namespace + +SolidRRectBlurContents::SolidRRectBlurContents() = default; + +SolidRRectBlurContents::~SolidRRectBlurContents() = default; + +void SolidRRectBlurContents::SetRRect(std::optional rect, + Size corner_radii) { + rect_ = rect; + corner_radii_ = corner_radii; +} + +void SolidRRectBlurContents::SetSigma(Sigma sigma) { + sigma_ = sigma; +} + +void SolidRRectBlurContents::SetColor(Color color) { + color_ = color.Premultiply(); +} + +Color SolidRRectBlurContents::GetColor() const { + return color_; +} + +static Point eccentricity(Point v, double sInverse) { + Point vOverS = v * sInverse * 0.5; + Point vOverS_squared = -(vOverS * vOverS); + return {std::exp(vOverS_squared.x), std::exp(vOverS_squared.y)}; +} + +static Scalar kTwoOverSqrtPi = 2.0 / std::sqrt(kPi); + +// use crate::math::compute_erf7; +static Scalar computeErf7(Scalar x) { + x *= kTwoOverSqrtPi; + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1.0 + x * x); +} + +static Point NegPos(Scalar v) { + return {std::min(v, 0.0f), std::max(v, 0.0f)}; +} + +static bool SetupFragInfo( + RRectBlurPipeline::FragmentShader::FragInfo& frag_info, + Scalar blurSigma, + Point center, + Point rSize, + Scalar radius) { + Scalar sigma = std::max(blurSigma * kSqrt2, 1.f); + + frag_info.center = rSize * 0.5f; + frag_info.minEdge = std::min(rSize.x, rSize.y); + double rMax = 0.5 * frag_info.minEdge; + double r0 = std::min(std::hypot(radius, sigma * 1.15), rMax); + frag_info.r1 = std::min(std::hypot(radius, sigma * 2.0), rMax); + + frag_info.exponent = 2.0 * frag_info.r1 / r0; + + frag_info.sInv = 1.0 / sigma; + + // Pull in long end (make less eccentric). + Point eccentricV = eccentricity(rSize, frag_info.sInv); + double delta = 1.25 * sigma * (eccentricV.x - eccentricV.y); + rSize += NegPos(delta); + + frag_info.adjust = rSize * 0.5 - frag_info.r1; + frag_info.exponentInv = 1.0 / frag_info.exponent; + frag_info.scale = + 0.5 * computeErf7(frag_info.sInv * 0.5 * + (std::max(rSize.x, rSize.y) - 0.5 * radius)); + + return frag_info.center.IsFinite() && // + frag_info.adjust.IsFinite() && // + std::isfinite(frag_info.minEdge) && // + std::isfinite(frag_info.r1) && // + std::isfinite(frag_info.exponent) && // + std::isfinite(frag_info.sInv) && // + std::isfinite(frag_info.exponentInv) && // + std::isfinite(frag_info.scale); +} + +std::optional SolidRRectBlurContents::GetCoverage( + const Entity& entity) const { + if (!rect_.has_value()) { + return std::nullopt; + } + + Scalar radius = PadForSigma(sigma_.sigma); + + return rect_->Expand(radius).TransformBounds(entity.GetTransform()); +} + +bool SolidRRectBlurContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (!rect_.has_value()) { + return true; + } + + using VS = RRectBlurPipeline::VertexShader; + using FS = RRectBlurPipeline::FragmentShader; + + Matrix basis_invert = entity.GetTransform().Basis().Invert(); + Vector2 max_sigmas = + Vector2((basis_invert * Vector2(500.f, 0.f)).GetLength(), + (basis_invert * Vector2(0.f, 500.f)).GetLength()); + Scalar max_sigma = std::min(max_sigmas.x, max_sigmas.y); + // Clamp the max kernel width/height to 1000 (@ 2x) to limit the extent + // of the blur and to kEhCloseEnough to prevent NaN calculations + // trying to evaluate a Gaussian distribution with a sigma of 0. + auto blur_sigma = std::clamp(sigma_.sigma, kEhCloseEnough, max_sigma); + // Increase quality by making the radius a bit bigger than the typical + // sigma->radius conversion we use for slower blurs. + Scalar blur_radius = PadForSigma(blur_sigma); + Rect positive_rect = rect_->GetPositive(); + Scalar left = -blur_radius; + Scalar top = -blur_radius; + Scalar right = positive_rect.GetWidth() + blur_radius; + Scalar bottom = positive_rect.GetHeight() + blur_radius; + + std::array vertices = { + VS::PerVertexData{Point(left, top)}, + VS::PerVertexData{Point(right, top)}, + VS::PerVertexData{Point(left, bottom)}, + VS::PerVertexData{Point(right, bottom)}, + }; + + ContentContextOptions opts = OptionsFromPassAndEntity(pass, entity); + opts.primitive_type = PrimitiveType::kTriangleStrip; + Color color = color_; + if (entity.GetBlendMode() == BlendMode::kClear) { + opts.is_for_rrect_blur_clear = true; + color = Color::White(); + } + + VS::FrameInfo frame_info; + frame_info.mvp = Entity::GetShaderTransform( + entity.GetShaderClipDepth(), pass, + entity.GetTransform() * + Matrix::MakeTranslation(positive_rect.GetOrigin())); + + FS::FragInfo frag_info; + frag_info.color = color; + Scalar radius = std::min(std::clamp(corner_radii_.width, kEhCloseEnough, + positive_rect.GetWidth() * 0.5f), + std::clamp(corner_radii_.height, kEhCloseEnough, + positive_rect.GetHeight() * 0.5f)); + if (!SetupFragInfo(frag_info, blur_sigma, positive_rect.GetCenter(), + Point(positive_rect.GetSize()), radius)) { + return true; + } + + auto& host_buffer = renderer.GetTransientsBuffer(); + pass.SetCommandLabel("RRect Shadow"); + pass.SetPipeline(renderer.GetRRectBlurPipeline(opts)); + pass.SetVertexBuffer(CreateVertexBuffer(vertices, host_buffer)); + + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + if (!pass.Draw().ok()) { + return false; + } + + return true; +} + +bool SolidRRectBlurContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + color_ = color_filter_proc(color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..f396d0487aba010e0930ed042a56b6a05fb90c9f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/solid_rrect_blur_contents.h @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_ + +#include +#include +#include + +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +class Path; +class HostBuffer; +struct VertexBuffer; + +/// @brief Draws a fast solid color blur of an rounded rectangle. Only supports +/// RRects with fully symmetrical radii. Also produces correct results for +/// rectangles (corner_radius=0) and circles (corner_radius=width/2=height/2). +class SolidRRectBlurContents final : public Contents { + public: + SolidRRectBlurContents(); + + ~SolidRRectBlurContents() override; + + void SetRRect(std::optional rect, Size corner_radii = {}); + + void SetSigma(Sigma sigma); + + void SetColor(Color color); + + Color GetColor() const; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + private: + std::optional rect_; + Size corner_radii_; + Sigma sigma_; + + Color color_; + + SolidRRectBlurContents(const SolidRRectBlurContents&) = delete; + + SolidRRectBlurContents& operator=(const SolidRRectBlurContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SOLID_RRECT_BLUR_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..1dfa1292203a7925eea2c572be3aae3a93391b4e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.cc @@ -0,0 +1,235 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "sweep_gradient_contents.h" + +#include "flutter/fml/logging.h" +#include "impeller/entity/contents/clip_contents.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/gradient_generator.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/gradient.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +SweepGradientContents::SweepGradientContents() = default; + +SweepGradientContents::~SweepGradientContents() = default; + +void SweepGradientContents::SetCenterAndAngles(Point center, + Degrees start_angle, + Degrees end_angle) { + center_ = center; + Scalar t0 = start_angle.degrees / 360; + Scalar t1 = end_angle.degrees / 360; + FML_DCHECK(t0 < t1); + bias_ = -t0; + scale_ = 1 / (t1 - t0); +} + +void SweepGradientContents::SetColors(std::vector colors) { + colors_ = std::move(colors); +} + +void SweepGradientContents::SetStops(std::vector stops) { + stops_ = std::move(stops); +} + +void SweepGradientContents::SetTileMode(Entity::TileMode tile_mode) { + tile_mode_ = tile_mode; +} + +const std::vector& SweepGradientContents::GetColors() const { + return colors_; +} + +const std::vector& SweepGradientContents::GetStops() const { + return stops_; +} + +bool SweepGradientContents::IsOpaque(const Matrix& transform) const { + if (GetOpacityFactor() < 1 || tile_mode_ == Entity::TileMode::kDecal) { + return false; + } + for (auto color : colors_) { + if (!color.IsOpaque()) { + return false; + } + } + return !AppliesAlphaForStrokeCoverage(transform); +} + +#define ARRAY_LEN(a) (sizeof(a) / sizeof(a[0])) +#define UNIFORM_FRAG_INFO(t) \ + t##GradientUniformFillPipeline::FragmentShader::FragInfo +#define UNIFORM_COLOR_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Sweep)::colors) +#define UNIFORM_STOP_SIZE ARRAY_LEN(UNIFORM_FRAG_INFO(Sweep)::stop_pairs) +static_assert(UNIFORM_COLOR_SIZE == kMaxUniformGradientStops); +static_assert(UNIFORM_STOP_SIZE == kMaxUniformGradientStops / 2); + +bool SweepGradientContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (renderer.GetDeviceCapabilities().SupportsSSBO()) { + return RenderSSBO(renderer, entity, pass); + } + if (colors_.size() <= kMaxUniformGradientStops && + stops_.size() <= kMaxUniformGradientStops) { + return RenderUniform(renderer, entity, pass); + } + return RenderTexture(renderer, entity, pass); +} + +bool SweepGradientContents::RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = SweepGradientSSBOFillPipeline::VertexShader; + using FS = SweepGradientSSBOFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + VS::BindFrameInfo(pass, + renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetSweepGradientSSBOFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.bias = bias_; + frag_info.scale = scale_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto colors = CreateGradientColors(colors_, stops_); + + frag_info.colors_length = colors.size(); + auto color_buffer = + host_buffer.Emplace(colors.data(), colors.size() * sizeof(StopData), + DefaultUniformAlignment()); + + pass.SetCommandLabel("SweepGradientSSBOFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindColorData(pass, color_buffer); + + return true; + }); +} + +bool SweepGradientContents::RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = SweepGradientUniformFillPipeline::VertexShader; + using FS = SweepGradientUniformFillPipeline::FragmentShader; + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + VS::BindFrameInfo(pass, + renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetSweepGradientUniformFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.bias = bias_; + frag_info.scale = scale_; + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.colors_length = PopulateUniformGradientColors( + colors_, stops_, frag_info.colors, frag_info.stop_pairs); + + frag_info.decal_border_color = decal_border_color_; + + pass.SetCommandLabel("SweepGradientUniformFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + + return true; + }); +} + +bool SweepGradientContents::RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = SweepGradientFillPipeline::VertexShader; + using FS = SweepGradientFillPipeline::FragmentShader; + + auto gradient_data = CreateGradientBuffer(colors_, stops_); + auto gradient_texture = + CreateGradientTexture(gradient_data, renderer.GetContext()); + if (gradient_texture == nullptr) { + return false; + } + + VS::FrameInfo frame_info; + frame_info.matrix = GetInverseEffectTransform(); + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetSweepGradientFillPipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &gradient_texture, &entity](RenderPass& pass) { + FS::FragInfo frag_info; + frag_info.center = center_; + frag_info.bias = bias_; + frag_info.scale = scale_; + frag_info.texture_sampler_y_coord_scale = + gradient_texture->GetYCoordScale(); + frag_info.tile_mode = static_cast(tile_mode_); + frag_info.decal_border_color = decal_border_color_; + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + frag_info.half_texel = + Vector2(0.5 / gradient_texture->GetSize().width, + 0.5 / gradient_texture->GetSize().height); + + SamplerDescriptor sampler_desc; + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + + pass.SetCommandLabel("SweepGradientFill"); + + FS::BindFragInfo( + pass, renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + FS::BindTextureSampler( + pass, gradient_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc)); + + return true; + }); +} + +bool SweepGradientContents::ApplyColorFilter( + const ColorFilterProc& color_filter_proc) { + for (Color& color : colors_) { + color = color_filter_proc(color); + } + decal_border_color_ = color_filter_proc(decal_border_color_); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..d145987e19f139acf7593972f97b375db1c02380 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/sweep_gradient_contents.h @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +class SweepGradientContents final : public ColorSourceContents { + public: + SweepGradientContents(); + + ~SweepGradientContents() override; + + // |Contents| + bool IsOpaque(const Matrix& transform) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + [[nodiscard]] bool ApplyColorFilter( + const ColorFilterProc& color_filter_proc) override; + + void SetCenterAndAngles(Point center, Degrees start_angle, Degrees end_angle); + + void SetColors(std::vector colors); + + void SetStops(std::vector stops); + + void SetTileMode(Entity::TileMode tile_mode); + + const std::vector& GetColors() const; + + const std::vector& GetStops() const; + + private: + bool RenderTexture(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderSSBO(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + bool RenderUniform(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const; + + Point center_; + Scalar bias_; + Scalar scale_; + std::vector colors_; + std::vector stops_; + Entity::TileMode tile_mode_; + Color decal_border_color_ = Color::BlackTransparent(); + + SweepGradientContents(const SweepGradientContents&) = delete; + + SweepGradientContents& operator=(const SweepGradientContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SWEEP_GRADIENT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.cc b/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..ddd2bc73f07377aee93faf4e61b4c777052fc7b5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.cc @@ -0,0 +1,159 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/test/recording_render_pass.h" + +#include + +namespace impeller::testing { + +RecordingRenderPass::RecordingRenderPass( + std::shared_ptr delegate, + const std::shared_ptr& context, + const RenderTarget& render_target) + : RenderPass(context, render_target), delegate_(std::move(delegate)) {} + +// |RenderPass| +void RecordingRenderPass::SetPipeline(PipelineRef pipeline) { + pending_.pipeline = pipeline; + if (delegate_) { + delegate_->SetPipeline(pipeline); + } +} + +void RecordingRenderPass::SetCommandLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + pending_.label = std::string(label); +#endif // IMPELLER_DEBUG + if (delegate_) { + delegate_->SetCommandLabel(label); + } +} + +// |RenderPass| +void RecordingRenderPass::SetStencilReference(uint32_t value) { + pending_.stencil_reference = value; + if (delegate_) { + delegate_->SetStencilReference(value); + } +} + +// |RenderPass| +void RecordingRenderPass::SetBaseVertex(uint64_t value) { + pending_.base_vertex = value; + if (delegate_) { + delegate_->SetBaseVertex(value); + } +} + +// |RenderPass| +void RecordingRenderPass::SetViewport(Viewport viewport) { + pending_.viewport = viewport; + if (delegate_) { + delegate_->SetViewport(viewport); + } +} + +// |RenderPass| +void RecordingRenderPass::SetScissor(IRect scissor) { + pending_.scissor = scissor; + if (delegate_) { + delegate_->SetScissor(scissor); + } +} + +// |RenderPass| +void RecordingRenderPass::SetInstanceCount(size_t count) { + pending_.instance_count = count; + if (delegate_) { + delegate_->SetInstanceCount(count); + } +} + +// |RenderPass| +bool RecordingRenderPass::SetVertexBuffer(VertexBuffer buffer) { + if (delegate_) { + return delegate_->SetVertexBuffer(buffer); + } + return true; +} + +// |RenderPass| +fml::Status RecordingRenderPass::Draw() { + commands_.emplace_back(std::move(pending_)); + pending_ = {}; + if (delegate_) { + return delegate_->Draw(); + } + return fml::Status(); +} + +// |RenderPass| +void RecordingRenderPass::OnSetLabel(std::string_view label) { + return; +} + +// |RenderPass| +bool RecordingRenderPass::OnEncodeCommands(const Context& context) const { + if (delegate_) { + return delegate_->EncodeCommands(); + } + return true; +} + +// |RenderPass| +bool RecordingRenderPass::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + if (delegate_) { + return delegate_->BindResource(stage, type, slot, metadata, view); + } + return true; +} + +// |RenderPass| +bool RecordingRenderPass::BindDynamicResource( + ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) { + if (delegate_) { + return delegate_->BindDynamicResource(stage, type, slot, + std::move(metadata), view); + } + return true; +} + +// |RenderPass| +bool RecordingRenderPass::BindDynamicResource( + ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (delegate_) { + return delegate_->BindDynamicResource( + stage, type, slot, std::move(metadata), texture, sampler); + } + return true; +} + +bool RecordingRenderPass::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (delegate_) { + return delegate_->BindResource(stage, type, slot, metadata, texture, + sampler); + } + return true; +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.h b/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..e84bec1edce5953649ba0a271710e7286f3aa4e1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/test/recording_render_pass.h @@ -0,0 +1,92 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_ + +#include "impeller/renderer/render_pass.h" + +namespace impeller::testing { + +class RecordingRenderPass : public RenderPass { + public: + explicit RecordingRenderPass(std::shared_ptr delegate, + const std::shared_ptr& context, + const RenderTarget& render_target); + + ~RecordingRenderPass() = default; + + const std::vector& GetCommands() const override { return commands_; } + + // |RenderPass| + void SetPipeline(PipelineRef pipeline) override; + + void SetCommandLabel(std::string_view label) override; + + // |RenderPass| + void SetStencilReference(uint32_t value) override; + + // |RenderPass| + void SetBaseVertex(uint64_t value) override; + + // |RenderPass| + void SetViewport(Viewport viewport) override; + + // |RenderPass| + void SetScissor(IRect scissor) override; + + // |RenderPass| + void SetInstanceCount(size_t count) override; + + // |RenderPass| + bool SetVertexBuffer(VertexBuffer buffer) override; + + // |RenderPass| + fml::Status Draw() override; + + bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + // |RenderPass| + void OnSetLabel(std::string_view label) override; + + // |RenderPass| + bool OnEncodeCommands(const Context& context) const override; + + bool IsValid() const override { return true; } + + private: + Command pending_; + std::shared_ptr delegate_; + std::vector commands_; +}; + +} // namespace impeller::testing + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEST_RECORDING_RENDER_PASS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/text_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/text_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..3e37ea5a6ef96ce435a3fb56958cf954cf0e8501 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/text_contents.cc @@ -0,0 +1,348 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/text_contents.h" + +#include +#include +#include + +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/typographer/glyph_atlas.h" + +namespace impeller { +Point SizeToPoint(Size size) { + return Point(size.width, size.height); +} + +using VS = GlyphAtlasPipeline::VertexShader; +using FS = GlyphAtlasPipeline::FragmentShader; + +TextContents::TextContents() = default; + +TextContents::~TextContents() = default; + +void TextContents::SetTextFrame(const std::shared_ptr& frame) { + frame_ = frame; +} + +void TextContents::SetColor(Color color) { + color_ = color; +} + +Color TextContents::GetColor() const { + return color_.WithAlpha(color_.alpha * inherited_opacity_); +} + +void TextContents::SetInheritedOpacity(Scalar opacity) { + inherited_opacity_ = opacity; +} + +void TextContents::SetOffset(Vector2 offset) { + offset_ = offset; +} + +void TextContents::SetForceTextColor(bool value) { + force_text_color_ = value; +} + +std::optional TextContents::GetCoverage(const Entity& entity) const { + return frame_->GetBounds().TransformBounds(entity.GetTransform()); +} + +void TextContents::SetTextProperties(Color color, + bool stroke, + Scalar stroke_width, + Cap stroke_cap, + Join stroke_join, + Scalar stroke_miter) { + if (frame_->HasColor()) { + // Alpha is always applied when rendering, remove it here so + // we do not double-apply the alpha. + properties_.color = color.WithAlpha(1.0); + } + if (stroke) { + properties_.stroke = true; + properties_.stroke_width = stroke_width; + properties_.stroke_cap = stroke_cap; + properties_.stroke_join = stroke_join; + properties_.stroke_miter = stroke_miter; + } +} + +namespace { +Scalar AttractToOne(Scalar x) { + // Epsilon was decided by looking at the floating point inaccuracies in + // the ScaledK test. + const Scalar epsilon = 0.005f; + if (std::abs(x - 1.f) < epsilon) { + return 1.f; + } + if (std::abs(x + 1.f) < epsilon) { + return -1.f; + } + return x; +} + +} // namespace + +void TextContents::ComputeVertexData( + VS::PerVertexData* vtx_contents, + const std::shared_ptr& frame, + Scalar scale, + const Matrix& entity_transform, + Vector2 offset, + std::optional glyph_properties, + const std::shared_ptr& atlas) { + // Common vertex information for all glyphs. + // All glyphs are given the same vertex information in the form of a + // unit-sized quad. The size of the glyph is specified in per instance data + // and the vertex shader uses this to size the glyph correctly. The + // interpolated vertex information is also used in the fragment shader to + // sample from the glyph atlas. + + constexpr std::array unit_points = {Point{0, 0}, Point{1, 0}, + Point{0, 1}, Point{1, 1}}; + + ISize atlas_size = atlas->GetTexture()->GetSize(); + bool is_translation_scale = entity_transform.IsTranslationScaleOnly(); + Matrix basis_transform = entity_transform.Basis(); + + VS::PerVertexData vtx; + size_t i = 0u; + size_t bounds_offset = 0u; + Rational rounded_scale = frame->GetScale(); + Scalar inverted_rounded_scale = static_cast(rounded_scale.Invert()); + Matrix unscaled_basis = + basis_transform * + Matrix::MakeScale({inverted_rounded_scale, inverted_rounded_scale, 1}); + + // In typical scales < 48x these values should be -1 or 1. We round to + // those to avoid inaccuracies. + unscaled_basis.m[0] = AttractToOne(unscaled_basis.m[0]); + unscaled_basis.m[5] = AttractToOne(unscaled_basis.m[5]); + + for (const TextRun& run : frame->GetRuns()) { + const Font& font = run.GetFont(); + const Matrix transform = frame->GetOffsetTransform(); + FontGlyphAtlas* font_atlas = nullptr; + + // Adjust glyph position based on the subpixel rounding + // used by the font. + Point subpixel_adjustment(0.5, 0.5); + switch (font.GetAxisAlignment()) { + case AxisAlignment::kNone: + break; + case AxisAlignment::kX: + subpixel_adjustment.x = 0.125; + break; + case AxisAlignment::kY: + subpixel_adjustment.y = 0.125; + break; + case AxisAlignment::kAll: + subpixel_adjustment.x = 0.125; + subpixel_adjustment.y = 0.125; + break; + } + + Point screen_offset = (entity_transform * Point(0, 0)); + for (const TextRun::GlyphPosition& glyph_position : + run.GetGlyphPositions()) { + const FrameBounds& frame_bounds = frame->GetFrameBounds(bounds_offset); + bounds_offset++; + auto atlas_glyph_bounds = frame_bounds.atlas_bounds; + auto glyph_bounds = frame_bounds.glyph_bounds; + + // If frame_bounds.is_placeholder is true, this is the first frame + // the glyph has been rendered and so its atlas position was not + // known when the glyph was recorded. Perform a slow lookup into the + // glyph atlas hash table. + if (frame_bounds.is_placeholder) { + if (!font_atlas) { + font_atlas = + atlas->GetOrCreateFontGlyphAtlas(ScaledFont{font, rounded_scale}); + } + + if (!font_atlas) { + VALIDATION_LOG << "Could not find font in the atlas."; + continue; + } + SubpixelPosition subpixel = TextFrame::ComputeSubpixelPosition( + glyph_position, font.GetAxisAlignment(), transform); + + std::optional maybe_atlas_glyph_bounds = + font_atlas->FindGlyphBounds(SubpixelGlyph{ + glyph_position.glyph, // + subpixel, // + glyph_properties // + }); + if (!maybe_atlas_glyph_bounds.has_value()) { + VALIDATION_LOG << "Could not find glyph position in the atlas."; + continue; + } + atlas_glyph_bounds = maybe_atlas_glyph_bounds.value().atlas_bounds; + } + + Rect scaled_bounds = glyph_bounds.Scale(inverted_rounded_scale); + // For each glyph, we compute two rectangles. One for the vertex + // positions and one for the texture coordinates (UVs). The atlas + // glyph bounds are used to compute UVs in cases where the + // destination and source sizes may differ due to clamping the sizes + // of large glyphs. + Point uv_origin = atlas_glyph_bounds.GetLeftTop() / atlas_size; + Point uv_size = SizeToPoint(atlas_glyph_bounds.GetSize()) / atlas_size; + + Point unrounded_glyph_position = + // This is for RTL text. + unscaled_basis * glyph_bounds.GetLeftTop() + + (basis_transform * glyph_position.position); + + Point screen_glyph_position = + (screen_offset + unrounded_glyph_position + subpixel_adjustment) + .Floor(); + for (const Point& point : unit_points) { + Point position; + if (is_translation_scale) { + position = (screen_glyph_position + + (unscaled_basis * point * glyph_bounds.GetSize())) + .Round(); + } else { + position = entity_transform * + (glyph_position.position + scaled_bounds.GetLeftTop() + + point * scaled_bounds.GetSize()); + } + vtx.uv = uv_origin + (uv_size * point); + vtx.position = position; + vtx_contents[i++] = vtx; + } + } + } +} + +bool TextContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + Color color = GetColor(); + if (color.IsTransparent()) { + return true; + } + + GlyphAtlas::Type type = frame_->GetAtlasType(); + const std::shared_ptr& atlas = + renderer.GetLazyGlyphAtlas()->CreateOrGetGlyphAtlas( + *renderer.GetContext(), renderer.GetTransientsBuffer(), type); + + if (!atlas || !atlas->IsValid()) { + VALIDATION_LOG << "Cannot render glyphs without prepared atlas."; + return false; + } + if (!frame_->IsFrameComplete()) { + VALIDATION_LOG << "Failed to find font glyph bounds."; + return false; + } + + // Information shared by all glyph draw calls. + pass.SetCommandLabel("TextFrame"); + auto opts = OptionsFromPassAndEntity(pass, entity); + opts.primitive_type = PrimitiveType::kTriangle; + pass.SetPipeline(renderer.GetGlyphAtlasPipeline(opts)); + + // Common vertex uniforms for all glyphs. + VS::FrameInfo frame_info; + frame_info.mvp = + Entity::GetShaderTransform(entity.GetShaderClipDepth(), pass, Matrix()); + bool is_translation_scale = entity.GetTransform().IsTranslationScaleOnly(); + Matrix entity_transform = entity.GetTransform(); + + VS::BindFrameInfo(pass, + renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); + + FS::FragInfo frag_info; + frag_info.use_text_color = force_text_color_ ? 1.0 : 0.0; + frag_info.text_color = ToVector(color.Premultiply()); + frag_info.is_color_glyph = type == GlyphAtlas::Type::kColorBitmap; + + FS::BindFragInfo(pass, + renderer.GetTransientsBuffer().EmplaceUniform(frag_info)); + + SamplerDescriptor sampler_desc; + if (is_translation_scale) { + sampler_desc.min_filter = MinMagFilter::kNearest; + sampler_desc.mag_filter = MinMagFilter::kNearest; + } else { + // Currently, we only propagate the scale of the transform to the atlas + // renderer, so if the transform has more than just a translation, we turn + // on linear sampling to prevent crunchiness caused by the pixel grid not + // being perfectly aligned. + // The downside is that this slightly over-blurs rotated/skewed text. + sampler_desc.min_filter = MinMagFilter::kLinear; + sampler_desc.mag_filter = MinMagFilter::kLinear; + } + + // No mipmaps for glyph atlas (glyphs are generated at exact scales). + sampler_desc.mip_filter = MipFilter::kBase; + + FS::BindGlyphAtlasSampler( + pass, // command + atlas->GetTexture(), // texture + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc) // sampler + ); + + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + size_t glyph_count = 0; + for (const auto& run : frame_->GetRuns()) { + glyph_count += run.GetGlyphPositions().size(); + } + size_t vertex_count = glyph_count * 4; + size_t index_count = glyph_count * 6; + + BufferView buffer_view = host_buffer.Emplace( + vertex_count * sizeof(VS::PerVertexData), alignof(VS::PerVertexData), + [&](uint8_t* data) { + VS::PerVertexData* vtx_contents = + reinterpret_cast(data); + ComputeVertexData(/*vtx_contents=*/vtx_contents, + /*frame=*/frame_, + /*scale=*/scale_, + /*entity_transform=*/entity_transform, + /*offset=*/offset_, + /*glyph_properties=*/GetGlyphProperties(), + /*atlas=*/atlas); + }); + BufferView index_buffer_view = host_buffer.Emplace( + index_count * sizeof(uint16_t), alignof(uint16_t), [&](uint8_t* data) { + uint16_t* indices = reinterpret_cast(data); + size_t j = 0; + for (auto i = 0u; i < glyph_count; i++) { + size_t base = i * 4; + indices[j++] = base + 0; + indices[j++] = base + 1; + indices[j++] = base + 2; + indices[j++] = base + 1; + indices[j++] = base + 2; + indices[j++] = base + 3; + } + }); + + pass.SetVertexBuffer(std::move(buffer_view)); + pass.SetIndexBuffer(index_buffer_view, IndexType::k16bit); + pass.SetElementCount(index_count); + + return pass.Draw().ok(); +} + +std::optional TextContents::GetGlyphProperties() const { + return (properties_.stroke || frame_->HasColor()) + ? std::optional(properties_) + : std::nullopt; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/text_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/text_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..58f202d5f056d5a25f2003870e0db1184bd4b2f5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/text_contents.h @@ -0,0 +1,93 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_CONTENTS_H_ + +#include + +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/geometry/color.h" +#include "impeller/typographer/font_glyph_pair.h" +#include "impeller/typographer/text_frame.h" + +namespace impeller { + +class LazyGlyphAtlas; +class Context; + +class TextContents final : public Contents { + public: + TextContents(); + + ~TextContents(); + + void SetTextFrame(const std::shared_ptr& frame); + + void SetColor(Color color); + + /// @brief Force the text color to apply to the rendered glyphs, even if those + /// glyphs are bitmaps. + /// + /// This is used to ensure that mask blurs work correctly on emoji. + void SetForceTextColor(bool value); + + /// Must be set after text frame. + void SetTextProperties(Color color, + bool stroke, + Scalar stroke_width, + Cap stroke_cap, + Join stroke_join, + Scalar stroke_miter); + + Color GetColor() const; + + // |Contents| + void SetInheritedOpacity(Scalar opacity) override; + + // The offset is only used for computing the subpixel glyph position. + void SetOffset(Vector2 offset); + + std::optional GetTextFrameBounds() const; + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + void SetScale(Scalar scale) { scale_ = scale; } + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + static void ComputeVertexData( + GlyphAtlasPipeline::VertexShader::PerVertexData* vtx_contents, + const std::shared_ptr& frame, + Scalar scale, + const Matrix& entity_transform, + Vector2 offset, + std::optional glyph_properties, + const std::shared_ptr& atlas); + + private: + std::optional GetGlyphProperties() const; + + std::shared_ptr frame_; + Scalar scale_ = 1.0; + Scalar inherited_opacity_ = 1.0; + Vector2 offset_; + bool force_text_color_ = false; + Color color_; + GlyphProperties properties_; + + TextContents(const TextContents&) = delete; + + TextContents& operator=(const TextContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/text_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/text_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..44f745017aef9fc2db9a883e0895bd07289e09fa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/text_contents_unittests.cc @@ -0,0 +1,381 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/geometry_asserts.h" +#include "flutter/impeller/renderer/testing/mocks.h" +#include "flutter/testing/testing.h" +#include "impeller/entity/contents/text_contents.h" +#include "impeller/playground/playground_test.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" +#include "txt/platform.h" + +#pragma GCC diagnostic ignored "-Wunreachable-code" + +namespace impeller { +namespace testing { + +using TextContentsTest = PlaygroundTest; +INSTANTIATE_PLAYGROUND_SUITE(TextContentsTest); + +using ::testing::Return; + +namespace { +struct TextOptions { + Scalar font_size = 50; + bool is_subpixel = false; +}; + +std::shared_ptr MakeTextFrame(const std::string& text, + const std::string_view& font_fixture, + const TextOptions& options) { + auto c_font_fixture = std::string(font_fixture); + auto mapping = flutter::testing::OpenFixtureAsSkData(c_font_fixture.c_str()); + if (!mapping) { + return nullptr; + } + sk_sp font_mgr = txt::GetDefaultFontManager(); + SkFont sk_font(font_mgr->makeFromData(mapping), options.font_size); + if (options.is_subpixel) { + sk_font.setSubpixel(true); + } + auto blob = SkTextBlob::MakeFromString(text.c_str(), sk_font); + if (!blob) { + return nullptr; + } + + return MakeTextFrameFromTextBlobSkia(blob); +} + +std::shared_ptr CreateGlyphAtlas( + Context& context, + const TypographerContext* typographer_context, + HostBuffer& host_buffer, + GlyphAtlas::Type type, + Rational scale, + const std::shared_ptr& atlas_context, + const std::shared_ptr& frame, + Point offset) { + frame->SetPerFrameData( + TextFrame::RoundScaledFontSize(scale), /*offset=*/offset, + /*transform=*/ + Matrix::MakeScale( + Vector3{static_cast(scale), static_cast(scale), 1}), + /*properties=*/std::nullopt); + return typographer_context->CreateGlyphAtlas(context, type, host_buffer, + atlas_context, {frame}); +} + +Rect PerVertexDataPositionToRect( + std::vector::iterator + data) { + Scalar right = FLT_MIN; + Scalar left = FLT_MAX; + Scalar top = FLT_MAX; + Scalar bottom = FLT_MIN; + for (int i = 0; i < 4; ++i) { + right = std::max(right, data[i].position.x); + left = std::min(left, data[i].position.x); + top = std::min(top, data[i].position.y); + bottom = std::max(bottom, data[i].position.y); + } + + return Rect::MakeLTRB(left, top, right, bottom); +} + +Rect PerVertexDataUVToRect( + std::vector::iterator data, + ISize texture_size) { + Scalar right = FLT_MIN; + Scalar left = FLT_MAX; + Scalar top = FLT_MAX; + Scalar bottom = FLT_MIN; + for (int i = 0; i < 4; ++i) { + right = std::max(right, data[i].uv.x * texture_size.width); + left = std::min(left, data[i].uv.x * texture_size.width); + top = std::min(top, data[i].uv.y * texture_size.height); + bottom = std::max(bottom, data[i].uv.y * texture_size.height); + } + + return Rect::MakeLTRB(left, top, right, bottom); +} + +double GetAspectRatio(Rect rect) { + return static_cast(rect.GetWidth()) / rect.GetHeight(); +} +} // namespace + +TEST_P(TextContentsTest, SimpleComputeVertexData) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + + std::shared_ptr text_frame = + MakeTextFrame("1", "ahem.ttf", TextOptions{.font_size = 50}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, /*scale=*/Rational(1, 1), + atlas_context, text_frame, /*offset=*/{0, 0}); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData(data.data(), text_frame, /*scale=*/1.0, + /*entity_transform=*/Matrix(), + /*offset=*/Vector2(0, 0), + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + // The -1 offset comes from Skia in `ComputeGlyphSize`. So since the font size + // is 50, the math appears to be to get back a 50x50 rect and apply 1 pixel + // of padding. + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -41, 52, 52)); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 52, 52)); +} + +TEST_P(TextContentsTest, SimpleComputeVertexData2x) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + std::shared_ptr text_frame = + MakeTextFrame("1", "ahem.ttf", TextOptions{.font_size = 50}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + Rational font_scale(2, 1); + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, font_scale, + atlas_context, text_frame, /*offset=*/{0, 0}); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData( + data.data(), text_frame, static_cast(font_scale), + /*entity_transform=*/ + Matrix::MakeScale({static_cast(font_scale), + static_cast(font_scale), 1}), + /*offset=*/Vector2(0, 0), + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -81, 102, 102)); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 102, 102)); +} + +TEST_P(TextContentsTest, MaintainsShape) { + std::shared_ptr text_frame = + MakeTextFrame("th", "ahem.ttf", TextOptions{.font_size = 50}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + + for (int i = 0; i <= 1000; ++i) { + Rational font_scale(440 + i, 1000.0); + Rect position_rect[2]; + Rect uv_rect[2]; + + { + std::vector data(12); + + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, font_scale, + atlas_context, text_frame, /*offset=*/{0, 0}); + ISize texture_size = atlas->GetTexture()->GetSize(); + + TextContents::ComputeVertexData( + data.data(), text_frame, static_cast(font_scale), + /*entity_transform=*/ + Matrix::MakeScale({static_cast(font_scale), + static_cast(font_scale), 1}), + /*offset=*/Vector2(0, 0), + /*glyph_properties=*/std::nullopt, atlas); + position_rect[0] = PerVertexDataPositionToRect(data.begin()); + uv_rect[0] = PerVertexDataUVToRect(data.begin(), texture_size); + position_rect[1] = PerVertexDataPositionToRect(data.begin() + 4); + uv_rect[1] = PerVertexDataUVToRect(data.begin() + 4, texture_size); + } + EXPECT_NEAR(GetAspectRatio(position_rect[1]), GetAspectRatio(uv_rect[1]), + 0.001) + << i; + } +} + +TEST_P(TextContentsTest, SimpleSubpixel) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + + std::shared_ptr text_frame = MakeTextFrame( + "1", "ahem.ttf", TextOptions{.font_size = 50, .is_subpixel = true}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + Point offset = Point(0.5, 0); + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, /*scale=*/Rational(1), + atlas_context, text_frame, offset); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData( + data.data(), text_frame, /*scale=*/1.0, + /*entity_transform=*/Matrix::MakeTranslation(offset), offset, + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + // The values at Point(0, 0). + // EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -41, 52, 52)); + // EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 52, 52)); + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-2, -41, 54, 52)); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 54, 52)); +} + +TEST_P(TextContentsTest, SimpleSubpixel3x) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + + std::shared_ptr text_frame = MakeTextFrame( + "1", "ahem.ttf", TextOptions{.font_size = 50, .is_subpixel = true}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + Rational font_scale(3, 1); + Point offset = {0.16667, 0}; + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, font_scale, + atlas_context, text_frame, offset); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData( + data.data(), text_frame, static_cast(font_scale), + /*entity_transform=*/ + Matrix::MakeTranslation(offset) * + Matrix::MakeScale({static_cast(font_scale), + static_cast(font_scale), 1}), + offset, + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + // Values at Point(0, 0) + // EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -121, 152, 152)); + // EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 152, 152)); + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-2, -121, 154, 152)) + << "position size:" << position_rect.GetSize(); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 154, 152)) + << "position size:" << position_rect.GetSize(); +} + +TEST_P(TextContentsTest, SimpleSubpixel26) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + + std::shared_ptr text_frame = MakeTextFrame( + "1", "ahem.ttf", TextOptions{.font_size = 50, .is_subpixel = true}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + Point offset = Point(0.26, 0); + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, /*scale=*/Rational(1), + atlas_context, text_frame, offset); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData( + data.data(), text_frame, /*scale=*/1.0, + /*entity_transform=*/Matrix::MakeTranslation(offset), offset, + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + // The values without subpixel. + // EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -41, 52, 52)); + // EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 52, 52)); + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-2, -41, 54, 52)); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 54, 52)); +} + +TEST_P(TextContentsTest, SimpleSubpixel80) { +#ifndef FML_OS_MACOSX + GTEST_SKIP() << "Results aren't stable across linux and macos."; +#endif + + std::vector data(4); + + std::shared_ptr text_frame = MakeTextFrame( + "1", "ahem.ttf", TextOptions{.font_size = 50, .is_subpixel = true}); + + std::shared_ptr context = TypographerContextSkia::Make(); + std::shared_ptr atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + std::shared_ptr host_buffer = HostBuffer::Create( + GetContext()->GetResourceAllocator(), GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + Point offset = Point(0.80, 0); + std::shared_ptr atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, /*scale=*/Rational(1), + atlas_context, text_frame, offset); + + ISize texture_size = atlas->GetTexture()->GetSize(); + TextContents::ComputeVertexData( + data.data(), text_frame, /*scale=*/1.0, + /*entity_transform=*/Matrix::MakeTranslation(offset), offset, + /*glyph_properties=*/std::nullopt, atlas); + + Rect position_rect = PerVertexDataPositionToRect(data.begin()); + Rect uv_rect = PerVertexDataUVToRect(data.begin(), texture_size); + // The values without subpixel. + // EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-1, -41, 52, 52)); + // EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 52, 52)); + EXPECT_RECT_NEAR(position_rect, Rect::MakeXYWH(-2, -41, 54, 52)); + EXPECT_RECT_NEAR(uv_rect, Rect::MakeXYWH(1.0, 1.0, 54, 52)); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.cc b/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.cc new file mode 100644 index 0000000000000000000000000000000000000000..6902d1239c0934d585c83fe11f03600395d67d73 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.cc @@ -0,0 +1,95 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/text_shadow_cache.h" + +#include "fml/closure.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/filters/filter_contents.h" +#include "impeller/geometry/sigma.h" + +namespace impeller { + +// Rounds sigma values for gaussian blur to nearest decimal. +static constexpr int32_t kMaxSigmaDenominator = 10; + +TextShadowCache::TextShadowCacheKey::TextShadowCacheKey(Scalar p_max_basis, + int64_t p_identifier, + bool p_is_single_glyph, + const Font& p_font, + Sigma p_sigma) + : max_basis(p_max_basis), + identifier(p_identifier), + is_single_glyph(p_is_single_glyph), + font(p_font), + rounded_sigma(Rational(std::round(p_sigma.sigma * kMaxSigmaDenominator), + kMaxSigmaDenominator)) {} + +void TextShadowCache::MarkFrameStart() { + for (auto& entry : entries_) { + entry.second.used_this_frame = false; + } +} + +void TextShadowCache::MarkFrameEnd() { + absl::erase_if(entries_, + [](const auto& pair) { return !pair.second.used_this_frame; }); +} + +std::optional TextShadowCache::Lookup( + const ContentContext& renderer, + const Entity& entity, + const std::shared_ptr& contents, + const TextShadowCacheKey& text_key) { + auto it = entries_.find(text_key); + + if (it != entries_.end()) { + it->second.used_this_frame = true; + Entity cache_entity = it->second.entity.Clone(); + cache_entity.SetClipDepth(entity.GetClipDepth()); + cache_entity.SetTransform(entity.GetTransform() * it->second.key_matrix); + return cache_entity; + } + + std::optional filter_coverage = contents->GetCoverage(entity); + if (!filter_coverage.has_value()) { + return std::nullopt; + } + + // Execute the filter to produce a snapshot that can be resued on subsequent + // frames. To prevent this texture from being re-used by the render target + // cache, we temporarily disable any RT caching. + renderer.GetRenderTargetCache()->DisableCache(); + fml::ScopedCleanupClosure closure( + [&] { renderer.GetRenderTargetCache()->EnableCache(); }); + std::optional maybe_entity = + contents->GetEntity(renderer, entity, contents->GetCoverageHint()); + if (!maybe_entity.has_value()) { + return std::nullopt; + } + + // The original entity has a transform matrix A. The snapshot entity has a + // transform matrix B. We need a function that converts A to B, so that if we + // render an entity with a slightly different transform matrix A', it appears + // in the correct position. + // A * K = B + // A-1 * A * K = A-1 * B + // K = A-1 * B + // + // The transform matrix K can be computed by inverse A times B. Multiplying + // any subsequent entity transforms by this matrix will correctly position + // them. + Matrix key_matrix = + entity.GetTransform().Invert() * maybe_entity->GetTransform(); + entries_[text_key] = + TextShadowCacheData{.entity = maybe_entity.value().Clone(), + .used_this_frame = true, + .key_matrix = key_matrix}; + + maybe_entity->SetClipDepth(entity.GetClipDepth()); + return maybe_entity; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.h b/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..3e9168b6ccb38de7cd1bde7980a9717ff2ec319d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/text_shadow_cache.h @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_SHADOW_CACHE_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_SHADOW_CACHE_H_ + +#include +#include + +#include "flutter/third_party/abseil-cpp/absl/container/flat_hash_map.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/sigma.h" + +namespace impeller { + +/// @brief A cache for blurred text that re-uses these across frames. +/// +/// Text shadows are generally stable, but expensive to compute as we use a +/// full gaussian blur. This class caches these shadows by text blob identifier +/// and holds them for at least one frame. +/// +/// Additionally, there is an optimization for a single glyph (generally an +/// Icon) that uses the content itself as a key. +/// +/// If there was a cheaper method of text frame identity, or a per-glyph caching +/// system this could be more efficient. As it exists, this mostly ameliorate +/// severe performance degradation for glyph shadows but does not provide +/// substantially better performance than Skia. +class TextShadowCache { + public: + TextShadowCache() = default; + + ~TextShadowCache() = default; + + /// @brief A key to look up cached glyph textures. + struct TextShadowCacheKey { + Scalar max_basis; + int64_t identifier; + bool is_single_glyph; + Font font; + Rational rounded_sigma; + + TextShadowCacheKey(Scalar p_max_basis, + int64_t p_identifier, + bool p_is_single_glyph, + const Font& p_font, + Sigma p_sigma); + + struct Hash { + std::size_t operator()(const TextShadowCacheKey& key) const { + return fml::HashCombine(key.max_basis, key.identifier, + key.is_single_glyph, key.font.GetHash(), + key.rounded_sigma.GetHash()); + } + }; + + struct Equal { + constexpr bool operator()(const TextShadowCacheKey& lhs, + const TextShadowCacheKey& rhs) const { + return lhs.max_basis == rhs.max_basis && + lhs.identifier == rhs.identifier && + lhs.is_single_glyph == rhs.is_single_glyph && + lhs.font.IsEqual(rhs.font) && + lhs.rounded_sigma == rhs.rounded_sigma; + } + }; + }; + + /// @brief Mark all glyph textures as unused this frame. + void MarkFrameStart(); + + /// @brief Remove all glyph textures that were not referenced at least once. + void MarkFrameEnd(); + + /// @brief Lookup the entity in the cache with the given filter/text contents, + /// returning the new entity to render. + /// + /// If the entity is not present, render and place in the cache. + std::optional Lookup(const ContentContext& renderer, + const Entity& entity, + const std::shared_ptr& contents, + const TextShadowCacheKey&); + + // Visible for testing. + size_t GetCacheSizeForTesting() const { return entries_.size(); } + + private: + TextShadowCache(const TextShadowCache&) = delete; + + TextShadowCache& operator=(const TextShadowCache&) = delete; + + struct TextShadowCacheData { + Entity entity; + bool used_this_frame = true; + Matrix key_matrix; + }; + + absl::flat_hash_map + entries_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXT_SHADOW_CACHE_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..62c0aef8052b336bfb6e27ce696fa2875038d8ce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.cc @@ -0,0 +1,259 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/texture_contents.h" + +#include +#include +#include + +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/texture_fill.frag.h" +#include "impeller/entity/texture_fill.vert.h" +#include "impeller/entity/texture_fill_strict_src.frag.h" +#include "impeller/entity/tiled_texture_fill_external.frag.h" +#include "impeller/geometry/constants.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +TextureContents::TextureContents() = default; + +TextureContents::~TextureContents() = default; + +std::shared_ptr TextureContents::MakeRect(Rect destination) { + auto contents = std::make_shared(); + contents->destination_rect_ = destination; + return contents; +} + +void TextureContents::SetLabel(std::string_view label) { + label_ = label; +} + +void TextureContents::SetDestinationRect(Rect rect) { + destination_rect_ = rect; +} + +void TextureContents::SetTexture(std::shared_ptr texture) { + texture_ = std::move(texture); +} + +std::shared_ptr TextureContents::GetTexture() const { + return texture_; +} + +void TextureContents::SetOpacity(Scalar opacity) { + opacity_ = opacity; +} + +void TextureContents::SetStencilEnabled(bool enabled) { + stencil_enabled_ = enabled; +} + +void TextureContents::SetInheritedOpacity(Scalar opacity) { + inherited_opacity_ = opacity; +} + +Scalar TextureContents::GetOpacity() const { + return opacity_ * inherited_opacity_; +} + +std::optional TextureContents::GetCoverage(const Entity& entity) const { + if (GetOpacity() == 0) { + return std::nullopt; + } + return destination_rect_.TransformBounds(entity.GetTransform()); +}; + +std::optional TextureContents::RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + const std::optional& sampler_descriptor, + bool msaa_enabled, + int32_t mip_count, + std::string_view label) const { + // Passthrough textures that have simple rectangle paths and complete source + // rects. + auto bounds = destination_rect_; + auto opacity = GetOpacity(); + if (source_rect_ == Rect::MakeSize(texture_->GetSize()) && + (opacity >= 1 - kEhCloseEnough || defer_applying_opacity_)) { + auto scale = Vector2(bounds.GetSize() / Size(texture_->GetSize())); + return Snapshot{ + .texture = texture_, + .transform = entity.GetTransform() * + Matrix::MakeTranslation(bounds.GetOrigin()) * + Matrix::MakeScale(scale), + .sampler_descriptor = sampler_descriptor.value_or(sampler_descriptor_), + .opacity = opacity}; + } + return Contents::RenderToSnapshot( + renderer, // renderer + entity, // entity + std::nullopt, // coverage_limit + sampler_descriptor.value_or(sampler_descriptor_), // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/mip_count, + label); // label +} + +bool TextureContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VS = TextureFillVertexShader; + using FS = TextureFillFragmentShader; + using FSStrict = TextureFillStrictSrcFragmentShader; + + if (destination_rect_.IsEmpty() || source_rect_.IsEmpty() || + texture_ == nullptr || texture_->GetSize().IsEmpty()) { + return true; // Nothing to render. + } + +#ifdef IMPELLER_ENABLE_OPENGLES + using FSExternal = TiledTextureFillExternalFragmentShader; + bool is_external_texture = + texture_->GetTextureDescriptor().type == TextureType::kTextureExternalOES; +#endif // IMPELLER_ENABLE_OPENGLES + + auto texture_coords = + Rect::MakeSize(texture_->GetSize()).Project(source_rect_); + auto& host_buffer = renderer.GetTransientsBuffer(); + + std::array vertices = { + VS::PerVertexData{destination_rect_.GetLeftTop(), + texture_coords.GetLeftTop()}, + VS::PerVertexData{destination_rect_.GetRightTop(), + texture_coords.GetRightTop()}, + VS::PerVertexData{destination_rect_.GetLeftBottom(), + texture_coords.GetLeftBottom()}, + VS::PerVertexData{destination_rect_.GetRightBottom(), + texture_coords.GetRightBottom()}, + }; + auto vertex_buffer = CreateVertexBuffer(vertices, host_buffer); + + VS::FrameInfo frame_info; + frame_info.mvp = entity.GetShaderTransform(pass); + frame_info.texture_sampler_y_coord_scale = texture_->GetYCoordScale(); + +#ifdef IMPELLER_DEBUG + if (label_.empty()) { + pass.SetCommandLabel("Texture Fill"); + } else { + pass.SetCommandLabel("Texture Fill: " + label_); + } +#endif // IMPELLER_DEBUG + + auto pipeline_options = OptionsFromPassAndEntity(pass, entity); + if (!stencil_enabled_) { + pipeline_options.stencil_mode = ContentContextOptions::StencilMode::kIgnore; + } + pipeline_options.primitive_type = PrimitiveType::kTriangleStrip; + + pipeline_options.depth_write_enabled = + stencil_enabled_ && pipeline_options.blend_mode == BlendMode::kSrc; + +#ifdef IMPELLER_ENABLE_OPENGLES + if (is_external_texture) { + pass.SetPipeline( + renderer.GetTiledTextureExternalPipeline(pipeline_options)); + } else { + pass.SetPipeline( + strict_source_rect_enabled_ + ? renderer.GetTextureStrictSrcPipeline(pipeline_options) + : renderer.GetTexturePipeline(pipeline_options)); + } +#else + pass.SetPipeline(strict_source_rect_enabled_ + ? renderer.GetTextureStrictSrcPipeline(pipeline_options) + : renderer.GetTexturePipeline(pipeline_options)); +#endif // IMPELLER_ENABLE_OPENGLES + + pass.SetVertexBuffer(vertex_buffer); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + if (strict_source_rect_enabled_) { + // For a strict source rect, shrink the texture coordinate range by half a + // texel to ensure that linear filtering does not sample anything outside + // the source rect bounds. + auto strict_texture_coords = + Rect::MakeSize(texture_->GetSize()).Project(source_rect_.Expand(-0.5)); + + FSStrict::FragInfo frag_info; + frag_info.source_rect = Vector4(strict_texture_coords.GetLTRB()); + frag_info.alpha = GetOpacity(); + FSStrict::BindFragInfo(pass, host_buffer.EmplaceUniform((frag_info))); + FSStrict::BindTextureSampler( + pass, texture_, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_descriptor_)); +#ifdef IMPELLER_ENABLE_OPENGLES + } else if (is_external_texture) { + FSExternal::FragInfo frag_info; + frag_info.x_tile_mode = + static_cast(sampler_descriptor_.width_address_mode); + frag_info.y_tile_mode = + static_cast(sampler_descriptor_.height_address_mode); + frag_info.alpha = GetOpacity(); + FSExternal::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + SamplerDescriptor sampler_desc; + // OES_EGL_image_external states that only CLAMP_TO_EDGE is valid, so + // we emulate all other tile modes here by remapping the texture + // coordinates. + sampler_desc.width_address_mode = SamplerAddressMode::kClampToEdge; + sampler_desc.height_address_mode = SamplerAddressMode::kClampToEdge; + sampler_desc.min_filter = sampler_descriptor_.min_filter; + sampler_desc.mag_filter = sampler_descriptor_.mag_filter; + sampler_desc.mip_filter = MipFilter::kBase; + + FSExternal::BindSAMPLEREXTERNALOESTextureSampler( + pass, texture_, + renderer.GetContext()->GetSamplerLibrary()->GetSampler(sampler_desc)); +#endif // IMPELLER_ENABLE_OPENGLES + } else { + FS::FragInfo frag_info; + frag_info.alpha = GetOpacity(); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform((frag_info))); + FS::BindTextureSampler( + pass, texture_, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_descriptor_)); + } + return pass.Draw().ok(); +} + +void TextureContents::SetSourceRect(const Rect& source_rect) { + source_rect_ = source_rect; +} + +const Rect& TextureContents::GetSourceRect() const { + return source_rect_; +} + +void TextureContents::SetStrictSourceRect(bool strict) { + strict_source_rect_enabled_ = strict; +} + +bool TextureContents::GetStrictSourceRect() const { + return strict_source_rect_enabled_; +} + +void TextureContents::SetSamplerDescriptor(const SamplerDescriptor& desc) { + sampler_descriptor_ = desc; +} + +const SamplerDescriptor& TextureContents::GetSamplerDescriptor() const { + return sampler_descriptor_; +} + +void TextureContents::SetDeferApplyingOpacity(bool defer_applying_opacity) { + defer_applying_opacity_ = defer_applying_opacity; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..f57f531b1095e5cd4abde0d72cdd5cc0fd2fc792 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/texture_contents.h @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_ + +#include + +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/contents/contents.h" + +namespace impeller { + +class Texture; + +class TextureContents final : public Contents { + public: + TextureContents(); + + ~TextureContents() override; + + /// @brief A common case factory that marks the texture contents as having a + /// destination rectangle. In this situation, a subpass can be avoided + /// when image filters are applied. + static std::shared_ptr MakeRect(Rect destination); + + void SetLabel(std::string_view label); + + void SetDestinationRect(Rect rect); + + void SetTexture(std::shared_ptr texture); + + std::shared_ptr GetTexture() const; + + void SetSamplerDescriptor(const SamplerDescriptor& desc); + + const SamplerDescriptor& GetSamplerDescriptor() const; + + void SetSourceRect(const Rect& source_rect); + + const Rect& GetSourceRect() const; + + void SetStrictSourceRect(bool strict); + + bool GetStrictSourceRect() const; + + void SetOpacity(Scalar opacity); + + Scalar GetOpacity() const; + + void SetStencilEnabled(bool enabled); + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + std::optional RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit = std::nullopt, + const std::optional& sampler_descriptor = std::nullopt, + bool msaa_enabled = true, + int32_t mip_count = 1, + std::string_view label = "Texture Snapshot") const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Contents| + void SetInheritedOpacity(Scalar opacity) override; + + void SetDeferApplyingOpacity(bool defer_applying_opacity); + + private: + std::string label_; + + Rect destination_rect_; + bool stencil_enabled_ = true; + + std::shared_ptr texture_; + SamplerDescriptor sampler_descriptor_ = {}; + Rect source_rect_; + bool strict_source_rect_enabled_ = false; + Scalar opacity_ = 1.0f; + Scalar inherited_opacity_ = 1.0f; + bool defer_applying_opacity_ = false; + + TextureContents(const TextureContents&) = delete; + + TextureContents& operator=(const TextureContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TEXTURE_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..75263102adab7e60a5eb9a093fc067b3ecfa02d5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.cc @@ -0,0 +1,255 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/contents/tiled_texture_contents.h" + +#include "fml/logging.h" +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/tiled_texture_fill.frag.h" +#include "impeller/entity/tiled_texture_fill_external.frag.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +static std::optional TileModeToAddressMode( + Entity::TileMode tile_mode, + const Capabilities& capabilities) { + switch (tile_mode) { + case Entity::TileMode::kClamp: + return SamplerAddressMode::kClampToEdge; + break; + case Entity::TileMode::kMirror: + return SamplerAddressMode::kMirror; + break; + case Entity::TileMode::kRepeat: + return SamplerAddressMode::kRepeat; + break; + case Entity::TileMode::kDecal: + if (capabilities.SupportsDecalSamplerAddressMode()) { + return SamplerAddressMode::kDecal; + } + return std::nullopt; + } +} + +TiledTextureContents::TiledTextureContents() = default; + +TiledTextureContents::~TiledTextureContents() = default; + +void TiledTextureContents::SetTexture(std::shared_ptr texture) { + texture_ = std::move(texture); +} + +void TiledTextureContents::SetTileModes(Entity::TileMode x_tile_mode, + Entity::TileMode y_tile_mode) { + x_tile_mode_ = x_tile_mode; + y_tile_mode_ = y_tile_mode; +} + +void TiledTextureContents::SetSamplerDescriptor(const SamplerDescriptor& desc) { + sampler_descriptor_ = desc; +} + +void TiledTextureContents::SetColorFilter(ColorFilterProc color_filter) { + color_filter_ = std::move(color_filter); +} + +std::shared_ptr TiledTextureContents::CreateFilterTexture( + const ContentContext& renderer) const { + if (!color_filter_) { + return nullptr; + } + auto color_filter_contents = color_filter_(FilterInput::Make(texture_)); + auto snapshot = color_filter_contents->RenderToSnapshot( + renderer, // renderer + Entity(), // entity + std::nullopt, // coverage_limit + std::nullopt, // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/1, + "TiledTextureContents Snapshot"); // label + if (snapshot.has_value()) { + return snapshot.value().texture; + } + return nullptr; +} + +SamplerDescriptor TiledTextureContents::CreateSamplerDescriptor( + const Capabilities& capabilities) const { + SamplerDescriptor descriptor = sampler_descriptor_; + auto width_mode = TileModeToAddressMode(x_tile_mode_, capabilities); + auto height_mode = TileModeToAddressMode(y_tile_mode_, capabilities); + if (width_mode.has_value()) { + descriptor.width_address_mode = width_mode.value(); + } + if (height_mode.has_value()) { + descriptor.height_address_mode = height_mode.value(); + } + return descriptor; +} + +bool TiledTextureContents::UsesEmulatedTileMode( + const Capabilities& capabilities) const { + return !TileModeToAddressMode(x_tile_mode_, capabilities).has_value() || + !TileModeToAddressMode(y_tile_mode_, capabilities).has_value(); +} + +// |Contents| +bool TiledTextureContents::IsOpaque(const Matrix& transform) const { + if (GetOpacityFactor() < 1 || x_tile_mode_ == Entity::TileMode::kDecal || + y_tile_mode_ == Entity::TileMode::kDecal) { + return false; + } + if (color_filter_) { + return false; + } + return texture_->IsOpaque() && !AppliesAlphaForStrokeCoverage(transform); +} + +bool TiledTextureContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (texture_ == nullptr) { + return true; + } + + using VS = TextureUvFillVertexShader; + using FS = TiledTextureFillFragmentShader; + + const auto texture_size = texture_->GetSize(); + if (texture_size.IsEmpty()) { + return true; + } + + VS::FrameInfo frame_info; + frame_info.texture_sampler_y_coord_scale = texture_->GetYCoordScale(); + frame_info.uv_transform = + Rect::MakeSize(texture_size).GetNormalizingTransform() * + GetInverseEffectTransform(); + +#ifdef IMPELLER_ENABLE_OPENGLES + using FSExternal = TiledTextureFillExternalFragmentShader; + if (texture_->GetTextureDescriptor().type == + TextureType::kTextureExternalOES) { + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, + [&renderer](ContentContextOptions options) { + return renderer.GetTiledTextureUvExternalPipeline(options); + }, + frame_info, + [this, &renderer](RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("TextureFill External"); +#endif // IMPELLER_DEBUG + + FML_DCHECK(!color_filter_); + FSExternal::FragInfo frag_info; + frag_info.x_tile_mode = + static_cast(sampler_descriptor_.width_address_mode); + frag_info.y_tile_mode = + static_cast(sampler_descriptor_.height_address_mode); + frag_info.alpha = GetOpacityFactor(); + FSExternal::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + SamplerDescriptor sampler_desc; + // OES_EGL_image_external states that only CLAMP_TO_EDGE is valid, + // so we emulate all other tile modes here by remapping the texture + // coordinates. + sampler_desc.width_address_mode = SamplerAddressMode::kClampToEdge; + sampler_desc.height_address_mode = SamplerAddressMode::kClampToEdge; + sampler_desc.min_filter = sampler_descriptor_.min_filter; + sampler_desc.mag_filter = sampler_descriptor_.mag_filter; + sampler_desc.mip_filter = MipFilter::kBase; + + FSExternal::BindSAMPLEREXTERNALOESTextureSampler( + pass, texture_, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + sampler_desc)); + return true; + }); + } +#endif // IMPELLER_ENABLE_OPENGLES + + PipelineBuilderCallback pipeline_callback = + [&renderer](ContentContextOptions options) { + return renderer.GetTiledTexturePipeline(options); + }; + return ColorSourceContents::DrawGeometry( + renderer, entity, pass, pipeline_callback, frame_info, + [this, &renderer, &entity](RenderPass& pass) { + auto& host_buffer = renderer.GetTransientsBuffer(); +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel("TextureFill"); +#endif // IMPELLER_DEBUG + + FS::FragInfo frag_info; + frag_info.x_tile_mode = static_cast(x_tile_mode_); + frag_info.y_tile_mode = static_cast(y_tile_mode_); + frag_info.alpha = + GetOpacityFactor() * + GetGeometry()->ComputeAlphaCoverage(entity.GetTransform()); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + + if (color_filter_) { + auto filtered_texture = CreateFilterTexture(renderer); + if (!filtered_texture) { + return false; + } + FS::BindTextureSampler( + pass, filtered_texture, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + CreateSamplerDescriptor(renderer.GetDeviceCapabilities()))); + } else { + FS::BindTextureSampler( + pass, texture_, + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + CreateSamplerDescriptor(renderer.GetDeviceCapabilities()))); + } + + return true; + }); +} + +std::optional TiledTextureContents::RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit, + const std::optional& sampler_descriptor, + bool msaa_enabled, + int32_t mip_count, + std::string_view label) const { + std::optional geometry_coverage = GetGeometry()->GetCoverage({}); + if (GetInverseEffectTransform().IsIdentity() && + GetGeometry()->IsAxisAlignedRect() && + (!geometry_coverage.has_value() || + Rect::MakeSize(texture_->GetSize()) + .Contains(geometry_coverage.value()))) { + auto coverage = GetCoverage(entity); + if (!coverage.has_value()) { + return std::nullopt; + } + auto scale = Vector2(coverage->GetSize() / Size(texture_->GetSize())); + + return Snapshot{ + .texture = texture_, + .transform = Matrix::MakeTranslation(coverage->GetOrigin()) * + Matrix::MakeScale(scale), + .sampler_descriptor = sampler_descriptor.value_or(sampler_descriptor_), + .opacity = GetOpacityFactor(), + }; + } + + return Contents::RenderToSnapshot( + renderer, // renderer + entity, // entity + std::nullopt, // coverage_limit + sampler_descriptor.value_or(sampler_descriptor_), // sampler_descriptor + true, // msaa_enabled + /*mip_count=*/1, + label); // label +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..78ce93dc2dd7d60dc2aff6dbb28df3a557df354d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents.h @@ -0,0 +1,86 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_TILED_TEXTURE_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_TILED_TEXTURE_CONTENTS_H_ + +#include +#include + +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/contents/color_source_contents.h" +#include "impeller/entity/contents/filters/color_filter_contents.h" +#include "impeller/entity/entity.h" +#include "impeller/renderer/capabilities.h" + +namespace impeller { + +class TiledTextureContents final : public ColorSourceContents { + public: + TiledTextureContents(); + + ~TiledTextureContents() override; + + using ColorFilterProc = + std::function(FilterInput::Ref)>; + + // |Contents| + bool IsOpaque(const Matrix& transform) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + void SetTexture(std::shared_ptr texture); + + void SetTileModes(Entity::TileMode x_tile_mode, Entity::TileMode y_tile_mode); + + void SetSamplerDescriptor(const SamplerDescriptor& desc); + + /// @brief Set a color filter to apply directly to this tiled texture + /// @param color_filter + /// + /// When applying a color filter to a tiled texture, we can reduce the + /// size and number of the subpasses required and the shader workload by + /// applying the filter to the untiled image and absorbing the opacity before + /// tiling it into the final location. + /// + /// This may not be a performance improvement if the image is tiled into a + /// much smaller size that its original texture size. + void SetColorFilter(ColorFilterProc color_filter); + + // |Contents| + std::optional RenderToSnapshot( + const ContentContext& renderer, + const Entity& entity, + std::optional coverage_limit = std::nullopt, + const std::optional& sampler_descriptor = std::nullopt, + bool msaa_enabled = true, + int32_t mip_count = 1, + std::string_view label = "Tiled Texture Snapshot") const override; + + private: + std::shared_ptr CreateFilterTexture( + const ContentContext& renderer) const; + + SamplerDescriptor CreateSamplerDescriptor( + const Capabilities& capabilities) const; + + bool UsesEmulatedTileMode(const Capabilities& capabilities) const; + + std::shared_ptr texture_; + SamplerDescriptor sampler_descriptor_ = {}; + Entity::TileMode x_tile_mode_ = Entity::TileMode::kClamp; + Entity::TileMode y_tile_mode_ = Entity::TileMode::kClamp; + ColorFilterProc color_filter_ = nullptr; + + TiledTextureContents(const TiledTextureContents&) = delete; + + TiledTextureContents& operator=(const TiledTextureContents&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_TILED_TEXTURE_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents_unittests.cc b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff306e531d7841490fcbbcb48d0a57f8e2f1cb01 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/tiled_texture_contents_unittests.cc @@ -0,0 +1,104 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/entity/contents/test/recording_render_pass.h" +#include "impeller/entity/contents/texture_contents.h" +#include "impeller/entity/contents/tiled_texture_contents.h" +#include "impeller/entity/entity_playground.h" +#include "impeller/playground/playground_test.h" +#include "third_party/googletest/googletest/include/gtest/gtest.h" + +namespace impeller { +namespace testing { + +using EntityTest = EntityPlayground; + +TEST_P(EntityTest, TiledTextureContentsRendersWithCorrectPipeline) { + TextureDescriptor texture_desc; + texture_desc.size = {100, 100}; + texture_desc.type = TextureType::kTexture2D; + texture_desc.format = PixelFormat::kR8G8B8A8UNormInt; + texture_desc.storage_mode = StorageMode::kDevicePrivate; + auto texture = + GetContext()->GetResourceAllocator()->CreateTexture(texture_desc); + + auto geom = Geometry::MakeCover(); + TiledTextureContents contents; + contents.SetTexture(texture); + contents.SetGeometry(geom.get()); + + auto content_context = GetContentContext(); + auto buffer = content_context->GetContext()->CreateCommandBuffer(); + auto render_target = + GetContentContext()->GetRenderTargetCache()->CreateOffscreenMSAA( + *content_context->GetContext(), {100, 100}, + /*mip_count=*/1); + auto render_pass = buffer->CreateRenderPass(render_target); + auto recording_pass = std::make_shared( + render_pass, GetContext(), render_target); + + ASSERT_TRUE(contents.Render(*GetContentContext(), {}, *recording_pass)); + const std::vector& commands = recording_pass->GetCommands(); + + ASSERT_EQ(commands.size(), 1u); +#ifdef IMPELLER_DEBUG + EXPECT_TRUE(commands[0].pipeline->GetDescriptor().GetLabel().find( + "TextureFill Pipeline") != std::string::npos); +#endif // IMPELLER_DEBUG + auto options = OptionsFromPassAndEntity(*recording_pass, {}); + options.primitive_type = PrimitiveType::kTriangleStrip; + EXPECT_EQ(commands[0].pipeline, + GetContentContext()->GetTiledTexturePipeline(options)); + + if (GetParam() == PlaygroundBackend::kMetal) { + recording_pass->EncodeCommands(); + } +} + +// GL_OES_EGL_image_external isn't supported on MacOS hosts. +#if !defined(FML_OS_MACOSX) +TEST_P(EntityTest, TiledTextureContentsRendersWithCorrectPipelineExternalOES) { + if (GetParam() != PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() + << "External OES textures are only valid for the OpenGLES backend."; + } + + TextureDescriptor texture_desc; + texture_desc.size = {100, 100}; + texture_desc.type = TextureType::kTextureExternalOES; + texture_desc.format = PixelFormat::kR8G8B8A8UNormInt; + texture_desc.storage_mode = StorageMode::kDevicePrivate; + auto texture = + GetContext()->GetResourceAllocator()->CreateTexture(texture_desc); + auto contents = TextureContents::MakeRect(Rect::MakeSize(texture->GetSize())); + contents->SetTexture(texture); + contents->SetSourceRect(Rect::MakeSize(texture->GetSize())); + contents->SetStrictSourceRect(false); + + auto content_context = GetContentContext(); + auto buffer = content_context->GetContext()->CreateCommandBuffer(); + auto render_target = + GetContentContext()->GetRenderTargetCache()->CreateOffscreenMSAA( + *content_context->GetContext(), {100, 100}, + /*mip_count=*/1); + auto render_pass = buffer->CreateRenderPass(render_target); + + ASSERT_TRUE(contents->Render(*GetContentContext(), {}, *render_pass)); + const std::vector& commands = render_pass->GetCommands(); + + ASSERT_EQ(commands.size(), 1u); + + auto options = OptionsFromPassAndEntity(*render_pass, {}); + options.primitive_type = PrimitiveType::kTriangleStrip; + EXPECT_EQ(commands[0].pipeline, + GetContentContext()->GetTiledTextureExternalPipeline(options)); +} +#endif + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.cc b/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.cc new file mode 100644 index 0000000000000000000000000000000000000000..1e0d06d631460647a9f0a1c71f855a65b1a0777c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.cc @@ -0,0 +1,215 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "vertices_contents.h" + +#include "fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/contents/filters/blend_filter_contents.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/entity/geometry/vertices_geometry.h" +#include "impeller/geometry/color.h" +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +namespace { +static std::optional TileModeToAddressMode( + Entity::TileMode tile_mode, + const Capabilities& capabilities) { + switch (tile_mode) { + case Entity::TileMode::kClamp: + return SamplerAddressMode::kClampToEdge; + break; + case Entity::TileMode::kMirror: + return SamplerAddressMode::kMirror; + break; + case Entity::TileMode::kRepeat: + return SamplerAddressMode::kRepeat; + break; + case Entity::TileMode::kDecal: + if (capabilities.SupportsDecalSamplerAddressMode()) { + return SamplerAddressMode::kDecal; + } + return std::nullopt; + } +} +} // namespace + +//------------------------------------------------------ +// VerticesSimpleBlendContents + +VerticesSimpleBlendContents::VerticesSimpleBlendContents() {} + +VerticesSimpleBlendContents::~VerticesSimpleBlendContents() {} + +void VerticesSimpleBlendContents::SetGeometry( + std::shared_ptr geometry) { + geometry_ = std::move(geometry); +} + +void VerticesSimpleBlendContents::SetAlpha(Scalar alpha) { + alpha_ = alpha; +} + +void VerticesSimpleBlendContents::SetBlendMode(BlendMode blend_mode) { + blend_mode_ = blend_mode; +} + +void VerticesSimpleBlendContents::SetTexture(std::shared_ptr texture) { + texture_ = std::move(texture); +} + +std::optional VerticesSimpleBlendContents::GetCoverage( + const Entity& entity) const { + return geometry_->GetCoverage(entity.GetTransform()); +} + +void VerticesSimpleBlendContents::SetSamplerDescriptor( + const SamplerDescriptor& descriptor) { + descriptor_ = descriptor; +} + +void VerticesSimpleBlendContents::SetTileMode(Entity::TileMode tile_mode_x, + Entity::TileMode tile_mode_y) { + tile_mode_x_ = tile_mode_x; + tile_mode_y_ = tile_mode_y; +} + +void VerticesSimpleBlendContents::SetEffectTransform(Matrix transform) { + inverse_matrix_ = transform.Invert(); +} + +void VerticesSimpleBlendContents::SetLazyTexture( + const LazyTexture& lazy_texture) { + lazy_texture_ = lazy_texture; +} + +void VerticesSimpleBlendContents::SetLazyTextureCoverage(Rect rect) { + lazy_texture_coverage_ = rect; +} + +bool VerticesSimpleBlendContents::Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + FML_DCHECK(texture_ || lazy_texture_ || blend_mode_ == BlendMode::kDst); + BlendMode blend_mode = blend_mode_; + if (!geometry_->HasVertexColors()) { + blend_mode = BlendMode::kSrc; + } + + std::shared_ptr texture; + if (blend_mode != BlendMode::kDst) { + if (!texture_) { + texture = lazy_texture_(renderer); + } else { + texture = texture_; + } + } else { + texture = renderer.GetEmptyTexture(); + } + if (!texture) { + VALIDATION_LOG << "Missing texture for VerticesSimpleBlendContents"; + return false; + } + + auto dst_sampler_descriptor = descriptor_; + dst_sampler_descriptor.width_address_mode = + TileModeToAddressMode(tile_mode_x_, renderer.GetDeviceCapabilities()) + .value_or(SamplerAddressMode::kClampToEdge); + dst_sampler_descriptor.height_address_mode = + TileModeToAddressMode(tile_mode_y_, renderer.GetDeviceCapabilities()) + .value_or(SamplerAddressMode::kClampToEdge); + + raw_ptr dst_sampler = + renderer.GetContext()->GetSamplerLibrary()->GetSampler( + dst_sampler_descriptor); + + GeometryResult geometry_result = geometry_->GetPositionUVColorBuffer( + lazy_texture_coverage_.has_value() ? lazy_texture_coverage_.value() + : Rect::MakeSize(texture->GetSize()), + inverse_matrix_, renderer, entity, pass); + if (geometry_result.vertex_buffer.vertex_count == 0) { + return true; + } + FML_DCHECK(geometry_result.mode == GeometryResult::Mode::kNormal); + + if (blend_mode <= Entity::kLastPipelineBlendMode) { + using VS = PorterDuffBlendPipeline::VertexShader; + using FS = PorterDuffBlendPipeline::FragmentShader; + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(SPrintF("DrawVertices Porterduff Blend (%s)", + BlendModeToString(blend_mode))); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer)); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = geometry_result.type; + auto inverted_blend_mode = + InvertPorterDuffBlend(blend_mode).value_or(BlendMode::kSrc); + pass.SetPipeline( + renderer.GetPorterDuffPipeline(inverted_blend_mode, options)); + + FS::BindTextureSamplerDst(pass, texture, dst_sampler); + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + + frame_info.texture_sampler_y_coord_scale = texture->GetYCoordScale(); + frame_info.mvp = geometry_result.transform; + + frag_info.output_alpha = alpha_; + frag_info.input_alpha = 1.0; + + // These values are ignored if the platform supports native decal mode. + frag_info.tmx = static_cast(tile_mode_x_); + frag_info.tmy = static_cast(tile_mode_y_); + + auto& host_buffer = renderer.GetTransientsBuffer(); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); + } + + using VS = VerticesUber1Shader::VertexShader; + using FS = VerticesUber1Shader::FragmentShader; + +#ifdef IMPELLER_DEBUG + pass.SetCommandLabel(SPrintF("DrawVertices Advanced Blend (%s)", + BlendModeToString(blend_mode))); +#endif // IMPELLER_DEBUG + pass.SetVertexBuffer(std::move(geometry_result.vertex_buffer)); + + auto options = OptionsFromPassAndEntity(pass, entity); + options.primitive_type = geometry_result.type; + pass.SetPipeline(renderer.GetDrawVerticesUberPipeline(blend_mode, options)); + + FS::BindTextureSampler(pass, texture, dst_sampler); + + VS::FrameInfo frame_info; + FS::FragInfo frag_info; + + frame_info.texture_sampler_y_coord_scale = texture->GetYCoordScale(); + frame_info.mvp = geometry_result.transform; + frag_info.alpha = alpha_; + frag_info.blend_mode = static_cast(blend_mode); + + // These values are ignored if the platform supports native decal mode. + frag_info.tmx = static_cast(tile_mode_x_); + frag_info.tmy = static_cast(tile_mode_y_); + + auto& host_buffer = renderer.GetTransientsBuffer(); + FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); + VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); + + return pass.Draw().ok(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.h b/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..2de134ea5ed75f7703502638b00db97f73ff4756 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/contents/vertices_contents.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_CONTENTS_VERTICES_CONTENTS_H_ +#define FLUTTER_IMPELLER_ENTITY_CONTENTS_VERTICES_CONTENTS_H_ + +#include + +#include "impeller/core/sampler_descriptor.h" +#include "impeller/entity/contents/contents.h" +#include "impeller/entity/entity.h" +#include "impeller/entity/geometry/vertices_geometry.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +/// A vertices contents for (optional) per-color vertices + texture and any +/// blend mode. +class VerticesSimpleBlendContents final : public Contents { + public: + VerticesSimpleBlendContents(); + + ~VerticesSimpleBlendContents() override; + + using LazyTexture = + std::function(const ContentContext& renderer)>; + + void SetGeometry(std::shared_ptr geometry); + + void SetAlpha(Scalar alpha); + + void SetBlendMode(BlendMode blend_mode); + + void SetTexture(std::shared_ptr texture); + + void SetLazyTexture(const LazyTexture& lazy_texture); + + void SetSamplerDescriptor(const SamplerDescriptor& descriptor); + + void SetTileMode(Entity::TileMode tile_mode_x, Entity::TileMode tile_mode_y); + + void SetEffectTransform(Matrix transform); + + void SetLazyTextureCoverage(Rect rect); + + // |Contents| + std::optional GetCoverage(const Entity& entity) const override; + + // |Contents| + bool Render(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + private: + Scalar alpha_ = 1.0; + std::shared_ptr geometry_; + std::shared_ptr texture_; + BlendMode blend_mode_ = BlendMode::kSrc; + SamplerDescriptor descriptor_ = {}; + Entity::TileMode tile_mode_x_ = Entity::TileMode::kClamp; + Entity::TileMode tile_mode_y_ = Entity::TileMode::kClamp; + Matrix inverse_matrix_ = {}; + std::optional lazy_texture_coverage_; + LazyTexture lazy_texture_; + + VerticesSimpleBlendContents(const VerticesSimpleBlendContents&) = delete; + + VerticesSimpleBlendContents& operator=(const VerticesSimpleBlendContents&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_VERTICES_CONTENTS_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..8565f0f0d8c7f93bd90f0d797a0a2a473441fe44 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.cc @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/impeller/entity/geometry/circle_geometry.h" + +#include "flutter/impeller/entity/geometry/line_geometry.h" +#include "impeller/core/formats.h" +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +CircleGeometry::CircleGeometry(const Point& center, Scalar radius) + : center_(center), radius_(radius), stroke_width_(-1.0f) { + FML_DCHECK(radius >= 0); +} + +CircleGeometry::~CircleGeometry() = default; + +CircleGeometry::CircleGeometry(const Point& center, + Scalar radius, + Scalar stroke_width) + : center_(center), + radius_(radius), + stroke_width_(std::max(stroke_width, 0.0f)) { + FML_DCHECK(radius >= 0); + FML_DCHECK(stroke_width >= 0); +} + +// |Geometry| +Scalar CircleGeometry::ComputeAlphaCoverage(const Matrix& transform) const { + if (stroke_width_ < 0) { + return 1; + } + return Geometry::ComputeStrokeAlphaCoverage(transform, stroke_width_); +} + +GeometryResult CircleGeometry::GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& transform = entity.GetTransform(); + + Scalar half_width = stroke_width_ < 0 ? 0.0 + : LineGeometry::ComputePixelHalfWidth( + transform, stroke_width_); + + // We call the StrokedCircle method which will simplify to a + // FilledCircleGenerator if the inner_radius is <= 0. + auto generator = renderer.GetTessellator().StrokedCircle(transform, center_, + radius_, half_width); + + return ComputePositionGeometry(renderer, generator, entity, pass); +} + +std::optional CircleGeometry::GetCoverage(const Matrix& transform) const { + Point corners[4]{ + {center_.x, center_.y - radius_}, + {center_.x + radius_, center_.y}, + {center_.x, center_.y + radius_}, + {center_.x - radius_, center_.y}, + }; + + for (int i = 0; i < 4; i++) { + corners[i] = transform * corners[i]; + } + return Rect::MakePointBounds(std::begin(corners), std::end(corners)); +} + +bool CircleGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + return false; +} + +bool CircleGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..cbbef0d119ba644f6121d4b429e953317aa6b44d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/circle_geometry.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +// Geometry class that can generate vertices (with or without texture +// coordinates) for either filled or stroked circles +class CircleGeometry final : public Geometry { + public: + explicit CircleGeometry(const Point& center, Scalar radius); + + explicit CircleGeometry(const Point& center, + Scalar radius, + Scalar stroke_width); + + ~CircleGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + // |Geometry| + Scalar ComputeAlphaCoverage(const Matrix& transform) const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + Point center_; + Scalar radius_; + Scalar stroke_width_; + + CircleGeometry(const CircleGeometry&) = delete; + + CircleGeometry& operator=(const CircleGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_CIRCLE_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..6c38d28d494ff3dda731db43a0bbd6b2e2719ebb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.cc @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/cover_geometry.h" + +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +CoverGeometry::CoverGeometry() = default; + +GeometryResult CoverGeometry::GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto rect = Rect::MakeSize(pass.GetRenderTargetSize()); + constexpr uint16_t kRectIndicies[4] = {0, 1, 2, 3}; + auto& host_buffer = renderer.GetTransientsBuffer(); + return GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = host_buffer.Emplace( + rect.GetTransformedPoints(entity.GetTransform().Invert()) + .data(), + 8 * sizeof(float), alignof(float)), + .index_buffer = host_buffer.Emplace( + kRectIndicies, 4 * sizeof(uint16_t), alignof(uint16_t)), + .vertex_count = 4, + .index_type = IndexType::k16bit, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +std::optional CoverGeometry::GetCoverage(const Matrix& transform) const { + return Rect::MakeMaximum(); +} + +bool CoverGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + return true; +} + +bool CoverGeometry::CanApplyMaskFilter() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..4be6359acf9468d05498811f97551d5bdfb7da4e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/cover_geometry.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_COVER_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_COVER_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +/// @brief A geometry that implements "drawPaint" like behavior by covering +/// the entire render pass area. +class CoverGeometry final : public Geometry { + public: + CoverGeometry(); + + ~CoverGeometry() override = default; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + bool CanApplyMaskFilter() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + CoverGeometry(const CoverGeometry&) = delete; + + CoverGeometry& operator=(const CoverGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_COVER_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..71f3acec1426d1a4fd141561dda8c7db511bf7ef --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.cc @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/impeller/entity/geometry/ellipse_geometry.h" + +#include "flutter/impeller/entity/geometry/line_geometry.h" + +namespace impeller { + +EllipseGeometry::EllipseGeometry(Rect bounds) : bounds_(bounds) {} + +GeometryResult EllipseGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + return ComputePositionGeometry( + renderer, + renderer.GetTessellator().FilledEllipse(entity.GetTransform(), bounds_), + entity, pass); +} + +std::optional EllipseGeometry::GetCoverage( + const Matrix& transform) const { + return bounds_.TransformBounds(transform); +} + +bool EllipseGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + return false; +} + +bool EllipseGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..924727072d04825618cad12045cfab5c3ce3e46f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/ellipse_geometry.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_ELLIPSE_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_ELLIPSE_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +// Geometry class that can generate vertices (with or without texture +// coordinates) for filled ellipses. Generating vertices for a stroked +// ellipse would require a lot more work since the line width must be +// applied perpendicular to the distorted ellipse shape. +class EllipseGeometry final : public Geometry { + public: + explicit EllipseGeometry(Rect bounds); + + ~EllipseGeometry() override = default; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + Rect bounds_; + + EllipseGeometry(const EllipseGeometry&) = delete; + + EllipseGeometry& operator=(const EllipseGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_ELLIPSE_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..72937bf0538fd1bfae1a83d3647c73fcba5ae47a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.cc @@ -0,0 +1,94 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/fill_path_geometry.h" + +#include "fml/logging.h" +#include "impeller/core/formats.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +FillPathGeometry::FillPathGeometry(const Path& path, + std::optional inner_rect) + : path_(path), inner_rect_(inner_rect) {} + +FillPathGeometry::~FillPathGeometry() {} + +GeometryResult FillPathGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& host_buffer = renderer.GetTransientsBuffer(); + + const auto& bounding_box = path_.GetBoundingBox(); + if (bounding_box.has_value() && bounding_box->IsEmpty()) { + return GeometryResult{ + .type = PrimitiveType::kTriangle, + .vertex_buffer = + VertexBuffer{ + .vertex_buffer = {}, + .vertex_count = 0, + .index_type = IndexType::k16bit, + }, + .transform = pass.GetOrthographicTransform() * entity.GetTransform(), + }; + } + + bool supports_primitive_restart = + renderer.GetDeviceCapabilities().SupportsPrimitiveRestart(); + bool supports_triangle_fan = + renderer.GetDeviceCapabilities().SupportsTriangleFan() && + supports_primitive_restart; + VertexBuffer vertex_buffer = renderer.GetTessellator().TessellateConvex( + path_, host_buffer, entity.GetTransform().GetMaxBasisLengthXY(), + /*supports_primitive_restart=*/supports_primitive_restart, + /*supports_triangle_fan=*/supports_triangle_fan); + + return GeometryResult{ + .type = supports_triangle_fan ? PrimitiveType::kTriangleFan + : PrimitiveType::kTriangleStrip, + .vertex_buffer = std::move(vertex_buffer), + .transform = entity.GetShaderTransform(pass), + .mode = GetResultMode(), + }; +} + +GeometryResult::Mode FillPathGeometry::GetResultMode() const { + const auto& bounding_box = path_.GetBoundingBox(); + if (path_.IsConvex() || + (bounding_box.has_value() && bounding_box->IsEmpty())) { + return GeometryResult::Mode::kNormal; + } + + switch (path_.GetFillType()) { + case FillType::kNonZero: + return GeometryResult::Mode::kNonZero; + case FillType::kOdd: + return GeometryResult::Mode::kEvenOdd; + } + + FML_UNREACHABLE(); +} + +std::optional FillPathGeometry::GetCoverage( + const Matrix& transform) const { + return path_.GetTransformedBoundingBox(transform); +} + +bool FillPathGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + if (!inner_rect_.has_value()) { + return false; + } + if (!transform.IsTranslationScaleOnly()) { + return false; + } + Rect coverage = inner_rect_->TransformBounds(transform); + return coverage.Contains(rect); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..7b930d0557f3ca726ab9ae76f2fe4cc4cbb16d9b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/fill_path_geometry.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_FILL_PATH_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_FILL_PATH_GEOMETRY_H_ + +#include + +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +/// @brief A geometry that is created from a filled path object. +class FillPathGeometry final : public Geometry { + public: + explicit FillPathGeometry(const Path& path, + std::optional inner_rect = std::nullopt); + + ~FillPathGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + // |Geometry| + GeometryResult::Mode GetResultMode() const override; + + Path path_; + std::optional inner_rect_; + + FillPathGeometry(const FillPathGeometry&) = delete; + + FillPathGeometry& operator=(const FillPathGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_FILL_PATH_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca0c4bfb07715d398db39d8c4eeab69f8550a7b6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/geometry.cc @@ -0,0 +1,144 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/geometry.h" + +#include +#include + +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/circle_geometry.h" +#include "impeller/entity/geometry/cover_geometry.h" +#include "impeller/entity/geometry/ellipse_geometry.h" +#include "impeller/entity/geometry/fill_path_geometry.h" +#include "impeller/entity/geometry/line_geometry.h" +#include "impeller/entity/geometry/rect_geometry.h" +#include "impeller/entity/geometry/round_rect_geometry.h" +#include "impeller/entity/geometry/round_superellipse_geometry.h" +#include "impeller/entity/geometry/stroke_path_geometry.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +GeometryResult Geometry::ComputePositionGeometry( + const ContentContext& renderer, + const Tessellator::VertexGenerator& generator, + const Entity& entity, + RenderPass& pass) { + using VT = SolidFillVertexShader::PerVertexData; + + size_t count = generator.GetVertexCount(); + + return GeometryResult{ + .type = generator.GetTriangleType(), + .vertex_buffer = + { + .vertex_buffer = renderer.GetTransientsBuffer().Emplace( + count * sizeof(VT), alignof(VT), + [&generator](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + generator.GenerateVertices([&vertices](const Point& p) { + *vertices++ = { + .position = p, + }; + }); + FML_DCHECK(vertices == reinterpret_cast(buffer) + + generator.GetVertexCount()); + }), + .vertex_count = count, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +GeometryResult::Mode Geometry::GetResultMode() const { + return GeometryResult::Mode::kNormal; +} + +std::unique_ptr Geometry::MakeFillPath( + const Path& path, + std::optional inner_rect) { + return std::make_unique(path, inner_rect); +} + +std::unique_ptr Geometry::MakeStrokePath(const Path& path, + Scalar stroke_width, + Scalar miter_limit, + Cap stroke_cap, + Join stroke_join) { + // Skia behaves like this. + if (miter_limit < 0) { + miter_limit = 4.0; + } + return std::make_unique(path, stroke_width, miter_limit, + stroke_cap, stroke_join); +} + +std::unique_ptr Geometry::MakeCover() { + return std::make_unique(); +} + +std::unique_ptr Geometry::MakeRect(const Rect& rect) { + return std::make_unique(rect); +} + +std::unique_ptr Geometry::MakeOval(const Rect& rect) { + return std::make_unique(rect); +} + +std::unique_ptr Geometry::MakeLine(const Point& p0, + const Point& p1, + Scalar width, + Cap cap) { + return std::make_unique(p0, p1, width, cap); +} + +std::unique_ptr Geometry::MakeCircle(const Point& center, + Scalar radius) { + return std::make_unique(center, radius); +} + +std::unique_ptr Geometry::MakeStrokedCircle(const Point& center, + Scalar radius, + Scalar stroke_width) { + return std::make_unique(center, radius, stroke_width); +} + +std::unique_ptr Geometry::MakeRoundRect(const Rect& rect, + const Size& radii) { + return std::make_unique(rect, radii); +} + +std::unique_ptr Geometry::MakeRoundSuperellipse( + const Rect& rect, + Scalar corner_radius) { + return std::make_unique(rect, corner_radius); +} + +bool Geometry::CoversArea(const Matrix& transform, const Rect& rect) const { + return false; +} + +bool Geometry::IsAxisAlignedRect() const { + return false; +} + +bool Geometry::CanApplyMaskFilter() const { + return true; +} + +// static +Scalar Geometry::ComputeStrokeAlphaCoverage(const Matrix& transform, + Scalar stroke_width) { + Scalar scaled_stroke_width = transform.GetMaxBasisLengthXY() * stroke_width; + if (scaled_stroke_width == 0.0 || scaled_stroke_width >= kMinStrokeSize) { + return 1.0; + } + // This scalling is eyeballed from Skia. + return std::clamp(scaled_stroke_width * 2.0f, 0.f, 1.f); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..27a14452fefcce9191e5a4894e67648436200754 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/geometry.h @@ -0,0 +1,131 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_ + +#include "impeller/core/formats.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/entity.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +class Tessellator; + +static constexpr Scalar kMinStrokeSize = 1.0f; + +struct GeometryResult { + enum class Mode { + /// The geometry has no overlapping triangles. + kNormal, + /// The geometry may have overlapping triangles. The geometry should be + /// stenciled with the NonZero fill rule. + kNonZero, + /// The geometry may have overlapping triangles. The geometry should be + /// stenciled with the EvenOdd fill rule. + kEvenOdd, + /// The geometry may have overlapping triangles, but they should not + /// overdraw or cancel each other out. This is a special case for stroke + /// geometry. + kPreventOverdraw, + }; + + PrimitiveType type = PrimitiveType::kTriangleStrip; + VertexBuffer vertex_buffer; + Matrix transform; + Mode mode = Mode::kNormal; +}; + +static const GeometryResult kEmptyResult = { + .vertex_buffer = + { + .index_type = IndexType::kNone, + }, +}; + +class Geometry { + public: + virtual ~Geometry() {} + + static std::unique_ptr MakeFillPath( + const Path& path, + std::optional inner_rect = std::nullopt); + + static std::unique_ptr MakeStrokePath( + const Path& path, + Scalar stroke_width = 0.0, + Scalar miter_limit = 4.0, + Cap stroke_cap = Cap::kButt, + Join stroke_join = Join::kMiter); + + static std::unique_ptr MakeCover(); + + static std::unique_ptr MakeRect(const Rect& rect); + + static std::unique_ptr MakeOval(const Rect& rect); + + static std::unique_ptr MakeLine(const Point& p0, + const Point& p1, + Scalar width, + Cap cap); + + static std::unique_ptr MakeCircle(const Point& center, + Scalar radius); + + static std::unique_ptr MakeStrokedCircle(const Point& center, + Scalar radius, + Scalar stroke_width); + + static std::unique_ptr MakeRoundRect(const Rect& rect, + const Size& radii); + + static std::unique_ptr MakeRoundSuperellipse(const Rect& rect, + Scalar corner_radius); + + virtual GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const = 0; + + virtual GeometryResult::Mode GetResultMode() const; + + virtual std::optional GetCoverage(const Matrix& transform) const = 0; + + /// @brief Compute an alpha value to simulate lower coverage of fractional + /// pixel strokes. + static Scalar ComputeStrokeAlphaCoverage(const Matrix& entity, + Scalar stroke_width); + + /// @brief Determines if this geometry, transformed by the given + /// `transform`, will completely cover all surface area of the given + /// `rect`. + /// + /// This is a conservative estimate useful for certain + /// optimizations. + /// + /// @returns `true` if the transformed geometry is guaranteed to cover the + /// given `rect`. May return `false` in many undetected cases where + /// the transformed geometry does in fact cover the `rect`. + virtual bool CoversArea(const Matrix& transform, const Rect& rect) const; + + virtual bool IsAxisAlignedRect() const; + + virtual bool CanApplyMaskFilter() const; + + virtual Scalar ComputeAlphaCoverage(const Matrix& transform) const { + return 1.0; + } + + static GeometryResult ComputePositionGeometry( + const ContentContext& renderer, + const Tessellator::VertexGenerator& generator, + const Entity& entity, + RenderPass& pass); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/geometry_unittests.cc b/flutter/engine/src/flutter/impeller/entity/geometry/geometry_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d2bc907c72dc3a7f795e6d6446bd6bab07cf9e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/geometry_unittests.cc @@ -0,0 +1,157 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/entity/contents/content_context.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/entity/geometry/stroke_path_geometry.h" +#include "impeller/geometry/constants.h" +#include "impeller/geometry/geometry_asserts.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/renderer/testing/mocks.h" + +inline ::testing::AssertionResult SolidVerticesNear( + std::vector a, + std::vector b) { + if (a.size() != b.size()) { + return ::testing::AssertionFailure() << "Colors length does not match"; + } + for (auto i = 0u; i < b.size(); i++) { + if (!PointNear(a[i], b[i])) { + return ::testing::AssertionFailure() << "Positions are not equal."; + } + } + return ::testing::AssertionSuccess(); +} + +inline ::testing::AssertionResult TextureVerticesNear( + std::vector a, + std::vector b) { + if (a.size() != b.size()) { + return ::testing::AssertionFailure() << "Colors length does not match"; + } + for (auto i = 0u; i < b.size(); i++) { + if (!PointNear(a[i].position, b[i].position)) { + return ::testing::AssertionFailure() << "Positions are not equal."; + } + if (!PointNear(a[i].texture_coords, b[i].texture_coords)) { + return ::testing::AssertionFailure() << "Texture coords are not equal."; + } + } + return ::testing::AssertionSuccess(); +} + +#define EXPECT_SOLID_VERTICES_NEAR(a, b) \ + EXPECT_PRED2(&::SolidVerticesNear, a, b) +#define EXPECT_TEXTURE_VERTICES_NEAR(a, b) \ + EXPECT_PRED2(&::TextureVerticesNear, a, b) + +namespace impeller { + +class ImpellerEntityUnitTestAccessor { + public: + static std::vector GenerateSolidStrokeVertices( + const Path::Polyline& polyline, + Scalar stroke_width, + Scalar miter_limit, + Join stroke_join, + Cap stroke_cap, + Scalar scale) { + return StrokePathGeometry::GenerateSolidStrokeVertices( + polyline, stroke_width, miter_limit, stroke_join, stroke_cap, scale); + } +}; + +namespace testing { + +TEST(EntityGeometryTest, RectGeometryCoversArea) { + auto geometry = Geometry::MakeRect(Rect::MakeLTRB(0, 0, 100, 100)); + ASSERT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(0, 0, 100, 100))); + ASSERT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(-1, 0, 100, 100))); + ASSERT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(1, 1, 100, 100))); + ASSERT_TRUE(geometry->CoversArea({}, Rect())); +} + +TEST(EntityGeometryTest, FillPathGeometryCoversArea) { + auto path = PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath(); + auto geometry = Geometry::MakeFillPath( + path, /* inner rect */ Rect::MakeLTRB(0, 0, 100, 100)); + ASSERT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(0, 0, 100, 100))); + ASSERT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(-1, 0, 100, 100))); + ASSERT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(1, 1, 100, 100))); + ASSERT_TRUE(geometry->CoversArea({}, Rect())); +} + +TEST(EntityGeometryTest, FillPathGeometryCoversAreaNoInnerRect) { + auto path = PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath(); + auto geometry = Geometry::MakeFillPath(path); + ASSERT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(0, 0, 100, 100))); + ASSERT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(-1, 0, 100, 100))); + ASSERT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(1, 1, 100, 100))); + ASSERT_FALSE(geometry->CoversArea({}, Rect())); +} + +TEST(EntityGeometryTest, LineGeometryCoverage) { + { + auto geometry = Geometry::MakeLine({10, 10}, {20, 10}, 2, Cap::kButt); + EXPECT_EQ(geometry->GetCoverage({}), Rect::MakeLTRB(10, 9, 20, 11)); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(10, 9, 20, 11))); + } + + { + auto geometry = Geometry::MakeLine({10, 10}, {20, 10}, 2, Cap::kSquare); + EXPECT_EQ(geometry->GetCoverage({}), Rect::MakeLTRB(9, 9, 21, 11)); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(9, 9, 21, 11))); + } + + { + auto geometry = Geometry::MakeLine({10, 10}, {10, 20}, 2, Cap::kButt); + EXPECT_EQ(geometry->GetCoverage({}), Rect::MakeLTRB(9, 10, 11, 20)); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(9, 10, 11, 20))); + } + + { + auto geometry = Geometry::MakeLine({10, 10}, {10, 20}, 2, Cap::kSquare); + EXPECT_EQ(geometry->GetCoverage({}), Rect::MakeLTRB(9, 9, 11, 21)); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(9, 9, 11, 21))); + } +} + +TEST(EntityGeometryTest, RoundRectGeometryCoversArea) { + auto geometry = + Geometry::MakeRoundRect(Rect::MakeLTRB(0, 0, 100, 100), Size(20, 20)); + EXPECT_FALSE(geometry->CoversArea({}, Rect::MakeLTRB(15, 15, 85, 85))); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(20, 20, 80, 80))); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(30, 1, 70, 99))); + EXPECT_TRUE(geometry->CoversArea({}, Rect::MakeLTRB(1, 30, 99, 70))); +} + +TEST(EntityGeometryTest, GeometryResultHasReasonableDefaults) { + GeometryResult result; + EXPECT_EQ(result.type, PrimitiveType::kTriangleStrip); + EXPECT_EQ(result.transform, Matrix()); + EXPECT_EQ(result.mode, GeometryResult::Mode::kNormal); +} + +TEST(EntityGeometryTest, AlphaCoverageStrokePaths) { + auto matrix = Matrix::MakeScale(Vector2{3.0, 3.0}); + EXPECT_EQ(Geometry::MakeStrokePath({}, 0.5)->ComputeAlphaCoverage(matrix), 1); + EXPECT_NEAR(Geometry::MakeStrokePath({}, 0.1)->ComputeAlphaCoverage(matrix), + 0.6, 0.05); + EXPECT_NEAR(Geometry::MakeStrokePath({}, 0.05)->ComputeAlphaCoverage(matrix), + 0.3, 0.05); + EXPECT_NEAR(Geometry::MakeStrokePath({}, 0.01)->ComputeAlphaCoverage(matrix), + 0.1, 0.1); + EXPECT_NEAR( + Geometry::MakeStrokePath({}, 0.0000005)->ComputeAlphaCoverage(matrix), + 1e-05, 0.001); + EXPECT_EQ(Geometry::MakeStrokePath({}, 0)->ComputeAlphaCoverage(matrix), 1); + EXPECT_EQ(Geometry::MakeStrokePath({}, 40)->ComputeAlphaCoverage(matrix), 1); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..2553e6e2ca4494bdaeddfcdc7efa805e45db06b0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.cc @@ -0,0 +1,182 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/line_geometry.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +LineGeometry::LineGeometry(Point p0, Point p1, Scalar width, Cap cap) + : p0_(p0), p1_(p1), width_(width), cap_(cap) { + FML_DCHECK(width >= 0); +} + +LineGeometry::~LineGeometry() = default; + +Scalar LineGeometry::ComputePixelHalfWidth(const Matrix& transform, + Scalar width) { + Scalar max_basis = transform.GetMaxBasisLengthXY(); + if (max_basis == 0) { + return {}; + } + + Scalar min_size = kMinStrokeSize / max_basis; + return std::max(width, min_size) * 0.5f; +} + +Vector2 LineGeometry::ComputeAlongVector(const Matrix& transform, + bool allow_zero_length, + Point p0, + Point p1, + Scalar width) { + Scalar stroke_half_width = ComputePixelHalfWidth(transform, width); + if (stroke_half_width < kEhCloseEnough) { + return {}; + } + + auto along = p1 - p0; + Scalar length = along.GetLength(); + if (length < kEhCloseEnough) { + if (!allow_zero_length) { + // We won't enclose any pixels unless the endpoints are extended + return {}; + } + return {stroke_half_width, 0}; + } else { + return along * stroke_half_width / length; + } +} + +bool LineGeometry::ComputeCorners(Point corners[4], + const Matrix& transform, + bool extend_endpoints, + Point p0, + Point p1, + Scalar width) { + auto along = ComputeAlongVector(transform, extend_endpoints, p0, p1, width); + if (along.IsZero()) { + return false; + } + + auto across = Vector2(along.y, -along.x); + corners[0] = p0 - across; + corners[1] = p1 - across; + corners[2] = p0 + across; + corners[3] = p1 + across; + if (extend_endpoints) { + corners[0] -= along; + corners[1] += along; + corners[2] -= along; + corners[3] += along; + } + return true; +} + +Scalar LineGeometry::ComputeAlphaCoverage(const Matrix& entity) const { + return Geometry::ComputeStrokeAlphaCoverage(entity, width_); +} + +namespace { +/// Minimizes the err when rounding to the closest 0.5 value. +/// If we round up, it drops down a half. If we round down it bumps up a half. +Scalar RoundToHalf(Scalar x) { + Scalar whole; + std::modf(x, &whole); + return whole + 0.5; +} +} // namespace + +GeometryResult LineGeometry::GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + using VT = SolidFillVertexShader::PerVertexData; + + Matrix transform = entity.GetTransform(); + auto radius = ComputePixelHalfWidth(transform, width_); + + Point p0 = p0_; + Point p1 = p1_; + + // Hairline pixel alignment. + if (width_ == 0.f && transform.IsTranslationScaleOnly()) { + p0 = transform * p0_; + p1 = transform * p1_; + transform = Matrix(); + if (std::fabs(p0.x - p1.x) < kEhCloseEnough) { + p0.x = RoundToHalf(p0.x); + p1.x = p0.x; + } else if (std::fabs(p0.y - p1.y) < kEhCloseEnough) { + p0.y = RoundToHalf(p0.y); + p1.y = p0.y; + } + } + + Entity fixed_transform = entity.Clone(); + fixed_transform.SetTransform(transform); + + if (cap_ == Cap::kRound) { + auto generator = + renderer.GetTessellator().RoundCapLine(transform, p0, p1, radius); + return ComputePositionGeometry(renderer, generator, fixed_transform, pass); + } + + Point corners[4]; + if (!ComputeCorners(corners, transform, cap_ == Cap::kSquare, p0, p1, + width_)) { + return kEmptyResult; + } + + auto& host_buffer = renderer.GetTransientsBuffer(); + + size_t count = 4; + BufferView vertex_buffer = host_buffer.Emplace( + count * sizeof(VT), alignof(VT), [&corners](uint8_t* buffer) { + auto vertices = reinterpret_cast(buffer); + for (auto& corner : corners) { + *vertices++ = { + .position = corner, + }; + } + }); + + return GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = vertex_buffer, + .vertex_count = count, + .index_type = IndexType::kNone, + }, + .transform = fixed_transform.GetShaderTransform(pass), + }; +} + +std::optional LineGeometry::GetCoverage(const Matrix& transform) const { + Point corners[4]; + // Note: MSAA boolean doesn't matter for coverage computation. + if (!ComputeCorners(corners, transform, cap_ != Cap::kButt, p0_, p1_, + width_)) { + return {}; + } + + for (int i = 0; i < 4; i++) { + corners[i] = transform * corners[i]; + } + return Rect::MakePointBounds(std::begin(corners), std::end(corners)); +} + +bool LineGeometry::CoversArea(const Matrix& transform, const Rect& rect) const { + if (!transform.IsTranslationScaleOnly() || !IsAxisAlignedRect()) { + return false; + } + auto coverage = GetCoverage(transform); + return coverage.has_value() ? coverage->Contains(rect) : false; +} + +bool LineGeometry::IsAxisAlignedRect() const { + return cap_ != Cap::kRound && (p0_.x == p1_.x || p0_.y == p1_.y); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..3eac8e90fb1f006a55bae61bc4f40167d904a44d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/line_geometry.h @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_LINE_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_LINE_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +class LineGeometry final : public Geometry { + public: + explicit LineGeometry(Point p0, Point p1, Scalar width, Cap cap); + + ~LineGeometry() override; + + static Scalar ComputePixelHalfWidth(const Matrix& transform, Scalar width); + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + Scalar ComputeAlphaCoverage(const Matrix& transform) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + Point GetP0() const { return p0_; } + Point GetP1() const { return p1_; } + Scalar GetWidth() const { return width_; } + Cap GetCap() const { return cap_; } + + static Vector2 ComputeAlongVector(const Matrix& transform, + bool allow_zero_length, + Point p0, + Point p1, + Scalar width); + + // Computes the 4 corners of a rectangle that defines the line and + // possibly extended endpoints which will be rendered under the given + // transform, and returns true if such a rectangle is defined. + // + // The coordinates will be generated in the original coordinate system + // of the line end points and the transform will only be used to determine + // the minimum line width. + // + // For kButt and kSquare end caps the ends should always be exteded as + // per that decoration, but for kRound caps the ends might be extended + // if the goal is to get a conservative bounds and might not be extended + // if the calling code is planning to draw the round caps on the ends. + // + // @return true if the transform and width were not degenerate + static bool ComputeCorners(Point corners[4], + const Matrix& transform, + bool extend_endpoints, + Point p0, + Point p1, + Scalar width); + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + Point p0_; + Point p1_; + Scalar width_; + Cap cap_; + + LineGeometry(const LineGeometry&) = delete; + + LineGeometry& operator=(const LineGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_LINE_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..35c1f416fe92a99b699c36e3a4ec4073958dcb50 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.cc @@ -0,0 +1,157 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/point_field_geometry.h" + +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +PointFieldGeometry::PointFieldGeometry(const Point* points, + size_t point_count, + Scalar radius, + bool round) + : point_count_(point_count), + radius_(radius), + round_(round), + points_(points) {} + +PointFieldGeometry::~PointFieldGeometry() = default; + +GeometryResult PointFieldGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (radius_ < 0.0 || point_count_ == 0) { + return {}; + } + const Matrix& transform = entity.GetTransform(); + Scalar max_basis = transform.GetMaxBasisLengthXY(); + if (max_basis == 0) { + return {}; + } + + Scalar min_size = 0.5f / max_basis; + Scalar radius = std::max(radius_, min_size); + HostBuffer& host_buffer = renderer.GetTransientsBuffer(); + BufferView buffer_view; + size_t vertex_count = 0; + + if (round_) { + // Get triangulation relative to {0, 0} so we can translate it to each + // point in turn. + Tessellator::EllipticalVertexGenerator generator = + renderer.GetTessellator().FilledCircle(transform, {}, radius); + FML_DCHECK(generator.GetTriangleType() == PrimitiveType::kTriangleStrip); + + std::vector circle_vertices; + circle_vertices.reserve(generator.GetVertexCount()); + generator.GenerateVertices([&circle_vertices](const Point& p) { // + circle_vertices.push_back(p); + }); + FML_DCHECK(circle_vertices.size() == generator.GetVertexCount()); + + vertex_count = (circle_vertices.size() + 2) * point_count_ - 2; + buffer_view = host_buffer.Emplace( + vertex_count * sizeof(Point), alignof(Point), [&](uint8_t* data) { + Point* output = reinterpret_cast(data); + size_t offset = 0; + + Point center = points_[0]; + for (auto& vertex : circle_vertices) { + output[offset++] = static_cast(center + vertex); + } + // For all subequent points, insert a degenerate triangle to break + // the strip. This could be optimized out if we switched to using + // primitive restart. + Point last_point = circle_vertices.back() + center; + for (size_t i = 1; i < point_count_; i++) { + Point center = points_[i]; + output[offset++] = last_point; + output[offset++] = static_cast(center + circle_vertices[0]); + for (const Point& vertex : circle_vertices) { + output[offset++] = static_cast(center + vertex); + } + last_point = circle_vertices.back() + center; + } + }); + } else { + vertex_count = 6 * point_count_ - 2; + buffer_view = host_buffer.Emplace( + vertex_count * sizeof(Point), alignof(Point), [&](uint8_t* data) { + Point* output = reinterpret_cast(data); + size_t offset = 0; + + Point point = points_[0]; + Point first = Point(point.x - radius, point.y - radius); + + // Z pattern from UL -> UR -> LL -> LR + Point last_point = Point(0, 0); + output[offset++] = first; + output[offset++] = Point(point.x + radius, point.y - radius); + output[offset++] = Point(point.x - radius, point.y + radius); + output[offset++] = last_point = + Point(point.x + radius, point.y + radius); + + // For all subequent points, insert a degenerate triangle to break + // the strip. This could be optimized out if we switched to using + // primitive restart. + for (size_t i = 1; i < point_count_; i++) { + Point point = points_[i]; + Point first = Point(point.x - radius, point.y - radius); + + output[offset++] = last_point; + output[offset++] = first; + + output[offset++] = first; + output[offset++] = Point(point.x + radius, point.y - radius); + output[offset++] = Point(point.x - radius, point.y + radius); + output[offset++] = last_point = + Point(point.x + radius, point.y + radius); + } + }); + } + + return GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + VertexBuffer{ + .vertex_buffer = std::move(buffer_view), + .index_buffer = {}, + .vertex_count = vertex_count, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +// |Geometry| +std::optional PointFieldGeometry::GetCoverage( + const Matrix& transform) const { + if (point_count_ > 0) { + // Doesn't use MakePointBounds as this isn't resilient to points that + // all lie along the same axis. + Scalar left = points_[0].x; + Scalar top = points_[0].y; + Scalar right = points_[0].x; + Scalar bottom = points_[0].y; + for (auto i = 1u; i < point_count_; i++) { + const Point point = points_[i]; + left = std::min(left, point.x); + top = std::min(top, point.y); + right = std::max(right, point.x); + bottom = std::max(bottom, point.y); + } + Rect coverage = Rect::MakeLTRB(left - radius_, top - radius_, + right + radius_, bottom + radius_); + return coverage.TransformBounds(transform); + } + return std::nullopt; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..8ab8e8b4ae0bb32c670f8bf6bf90b4b4b613def8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/point_field_geometry.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +/// @brief A geometry class specialized for Canvas::DrawPoints. +/// +/// Does not hold ownership of the allocated point data, which is expected to be +/// maintained via the display list structure. +class PointFieldGeometry final : public Geometry { + public: + PointFieldGeometry(const Point* points, + size_t point_count, + Scalar radius, + bool round); + + ~PointFieldGeometry() override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + size_t point_count_; + Scalar radius_; + bool round_; + const Point* points_; + + PointFieldGeometry(const PointFieldGeometry&) = delete; + + PointFieldGeometry& operator=(const PointFieldGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_POINT_FIELD_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..19de79d718610f14473ed916acd82c5a8991116e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.cc @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/rect_geometry.h" + +namespace impeller { + +RectGeometry::RectGeometry(Rect rect) : rect_(rect) {} + +RectGeometry::~RectGeometry() = default; + +GeometryResult RectGeometry::GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + auto& host_buffer = renderer.GetTransientsBuffer(); + return GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = host_buffer.Emplace( + rect_.GetPoints().data(), 8 * sizeof(float), alignof(float)), + .vertex_count = 4, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +std::optional RectGeometry::GetCoverage(const Matrix& transform) const { + return rect_.TransformBounds(transform); +} + +bool RectGeometry::CoversArea(const Matrix& transform, const Rect& rect) const { + if (!transform.IsTranslationScaleOnly()) { + return false; + } + Rect coverage = rect_.TransformBounds(transform); + return coverage.Contains(rect); +} + +bool RectGeometry::IsAxisAlignedRect() const { + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..40457939ad63f2095bf4da935aa7538ea72b568b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/rect_geometry.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_RECT_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_RECT_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +class RectGeometry final : public Geometry { + public: + explicit RectGeometry(Rect rect); + + ~RectGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + private: + Rect rect_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_RECT_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..060303c605eaac0d2f9e311d0f83073f6625b654 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.cc @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/entity/geometry/round_rect_geometry.h" + +namespace impeller { + +RoundRectGeometry::RoundRectGeometry(const Rect& bounds, const Size& radii) + : bounds_(bounds), radii_(radii) {} + +RoundRectGeometry::~RoundRectGeometry() = default; + +GeometryResult RoundRectGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + return ComputePositionGeometry(renderer, + renderer.GetTessellator().FilledRoundRect( + entity.GetTransform(), bounds_, radii_), + entity, pass); +} + +std::optional RoundRectGeometry::GetCoverage( + const Matrix& transform) const { + return bounds_.TransformBounds(transform); +} + +bool RoundRectGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + if (!transform.IsTranslationScaleOnly()) { + return false; + } + bool flat_on_tb = bounds_.GetWidth() > radii_.width * 2; + bool flat_on_lr = bounds_.GetHeight() > radii_.height * 2; + if (!flat_on_tb && !flat_on_lr) { + return false; + } + // We either transform the bounds and delta-transform the radii, + // or we compute the vertical and horizontal bounds and then + // transform each. Either way there are 2 transform operations. + // We could also get a weaker answer by computing just the + // "inner rect" and only doing a coverage analysis on that, + // but this process will produce more culling results. + if (flat_on_tb) { + Rect vertical_bounds = bounds_.Expand(Size{-radii_.width, 0}); + Rect coverage = vertical_bounds.TransformBounds(transform); + if (coverage.Contains(rect)) { + return true; + } + } + if (flat_on_lr) { + Rect horizontal_bounds = bounds_.Expand(Size{0, -radii_.height}); + Rect coverage = horizontal_bounds.TransformBounds(transform); + if (coverage.Contains(rect)) { + return true; + } + } + return false; +} + +bool RoundRectGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..1cf73b812bd5cf307318ed2e6146fd88b8391dcc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/round_rect_geometry.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_RECT_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_RECT_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +// Geometry class that can generate vertices (with or without texture +// coordinates) for filled ellipses. Generating vertices for a stroked +// ellipse would require a lot more work since the line width must be +// applied perpendicular to the distorted ellipse shape. +class RoundRectGeometry final : public Geometry { + public: + explicit RoundRectGeometry(const Rect& bounds, const Size& radii); + + ~RoundRectGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + const Rect bounds_; + const Size radii_; + + RoundRectGeometry(const RoundRectGeometry&) = delete; + + RoundRectGeometry& operator=(const RoundRectGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_RECT_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..4dee1949cef7e415b1f7f1b0ec4f943a18c3bf6c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.cc @@ -0,0 +1,465 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/impeller/entity/geometry/round_superellipse_geometry.h" +#include "flutter/impeller/geometry/round_superellipse_param.h" + +#include "impeller/geometry/constants.h" + +namespace impeller { + +namespace { + +constexpr auto kGapFactor = RoundSuperellipseParam::kGapFactor; + +// An interface for classes that arranges a point list that forms a convex +// contour into a triangle strip. +class ConvexRearranger { + public: + ConvexRearranger() {} + + virtual ~ConvexRearranger() {} + + virtual size_t ContourLength() const = 0; + + virtual Point GetPoint(size_t i) const = 0; + + void RearrangeIntoTriangleStrip(Point* output) { + size_t index_count = 0; + + output[index_count++] = GetPoint(0); + + size_t a = 1; + size_t contour_length = ContourLength(); + size_t b = contour_length - 1; + while (a < b) { + output[index_count++] = GetPoint(a); + output[index_count++] = GetPoint(b); + a++; + b--; + } + if (a == b) { + output[index_count++] = GetPoint(b); + } + } + + private: + ConvexRearranger(const ConvexRearranger&) = delete; + ConvexRearranger& operator=(const ConvexRearranger&) = delete; +}; + +// A convex rearranger whose contour is concatenated from 4 quadrant segments. +// +// The input quadrant curves must travel from the Y axis to the X axis, and +// include both ends. This means that the points on the axes are duplicate +// between segments, and will be omitted by this class. +class UnevenQuadrantsRearranger : public ConvexRearranger { + public: + UnevenQuadrantsRearranger(Point* cache, size_t segment_capacity) + : cache_(cache), segment_capacity_(segment_capacity) {} + + Point* QuadCache(size_t i) { return cache_ + segment_capacity_ * i; } + + const Point* QuadCache(size_t i) const { + return cache_ + segment_capacity_ * i; + } + + size_t& QuadSize(size_t i) { return lengths_[i]; } + + size_t ContourLength() const override { + return lengths_[0] + lengths_[1] + lengths_[2] + lengths_[3] - 4; + } + + Point GetPoint(size_t i) const override { + // output from index + // 0 ... l0-2 quads[0] 0 ... l0-2 + // next 0 ... l1-2 quads[1] l1-1 ... 1 + // next 0 ... l2-2 quads[2] 0 ... l2-2 + // next 0 ... l3-2 quads[3] l3-1 ... 1 + size_t high = lengths_[0] - 1; + if (i < high) { + return QuadCache(0)[i]; + } + high += lengths_[1] - 1; + if (i < high) { + return QuadCache(1)[high - i]; + } + size_t low = high; + high += lengths_[2] - 1; + if (i < high) { + return QuadCache(2)[i - low]; + } + high += lengths_[3] - 1; + if (i < high) { + return QuadCache(3)[high - i]; + } else { + // Unreachable + return Point(); + } + } + + private: + Point* cache_; + size_t segment_capacity_; + size_t lengths_[4]; +}; + +// A convex rearranger whose contour is concatenated from 4 identical quadrant +// segments. +// +// The input curve must travel from the Y axis to the X axis and include both +// ends. This means that the points on the axes are duplicate between segments, +// and will be omitted by this class. +class MirroredQuadrantRearranger : public ConvexRearranger { + public: + MirroredQuadrantRearranger(Point center, Point* cache) + : center_(center), cache_(cache) {} + + size_t& QuadSize() { return l_; } + + size_t ContourLength() const override { return l_ * 4 - 4; } + + Point GetPoint(size_t i) const override { + // output from index + // 0 ... l-2 quad 0 ... l-2 + // next 0 ... l-2 quad l-1 ... 1 + // next 0 ... l-2 quad 0 ... l-2 + // next 0 ... l-2 quad l-1 ... 1 + size_t high = l_ - 1; + if (i < high) { + return cache_[i] + center_; + } + high += l_ - 1; + if (i < high) { + return cache_[high - i] * Point{1, -1} + center_; + } + size_t low = high; + high += l_ - 1; + if (i < high) { + return cache_[i - low] * Point{-1, -1} + center_; + } + high += l_ - 1; + if (i < high) { + return cache_[high - i] * Point{-1, 1} + center_; + } else { + // Unreachable + return Point(); + } + } + + private: + Point center_; + Point* cache_; + size_t l_ = 0; +}; + +// A matrix that swaps the coordinates of a point. +// clang-format off +constexpr Matrix kFlip = Matrix( + 0.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); +// clang-format on + +// The max angular step that the algorithm will traverse a quadrant of the +// curve. +// +// This limits the max number of points of the curve. +constexpr Scalar kMaxQuadrantSteps = 40; + +// Calculates the angular step size for a smooth curve. +// +// Returns the angular step needed to ensure a curve appears smooth +// based on the smallest dimension of a shape. Smaller dimensions require +// larger steps as less detail is needed for smoothness. +// +// The `minDimension` is the smallest dimension (e.g., width or height) of the +// shape. +// +// The `fullAngle` is the total angular range to traverse. +Scalar CalculateStep(Scalar minDimension, Scalar fullAngle) { + constexpr Scalar kMinAngleStep = kPiOver2 / kMaxQuadrantSteps; + + // Assumes at least 1 point is needed per pixel to achieve sufficient + // smoothness. + constexpr Scalar pointsPerPixel = 1.0; + size_t pointsByDimension = + static_cast(std::ceil(minDimension * pointsPerPixel)); + Scalar angleByDimension = fullAngle / pointsByDimension; + + return std::min(kMinAngleStep, angleByDimension); +} + +// Draw a superellipsoid arc. +// +// The superellipse is centered at the origin and has degree `n` and both +// semi-axes equal to `a`. The arc starts from positive Y axis and spans from 0 +// to `max_theta` radiance clockwise if `reverse` is false, or from `max_theta` +// to 0 otherwise. +// +// The resulting points, transformed by `transform`, are appended to `output`. +// The starting point is included, but the ending point is excluded. +// +// Returns the number of points generated. +size_t DrawSuperellipsoidArc(Point* output, + Scalar a, + Scalar n, + Scalar max_theta, + bool reverse, + const Matrix& transform) { + Point* next = output; + Scalar angle = reverse ? max_theta : 0.0f; + Scalar step = + (reverse ? -1 : 1) * + CalculateStep(a - a * pow(abs(cosf(max_theta)), 2 / n), max_theta); + Scalar end = reverse ? 0.0f : max_theta; + while ((angle < end) != reverse) { + Scalar x = a * pow(abs(sinf(angle)), 2 / n); + Scalar y = a * pow(abs(cosf(angle)), 2 / n); + *(next++) = transform * Point(x, y); + angle += step; + } + return next - output; +} + +// Draws a circular arc centered at the origin with a radius of `r`, starting at +// `start`, and spanning `max_angle` clockwise. +// +// If `reverse` is false, points are generated from `start` to `start + +// max_angle`. If `reverse` is true, points are generated from `start + +// max_angle` back to `start`. +// +// The generated points, transformed by `transform`, are appended to `output`. +// The starting point is included, but the ending point is excluded. +// +// Returns the number of points generated. +size_t DrawCircularArc(Point* output, + Point start, + Scalar max_angle, + bool reverse, + const Matrix& transform) { + /* Denote the middle point of S and E as M. The key is to find the center of + * the circle. + * S --__ + * / ⟍ `、 + * / M ⟍\ + * / ⟋ E + * / ⟋ ↗ + * / ⟋ + * / ⟋ r + * C ᜱ ↙ + */ + + Point end = start.Rotate(Radians(-max_angle)); + + Point* next = output; + Scalar angle = reverse ? max_angle : 0.0f; + Scalar step = + (reverse ? -1 : 1) * CalculateStep(std::abs(start.y - end.y), max_angle); + Scalar end_angle = reverse ? 0.0f : max_angle; + + while ((angle < end_angle) != reverse) { + *(next++) = transform * start.Rotate(Radians(-angle)); + angle += step; + } + return next - output; +} + +// Draws an arc representing the top 1/8 segment of a square-like rounded +// superellipse centered at the origin. +// +// If `reverse_and_flip` is false, the resulting arc spans from 0 (inclusive) to +// pi/4 (exclusive), moving clockwise starting from the positive Y-axis. If +// `reverse` is true, the curve spans from pi/4 (inclusive) to 0 (inclusive) +// counterclockwise instead, and all points have their x and y coordinates +// flipped. +// +// Either way, each point is then transformed by `external_transform` and +// appended to `output`. +// +// Returns the number of points generated. +size_t DrawOctantSquareLikeSquircle(Point* output, + const RoundSuperellipseParam::Octant& param, + bool reverse_and_flip, + const Matrix& external_transform) { + Matrix transform = external_transform * Matrix::MakeTranslation(param.offset); + if (reverse_and_flip) { + transform = transform * kFlip; + } + if (param.se_n < 2) { + // It's a square. + *output = transform * Point(param.se_a, param.se_a); + return 1; + } + + /* The following figure shows the first quadrant of a square-like rounded + * superellipse. The target arc consists a superellipsoid arc (AJ) and a + * circular arc (JM). + * + * superelipse + * A ↓ circular arc + * ---------...._J ↙ + * | / `⟍ M (where x=y) + * | / ⟋ ⟍ + * | / ⟋ \ + * | / ⟋ | + * | ᜱD | + * | ⟋ | + * | ⟋ | + * |⟋ | + * +--------------------| A' + * O + * ←-------- a ---------→ + */ + + Point* next = output; + if (!reverse_and_flip) { + // Arc [A, J) + next += + DrawSuperellipsoidArc(next, param.se_a, param.se_n, param.se_max_theta, + reverse_and_flip, transform); + // Arc [J, M) + next += DrawCircularArc( + next, param.circle_start - param.circle_center, + param.circle_max_angle.radians, reverse_and_flip, + transform * Matrix::MakeTranslation(param.circle_center)); + } else { + // Arc [M, J) + next += DrawCircularArc( + next, param.circle_start - param.circle_center, + param.circle_max_angle.radians, reverse_and_flip, + transform * Matrix::MakeTranslation(param.circle_center)); + // Arc [J, A) + next += + DrawSuperellipsoidArc(next, param.se_a, param.se_n, param.se_max_theta, + reverse_and_flip, transform); + // Point A + *(next++) = transform * Point(0, param.se_a); + } + return next - output; +} + +// Draw a quadrant curve, both ends included. +// +// Returns the number of points. +static size_t DrawQuadrant(Point* output, + const RoundSuperellipseParam::Quadrant& param) { + Point* next = output; + auto transform = Matrix::MakeTranslateScale(param.signed_scale, param.offset); + + next += DrawOctantSquareLikeSquircle(next, param.top, + /*reverse_and_flip=*/false, transform); + + next += DrawOctantSquareLikeSquircle(next, param.right, + /*reverse_and_flip=*/true, transform); + + return next - output; +} + +} // namespace + +RoundSuperellipseGeometry::RoundSuperellipseGeometry(const Rect& bounds, + const RoundingRadii& radii) + : bounds_(bounds.GetPositive()), radii_(radii.Scaled(bounds_)) {} + +RoundSuperellipseGeometry::RoundSuperellipseGeometry(const Rect& bounds, + float corner_radius) + : RoundSuperellipseGeometry(bounds, + RoundingRadii::MakeRadius(corner_radius)) {} + +RoundSuperellipseGeometry::~RoundSuperellipseGeometry() {} + +GeometryResult RoundSuperellipseGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + Point* cache = renderer.GetTessellator().GetStrokePointCache().data(); + + // The memory size (in units of Points) allocated to store each quadrants. + constexpr size_t kMaxQuadSize = kPointArenaSize / 4; + // Since the curve is traversed in steps bounded by kMaxQuadrantSteps, the + // curving part will have fewer points than kMaxQuadrantSteps. Multiply it by + // 2 for storing other sporatic points (an extremely conservative estimate). + static_assert(kMaxQuadSize > 2 * kMaxQuadrantSteps); + + ConvexRearranger* rearranger; + std::variant + rearranger_holder; + + auto param = RoundSuperellipseParam::MakeBoundsRadii(bounds_, radii_); + + if (param.all_corners_same) { + rearranger_holder.emplace(bounds_.GetCenter(), + cache); + auto& t = std::get(rearranger_holder); + rearranger = &t; + + // The quadrant must be drawn at the origin so that it can be rotated later. + param.top_right.offset = Point(); + t.QuadSize() = DrawQuadrant(cache, param.top_right); + } else { + rearranger_holder.emplace(cache, kMaxQuadSize); + auto& t = std::get(rearranger_holder); + rearranger = &t; + + t.QuadSize(0) = DrawQuadrant(t.QuadCache(0), param.top_right); + t.QuadSize(1) = DrawQuadrant(t.QuadCache(1), param.bottom_right); + t.QuadSize(2) = DrawQuadrant(t.QuadCache(2), param.bottom_left); + t.QuadSize(3) = DrawQuadrant(t.QuadCache(3), param.top_left); + } + + size_t contour_length = rearranger->ContourLength(); + BufferView vertex_buffer = renderer.GetTransientsBuffer().Emplace( + nullptr, sizeof(Point) * contour_length, alignof(Point)); + Point* vertex_data = + reinterpret_cast(vertex_buffer.GetBuffer()->OnGetContents() + + vertex_buffer.GetRange().offset); + rearranger->RearrangeIntoTriangleStrip(vertex_data); + + return GeometryResult{ + .type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = vertex_buffer, + .vertex_count = contour_length, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +std::optional RoundSuperellipseGeometry::GetCoverage( + const Matrix& transform) const { + return bounds_.TransformBounds(transform); +} + +bool RoundSuperellipseGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + if (!transform.IsTranslationScaleOnly()) { + return false; + } + Scalar left_inset = std::max(radii_.top_left.width, radii_.bottom_left.width); + Scalar right_inset = + std::max(radii_.top_right.width, radii_.bottom_right.width); + Scalar top_inset = std::max(radii_.top_left.height, radii_.top_right.height); + Scalar bottom_inset = + std::max(radii_.bottom_left.height, radii_.bottom_right.height); + Rect coverage = + Rect::MakeLTRB(bounds_.GetLeft() + left_inset * kGapFactor, + bounds_.GetTop() + top_inset * kGapFactor, + bounds_.GetRight() - right_inset * kGapFactor, + bounds_.GetBottom() - bottom_inset * kGapFactor); + return coverage.TransformBounds(transform).Contains(rect); +} + +bool RoundSuperellipseGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..9cb17474961cae6b9f09db2c81d948491bb6ded0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/round_superellipse_geometry.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_SUPERELLIPSE_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_SUPERELLIPSE_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/rounding_radii.h" + +namespace impeller { + +/// Geometry class that can generate vertices for a rounded superellipse. +/// +/// A rounded superellipse is a shape similar to a typical rounded rectangle +/// (`RoundRect`), but with smoother transitions between the straight sides and +/// the rounded corners. It resembles the `RoundedRectangle` shape in SwiftUI +/// with the `.continuous` corner style. Technically, it is created by replacing +/// the four corners of a superellipse (also known as a Lamé curve) with +/// circular arcs. +/// +/// The `bounds` defines the position and size of the shape. The `corner_radius` +/// corresponds to SwiftUI's `cornerRadius` parameter, which is close to, but +/// not exactly equals to, the radius of the corner circles. +class RoundSuperellipseGeometry final : public Geometry { + public: + RoundSuperellipseGeometry(const Rect& bounds, const RoundingRadii& radii); + RoundSuperellipseGeometry(const Rect& bounds, float corner_radius); + + ~RoundSuperellipseGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + const Rect bounds_; + const RoundingRadii radii_; + + RoundSuperellipseGeometry(const RoundSuperellipseGeometry&) = delete; + + RoundSuperellipseGeometry& operator=(const RoundSuperellipseGeometry&) = + delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_ROUND_SUPERELLIPSE_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..6df79c453cb3ddb1b41dabd3e0b69484d0ea94e6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.cc @@ -0,0 +1,681 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/stroke_path_geometry.h" + +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/entity/contents/pipelines.h" +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/constants.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/separated_vector.h" +#include "impeller/geometry/wangs_formula.h" + +namespace impeller { + +namespace { + +class PositionWriter { + public: + explicit PositionWriter(std::vector& points) + : points_(points), oversized_() { + FML_DCHECK(points_.size() == kPointArenaSize); + } + + void AppendVertex(const Point& point) { + if (offset_ >= kPointArenaSize) { + oversized_.push_back(point); + } else { + points_[offset_++] = point; + } + } + + /// @brief Return the number of points used in the arena, followed by + /// the number of points allocated in the overized buffer. + std::pair GetUsedSize() const { + return std::make_pair(offset_, oversized_.size()); + } + + bool HasOversizedBuffer() const { return !oversized_.empty(); } + + const std::vector& GetOversizedBuffer() const { return oversized_; } + + private: + std::vector& points_; + std::vector oversized_; + size_t offset_ = 0u; +}; + +using CapProc = std::function; + +using JoinProc = std::function; + +class StrokeGenerator { + public: + StrokeGenerator(const Path::Polyline& p_polyline, + const Scalar p_stroke_width, + const Scalar p_scaled_miter_limit, + const JoinProc& p_join_proc, + const CapProc& p_cap_proc, + const Scalar p_scale) + : polyline(p_polyline), + stroke_width(p_stroke_width), + scaled_miter_limit(p_scaled_miter_limit), + join_proc(p_join_proc), + cap_proc(p_cap_proc), + scale(p_scale) {} + + void Generate(PositionWriter& vtx_builder) { + for (size_t contour_i = 0; contour_i < polyline.contours.size(); + contour_i++) { + const Path::PolylineContour& contour = polyline.contours[contour_i]; + size_t contour_start_point_i, contour_end_point_i; + std::tie(contour_start_point_i, contour_end_point_i) = + polyline.GetContourPointBounds(contour_i); + + size_t contour_delta = contour_end_point_i - contour_start_point_i; + if (contour_delta == 0) { + continue; // This contour has no renderable content. + } + + if (contour_i > 0) { + // This branch only executes when we've just finished drawing a contour + // and are switching to a new one. + // We're drawing a triangle strip, so we need to "pick up the pen" by + // appending two vertices at the end of the previous contour and two + // vertices at the start of the new contour (thus connecting the two + // contours with two zero volume triangles, which will be discarded by + // the rasterizer). + vtx.position = polyline.GetPoint(contour_start_point_i - 1); + // Append two vertices when "picking up" the pen so that the triangle + // drawn when moving to the beginning of the new contour will have zero + // volume. + vtx_builder.AppendVertex(vtx.position); + vtx_builder.AppendVertex(vtx.position); + + vtx.position = polyline.GetPoint(contour_start_point_i); + // Append two vertices at the beginning of the new contour, which + // appends two triangles of zero area. + vtx_builder.AppendVertex(vtx.position); + vtx_builder.AppendVertex(vtx.position); + } + + if (contour_delta == 1) { + Point p = polyline.GetPoint(contour_start_point_i); + cap_proc(vtx_builder, p, {-stroke_width * 0.5f, 0}, scale, + /*reverse=*/false); + cap_proc(vtx_builder, p, {stroke_width * 0.5f, 0}, scale, + /*reverse=*/false); + continue; + } + + previous_offset = offset; + offset = ComputeOffset(contour_start_point_i, contour_start_point_i, + contour_end_point_i, contour); + const Point contour_first_offset = offset.GetVector(); + + // Generate start cap. + if (!polyline.contours[contour_i].is_closed) { + Point cap_offset = + Vector2(-contour.start_direction.y, contour.start_direction.x) * + stroke_width * 0.5f; // Counterclockwise normal + cap_proc(vtx_builder, polyline.GetPoint(contour_start_point_i), + cap_offset, scale, /*reverse=*/true); + } + + for (size_t contour_component_i = 0; + contour_component_i < contour.components.size(); + contour_component_i++) { + const Path::PolylineContour::Component& component = + contour.components[contour_component_i]; + bool is_last_component = + contour_component_i == contour.components.size() - 1; + + size_t component_start_index = component.component_start_index; + size_t component_end_index = + is_last_component ? contour_end_point_i - 1 + : contour.components[contour_component_i + 1] + .component_start_index; + if (component.is_curve) { + AddVerticesForCurveComponent( + vtx_builder, component_start_index, component_end_index, + contour_start_point_i, contour_end_point_i, contour); + } else { + AddVerticesForLinearComponent( + vtx_builder, component_start_index, component_end_index, + contour_start_point_i, contour_end_point_i, contour); + } + } + + // Generate end cap or join. + if (!contour.is_closed) { + auto cap_offset = + Vector2(-contour.end_direction.y, contour.end_direction.x) * + stroke_width * 0.5f; // Clockwise normal + cap_proc(vtx_builder, polyline.GetPoint(contour_end_point_i - 1), + cap_offset, scale, /*reverse=*/false); + } else { + join_proc(vtx_builder, polyline.GetPoint(contour_start_point_i), + offset.GetVector(), contour_first_offset, scaled_miter_limit, + scale); + } + } + } + + /// Computes offset by calculating the direction from point_i - 1 to point_i + /// if point_i is within `contour_start_point_i` and `contour_end_point_i`; + /// Otherwise, it uses direction from contour. + SeparatedVector2 ComputeOffset(const size_t point_i, + const size_t contour_start_point_i, + const size_t contour_end_point_i, + const Path::PolylineContour& contour) const { + Point direction; + if (point_i >= contour_end_point_i) { + direction = contour.end_direction; + } else if (point_i <= contour_start_point_i) { + direction = -contour.start_direction; + } else { + direction = (polyline.GetPoint(point_i) - polyline.GetPoint(point_i - 1)) + .Normalize(); + } + return SeparatedVector2(Vector2{-direction.y, direction.x}, + stroke_width * 0.5f); + } + + void AddVerticesForLinearComponent(PositionWriter& vtx_builder, + const size_t component_start_index, + const size_t component_end_index, + const size_t contour_start_point_i, + const size_t contour_end_point_i, + const Path::PolylineContour& contour) { + bool is_last_component = component_start_index == + contour.components.back().component_start_index; + + for (size_t point_i = component_start_index; point_i < component_end_index; + point_i++) { + bool is_end_of_component = point_i == component_end_index - 1; + + Point offset_vector = offset.GetVector(); + + vtx.position = polyline.GetPoint(point_i) + offset_vector; + vtx_builder.AppendVertex(vtx.position); + vtx.position = polyline.GetPoint(point_i) - offset_vector; + vtx_builder.AppendVertex(vtx.position); + + // For line components, two additional points need to be appended + // prior to appending a join connecting the next component. + vtx.position = polyline.GetPoint(point_i + 1) + offset_vector; + vtx_builder.AppendVertex(vtx.position); + vtx.position = polyline.GetPoint(point_i + 1) - offset_vector; + vtx_builder.AppendVertex(vtx.position); + + previous_offset = offset; + offset = ComputeOffset(point_i + 2, contour_start_point_i, + contour_end_point_i, contour); + if (!is_last_component && is_end_of_component) { + // Generate join from the current line to the next line. + join_proc(vtx_builder, polyline.GetPoint(point_i + 1), + previous_offset.GetVector(), offset.GetVector(), + scaled_miter_limit, scale); + } + } + } + + void AddVerticesForCurveComponent(PositionWriter& vtx_builder, + const size_t component_start_index, + const size_t component_end_index, + const size_t contour_start_point_i, + const size_t contour_end_point_i, + const Path::PolylineContour& contour) { + bool is_last_component = component_start_index == + contour.components.back().component_start_index; + + for (size_t point_i = component_start_index; point_i < component_end_index; + point_i++) { + bool is_end_of_component = point_i == component_end_index - 1; + + vtx.position = polyline.GetPoint(point_i) + offset.GetVector(); + vtx_builder.AppendVertex(vtx.position); + vtx.position = polyline.GetPoint(point_i) - offset.GetVector(); + vtx_builder.AppendVertex(vtx.position); + + previous_offset = offset; + offset = ComputeOffset(point_i + 2, contour_start_point_i, + contour_end_point_i, contour); + + // If the angle to the next segment is too sharp, round out the join. + if (!is_end_of_component) { + constexpr Scalar kAngleThreshold = 10 * kPi / 180; + // `std::cosf` is not constexpr-able, unfortunately, so we have to bake + // the alignment constant. + constexpr Scalar kAlignmentThreshold = + 0.984807753012208; // std::cosf(kThresholdAngle) -- 10 degrees + + // Use a cheap dot product to determine whether the angle is too sharp. + if (previous_offset.GetAlignment(offset) < kAlignmentThreshold) { + Scalar angle_total = previous_offset.AngleTo(offset).radians; + Scalar angle = kAngleThreshold; + + // Bridge the large angle with additional geometry at + // `kAngleThreshold` interval. + while (angle < std::abs(angle_total)) { + Scalar signed_angle = angle_total < 0 ? -angle : angle; + Point offset = + previous_offset.GetVector().Rotate(Radians(signed_angle)); + vtx.position = polyline.GetPoint(point_i) + offset; + vtx_builder.AppendVertex(vtx.position); + vtx.position = polyline.GetPoint(point_i) - offset; + vtx_builder.AppendVertex(vtx.position); + + angle += kAngleThreshold; + } + } + } + + // For curve components, the polyline is detailed enough such that + // it can avoid worrying about joins altogether. + if (is_end_of_component) { + // Append two additional vertices to close off the component. If we're + // on the _last_ component of the contour then we need to use the + // contour's end direction. + // `ComputeOffset` returns the contour's end direction when attempting + // to grab offsets past `contour_end_point_i`, so just use `offset` when + // we're on the last component. + Point last_component_offset = is_last_component + ? offset.GetVector() + : previous_offset.GetVector(); + vtx.position = polyline.GetPoint(point_i + 1) + last_component_offset; + vtx_builder.AppendVertex(vtx.position); + vtx.position = polyline.GetPoint(point_i + 1) - last_component_offset; + vtx_builder.AppendVertex(vtx.position); + // Generate join from the current line to the next line. + if (!is_last_component) { + join_proc(vtx_builder, polyline.GetPoint(point_i + 1), + previous_offset.GetVector(), offset.GetVector(), + scaled_miter_limit, scale); + } + } + } + } + + const Path::Polyline& polyline; + const Scalar stroke_width; + const Scalar scaled_miter_limit; + const JoinProc& join_proc; + const CapProc& cap_proc; + const Scalar scale; + + SeparatedVector2 previous_offset; + SeparatedVector2 offset; + SolidFillVertexShader::PerVertexData vtx; +}; + +void CreateButtCap(PositionWriter& vtx_builder, + const Point& position, + const Point& offset, + Scalar scale, + bool reverse) { + Point orientation = offset * (reverse ? -1 : 1); + vtx_builder.AppendVertex(position + orientation); + vtx_builder.AppendVertex(position - orientation); +} + +void CreateRoundCap(PositionWriter& vtx_builder, + const Point& position, + const Point& offset, + Scalar scale, + bool reverse) { + Point orientation = offset * (reverse ? -1 : 1); + Point forward(offset.y, -offset.x); + Point forward_normal = forward.Normalize(); + + CubicPathComponent arc; + if (reverse) { + arc = CubicPathComponent( + forward, forward + orientation * PathBuilder::kArcApproximationMagic, + orientation + forward * PathBuilder::kArcApproximationMagic, + orientation); + } else { + arc = CubicPathComponent( + orientation, + orientation + forward * PathBuilder::kArcApproximationMagic, + forward + orientation * PathBuilder::kArcApproximationMagic, forward); + } + + Point vtx = position + orientation; + vtx_builder.AppendVertex(vtx); + vtx = position - orientation; + vtx_builder.AppendVertex(vtx); + + Scalar line_count = std::ceilf(ComputeCubicSubdivisions(scale, arc)); + for (size_t i = 1; i < line_count; i++) { + Point point = arc.Solve(i / line_count); + vtx = position + point; + vtx_builder.AppendVertex(vtx); + vtx = position + (-point).Reflect(forward_normal); + vtx_builder.AppendVertex(vtx); + } + + Point point = arc.p2; + vtx = position + point; + vtx_builder.AppendVertex(position + point); + vtx = position + (-point).Reflect(forward_normal); + vtx_builder.AppendVertex(vtx); +} + +void CreateSquareCap(PositionWriter& vtx_builder, + const Point& position, + const Point& offset, + Scalar scale, + bool reverse) { + Point orientation = offset * (reverse ? -1 : 1); + Point forward(offset.y, -offset.x); + + Point vtx = position + orientation; + vtx_builder.AppendVertex(vtx); + vtx = position - orientation; + vtx_builder.AppendVertex(vtx); + vtx = position + orientation + forward; + vtx_builder.AppendVertex(vtx); + vtx = position - orientation + forward; + vtx_builder.AppendVertex(vtx); +} + +Scalar CreateBevelAndGetDirection(PositionWriter& vtx_builder, + const Point& position, + const Point& start_offset, + const Point& end_offset) { + Point vtx = position; + vtx_builder.AppendVertex(vtx); + + Scalar dir = start_offset.Cross(end_offset) > 0 ? -1 : 1; + vtx = position + start_offset * dir; + vtx_builder.AppendVertex(vtx); + vtx = position + end_offset * dir; + vtx_builder.AppendVertex(vtx); + + return dir; +} + +void CreateMiterJoin(PositionWriter& vtx_builder, + const Point& position, + const Point& start_offset, + const Point& end_offset, + Scalar miter_limit, + Scalar scale) { + Point start_normal = start_offset.Normalize(); + Point end_normal = end_offset.Normalize(); + + // 1 for no joint (straight line), 0 for max joint (180 degrees). + Scalar alignment = (start_normal.Dot(end_normal) + 1) / 2; + if (ScalarNearlyEqual(alignment, 1)) { + return; + } + + Scalar direction = CreateBevelAndGetDirection(vtx_builder, position, + start_offset, end_offset); + + Point miter_point = (((start_offset + end_offset) / 2) / alignment); + if (miter_point.GetDistanceSquared({0, 0}) > miter_limit * miter_limit) { + return; // Convert to bevel when we exceed the miter limit. + } + + // Outer miter point. + vtx_builder.AppendVertex(position + miter_point * direction); +} + +void CreateRoundJoin(PositionWriter& vtx_builder, + const Point& position, + const Point& start_offset, + const Point& end_offset, + Scalar miter_limit, + Scalar scale) { + Point start_normal = start_offset.Normalize(); + Point end_normal = end_offset.Normalize(); + + // 0 for no joint (straight line), 1 for max joint (180 degrees). + Scalar alignment = 1 - (start_normal.Dot(end_normal) + 1) / 2; + if (ScalarNearlyEqual(alignment, 0)) { + return; + } + + Scalar direction = CreateBevelAndGetDirection(vtx_builder, position, + start_offset, end_offset); + + Point middle = + (start_offset + end_offset).Normalize() * start_offset.GetLength(); + Point middle_normal = middle.Normalize(); + + Point middle_handle = middle + Point(-middle.y, middle.x) * + PathBuilder::kArcApproximationMagic * + alignment * direction; + Point start_handle = start_offset + Point(start_offset.y, -start_offset.x) * + PathBuilder::kArcApproximationMagic * + alignment * direction; + + CubicPathComponent arc(start_offset, start_handle, middle_handle, middle); + Scalar line_count = std::ceilf(ComputeCubicSubdivisions(scale, arc)); + for (size_t i = 1; i < line_count; i++) { + Point point = arc.Solve(i / line_count); + vtx_builder.AppendVertex(position + point * direction); + vtx_builder.AppendVertex(position + + (-point * direction).Reflect(middle_normal)); + } + vtx_builder.AppendVertex(position + arc.p2 * direction); + vtx_builder.AppendVertex(position + + (-arc.p2 * direction).Reflect(middle_normal)); +} + +void CreateBevelJoin(PositionWriter& vtx_builder, + const Point& position, + const Point& start_offset, + const Point& end_offset, + Scalar miter_limit, + Scalar scale) { + CreateBevelAndGetDirection(vtx_builder, position, start_offset, end_offset); +} + +void CreateSolidStrokeVertices(PositionWriter& vtx_builder, + const Path::Polyline& polyline, + Scalar stroke_width, + Scalar scaled_miter_limit, + const JoinProc& join_proc, + const CapProc& cap_proc, + Scalar scale) { + StrokeGenerator stroke_generator(polyline, stroke_width, scaled_miter_limit, + join_proc, cap_proc, scale); + stroke_generator.Generate(vtx_builder); +} + +// static + +JoinProc GetJoinProc(Join stroke_join) { + switch (stroke_join) { + case Join::kBevel: + return &CreateBevelJoin; + case Join::kMiter: + return &CreateMiterJoin; + case Join::kRound: + return &CreateRoundJoin; + } +} + +CapProc GetCapProc(Cap stroke_cap) { + switch (stroke_cap) { + case Cap::kButt: + return &CreateButtCap; + case Cap::kRound: + return &CreateRoundCap; + case Cap::kSquare: + return &CreateSquareCap; + } +} +} // namespace + +std::vector StrokePathGeometry::GenerateSolidStrokeVertices( + const Path::Polyline& polyline, + Scalar stroke_width, + Scalar miter_limit, + Join stroke_join, + Cap stroke_cap, + Scalar scale) { + auto scaled_miter_limit = stroke_width * miter_limit * 0.5f; + JoinProc join_proc = GetJoinProc(stroke_join); + CapProc cap_proc = GetCapProc(stroke_cap); + StrokeGenerator stroke_generator(polyline, stroke_width, scaled_miter_limit, + join_proc, cap_proc, scale); + std::vector points(4096); + PositionWriter vtx_builder(points); + stroke_generator.Generate(vtx_builder); + return points; +} + +StrokePathGeometry::StrokePathGeometry(const Path& path, + Scalar stroke_width, + Scalar miter_limit, + Cap stroke_cap, + Join stroke_join) + : path_(path), + stroke_width_(stroke_width), + miter_limit_(miter_limit), + stroke_cap_(stroke_cap), + stroke_join_(stroke_join) {} + +StrokePathGeometry::~StrokePathGeometry() = default; + +Scalar StrokePathGeometry::GetStrokeWidth() const { + return stroke_width_; +} + +Scalar StrokePathGeometry::GetMiterLimit() const { + return miter_limit_; +} + +Cap StrokePathGeometry::GetStrokeCap() const { + return stroke_cap_; +} + +Join StrokePathGeometry::GetStrokeJoin() const { + return stroke_join_; +} + +Scalar StrokePathGeometry::ComputeAlphaCoverage(const Matrix& transform) const { + return Geometry::ComputeStrokeAlphaCoverage(transform, stroke_width_); +} + +GeometryResult StrokePathGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + if (stroke_width_ < 0.0) { + return {}; + } + Scalar max_basis = entity.GetTransform().GetMaxBasisLengthXY(); + if (max_basis == 0) { + return {}; + } + + Scalar min_size = kMinStrokeSize / max_basis; + Scalar stroke_width = std::max(stroke_width_, min_size); + + auto& host_buffer = renderer.GetTransientsBuffer(); + auto scale = entity.GetTransform().GetMaxBasisLengthXY(); + + PositionWriter position_writer( + renderer.GetTessellator().GetStrokePointCache()); + Path::Polyline polyline = + renderer.GetTessellator().CreateTempPolyline(path_, scale); + + CreateSolidStrokeVertices(position_writer, polyline, stroke_width, + miter_limit_ * stroke_width_ * 0.5f, + GetJoinProc(stroke_join_), GetCapProc(stroke_cap_), + scale); + + const auto [arena_length, oversized_length] = position_writer.GetUsedSize(); + if (!position_writer.HasOversizedBuffer()) { + BufferView buffer_view = host_buffer.Emplace( + renderer.GetTessellator().GetStrokePointCache().data(), + arena_length * sizeof(Point), alignof(Point)); + + return GeometryResult{.type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = buffer_view, + .vertex_count = arena_length, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + .mode = GeometryResult::Mode::kPreventOverdraw}; + } + const std::vector& oversized_data = + position_writer.GetOversizedBuffer(); + BufferView buffer_view = host_buffer.Emplace( + /*buffer=*/nullptr, // + (arena_length + oversized_length) * sizeof(Point), // + alignof(Point) // + ); + memcpy(buffer_view.GetBuffer()->OnGetContents() + + buffer_view.GetRange().offset, // + renderer.GetTessellator().GetStrokePointCache().data(), // + arena_length * sizeof(Point) // + ); + memcpy(buffer_view.GetBuffer()->OnGetContents() + + buffer_view.GetRange().offset + arena_length * sizeof(Point), // + oversized_data.data(), // + oversized_data.size() * sizeof(Point) // + ); + buffer_view.GetBuffer()->Flush(buffer_view.GetRange()); + + return GeometryResult{.type = PrimitiveType::kTriangleStrip, + .vertex_buffer = + { + .vertex_buffer = buffer_view, + .vertex_count = arena_length + oversized_length, + .index_type = IndexType::kNone, + }, + .transform = entity.GetShaderTransform(pass), + .mode = GeometryResult::Mode::kPreventOverdraw}; +} + +GeometryResult::Mode StrokePathGeometry::GetResultMode() const { + return GeometryResult::Mode::kPreventOverdraw; +} + +std::optional StrokePathGeometry::GetCoverage( + const Matrix& transform) const { + auto path_bounds = path_.GetBoundingBox(); + if (!path_bounds.has_value()) { + return std::nullopt; + } + + Scalar max_radius = 0.5; + if (stroke_cap_ == Cap::kSquare) { + max_radius = max_radius * kSqrt2; + } + if (stroke_join_ == Join::kMiter) { + max_radius = std::max(max_radius, miter_limit_ * 0.5f); + } + Scalar max_basis = transform.GetMaxBasisLengthXY(); + if (max_basis == 0) { + return {}; + } + // Use the most conervative coverage setting. + Scalar min_size = kMinStrokeSize / max_basis; + max_radius *= std::max(stroke_width_, min_size); + return path_bounds->Expand(max_radius).TransformBounds(transform); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..95970d9dec3bac1dfb3c6b1b24092543d028a5fe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/stroke_path_geometry.h @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" +#include "impeller/geometry/matrix.h" + +namespace impeller { + +/// @brief A geometry that is created from a stroked path object. +class StrokePathGeometry final : public Geometry { + public: + StrokePathGeometry(const Path& path, + Scalar stroke_width, + Scalar miter_limit, + Cap stroke_cap, + Join stroke_join); + + ~StrokePathGeometry() override; + + Scalar GetStrokeWidth() const; + + Scalar GetMiterLimit() const; + + Cap GetStrokeCap() const; + + Join GetStrokeJoin() const; + + Scalar ComputeAlphaCoverage(const Matrix& transform) const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + GeometryResult::Mode GetResultMode() const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + // Private for benchmarking and debugging + static std::vector GenerateSolidStrokeVertices( + const Path::Polyline& polyline, + Scalar stroke_width, + Scalar miter_limit, + Join stroke_join, + Cap stroke_cap, + Scalar scale); + + friend class ImpellerBenchmarkAccessor; + friend class ImpellerEntityUnitTestAccessor; + + bool SkipRendering() const; + + Path path_; + Scalar stroke_width_; + Scalar miter_limit_; + Cap stroke_cap_; + Join stroke_join_; + + StrokePathGeometry(const StrokePathGeometry&) = delete; + + StrokePathGeometry& operator=(const StrokePathGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_STROKE_PATH_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..5fe5fd660afe9aaa508742d1cdbd2eba7d186db2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.cc @@ -0,0 +1,113 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/impeller/entity/geometry/superellipse_geometry.h" + +#include "impeller/geometry/constants.h" + +namespace impeller { + +SuperellipseGeometry::SuperellipseGeometry(const Point& center, + Scalar radius, + Scalar degree, + Scalar alpha, + Scalar beta) + : center_(center), + degree_(degree), + radius_(radius), + alpha_(alpha), + beta_(beta) {} + +SuperellipseGeometry::~SuperellipseGeometry() {} + +GeometryResult SuperellipseGeometry::GetPositionBuffer( + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const { + // https://math.stackexchange.com/questions/2573746/superellipse-parametric-equation + Scalar a = alpha_; + Scalar b = beta_; + Scalar n = degree_; + + // TODO(jonahwilliams): determine parameter values based on scaling factor. + Scalar step = kPi / 80; + + // Generate the points for the top left quadrant, and then mirror to the other + // quadrants. + std::vector points; + points.reserve(41); + for (int i = 0; i <= 40; i++) { + Scalar t = i * step; + Scalar x = a * pow(abs(cos(t)), 2 / n); + Scalar y = b * pow(abs(sin(t)), 2 / n); + points.emplace_back(x * radius_, y * radius_); + } + + static constexpr Point reflection[4] = {{1, 1}, {-1, 1}, {-1, -1}, {1, -1}}; + + // Reflect into the 4 quadrants and generate the tessellated mesh. The + // iteration order is reversed so that the trianges are continuous from + // quadrant to quadrant. + std::vector geometry; + geometry.reserve(1 + 4 * points.size()); + geometry.push_back(center_); + for (auto i = 0u; i < points.size(); i++) { + geometry.push_back(center_ + (reflection[0] * points[i])); + } + for (auto i = 0u; i < points.size(); i++) { + geometry.push_back(center_ + + (reflection[1] * points[points.size() - i - 1])); + } + for (auto i = 0u; i < points.size(); i++) { + geometry.push_back(center_ + (reflection[2] * points[i])); + } + for (auto i = 0u; i < points.size(); i++) { + geometry.push_back(center_ + + (reflection[3] * points[points.size() - i - 1])); + } + + std::vector indices; + indices.reserve(geometry.size() * 3); + for (auto i = 2u; i < geometry.size(); i++) { + indices.push_back(0); + indices.push_back(i - 1); + indices.push_back(i); + } + + auto& host_buffer = renderer.GetTransientsBuffer(); + return GeometryResult{ + .type = PrimitiveType::kTriangle, + .vertex_buffer = + { + .vertex_buffer = host_buffer.Emplace( + geometry.data(), geometry.size() * sizeof(Point), + alignof(Point)), + .index_buffer = host_buffer.Emplace( + indices.data(), indices.size() * sizeof(uint16_t), + alignof(uint16_t)), + .vertex_count = indices.size(), + .index_type = IndexType::k16bit, + }, + .transform = entity.GetShaderTransform(pass), + }; +} + +std::optional SuperellipseGeometry::GetCoverage( + const Matrix& transform) const { + return Rect::MakeOriginSize(center_ - Point(radius_, radius_), + Size(radius_ * 2, radius_ * 2)); +} + +bool SuperellipseGeometry::CoversArea(const Matrix& transform, + const Rect& rect) const { + return false; +} + +bool SuperellipseGeometry::IsAxisAlignedRect() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..b01845bac57b1f0ef25d546bfb6e98044f6af8f1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/superellipse_geometry.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_SUPERELLIPSE_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_SUPERELLIPSE_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +/// Geometry class that can generate vertices for a superellipse. +/// +/// A Superellipse is an ellipse-like shape that is defined by the parameters N, +/// alpha, and beta: +/// +/// 1 = |x / b| ^n + |y / a| ^n +/// +/// The radius and center apply a uniform scaling and offset that is separate +/// from alpha or beta. When n = 4, the shape is referred to as a rectellipse. +/// +/// See also: https://en.wikipedia.org/wiki/Superellipse +class SuperellipseGeometry final : public Geometry { + public: + explicit SuperellipseGeometry(const Point& center, + Scalar radius, + Scalar degree, + Scalar alpha, + Scalar beta); + + ~SuperellipseGeometry() override; + + // |Geometry| + bool CoversArea(const Matrix& transform, const Rect& rect) const override; + + // |Geometry| + bool IsAxisAlignedRect() const override; + + private: + // |Geometry| + GeometryResult GetPositionBuffer(const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const override; + + // |Geometry| + std::optional GetCoverage(const Matrix& transform) const override; + + Point center_; + // 4 is a rectellipse + Scalar degree_; + Scalar radius_; + Scalar alpha_; + Scalar beta_; + + SuperellipseGeometry(const SuperellipseGeometry&) = delete; + + SuperellipseGeometry& operator=(const SuperellipseGeometry&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_SUPERELLIPSE_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.cc b/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..2d27592853513932414f198ed91c3ec1080bf451 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/entity/geometry/vertices_geometry.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.h b/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.h new file mode 100644 index 0000000000000000000000000000000000000000..47d2e7861307630b024e719258bec708fee264ce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/geometry/vertices_geometry.h @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_ +#define FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_ + +#include "impeller/entity/geometry/geometry.h" + +namespace impeller { + +/// @brief A geometry that is created from a vertices object. +class VerticesGeometry : public Geometry { + public: + virtual GeometryResult GetPositionUVColorBuffer( + Rect texture_coverage, + Matrix effect_transform, + const ContentContext& renderer, + const Entity& entity, + RenderPass& pass) const = 0; + + virtual bool HasVertexColors() const = 0; + + virtual bool HasTextureCoordinates() const = 0; + + virtual std::optional GetTextureCoordinateCoverage() const = 0; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_ENTITY_GEOMETRY_VERTICES_GEOMETRY_H_ diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.frag b/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.frag new file mode 100644 index 0000000000000000000000000000000000000000..ff553b7c6b25e42544ceab710c26c213c782600d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.frag @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include "blend_select.glsl" + +layout(constant_id = 0) const float blend_type = 0.0; +layout(constant_id = 1) const float supports_decal = 1.0; + +uniform BlendInfo { + float16_t dst_input_alpha; + float16_t src_input_alpha; + float16_t color_factor; + f16vec4 color; // This color input is expected to be unpremultiplied. + float supports_decal_sampler_address_mode; +} +blend_info; + +uniform f16sampler2D texture_sampler_dst; +uniform f16sampler2D texture_sampler_src; + +in vec2 v_dst_texture_coords; +in vec2 v_src_texture_coords; + +out f16vec4 frag_color; + +f16vec4 Sample(f16sampler2D texture_sampler, vec2 texture_coords) { + if (supports_decal > 0.0) { + return texture(texture_sampler, texture_coords); + } + return IPHalfSampleDecal(texture_sampler, texture_coords); +} + +void main() { + f16vec4 dst = + IPHalfUnpremultiply(Sample(texture_sampler_dst, // sampler + v_dst_texture_coords // texture coordinates + )); + dst.a *= blend_info.dst_input_alpha; + f16vec4 src = blend_info.color_factor > 0.0hf + ? blend_info.color + : IPHalfUnpremultiply(Sample( + texture_sampler_src, // sampler + v_src_texture_coords // texture coordinates + )); + if (blend_info.color_factor == 0.0hf) { + src.a *= blend_info.src_input_alpha; + } + + f16vec3 blend_result = AdvancedBlend(dst.rgb, src.rgb, int(blend_type)); + + frag_color = IPApplyBlendedColor(dst, src, blend_result); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.vert b/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.vert new file mode 100644 index 0000000000000000000000000000000000000000..5a5535ab869d6345ffe29d760439127a7e696c67 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/advanced_blend.vert @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + float dst_y_coord_scale; + float src_y_coord_scale; +} +frame_info; + +in vec2 vertices; +in vec2 dst_texture_coords; +in vec2 src_texture_coords; + +out vec2 v_dst_texture_coords; +out vec2 v_src_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0); + v_dst_texture_coords = + IPRemapCoords(dst_texture_coords, frame_info.dst_y_coord_scale); + v_src_texture_coords = + IPRemapCoords(src_texture_coords, frame_info.src_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/blend_select.glsl b/flutter/engine/src/flutter/impeller/entity/shaders/blending/blend_select.glsl new file mode 100644 index 0000000000000000000000000000000000000000..57a18c63defbb789c3c4061935a92004916ba352 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/blend_select.glsl @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +// kScreen = 0, +// kOverlay, +// kDarken, +// kLighten, +// kColorDodge, +// kColorBurn, +// kHardLight, +// kSoftLight, +// kDifference, +// kExclusion, +// kMultiply, +// kHue, +// kSaturation, +// kColor, +// kLuminosity, +// Note, this isn't a switch as GLSL ES 1.0 does not support them. +f16vec3 AdvancedBlend(f16vec3 dst, f16vec3 src, int blend_type) { + if (blend_type == 0) { + return IPBlendScreen(dst, src); + } + if (blend_type == 1) { + return IPBlendOverlay(dst, src); + } + if (blend_type == 2) { + return IPBlendDarken(dst, src); + } + if (blend_type == 3) { + return IPBlendLighten(dst, src); + } + if (blend_type == 4) { + return IPBlendColorDodge(dst, src); + } + if (blend_type == 5) { + return IPBlendColorBurn(dst, src); + } + if (blend_type == 6) { + return IPBlendHardLight(dst, src); + } + if (blend_type == 7) { + return IPBlendSoftLight(dst, src); + } + if (blend_type == 8) { + return IPBlendDifference(dst, src); + } + if (blend_type == 9) { + return IPBlendExclusion(dst, src); + } + if (blend_type == 10) { + return IPBlendMultiply(dst, src); + } + if (blend_type == 11) { + return IPBlendHue(dst, src); + } + if (blend_type == 12) { + return IPBlendSaturation(dst, src); + } + if (blend_type == 13) { + return IPBlendColor(dst, src); + } + if (blend_type == 14) { + return IPBlendLuminosity(dst, src); + } + return f16vec3(0.0hf); +} + +f16vec3 AdvancedBlendHalf1(f16vec3 dst, f16vec3 src, int blend_type) { + if (blend_type == 0) { + return IPBlendScreen(dst, src); + } + if (blend_type == 1) { + return IPBlendOverlay(dst, src); + } + if (blend_type == 2) { + return IPBlendDarken(dst, src); + } + if (blend_type == 3) { + return IPBlendLighten(dst, src); + } + if (blend_type == 4) { + return IPBlendColorDodge(dst, src); + } + if (blend_type == 5) { + return IPBlendColorBurn(dst, src); + } + if (blend_type == 6) { + return IPBlendHardLight(dst, src); + } + return f16vec3(0.0hf); +} + +f16vec3 AdvancedBlendHalf2(f16vec3 dst, f16vec3 src, int blend_type) { + if (blend_type == 7) { + return IPBlendSoftLight(dst, src); + } + if (blend_type == 8) { + return IPBlendDifference(dst, src); + } + if (blend_type == 9) { + return IPBlendExclusion(dst, src); + } + if (blend_type == 10) { + return IPBlendMultiply(dst, src); + } + if (blend_type == 11) { + return IPBlendHue(dst, src); + } + if (blend_type == 12) { + return IPBlendSaturation(dst, src); + } + if (blend_type == 13) { + return IPBlendColor(dst, src); + } + if (blend_type == 14) { + return IPBlendLuminosity(dst, src); + } + return f16vec3(0.0hf); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.frag b/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.frag new file mode 100644 index 0000000000000000000000000000000000000000..624bb7dc17d71280799bde0f82dc307e2c4c1b27 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.frag @@ -0,0 +1,58 @@ +#version 450 + +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include "blend_select.glsl" + +// Warning: if any of the constant values or layouts are changed in this +// file, then the hard-coded constant value in +// impeller/renderer/backend/vulkan/binding_helpers_vk.cc +layout(constant_id = 0) const float blend_type = 0; +layout(constant_id = 1) const float supports_decal = 1; + +layout(input_attachment_index = 0) uniform subpassInputMS uSub; + +vec4 ReadDestination() { + return (subpassLoad(uSub, 0) + subpassLoad(uSub, 1) + subpassLoad(uSub, 2) + + subpassLoad(uSub, 3)) / + vec4(4.0); +} + +uniform sampler2D texture_sampler_src; + +uniform FragInfo { + float16_t src_input_alpha; + float16_t dst_input_alpha; +} +frag_info; + +in vec2 v_src_texture_coords; + +out vec4 frag_color; + +vec4 Sample(sampler2D texture_sampler, vec2 texture_coords) { + if (supports_decal > 1) { + return texture(texture_sampler, texture_coords); + } + return IPSampleDecal(texture_sampler, texture_coords); +} + +void main() { + f16vec4 dst = IPHalfUnpremultiply(f16vec4(ReadDestination())); + dst.a *= frag_info.dst_input_alpha; + f16vec4 src = IPHalfUnpremultiply( + f16vec4(Sample(texture_sampler_src, // sampler + v_src_texture_coords // texture coordinates + ))); + src.a *= frag_info.src_input_alpha; + + f16vec3 blend_result = AdvancedBlend(dst.rgb, src.rgb, int(blend_type)); + + frag_color = IPApplyBlendedColor(dst, src, blend_result); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.vert b/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.vert new file mode 100644 index 0000000000000000000000000000000000000000..362362e4e3f8f9be94137570bbfd3869570d1d73 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/framebuffer_blend.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +// Warning: if any of the constant values or layouts are changed in this +// file, then the hard-coded constant value in +// impeller/renderer/backend/vulkan/binding_helpers_vk.cc +uniform FrameInfo { + mat4 mvp; + float src_y_coord_scale; +} +frame_info; + +in vec2 vertices; +in vec2 src_texture_coords; + +out vec2 v_src_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0); + v_src_texture_coords = + IPRemapCoords(src_texture_coords, frame_info.src_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.frag b/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.frag new file mode 100644 index 0000000000000000000000000000000000000000..d7eb34caf554701518769ebc8dc46645b686a589 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.frag @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include + +// see GetPorterDuffSpecConstants in content_context.cc for actual constants +layout(constant_id = 0) const float supports_decal = 1.0; +layout(constant_id = 1) const float src_coeff = 1.0; +layout(constant_id = 2) const float src_coeff_dst_alpha = 1.0; +layout(constant_id = 3) const float dst_coeff = 1.0; +layout(constant_id = 4) const float dst_coeff_src_alpha = 1.0; +layout(constant_id = 5) const float dst_coeff_src_color = 1.0; + +uniform f16sampler2D texture_sampler_dst; + +uniform FragInfo { + float16_t input_alpha; + float16_t output_alpha; + float tmx; + float tmy; +} +frag_info; + +in vec2 v_texture_coords; +in f16vec4 v_color; + +out vec4 frag_color; + +f16vec4 Sample(f16sampler2D texture_sampler, + vec2 texture_coords, + float tmx, + float tmy) { + if (supports_decal > 0.0) { + return texture(texture_sampler, texture_coords); + } + return IPHalfSampleWithTileMode(texture_sampler, texture_coords, tmx, tmy); +} + +void main() { + f16vec4 dst = Sample(texture_sampler_dst, v_texture_coords, frag_info.tmx, + frag_info.tmy) * + frag_info.input_alpha; + f16vec4 src = v_color; + frag_color = f16vec4(src * (src_coeff + dst.a * src_coeff_dst_alpha) + + dst * (dst_coeff + src.a * dst_coeff_src_alpha + + src * dst_coeff_src_color)); + frag_color *= frag_info.output_alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.vert b/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.vert new file mode 100644 index 0000000000000000000000000000000000000000..56c115e23df2c10cf8a0d7e6de53d888d3262e39 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/porter_duff_blend.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + float texture_sampler_y_coord_scale; +} +frame_info; + +in vec2 vertices; +in vec2 texture_coords; +in vec4 color; + +out mediump vec2 v_texture_coords; +out mediump f16vec4 v_color; + +void main() { + gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0); + v_color = f16vec4(color); + v_texture_coords = + IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber.glsl b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber.glsl new file mode 100644 index 0000000000000000000000000000000000000000..05845bb0d9f23eea8427d1c7b7005fa7cf986670 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber.glsl @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include "blend_select.glsl" + +layout(constant_id = 0) const float supports_decal = 1.0; + +uniform FragInfo { + float16_t alpha; + float16_t blend_mode; + float tmx; + float tmy; +} +frag_info; + +uniform f16sampler2D texture_sampler; + +in mediump vec2 v_texture_coords; +in mediump f16vec4 v_color; + +out f16vec4 frag_color; + +f16vec4 Sample(f16sampler2D texture_sampler, + vec2 texture_coords, + float tmx, + float tmy) { + if (supports_decal > 0.0) { + return texture(texture_sampler, texture_coords); + } + return IPHalfSampleWithTileMode(texture_sampler, texture_coords, tmx, tmy); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_1.frag b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_1.frag new file mode 100644 index 0000000000000000000000000000000000000000..86335d1d9a330db898ebfa780ed9a63d180aeea5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_1.frag @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "vertices_uber.glsl" + +// A shader that implements the required src/dst blending for drawVertices and +// drawAtlas advanced blends without requiring an offscreen render pass. This is +// done in a single shader to reduce the permutations of PSO needed at runtime +// for rarely used features. +void main() { + f16vec4 dst = IPHalfUnpremultiply(v_color); + f16vec4 src = IPHalfUnpremultiply( + Sample(texture_sampler, v_texture_coords, frag_info.tmx, frag_info.tmy)); + f16vec3 blend_result = + AdvancedBlendHalf1(dst.rgb, src.rgb, int(frag_info.blend_mode - 14.0)); + frag_color = IPApplyBlendedColor(dst, src, blend_result); + frag_color *= frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_2.frag b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_2.frag new file mode 100644 index 0000000000000000000000000000000000000000..2878219790d78e594f50135a8a7bb4a3be94919d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/blending/vertices_uber_2.frag @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "vertices_uber.glsl" + +// A shader that implements the required src/dst blending for drawVertices and +// drawAtlas advanced blends without requiring an offscreen render pass. This is +// done in a single shader to reduce the permutations of PSO needed at runtime +// for rarely used features. +void main() { + f16vec4 dst = IPHalfUnpremultiply(v_color); + f16vec4 src = IPHalfUnpremultiply( + Sample(texture_sampler, v_texture_coords, frag_info.tmx, frag_info.tmy)); + f16vec3 blend_result = + AdvancedBlendHalf2(dst.rgb, src.rgb, int(frag_info.blend_mode - 14.0)); + frag_color = IPApplyBlendedColor(dst, src, blend_result); + frag_color *= frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/clip.frag b/flutter/engine/src/flutter/impeller/entity/shaders/clip.frag new file mode 100644 index 0000000000000000000000000000000000000000..61d44949136b6aaeaf6bdce4438679929dd6b984 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/clip.frag @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include + +void main() {} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/clip.vert b/flutter/engine/src/flutter/impeller/entity/shaders/clip.vert new file mode 100644 index 0000000000000000000000000000000000000000..4a8f9f2df65edcf63bcb91e8fb7584314b9333a1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/clip.vert @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform FrameInfo { + mat4 mvp; + float depth; +} +frame_info; + +in vec2 position; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + // We can just absorb W and override the depth value here because we don't + // need to worry about perspective correcting any vertex attributes when + // drawing clips. + gl_Position /= gl_Position.w; + gl_Position.z = frame_info.depth; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/downsample.glsl b/flutter/engine/src/flutter/impeller/entity/shaders/downsample.glsl new file mode 100644 index 0000000000000000000000000000000000000000..9a1bcf741c8715fef9f97e3c1fad38fa60f8ad9a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/downsample.glsl @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + float edge; + float ratio; + vec2 pixel_size; +} +frag_info; + +in highp vec2 v_texture_coords; + +out vec4 frag_color; + +vec4 Sample(vec2 uv) { +#ifdef SUPPORTS_DECAL + return texture(texture_sampler, uv, float16_t(kDefaultMipBias)); +#else + if ((uv.x < 0 || uv.y < 0 || uv.x > 1 || uv.y > 1)) { + return vec4(0); + } else { + return texture(texture_sampler, uv, float16_t(kDefaultMipBias)); + } +#endif +} + +void main() { + vec4 total = vec4(0.0); + for (float i = -frag_info.edge; i <= frag_info.edge; i += 2) { + for (float j = -frag_info.edge; j <= frag_info.edge; j += 2) { + total += (Sample(v_texture_coords + frag_info.pixel_size * vec2(i, j)) * + frag_info.ratio); + } + } + frag_color = total; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/border_mask_blur.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/border_mask_blur.frag new file mode 100644 index 0000000000000000000000000000000000000000..55247604ad9537acdcdf02922b81812974838b14 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/border_mask_blur.frag @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +// Constant time mask blur for image borders. +// +// This mask blur extends the geometry of the source image (with clamp border +// sampling) and applies a Gaussian blur to the alpha mask at the edges. +// +// The blur itself works by mapping the Gaussian distribution's indefinite +// integral (using an erf approximation) to the 4 edges of the UV rectangle and +// multiplying them. + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + float16_t src_factor; + float16_t inner_blur_factor; + float16_t outer_blur_factor; + float16_t alpha; + + f16vec2 sigma_uv; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +float16_t BoxBlurMask(f16vec2 uv) { + // LTRB + return IPGaussianIntegral(uv.x, frag_info.sigma_uv.x) * // + IPGaussianIntegral(uv.y, frag_info.sigma_uv.y) * // + IPGaussianIntegral(1.0hf - uv.x, frag_info.sigma_uv.x) * // + IPGaussianIntegral(1.0hf - uv.y, frag_info.sigma_uv.y); +} + +void main() { + f16vec4 image_color = texture(texture_sampler, v_texture_coords); + float16_t blur_factor = BoxBlurMask(f16vec2(v_texture_coords)); + + float16_t within_bounds = + float16_t(v_texture_coords.x >= 0.0 && v_texture_coords.y >= 0.0 && + v_texture_coords.x < 1.0 && v_texture_coords.y < 1.0); + float16_t inner_factor = + (frag_info.inner_blur_factor * blur_factor + frag_info.src_factor) * + within_bounds; + float16_t outer_factor = + frag_info.outer_blur_factor * blur_factor * (1.0hf - within_bounds); + + float16_t mask_factor = inner_factor + outer_factor; + frag_color = image_color * mask_factor; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/color_matrix_color_filter.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/color_matrix_color_filter.frag new file mode 100644 index 0000000000000000000000000000000000000000..c9e74b1eda0efce36b4fcc5635686e7855ccd152 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/color_matrix_color_filter.frag @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +// A color filter that transforms colors through a 4x5 color matrix. +// +// This filter can be used to change the saturation of pixels, convert from YUV +// to RGB, etc. +// +// 4x5 matrix for transforming the color and alpha components of a Bitmap. +// The matrix can be passed as single array, and is treated as follows: +// +// [ a, b, c, d, e, +// f, g, h, i, j, +// k, l, m, n, o, +// p, q, r, s, t ] +// +// When applied to a color [R, G, B, A], the resulting color is computed as: +// +// R’ = a*R + b*G + c*B + d*A + e; +// G’ = f*R + g*G + h*B + i*A + j; +// B’ = k*R + l*G + m*B + n*A + o; +// A’ = p*R + q*G + r*B + s*A + t; +// +// That resulting color [R’, G’, B’, A’] then has each channel clamped to the 0 +// to 255 range. + +uniform FragInfo { + mat4 color_m; + f16vec4 color_v; + float16_t input_alpha; + float16_t output_alpha; +} +frag_info; + +uniform f16sampler2D input_texture; + +in highp vec2 v_texture_coords; +out f16vec4 frag_color; + +void main() { + f16vec4 input_color = + texture(input_texture, v_texture_coords) * frag_info.input_alpha; + + // unpremultiply first, as filter inputs are premultiplied. + f16vec4 color = IPHalfUnpremultiply(input_color); + + color = clamp(f16mat4(frag_info.color_m) * color + frag_info.color_v, + float16_t(0), float16_t(1.0)); + + // premultiply the outputs + frag_color = IPHalfPremultiply(color) * frag_info.output_alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position.vert b/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position.vert new file mode 100644 index 0000000000000000000000000000000000000000..5a631d8b1f039095cd65d33b03352ef8b9328dd9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position.vert @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + float texture_sampler_y_coord_scale; +} +frame_info; + +in vec2 position; + +out vec2 v_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_texture_coords = + IPRemapCoords(position, frame_info.texture_sampler_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position_uv.vert b/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position_uv.vert new file mode 100644 index 0000000000000000000000000000000000000000..0dbc6fd4bfad431ad2d5e89a819992613da9f9ad --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/filter_position_uv.vert @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + float texture_sampler_y_coord_scale; +} +frame_info; + +in vec2 position; +in vec2 texture_coords; + +out vec2 v_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_texture_coords = + IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/gaussian.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/gaussian.frag new file mode 100644 index 0000000000000000000000000000000000000000..a6d58f8e2b0a8e537fa940d9b8387182eca56e32 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/gaussian.frag @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include + +uniform f16sampler2D texture_sampler; + +layout(constant_id = 0) const float supports_decal = 1.0; + +uniform KernelSamples { + float sample_count; + + // X, Y are uv offset and Z is Coefficient. W is padding. + vec4 sample_data[50]; +} +kernel_samples; + +f16vec4 Sample(f16sampler2D tex, vec2 coords) { + if (supports_decal == 1.0) { + return texture(tex, coords); + } + return IPHalfSampleDecal(tex, coords); +} + +in vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + f16vec4 total_color = f16vec4(0.0hf); + + for (int i = 0; i < int(kernel_samples.sample_count); i++) { + float16_t coefficient = float16_t(kernel_samples.sample_data[i].z); + total_color += coefficient * + Sample(texture_sampler, + v_texture_coords + kernel_samples.sample_data[i].xy); + } + + frag_color = total_color; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/linear_to_srgb_filter.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/linear_to_srgb_filter.frag new file mode 100644 index 0000000000000000000000000000000000000000..d1f9e82930230aa499129ece00c7d3ed03f43b97 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/linear_to_srgb_filter.frag @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include + +// A color filter that applies the sRGB gamma curve to the color. +// +// This filter is used so that the colors are suitable for display in monitors. + +uniform f16sampler2D input_texture; + +uniform FragInfo { + float16_t input_alpha; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + f16vec4 input_color = + texture(input_texture, v_texture_coords) * frag_info.input_alpha; + + f16vec4 color = IPHalfUnpremultiply(input_color); + for (int i = 0; i < 3; i++) { + if (color[i] <= 0.0031308hf) { + color[i] = (color[i]) * 12.92hf; + } else { + color[i] = 1.055hf * pow(color[i], (1.0hf / 2.4hf)) - 0.055hf; + } + } + + frag_color = IPHalfPremultiply(color); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/morphology_filter.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/morphology_filter.frag new file mode 100644 index 0000000000000000000000000000000000000000..5cd47811367e43750e719d622c3b174520d295d3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/morphology_filter.frag @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +layout(constant_id = 0) const float supports_decal = 1.0; + +#include +#include +#include + +// These values must correspond to the order of the items in the +// 'FilterContents::MorphType' enum class. +// const float kMorphTypeDilate = 0.0; +// const float kMorphTypeErode = 1.0; + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + f16vec2 uv_offset; + float16_t radius; + float morph_type; + float supports_decal_sampler_address_mode; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + f16vec4 result = frag_info.morph_type == /*kMorphTypeDilate*/ 0.0 + ? f16vec4(0.0) + : f16vec4(1.0); + for (float16_t i = -frag_info.radius; i <= frag_info.radius; i++) { + vec2 texture_coords = v_texture_coords + frag_info.uv_offset * i; + + f16vec4 color; + if (supports_decal == 1) { + color = texture(texture_sampler, texture_coords); + } else { + color = IPHalfSampleDecal(texture_sampler, texture_coords); + } + + if (frag_info.morph_type == /*kMorphTypeDilate*/ 0.0) { + result = max(color, result); + } else { + result = min(color, result); + } + } + + frag_color = result; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/srgb_to_linear_filter.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/srgb_to_linear_filter.frag new file mode 100644 index 0000000000000000000000000000000000000000..67736e2185563708c9d936c4b1b5ed955c511743 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/srgb_to_linear_filter.frag @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include + +// Creates a color filter that applies the inverse of the sRGB gamma curve +// to the RGB channels. + +#include + +uniform f16sampler2D input_texture; + +uniform FragInfo { + float16_t input_alpha; +} +frag_info; + +in highp vec2 v_texture_coords; +out f16vec4 frag_color; + +void main() { + f16vec4 input_color = + texture(input_texture, v_texture_coords) * frag_info.input_alpha; + + f16vec4 color = IPHalfUnpremultiply(input_color); + for (int i = 0; i < 3; i++) { + if (color[i] <= 0.04045hf) { + color[i] = color[i] / 12.92hf; + } else { + color[i] = pow((color[i] + 0.055hf) / 1.055hf, 2.4hf); + } + } + + frag_color = IPHalfPremultiply(color); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/filters/yuv_to_rgb_filter.frag b/flutter/engine/src/flutter/impeller/entity/shaders/filters/yuv_to_rgb_filter.frag new file mode 100644 index 0000000000000000000000000000000000000000..b2f9416e180048f5e948aefa0273b588dacb2b22 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/filters/yuv_to_rgb_filter.frag @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +uniform f16sampler2D y_texture; +uniform f16sampler2D uv_texture; + +// These values must correspond to the order of the items in the +// 'YUVColorSpace' enum class. +// const float kBT601LimitedRange = 0.0; +// const float kBT601FullRange = 1.0; + +uniform FragInfo { + mat4 matrix; + float yuv_color_space; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + f16vec3 yuv; + f16vec3 yuv_offset = f16vec3(0.0hf, 0.5hf, 0.5hf); + if (frag_info.yuv_color_space == /*kBT601LimitedRange*/ 0.0) { + yuv_offset.x = 16.0hf / 255.0hf; + } + + yuv.x = texture(y_texture, v_texture_coords).r; + yuv.yz = texture(uv_texture, v_texture_coords).rg; + frag_color = f16mat4(frag_info.matrix) * f16vec4(yuv - yuv_offset, 1.0hf); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag b/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag new file mode 100644 index 0000000000000000000000000000000000000000..6d985c7889906939c60a7afb4f92e0e009139c00 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.frag @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include + +uniform f16sampler2D glyph_atlas_sampler; + +layout(constant_id = 0) const float use_alpha_color_channel = 1.0; + +uniform FragInfo { + float is_color_glyph; + float use_text_color; + f16vec4 text_color; +} +frag_info; + +in highp vec2 v_uv; + +out f16vec4 frag_color; + +void main() { + f16vec4 value = texture(glyph_atlas_sampler, v_uv); + + if (frag_info.is_color_glyph == 1.0) { + if (frag_info.use_text_color == 1.0) { + frag_color = value.aaaa * frag_info.text_color; + } else { + frag_color = value * frag_info.text_color.aaaa; + } + } else { + if (use_alpha_color_channel == 1.0) { + frag_color = value.aaaa * frag_info.text_color; + } else { + frag_color = value.rrrr * frag_info.text_color; + } + } +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert b/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert new file mode 100644 index 0000000000000000000000000000000000000000..75a8d2fa8a36148e3fdc63c9dd8ae06612e5467e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/glyph_atlas.vert @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 uv; +in vec2 position; + +out vec2 v_uv; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0, 1); + v_uv = uv; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_conical.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_conical.frag new file mode 100644 index 0000000000000000000000000000000000000000..5f5b3e332e90d57d4682ace41042a134d8761e8e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_conical.frag @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTConical(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + frag_color = DoConicalGradientTextureFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_radial.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_radial.frag new file mode 100644 index 0000000000000000000000000000000000000000..8dce92c60adc86b32cf56990f807b4f03ac92d96 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_radial.frag @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTRadial(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + frag_color = DoConicalGradientTextureFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip.frag new file mode 100644 index 0000000000000000000000000000000000000000..4997ef92c6a2cae4c18d2b1188a1065ff032579d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip.frag @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTStrip(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + frag_color = DoConicalGradientTextureFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip_radial.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip_radial.frag new file mode 100644 index 0000000000000000000000000000000000000000..377b7370e9d4259a1325ec36063afb8b39b3b1e8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_fill_strip_radial.frag @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = vec2(0.0, -1.0); + frag_color = DoConicalGradientTextureFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_ssbo_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_ssbo_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..6282d9e4ec589c5416533eb5762a7cb0cdb7419f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_ssbo_fill.frag @@ -0,0 +1,71 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include + +layout(constant_id = 0) const float kind = 3.0; + +struct ColorPoint { + vec4 color; + float stop; +}; + +layout(std140) readonly buffer ColorData { + ColorPoint colors[]; +} +color_data; + +uniform FragInfo { + highp vec2 center; + float radius; + float tile_mode; + vec4 decal_border_color; + float alpha; + int colors_length; + vec2 focus; + float focus_radius; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = IPComputeConicalT(kind, frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + + float t = res.x; + vec4 result_color = vec4(0); + if (res.y < 0.0 || + ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal)) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + for (int i = 1; i < frag_info.colors_length; i++) { + ColorPoint prev_point = color_data.colors[i - 1]; + ColorPoint current_point = color_data.colors[i]; + if (t >= prev_point.stop && t <= current_point.stop) { + float delta = (current_point.stop - prev_point.stop); + if (delta < 0.001) { + result_color = current_point.color; + } else { + float ratio = (t - prev_point.stop) / delta; + result_color = mix(prev_point.color, current_point.color, ratio); + } + break; + } + } + } + + frag_color = IPPremultiply(result_color) * frag_info.alpha; + frag_color = IPOrderedDither8x8(frag_color, gl_FragCoord.xy); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_conical.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_conical.frag new file mode 100644 index 0000000000000000000000000000000000000000..d83cad2d5cf00991a2a2a2f39355b62f2ab4a688 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_conical.frag @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTConical(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + frag_color = DoConicalGradientUniformFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_radial.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_radial.frag new file mode 100644 index 0000000000000000000000000000000000000000..ab98e5e094a6ba3649dadb0915f01523cc28ae85 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_radial.frag @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTRadial(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + + frag_color = DoConicalGradientUniformFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip.frag new file mode 100644 index 0000000000000000000000000000000000000000..2292614338f59da0e8c81cb83f3a29c9890f2cc4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip.frag @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = + IPComputeConicalTStrip(frag_info.focus, frag_info.focus_radius, + frag_info.center, frag_info.radius, v_position); + + frag_color = DoConicalGradientUniformFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip_radial.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip_radial.frag new file mode 100644 index 0000000000000000000000000000000000000000..e730bd282c71ef40871faacdcfd63027e72adb22 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/conical_gradient_uniform_fill_strip_radial.frag @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include +#include +#include +#include +#include +#include + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 res = vec2(0.0, -1.0); + frag_color = DoConicalGradientUniformFill(res); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.frag new file mode 100644 index 0000000000000000000000000000000000000000..b52f9aa3b2b55e8209656c87994e77ce57e4a4d8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.frag @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +uniform FragInfo { + float alpha; +} +frag_info; + +in vec4 v_color; + +out vec4 frag_color; + +void main() { + frag_color = IPPremultiply(v_color) * frag_info.alpha; + // mod operator is not supported in GLES 2.0 +#ifndef IMPELLER_TARGET_OPENGLES + frag_color = IPOrderedDither8x8(frag_color, gl_FragCoord.xy); +#endif // IMPELLER_TARGET_OPENGLES +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.vert b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.vert new file mode 100644 index 0000000000000000000000000000000000000000..44f1acae66c62092b1b75b30615d8e3f93dc98bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/fast_gradient.vert @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; +in mediump vec4 color; + +// The geometry of the fast gradient draws is designed so that the +// varying unit will perform the correct color interpolation. +out mediump vec4 v_color; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_color = color; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/gradient_fill.vert b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/gradient_fill.vert new file mode 100644 index 0000000000000000000000000000000000000000..824f496ea8c2231a0ba6975ac54113c255dc25e4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/gradient_fill.vert @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + mat4 matrix; +} +frame_info; + +in vec2 position; + +out vec2 v_position; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_position = IPVec2TransformPosition(frame_info.matrix, position); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..4d9a90f89646479c84a264a3ae629f6afca6b5ef --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_fill.frag @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +uniform sampler2D texture_sampler; + +uniform FragInfo { + highp vec2 start_point; + highp vec2 end_point; + float tile_mode; + vec4 decal_border_color; + float texture_sampler_y_coord_scale; + float alpha; + vec2 half_texel; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 start_to_end = frag_info.end_point - frag_info.start_point; + vec2 start_to_position = v_position - frag_info.start_point; + float t = + dot(start_to_position, start_to_end) / dot(start_to_end, start_to_end); + frag_color = + IPSampleLinearWithTileMode(texture_sampler, // + vec2(t, 0.5), // + frag_info.texture_sampler_y_coord_scale, // + frag_info.half_texel, // + frag_info.tile_mode, // + frag_info.decal_border_color); + frag_color = IPPremultiply(frag_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_ssbo_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_ssbo_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..00d5d5529faeed009ef2928b72cc51f01d5176d1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_ssbo_fill.frag @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include + +struct ColorPoint { + vec4 color; + float stop; + float inverse_delta; +}; + +layout(std140) readonly buffer ColorData { + ColorPoint colors[]; +} +color_data; + +uniform FragInfo { + highp vec2 start_point; + highp vec2 end_point; + float alpha; + float tile_mode; + vec4 decal_border_color; + int colors_length; + highp vec2 start_to_end; + float inverse_dot_start_to_end; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + highp vec2 start_to_position = v_position - frag_info.start_point; + highp float t = dot(start_to_position, frag_info.start_to_end) * + frag_info.inverse_dot_start_to_end; + + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + frag_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + for (int i = 1; i < frag_info.colors_length; i++) { + ColorPoint prev_point = color_data.colors[i - 1]; + ColorPoint current_point = color_data.colors[i]; + if (t >= prev_point.stop && t <= current_point.stop) { + if (current_point.inverse_delta > 1000.0) { + frag_color = current_point.color; + } else { + float ratio = (t - prev_point.stop) * current_point.inverse_delta; + frag_color = mix(prev_point.color, current_point.color, ratio); + } + break; + } + } + } + + frag_color = IPPremultiply(frag_color) * frag_info.alpha; + frag_color = IPOrderedDither8x8(frag_color, gl_FragCoord.xy); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_uniform_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_uniform_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..ace605876d9be7379d54753591f54c32a941c1a3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/linear_gradient_uniform_fill.frag @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include +#include + +uniform FragInfo { + highp vec2 start_point; + highp vec2 start_to_end; + float alpha; + float tile_mode; + float colors_length; + float inverse_dot_start_to_end; + vec4 decal_border_color; + vec4 colors[256]; + vec4 stop_pairs[128]; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + highp vec2 start_to_position = v_position - frag_info.start_point; + highp float t = dot(start_to_position, frag_info.start_to_end) * + frag_info.inverse_dot_start_to_end; + + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + frag_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + vec2 prev_stop = frag_info.stop_pairs[0].xy; + bool even = false; + for (int i = 1; i < frag_info.colors_length; i++) { + // stop_pairs[i/2].xy = values for stop i + // stop_pairs[i/2].zw = values for stop i+1 + vec2 cur_stop = even ? frag_info.stop_pairs[i / 2].xy + : frag_info.stop_pairs[i / 2].zw; + even = !even; + // stop.x == t value + // stop.y == inverse_delta to next stop + if (t >= prev_stop.x && t <= cur_stop.x) { + if (cur_stop.y > 1000.0) { + frag_color = frag_info.colors[i]; + } else { + float ratio = (t - prev_stop.x) * cur_stop.y; + frag_color = mix(frag_info.colors[i - 1], frag_info.colors[i], ratio); + } + break; + } + prev_stop = cur_stop; + } + } + + frag_color = IPPremultiply(frag_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..c1bbe80af7e06613d991293da9bc2da1fb6dfab3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_fill.frag @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include + +uniform sampler2D texture_sampler; + +uniform FragInfo { + highp vec2 center; + float radius; + float tile_mode; + vec4 decal_border_color; + float texture_sampler_y_coord_scale; + float alpha; + vec2 half_texel; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + float len = length(v_position - frag_info.center); + float t = len / frag_info.radius; + frag_color = + IPSampleLinearWithTileMode(texture_sampler, // + vec2(t, 0.5), // + frag_info.texture_sampler_y_coord_scale, // + frag_info.half_texel, // + frag_info.tile_mode, // + frag_info.decal_border_color); + frag_color = IPPremultiply(frag_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_ssbo_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_ssbo_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..2a7390ce39e0b649c139d8540a28987a6c1e0640 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_ssbo_fill.frag @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include +#include + +struct ColorPoint { + vec4 color; + float stop; +}; + +layout(std140) readonly buffer ColorData { + ColorPoint colors[]; +} +color_data; + +uniform FragInfo { + highp vec2 center; + float radius; + float tile_mode; + vec4 decal_border_color; + float alpha; + int colors_length; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + float len = length(v_position - frag_info.center); + float t = len / frag_info.radius; + + vec4 result_color = vec4(0); + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + for (int i = 1; i < frag_info.colors_length; i++) { + ColorPoint prev_point = color_data.colors[i - 1]; + ColorPoint current_point = color_data.colors[i]; + if (t >= prev_point.stop && t <= current_point.stop) { + float delta = (current_point.stop - prev_point.stop); + if (delta < 0.001) { + result_color = current_point.color; + } else { + float ratio = (t - prev_point.stop) / delta; + result_color = mix(prev_point.color, current_point.color, ratio); + } + break; + } + } + } + + frag_color = IPPremultiply(result_color) * frag_info.alpha; + frag_color = IPOrderedDither8x8(frag_color, gl_FragCoord.xy); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_uniform_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_uniform_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..f20163e68652d08c5344177482a3d178f1022a31 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/radial_gradient_uniform_fill.frag @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include +#include + +uniform FragInfo { + highp vec2 center; + float radius; + float tile_mode; + float alpha; + float colors_length; + vec4 decal_border_color; + vec4 colors[256]; + vec4 stop_pairs[128]; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + float len = length(v_position - frag_info.center); + float t = len / frag_info.radius; + + vec4 result_color = vec4(0); + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + vec2 prev_stop = frag_info.stop_pairs[0].xy; + bool even = false; + for (int i = 1; i < frag_info.colors_length; i++) { + // stop_pairs[i/2].xy = values for stop i + // stop_pairs[i/2].zw = values for stop i+1 + vec2 cur_stop = even ? frag_info.stop_pairs[i / 2].xy + : frag_info.stop_pairs[i / 2].zw; + even = !even; + // stop.x == t value + // stop.y == inverse_delta to next stop + if (t >= prev_stop.x && t <= cur_stop.x) { + if (cur_stop.y > 1000.0) { + result_color = frag_info.colors[i]; + } else { + float ratio = (t - prev_stop.x) * cur_stop.y; + result_color = + mix(frag_info.colors[i - 1], frag_info.colors[i], ratio); + } + break; + } + prev_stop = cur_stop; + } + } + + frag_color = IPPremultiply(result_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..fba9e2b4586e2a59e7a61c74f35f917ed4975267 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_fill.frag @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include +#include +#include + +uniform sampler2D texture_sampler; + +uniform FragInfo { + highp vec2 center; + float bias; + float scale; + float tile_mode; + vec4 decal_border_color; + float texture_sampler_y_coord_scale; + float alpha; + vec2 half_texel; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 coord = v_position - frag_info.center; + float angle = atan(-coord.y, -coord.x); + + float t = (angle * k1Over2Pi + 0.5 + frag_info.bias) * frag_info.scale; + frag_color = + IPSampleLinearWithTileMode(texture_sampler, // + vec2(t, 0.5), // + frag_info.texture_sampler_y_coord_scale, // + frag_info.half_texel, // + frag_info.tile_mode, // + frag_info.decal_border_color); + frag_color = IPPremultiply(frag_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_ssbo_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_ssbo_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..20d7f7d91b1481d886c77ee7b1f1502b908fda39 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_ssbo_fill.frag @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include +#include + +struct ColorPoint { + vec4 color; + float stop; +}; + +layout(std140) readonly buffer ColorData { + ColorPoint colors[]; +} +color_data; + +uniform FragInfo { + highp vec2 center; + float bias; + float scale; + float tile_mode; + vec4 decal_border_color; + float alpha; + int colors_length; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 coord = v_position - frag_info.center; + float angle = atan(-coord.y, -coord.x); + float t = (angle * k1Over2Pi + 0.5 + frag_info.bias) * frag_info.scale; + + vec4 result_color = vec4(0); + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + for (int i = 1; i < frag_info.colors_length; i++) { + ColorPoint prev_point = color_data.colors[i - 1]; + ColorPoint current_point = color_data.colors[i]; + if (t >= prev_point.stop && t <= current_point.stop) { + float delta = (current_point.stop - prev_point.stop); + if (delta < 0.001) { + result_color = current_point.color; + } else { + float ratio = (t - prev_point.stop) / delta; + result_color = mix(prev_point.color, current_point.color, ratio); + } + break; + } + } + } + + frag_color = IPPremultiply(result_color) * frag_info.alpha; + frag_color = IPOrderedDither8x8(frag_color, gl_FragCoord.xy); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_uniform_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_uniform_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..d25b62c5ba857cd10e5e8a267f709243bc4cd438 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/gradients/sweep_gradient_uniform_fill.frag @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include +#include + +uniform FragInfo { + highp vec2 center; + float bias; + float scale; + float tile_mode; + float alpha; + float colors_length; + vec4 decal_border_color; + vec4 colors[256]; + vec4 stop_pairs[128]; +} +frag_info; + +highp in vec2 v_position; + +out vec4 frag_color; + +void main() { + vec2 coord = v_position - frag_info.center; + float angle = atan(-coord.y, -coord.x); + float t = (angle * k1Over2Pi + 0.5 + frag_info.bias) * frag_info.scale; + + vec4 result_color = vec4(0); + if ((t < 0.0 || t > 1.0) && frag_info.tile_mode == kTileModeDecal) { + result_color = frag_info.decal_border_color; + } else { + t = IPFloatTile(t, frag_info.tile_mode); + + vec2 prev_stop = frag_info.stop_pairs[0].xy; + bool even = false; + for (int i = 1; i < frag_info.colors_length; i++) { + // stop_pairs[i/2].xy = values for stop i + // stop_pairs[i/2].zw = values for stop i+1 + vec2 cur_stop = even ? frag_info.stop_pairs[i / 2].xy + : frag_info.stop_pairs[i / 2].zw; + even = !even; + // stop.x == t value + // stop.y == inverse_delta to next stop + if (t >= prev_stop.x && t <= cur_stop.x) { + if (cur_stop.y > 1000.0) { + result_color = frag_info.colors[i]; + } else { + float ratio = (t - prev_stop.x) * cur_stop.y; + result_color = + mix(frag_info.colors[i - 1], frag_info.colors[i], ratio); + } + break; + } + prev_stop = cur_stop; + } + } + + frag_color = IPPremultiply(result_color) * frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/line.frag b/flutter/engine/src/flutter/impeller/entity/shaders/line.frag new file mode 100644 index 0000000000000000000000000000000000000000..a7da54bf6a22689131d680563349ab9263418513 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/line.frag @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include + +uniform FragInfo { + vec4 color; +} +frag_info; + +uniform sampler2D curve; + +highp in vec2 v_position; +// These should be `flat` but that doesn't work in our glsl compiler. It +// shouldn't make any visual difference. +highp in vec3 v_e0; +highp in vec3 v_e1; +highp in vec3 v_e2; +highp in vec3 v_e3; + +out vec4 frag_color; + +float lookup(float x) { + return texture(curve, vec2(x, 0)).r; +} + +float CalculateLine() { + vec3 pos = vec3(v_position.xy, 1.0); + vec4 d = vec4(dot(pos, v_e0), dot(pos, v_e1), dot(pos, v_e2), dot(pos, v_e3)); + + if (any(lessThan(d, vec4(0.0)))) { + return 0.0; + } + + return lookup(min(d.x, d.z)) * lookup(min(d.y, d.w)); +} + +void main() { + float line = CalculateLine(); + frag_color = vec4(frag_info.color.xyz, line); + ////////////////////////////////////////////////////////////////////////////// + // This is a nice way to visually debug this shader: + // frag_color = + // vec4(mix(vec3(1, 0,0), frag_info.color.xyz, line), 1.0); + ////////////////////////////////////////////////////////////////////////////// + frag_color = IPPremultiply(frag_color); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/line.vert b/flutter/engine/src/flutter/impeller/entity/shaders/line.vert new file mode 100644 index 0000000000000000000000000000000000000000..938bfdc2825d921603eb99d42846d4d76e63c73f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/line.vert @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; + +in vec3 e0; +in vec3 e1; +in vec3 e2; +in vec3 e3; + +out vec2 v_position; +out vec3 v_e0; +out vec3 v_e1; +out vec3 v_e2; +out vec3 v_e3; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_position = position; + v_e0 = e0; + v_e1 = e1; + v_e2 = e2; + v_e3 = e3; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.frag b/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.frag new file mode 100644 index 0000000000000000000000000000000000000000..934262de90b6600c6beffa39dafb71af3f7143d0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.frag @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// The math for this shader was based on the work done in Raph Levien's blog +// post "Blurred rounded rectangles": +// https://web.archive.org/web/20231103044404/https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html + +precision highp float; + +#include +#include +#include + +uniform FragInfo { + f16vec4 color; + vec2 center; + vec2 adjust; + float minEdge; + float r1; + float exponent; + float sInv; + float exponentInv; + float scale; +} +frag_info; + +in vec2 v_position; + +out f16vec4 frag_color; + +const float kTwoOverSqrtPi = 2.0 / sqrt(3.1415926); + +float maxXY(vec2 v) { + return max(v.x, v.y); +} + +// use crate::math::compute_erf7; +float computeErf7(float x) { + x *= kTwoOverSqrtPi; + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1.0 + x * x); +} + +// The length formula, but with an exponent other than 2 +float powerDistance(vec2 p) { + float xp = POW(p.x, frag_info.exponent); + float yp = POW(p.y, frag_info.exponent); + return POW(xp + yp, frag_info.exponentInv); +} + +void main() { + vec2 adjusted = abs(v_position - frag_info.center) - frag_info.adjust; + + float dPos = powerDistance(max(adjusted, 0.0)); + float dNeg = min(maxXY(adjusted), 0.0); + float d = dPos + dNeg - frag_info.r1; + float z = + frag_info.scale * (computeErf7(frag_info.sInv * (frag_info.minEdge + d)) - + computeErf7(frag_info.sInv * d)); + + frag_color = frag_info.color * float16_t(z); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.vert b/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.vert new file mode 100644 index 0000000000000000000000000000000000000000..87382f6b4dcbe7226ba4cc498999c0cfbf0add87 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/rrect_blur.vert @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; + +out vec2 v_position; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + // The fragment stage uses local coordinates to compute the blur. + v_position = position; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/runtime_effect.vert b/flutter/engine/src/flutter/impeller/entity/shaders/runtime_effect.vert new file mode 100644 index 0000000000000000000000000000000000000000..77b92d221142ce92b4c59c8353fda9258ef277b5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/runtime_effect.vert @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; +// Note: The GLES backend uses name matching for attribute locations. This name +// must match the name of the attribute input in: +// impeller/compiler/shader_lib/flutter/runtime_effect.glsl +out vec2 _fragCoord; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + _fragCoord = position; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..b00d69b2db7e0f1077a95cf2f67e4b0bc6d9d19c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.frag @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include + +uniform FragInfo { + vec4 color; +} +frag_info; + +out vec4 frag_color; + +void main() { + frag_color = frag_info.color; +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.vert b/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.vert new file mode 100644 index 0000000000000000000000000000000000000000..4d8e67e74a2ef986f2f19f6632b1c33fb18229bb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/solid_fill.vert @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample.frag b/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample.frag new file mode 100644 index 0000000000000000000000000000000000000000..5b7b14d10700235b53d3c7e429b6a1e6a3a1c33b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample.frag @@ -0,0 +1,7 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define SUPPORTS_DECAL 1 + +#include diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample_gles.frag b/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample_gles.frag new file mode 100644 index 0000000000000000000000000000000000000000..a16583437c2d7dbfc5f57f52af991dcb20391815 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_downsample_gles.frag @@ -0,0 +1,5 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..bd9dbd30c374e7fe5e495f25d356af5cdf37d33d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.frag @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + float alpha; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + f16vec4 sampled = + texture(texture_sampler, v_texture_coords, float16_t(kDefaultMipBias)); + frag_color = sampled * float16_t(frag_info.alpha); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.vert b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.vert new file mode 100644 index 0000000000000000000000000000000000000000..49338765bd3876fd5a87494378416079fb8d9db6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill.vert @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +uniform FrameInfo { + mat4 mvp; + float texture_sampler_y_coord_scale; +} +frame_info; + +in vec2 position; +in vec2 texture_coords; + +out highp vec2 v_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_texture_coords = + IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill_strict_src.frag b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill_strict_src.frag new file mode 100644 index 0000000000000000000000000000000000000000..0165250b8a9682368e8169b23adb445703fc8708 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_fill_strict_src.frag @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + vec4 source_rect; + float alpha; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + vec2 texture_coords = vec2(clamp(v_texture_coords.x, frag_info.source_rect.x, + frag_info.source_rect.z), + clamp(v_texture_coords.y, frag_info.source_rect.y, + frag_info.source_rect.w)); + f16vec4 sampled = + texture(texture_sampler, texture_coords, float16_t(kDefaultMipBias)); + frag_color = sampled * float16_t(frag_info.alpha); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/texture_uv_fill.vert b/flutter/engine/src/flutter/impeller/entity/shaders/texture_uv_fill.vert new file mode 100644 index 0000000000000000000000000000000000000000..cd07abfdaea59f6ba285a08b15524d76beed8de2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/texture_uv_fill.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +// A shader that computes texture UVs from a normalizing transform. +uniform FrameInfo { + mat4 mvp; + // A normlizing transform created from the texture bounds and effect transform + mat4 uv_transform; + float texture_sampler_y_coord_scale; +} +frame_info; + +in vec2 position; + +out highp vec2 v_texture_coords; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + vec2 texture_coords = (frame_info.uv_transform * vec4(position, 0.0, 1.0)).xy; + v_texture_coords = + IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill.frag b/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill.frag new file mode 100644 index 0000000000000000000000000000000000000000..25b2af3526ecfb4151a8028fb0e20f30f59cea35 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill.frag @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include +#include + +layout(constant_id = 0) const float supports_decal = 1.0; + +uniform f16sampler2D texture_sampler; + +uniform FragInfo { + float x_tile_mode; + float y_tile_mode; + float alpha; +} +frag_info; + +in highp vec2 v_texture_coords; + +out f16vec4 frag_color; + +void main() { + if (supports_decal == 1.0) { + frag_color = texture(texture_sampler, // sampler + v_texture_coords, // texture coordinates + float16_t(kDefaultMipBias)) * + float16_t(frag_info.alpha); + } else { + frag_color = IPHalfSampleWithTileMode( + texture_sampler, // sampler + v_texture_coords, // texture coordinates + float16_t(frag_info.x_tile_mode), // x tile mode + float16_t(frag_info.y_tile_mode) // y tile mode + ) * + float16_t(frag_info.alpha); + } +} diff --git a/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill_external.frag b/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill_external.frag new file mode 100644 index 0000000000000000000000000000000000000000..610c4bb44936c11d0e10072702c68c9b0b6ee667 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/entity/shaders/tiled_texture_fill_external.frag @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision mediump float; + +#include + +uniform sampler2D SAMPLER_EXTERNAL_OES_texture_sampler; + +uniform FragInfo { + float x_tile_mode; + float y_tile_mode; + float alpha; +} +frag_info; + +in highp vec2 v_texture_coords; + +out vec4 frag_color; + +void main() { + frag_color = + IPSampleWithTileModeOES(SAMPLER_EXTERNAL_OES_texture_sampler, // sampler + v_texture_coords, // texture coordinates + frag_info.x_tile_mode, // x tile mode + frag_info.y_tile_mode // y tile mode + ) * + frag_info.alpha; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/README.md b/flutter/engine/src/flutter/impeller/fixtures/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5c937aab5e4b3ee7c1c448b4a349a875044b0af7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/README.md @@ -0,0 +1,5 @@ +# The Impeller Fixtures Set + +Unlike other targets in the buildroot, all Impeller unit-tests use the same +fixture set and are invoked using a single test harness (`impeller_unittest`). +This is for convenience but also to make working with shader libraries easier. diff --git a/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.frag b/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.frag new file mode 100644 index 0000000000000000000000000000000000000000..fc61864108b1dda590006dd9bd501e4b2d086719 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.frag @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec4 v_color; +out vec4 frag_color; + +void main() { + frag_color = v_color; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.vert b/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.vert new file mode 100644 index 0000000000000000000000000000000000000000..91a85ec71020855c66281ba32d95ab9b48f58be0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/flutter_gpu_unlit.vert @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform VertInfo { // 128 bytes (alignment = NPOT(largest member)) + mat4 mvp; // offset 0 bytes, size 64 bytes + vec4 color; // offset 64 bytes, size 16 bytes +} +vert_info; + +in vec2 position; +out vec4 v_color; + +void main() { + v_color = vert_info.color; + gl_Position = vert_info.mvp * vec4(position, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/golden_paths.h b/flutter/engine/src/flutter/impeller/fixtures/golden_paths.h new file mode 100644 index 0000000000000000000000000000000000000000..16767f766b776145d99cdcd048296c8941a41663 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/golden_paths.h @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_FIXTURES_GOLDEN_PATHS_H_ +#define FLUTTER_IMPELLER_FIXTURES_GOLDEN_PATHS_H_ + +#include + +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/point.h" + +namespace impeller { +namespace testing { + +std::vector golden_cubic_and_quad_points = { + {139.982, 19.5003}, {140.018, 20.4997}, {131.747, 19.8026}, + {131.783, 20.802}, {131.715, 19.8048}, {131.815, 20.7998}, + {123.622, 20.6102}, {123.721, 21.6053}, {123.59, 20.6145}, + {123.753, 21.601}, {115.652, 21.9306}, {115.816, 22.9171}, + {115.619, 21.9372}, {115.848, 22.9105}, {107.85, 23.7687}, + {108.08, 24.742}, {107.817, 23.7777}, {108.113, 24.733}, + {100.23, 26.1264}, {100.526, 27.0817}, {100.197, 26.1378}, + {100.558, 27.0703}, {92.8037, 29.0025}, {93.165, 29.935}, + {92.7736, 29.0154}, {93.1952, 29.9221}, {85.708, 32.3003}, + {86.1296, 33.2071}, {85.68, 32.3144}, {86.1576, 33.193}, + {78.8865, 36.008}, {79.3641, 36.8865}, {78.8588, 36.0242}, + {79.3918, 36.8703}, {72.3485, 40.125}, {72.8815, 40.9711}, + {72.3216, 40.1432}, {72.9084, 40.9529}, {66.1045, 44.6479}, + {66.6913, 45.4577}, {66.0788, 44.6679}, {66.717, 45.4378}, + {60.1632, 49.5711}, {60.8014, 50.341}, {60.139, 49.5924}, + {60.8255, 50.3196}, {54.5317, 54.8864}, {55.2183, 55.6136}, + {54.5094, 54.909}, {55.2406, 55.591}, {49.254, 60.5436}, + {49.9853, 61.2257}, {49.2329, 60.5677}, {50.0063, 61.2016}, + {44.3684, 66.5025}, {45.1418, 67.1364}, {44.3488, 66.5281}, + {45.1614, 67.1108}, {39.8827, 72.7564}, {40.6954, 73.3391}, + {39.8648, 72.7832}, {40.7133, 73.3123}, {35.8029, 79.297}, + {36.6515, 79.8261}, {35.7869, 79.3246}, {36.6675, 79.7985}, + {32.1328, 86.1144}, {33.0134, 86.5883}, {32.1188, 86.1424}, + {33.0273, 86.5603}, {28.8739, 93.1973}, {29.7824, 93.6152}, + {28.8613, 93.2272}, {29.795, 93.5853}, {26.0399, 100.583}, + {26.9736, 100.941}, {26.0288, 100.615}, {26.9847, 100.908}, + {23.7144, 108.15}, {24.6704, 108.444}, {23.7056, 108.183}, + {24.6792, 108.411}, {21.9002, 115.886}, {22.8738, 116.115}, + {21.8937, 115.919}, {22.8804, 116.082}, {20.5962, 123.779}, + {21.5828, 123.942}, {20.592, 123.812}, {21.5871, 123.91}, + {19.7985, 131.816}, {20.7936, 131.914}, {19.7964, 131.847}, + {20.7957, 131.883}, {19.5003, 139.982}, {20.4997, 140.018}, + {20.2883, 140.409}, {19.7117, 139.591}, {29.9421, 133.595}, + {29.3655, 132.778}, {29.9544, 133.586}, {29.3532, 132.787}, + {39.1905, 126.639}, {38.5894, 125.839}, {39.2039, 126.628}, + {38.576, 125.85}, {47.9822, 119.545}, {47.3542, 118.767}, + {47.9968, 119.533}, {47.3396, 118.779}, {56.2739, 112.316}, + {55.6167, 111.562}, {56.2898, 112.302}, {55.6008, 111.577}, + {64.0197, 104.952}, {63.3307, 104.228}, {64.0369, 104.935}, + {63.3134, 104.245}, {71.1714, 97.4578}, {70.4479, 96.7675}, + {71.1899, 97.4373}, {70.4294, 96.7879}, {77.6791, 89.8381}, + {76.9187, 89.1887}, {77.6987, 89.8137}, {76.8991, 89.2131}, + {83.4923, 82.1009}, {82.6928, 81.5003}, {83.5125, 82.0718}, + {82.6725, 81.5293}, {88.5609, 74.2563}, {87.7209, 73.7138}, + {88.5812, 74.2221}, {87.7007, 73.748}, {92.8369, 66.3173}, + {91.9564, 65.8432}, {92.8562, 66.2772}, {91.9371, 65.8833}, + {96.2756, 58.299}, {95.3564, 57.9051}, {96.2927, 58.253}, + {95.3393, 57.951}, {98.8374, 50.2196}, {97.8841, 49.9176}, + {98.8508, 50.1681}, {97.8708, 49.969}, {100.49, 42.0995}, + {99.51, 41.9005}, {100.49, 42.0995}, {99.51, 41.9005}, +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_FIXTURES_GOLDEN_PATHS_H_ diff --git a/flutter/engine/src/flutter/impeller/fixtures/gradient.frag b/flutter/engine/src/flutter/impeller/fixtures/gradient.frag new file mode 100644 index 0000000000000000000000000000000000000000..249efd246969b806bb69362f5f79b48573408530 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/gradient.frag @@ -0,0 +1,10 @@ +#include + +uniform vec2 uSize; + +out vec4 fragColor; + +void main() { + float v = FlutterFragCoord().y / uSize.y; + fragColor = vec4(v, v, v, 1); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/half.frag b/flutter/engine/src/flutter/impeller/fixtures/half.frag new file mode 100644 index 0000000000000000000000000000000000000000..527476d8b6eb8983303350317e8c1ffe398a52d9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/half.frag @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#extension GL_AMD_gpu_shader_half_float : enable +#extension GL_AMD_gpu_shader_half_float_fetch : enable +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable + +uniform FragInfo { + float16_t half_1; + f16vec2 half_2; + f16vec3 half_3; + f16vec4 half_4; +} +frag_info; + +out vec4 frag_color; + +void main() { + frag_color = vec4(0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/impeller.frag b/flutter/engine/src/flutter/impeller/fixtures/impeller.frag new file mode 100644 index 0000000000000000000000000000000000000000..5c2261ae8cb0e1f9aff4bc76b0d5f9b51f91d3f2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/impeller.frag @@ -0,0 +1,437 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform samplerCube cube_map; +uniform sampler2D blue_noise; + +uniform FragInfo { + vec2 texture_size; + float time; +} +frag_info; + +in vec2 v_screen_position; +out vec4 frag_color; + +const float kPi = acos(-1.0); +const float kHalfSqrtTwo = sqrt(2.0) / 2.0; +const float kEpsilon = 0.001; + +// Materials (Albedo + reflectivity) +const vec4 kBottomColor = vec4(0.0, 0.34, 0.61, 0.5); +const vec4 kMiddleColor = vec4(0.16, 0.71, 0.96, 0.5); +const vec4 kTopColor = vec4(0.33, 0.77, 0.97, 0.5); +const vec4 kImpellerOuterColor = vec4(0.16, 0.71, 0.96, 0.5); +const vec4 kImpellerRimColor = vec4(0.1, 0.1, 0.1, 0.0); +const vec4 kImpellerBladeColor = vec4(0.1, 0.1, 0.1, 1.3); + +// Scene +const int kMaxSteps = 70; +const float kMaxDistance = 300.0; +const vec3 kSunDirection = normalize(vec3(2, -5, 3)); +const float kGlowBlend = 1.1; +const vec4 kGlowColor = vec4(0.86, 0.98, 1.0, 1); +const vec4 kGlowColor2 = vec4(1.66, 0.98, 0.5, 1); +// These refraction ratios are inverted for style purposes. +const float kAirToGlassIOR = 1.10; +const float kGlassToAirIOR = 1.0 / kAirToGlassIOR; + +// Camera +const float kFocalLength = 12.0; +const float kApertureSize = 0.5; +const int kRaysPerFrag = 4; + +mat3 RotateEuler(vec3 r) { + return mat3( + cos(r.x) * cos(r.y), cos(r.x) * sin(r.y) * sin(r.z) - sin(r.x) * cos(r.z), + cos(r.x) * sin(r.y) * cos(r.z) + sin(r.x) * sin(r.z), sin(r.x) * cos(r.y), + sin(r.x) * sin(r.y) * sin(r.z) + cos(r.x) * cos(r.z), + sin(r.x) * sin(r.y) * cos(r.z) - cos(r.x) * sin(r.z), -sin(r.y), + cos(r.y) * sin(r.z), cos(r.y) * cos(r.z)); +} + +//------------------------------------------------------------------------------ +/// Noise functions. +/// + +vec2 Hash(float seed) { + vec2 n = vec2(dot(vec2(seed, -0.1), vec2(13.8767971, 22.2091485)), + dot(vec2(seed, -0.2), vec2(12.3432217, 48.0579381))); + return fract(sin(n) * 24791.8159993); +} + +vec4 BlueNoise(vec2 uv) { + return texture(blue_noise, uv); +} + +vec4 BlueNoiseWithRandomOffset(vec2 screen_position, float seed) { + return BlueNoise(screen_position / 256.0 + Hash(seed)); +} + +//------------------------------------------------------------------------------ +/// Primitive distance functions. +/// + +float SphereDistance(vec3 sample_position, + vec3 sphere_position, + float sphere_size) { + return length(sample_position - sphere_position) - sphere_size; +} + +float CuboidDistance(vec3 sample_position, vec3 cuboid_size) { + vec3 space = abs(sample_position) - cuboid_size; + return length(max(space, 0.0)) + + min(max(space.x, max(space.y, space.z)), 0.0); +} + +//------------------------------------------------------------------------------ +/// Scene distance functions. +/// + +float GlassBox(vec3 pos) { + mat3 basis = RotateEuler(vec3(frag_info.time * 0.21, frag_info.time * 0.24, + frag_info.time * 0.17)); + vec3 glass_box_pos = pos + vec3(0, -4.5 + sin(frag_info.time), 0.0); + return CuboidDistance(basis * glass_box_pos, vec3(1, 1, 1)) - 3.0; +} + +vec2 FlutterLogoField(vec3 pos) { + pos *= 1.3; // Scale down a bit. + + // The shape below is made up of three parallelepipeds, each of which is a + // cuboid in scaled + skewed space. These shape fields are multiplied by the + // inverse of the max basis vector length of the space (i.e. 1 / sqrt(2); the + // same as kHalfSqrtTwo), which scales down the ray march step size by the + // right amount to avoid overstepping errors. + const float kFieldScale = kHalfSqrtTwo * 1.0 / 1.3; + + vec3 r = vec3(sin(frag_info.time * 1.137) / 7.0, // + sin(frag_info.time * 1.398 + 0.7) / 8.0, // + sin(frag_info.time * 0.873 + 0.3) / 5.0); + // This homegrown rotation matrix isn't perfect, but it's fine for the < PI/2 + // rotation being applied to the logo. + mat3 logo_basis = mat3(cos(r.z) * cos(r.y), sin(r.z), -sin(r.y), // + -sin(r.z), cos(r.z) * cos(r.x), -sin(r.x), // + sin(r.y), sin(r.x), cos(r.x) * cos(r.y)); + vec3 logo_pos = + logo_basis * pos + vec3(-1.0, -4.0 + sin(frag_info.time), 0.0); + + // Bottom prism. + + float logo0 = + CuboidDistance(logo_pos + vec3(-logo_pos.y, 0, 0), vec3(1, 2, 0.6)) * + kFieldScale; + float logo0_cutoff_plane = + dot(logo_pos + vec3(0.5, 0.5, 0), normalize(vec3(1, 1, 0))); + logo0 = max(logo0, logo0_cutoff_plane); + + float dist = logo0; + float material = 1.0; + + // Middle prism. + + float logo1 = + CuboidDistance(logo_pos + vec3(logo_pos.y, 0, 0), vec3(1, 2, 0.7)) * + kFieldScale; + float logo1_cutoff_plane = + dot(logo_pos + vec3(-0.5, 0.5, 0), normalize(vec3(1, -1, 0))); + logo1 = max(logo1, logo1_cutoff_plane); + + if (logo1 < dist) { + dist = logo1; + + float material_cutoff_plane = + dot(logo_pos + vec3(0.5, -0.5, 0), normalize(vec3(1, -1, 0))); + material = material_cutoff_plane > 0.0 ? 2.0 : 3.0; + } + + // Top prism. + + float logo2 = CuboidDistance(logo_pos + vec3(logo_pos.y - 3.0, -2, 0), + vec3(1, 3.5, 0.7)) * + kFieldScale; + logo2 = max(logo2, logo1_cutoff_plane); + + if (logo2 < dist) { + dist = logo2; + material = 3.0; + } + + return vec2(dist, material); +} + +vec2 InnerGlassBoxField(vec3 pos) { + vec2 flutter_logo = FlutterLogoField(pos); + float dist = flutter_logo.x; + float material = flutter_logo.y; + + // Inner glass box. + float glass_box = -GlassBox(pos); + if (glass_box < dist) { + dist = glass_box; + material = -3.0; // Transfer from glass to air. + } + + return vec2(dist, material); +} + +vec2 ImpellerField(vec3 pos) { + float xz_dist = length(pos.xz); + float impeller = min(0.5, xz_dist / 3.0) * + sin(xz_dist * 2.0 - mod(frag_info.time, kPi) * 30.0 + + atan(pos.z, pos.x) * 6.0) * + 1.5; + float impeller_side = xz_dist / 2.0 - 4.0; + float stage_height = + mix(impeller, impeller_side, clamp(xz_dist - 4.6, 0.0, 1.0)); + float stage_plane = + dot(pos + vec3(0, 3.0 + stage_height, 0), normalize(vec3(0, 1, 0))) * 0.5; + float stage_sphere = SphereDistance(pos + vec3(0, 2, 0), vec3(0), 6.0); + float stage = max(stage_plane, stage_sphere); + + float material = 4.0; + if (xz_dist < 5.6 && pos.y > -7.0) { + material = (pos.y > -2.36 && pos.y < -2.1) ? 5.0 : 6.0; + } else { + material = 4.0; + } + + return vec2(stage, material); +} + +vec2 SceneField(vec3 pos) { + float glass_box = GlassBox(pos); + float dist = glass_box; + float material = -2.0; // Transfer from air to glass. + + vec2 impeller = ImpellerField(pos); + if (impeller.x < dist) { + dist = impeller.x; + material = impeller.y; + } + + return vec2(dist - 0.01, material); +} + +/// For shadows, just ignore the glass box. +vec2 ShadowField(vec3 pos) { + vec2 flutter_logo = FlutterLogoField(pos); + float dist = flutter_logo.x; + float material = flutter_logo.y; + + vec2 impeller = ImpellerField(pos); + if (impeller.x < dist) { + dist = impeller.x; + material = impeller.y; + } + + return vec2(dist, material); +} + +//------------------------------------------------------------------------------ +/// Surface computation. +/// + +vec2 March(vec3 sample_position, + vec3 dir, + out int steps_taken, + bool inside_glass_box, + bool shadow) { + float depth = 0.0; + for (int i = 0; i < kMaxSteps; i++) { + if (depth > kMaxDistance) { + steps_taken = i; + return vec2(kMaxDistance, -1.0); + } + + vec3 pos = sample_position + dir * depth; + vec2 result; + if (shadow) { + result = ShadowField(pos); + } else { + result = inside_glass_box ? InnerGlassBoxField(pos) : SceneField(pos); + } + if (abs(result.x) < kEpsilon) { + steps_taken = i; + return vec2(depth, result.y); + } + + depth += result.x; + } + steps_taken = kMaxSteps; + return vec2(kMaxDistance, -1.0); +} + +vec3 SceneGradient(vec3 sample_position) { + return normalize( + vec3(SceneField(sample_position + vec3(kEpsilon, 0, 0)).x - + SceneField(sample_position + vec3(-kEpsilon, 0, 0)).x, + SceneField(sample_position + vec3(0, kEpsilon, 0)).x - + SceneField(sample_position + vec3(0, -kEpsilon, 0)).x, + SceneField(sample_position + vec3(0, 0, kEpsilon)).x - + SceneField(sample_position + vec3(0, 0, -kEpsilon)).x)); +} + +vec3 InnerGlassGradient(vec3 sample_position) { + return normalize( + vec3(InnerGlassBoxField(sample_position + vec3(kEpsilon, 0, 0)).x - + InnerGlassBoxField(sample_position + vec3(-kEpsilon, 0, 0)).x, + InnerGlassBoxField(sample_position + vec3(0, kEpsilon, 0)).x - + InnerGlassBoxField(sample_position + vec3(0, -kEpsilon, 0)).x, + InnerGlassBoxField(sample_position + vec3(0, 0, kEpsilon)).x - + InnerGlassBoxField(sample_position + vec3(0, 0, -kEpsilon)).x)); +} + +float MarchShadow(vec3 position) { + int shadow_steps; + vec2 shadow_result = March(position + -kSunDirection * 0.03, -kSunDirection, + shadow_steps, false, true); + float shadow_percentage = (float(shadow_steps)) / float(kMaxSteps); + float shadow_multiplier = 1.6 - shadow_percentage; + if (shadow_result.x < kMaxDistance) { + shadow_multiplier = 0.6; + } + return shadow_multiplier; +} + +//------------------------------------------------------------------------------ +/// Color composition. +/// + +vec4 EnvironmentColor(vec3 ray_direction) { + return texture(cube_map, ray_direction); +} + +vec4 SurfaceColor(vec3 ray_direction, + vec3 surface_position, + vec3 surface_normal, + float material, + float shadow_multiplier) { + vec3 reflection_direction = reflect(ray_direction, surface_normal); + vec4 reflection_color = texture(cube_map, reflection_direction); + + vec4 material_value; + if (material < 1.5) { + material_value = kBottomColor; + } else if (material < 2.5) { + material_value = kMiddleColor; + } else if (material < 3.5) { + material_value = kTopColor; + } else if (material < 4.5) { + material_value = kImpellerOuterColor; + } else if (material < 5.5) { + material_value = kImpellerRimColor; + } else { + material_value = kImpellerBladeColor; + } + + return mix(vec4(material_value.rgb * shadow_multiplier, 1.0), + reflection_color, + dot(-ray_direction, surface_normal) - 1.0 + material_value.a); +} + +vec4 SceneColor(vec3 ray_position, + vec3 ray_direction, + vec3 surface_normal, + float dist, + float material, + int steps_taken, + float shadow_multiplier, + vec4 ray_noise) { + vec4 result_color; + if (dist >= kMaxDistance) { + result_color = EnvironmentColor(ray_direction); + } else { + vec3 surface_position = ray_position + ray_direction * dist; + result_color = SurfaceColor(ray_direction, surface_position, surface_normal, + material, shadow_multiplier); + } + float glow_factor = float(steps_taken) / float(kMaxSteps); + vec4 glow_color = + mix(kGlowColor, kGlowColor2, sin(frag_info.time / 3.0) * 0.5 + 0.5); + return mix(result_color, glow_color, glow_factor * kGlowBlend); +} + +vec4 CombinedColor(vec3 ray_position, vec3 ray_direction, vec4 ray_noise) { + int steps_taken; + vec2 result = March(ray_position, ray_direction, steps_taken, false, false); + ray_position = ray_position + ray_direction * result.x; + vec3 surface_normal = SceneGradient(ray_position); + + float glass_reflection_factor = 0.0; + vec4 glass_reflection_color = vec4(0); + if (result.y == -2.0) { // March into the glass. + vec3 glass_reflection_direction = reflect(ray_direction, surface_normal); + glass_reflection_color = EnvironmentColor(glass_reflection_direction); + glass_reflection_factor = + 0.5 - dot(glass_reflection_direction, surface_normal) * 0.6; + + ray_direction = refract(ray_direction, surface_normal, kAirToGlassIOR); + ray_position += ray_direction * 0.5; + int steps; + result = March(ray_position, ray_direction, steps, true, false); + steps_taken += steps; + + ray_position = ray_position + ray_direction * result.x; + surface_normal = InnerGlassGradient(ray_position); + } + + if (result.y == -3.0) { // March out of the glass. + ray_direction = refract(ray_direction, surface_normal, kGlassToAirIOR); + ray_position += ray_direction * 1.0; + int steps; + result = March(ray_position + ray_direction * result.x, ray_direction, + steps, false, false); + steps_taken += steps; + ray_position = ray_position + ray_direction * result.x; + surface_normal = SceneGradient(ray_position); + } + + float shadow_multiplier = MarchShadow(ray_position); + vec4 scene_color = + SceneColor(ray_position, ray_direction, surface_normal, result.x, + result.y, steps_taken, shadow_multiplier, ray_noise); + + return mix(scene_color, glass_reflection_color, glass_reflection_factor); +} + +//------------------------------------------------------------------------------ +/// Camera/lens. +/// + +vec3 GetFragDirection(vec2 uv, vec3 cam_forward) { + vec2 lens_uv = + (uv - 0.5 * frag_info.texture_size) / frag_info.texture_size.xx; + vec3 cam_right = cross(cam_forward, vec3(0, 1, 0)); + vec3 cam_up = cross(cam_forward, cam_right); + + float fov = 65.0 * kPi / 180.0; + return normalize(cam_forward * cos(fov) + cam_right * lens_uv.x * sin(fov) + + cam_up * lens_uv.y * sin(fov)); +} + +void main() { + float cam_time = frag_info.time / 2.0; + vec3 cam_position = + vec3(-sin(cam_time + 0.2) * 6.25, -cos(cam_time + 0.3) * 2.9 + 1.0, + -cos(cam_time - 0.1) * 5.4) * + 2.0; + vec3 cam_direction = normalize(-cam_position); + cam_position += vec3(0, 2, 0); + + vec3 ray_direction = GetFragDirection(v_screen_position, cam_direction); + vec3 lens_position = cam_position + ray_direction * kFocalLength; + + for (int i = 0; i < kRaysPerFrag; i++) { + vec4 ray_noise = BlueNoiseWithRandomOffset( + v_screen_position, float(i) + mod(frag_info.time, 10.0)); + // The rays should be starting from a flat position on the lens, but just + // jittering them around in a 3d box looks good enough. + vec3 ray_start = cam_position + ray_noise.xyz * kApertureSize; + vec3 ray_direction = normalize(lens_position - ray_start); + + vec4 result_color = CombinedColor(ray_start, ray_direction, ray_noise); + frag_color += result_color / float(kRaysPerFrag); + } +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/impeller.vert b/flutter/engine/src/flutter/impeller/fixtures/impeller.vert new file mode 100644 index 0000000000000000000000000000000000000000..3aa5bec5b8a927c12fb482be05ca4847426a47bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/impeller.vert @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 vertex_position; +out vec2 v_screen_position; + +void main() { + v_screen_position = vertex_position; + gl_Position = frame_info.mvp * vec4(vertex_position, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.frag b/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.frag new file mode 100644 index 0000000000000000000000000000000000000000..ef66d0712a1f9c540a059e40f31e7d6bca48fbe5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.frag @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FragInfo { + vec4 unused_color; + vec4 color; +} +frag_info; + +in vec2 v_position; + +out vec4 frag_color; + +float SphereDistance(vec2 position, float radius) { + return length(v_position - position) - radius; +} + +void main() { + frag_color = frag_info.color; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.vert b/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.vert new file mode 100644 index 0000000000000000000000000000000000000000..6da02700d2821d3deeab9294c1ba9757b5c2957b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/inactive_uniforms.vert @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 position; + +out vec2 v_position; + +void main() { + gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); + v_position = position; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/ink_sparkle.frag b/flutter/engine/src/flutter/impeller/fixtures/ink_sparkle.frag new file mode 100644 index 0000000000000000000000000000000000000000..6e2940cf1a40270b92cc1eb2241372cdd2c9f832 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/ink_sparkle.frag @@ -0,0 +1,112 @@ +#version 320 es + +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +#include + +layout(location = 0) uniform vec4 u_color; +layout(location = 1) uniform float u_alpha; +layout(location = 2) uniform vec4 u_sparkle_color; +layout(location = 3) uniform float u_sparkle_alpha; +layout(location = 4) uniform float u_blur; +layout(location = 5) uniform vec2 u_center; +layout(location = 6) uniform float u_radius_scale; +layout(location = 7) uniform float u_max_radius; +layout(location = 8) uniform vec2 u_resolution_scale; +layout(location = 9) uniform vec2 u_noise_scale; +layout(location = 10) uniform float u_noise_phase; +layout(location = 11) uniform vec2 u_circle1; +layout(location = 12) uniform vec2 u_circle2; +layout(location = 13) uniform vec2 u_circle3; +layout(location = 14) uniform vec2 u_rotation1; +layout(location = 15) uniform vec2 u_rotation2; +layout(location = 16) uniform vec2 u_rotation3; + +layout(location = 0) out vec4 fragColor; + +const float PI = 3.1415926535897932384626; +const float PI_ROTATE_RIGHT = PI * 0.0078125; +const float PI_ROTATE_LEFT = PI * -0.0078125; +const float ONE_THIRD = 1. / 3.; +const vec2 TURBULENCE_SCALE = vec2(0.8); + +float triangle_noise(highp vec2 n) { + n = fract(n * vec2(5.3987, 5.4421)); + n += dot(n.yx, n.xy + vec2(21.5351, 14.3137)); + float xy = n.x * n.y; + return fract(xy * 95.4307) + fract(xy * 75.04961) - 1.0; +} + +float threshold(float v, float l, float h) { + return step(l, v) * (1.0 - step(h, v)); +} + +mat2 rotate2d(vec2 rad) { + return mat2(rad.x, -rad.y, rad.y, rad.x); +} + +float soft_circle(vec2 uv, vec2 xy, float radius, float blur) { + float blur_half = blur * 0.5; + float d = distance(uv, xy); + return 1.0 - smoothstep(1.0 - blur_half, 1.0 + blur_half, d / radius); +} + +float soft_ring(vec2 uv, vec2 xy, float radius, float thickness, float blur) { + float circle_outer = soft_circle(uv, xy, radius + thickness, blur); + float circle_inner = soft_circle(uv, xy, max(radius - thickness, 0.0), blur); + return clamp(circle_outer - circle_inner, 0.0, 1.0); +} + +float circle_grid(vec2 resolution, + vec2 p, + vec2 xy, + vec2 rotation, + float cell_diameter) { + p = rotate2d(rotation) * (xy - p) + xy; + p = mod(p, cell_diameter) / resolution; + float cell_uv = cell_diameter / resolution.y * 0.5; + float r = 0.65 * cell_uv; + return soft_circle(p, vec2(cell_uv), r, r * 50.0); +} + +float sparkle(vec2 uv, float t) { + float n = triangle_noise(uv); + float s = threshold(n, 0.0, 0.05); + s += threshold(n + sin(PI * (t + 0.35)), 0.1, 0.15); + s += threshold(n + sin(PI * (t + 0.7)), 0.2, 0.25); + s += threshold(n + sin(PI * (t + 1.05)), 0.3, 0.35); + return clamp(s, 0.0, 1.0) * 0.55; +} + +float turbulence(vec2 uv) { + vec2 uv_scale = uv * TURBULENCE_SCALE; + float g1 = + circle_grid(TURBULENCE_SCALE, uv_scale, u_circle1, u_rotation1, 0.17); + float g2 = + circle_grid(TURBULENCE_SCALE, uv_scale, u_circle2, u_rotation2, 0.2); + float g3 = + circle_grid(TURBULENCE_SCALE, uv_scale, u_circle3, u_rotation3, 0.275); + float v = (g1 * g1 + g2 - g3) * 0.5; + return clamp(0.45 + 0.8 * v, 0.0, 1.0); +} + +void main() { + vec2 p = FlutterFragCoord(); + vec2 uv = p * u_resolution_scale; + vec2 density_uv = uv - mod(p, u_noise_scale); + float radius = u_max_radius * u_radius_scale; + float turbulence = turbulence(uv); + float ring = soft_ring(p, u_center, radius, 0.05 * u_max_radius, u_blur); + float sparkle = + sparkle(density_uv, u_noise_phase) * ring * turbulence * u_sparkle_alpha; + float wave_alpha = + soft_circle(p, u_center, radius, u_blur) * u_alpha * u_color.a; + vec4 wave_color = vec4(u_color.rgb * wave_alpha, wave_alpha); + vec4 sparkle_color = + vec4(u_sparkle_color.rgb * u_sparkle_color.a, u_sparkle_color.a); + fragColor = mix(wave_color, sparkle_color, sparkle); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.frag b/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.frag new file mode 100644 index 0000000000000000000000000000000000000000..ccad5b7d3e1410d28c0eb49cd2adb6fd31150a74 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.frag @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec4 v_color; + +out vec4 frag_color; + +void main() { + frag_color = v_color; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.vert b/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.vert new file mode 100644 index 0000000000000000000000000000000000000000..9a674726cd900c28e69258ed69b673121d7fd26f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/instanced_draw.vert @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifdef IMPELLER_TARGET_OPENGLES + +void main() { + // Instancing is not supported on legacy targets and test will be disabled. +} + +#else // IMPELLER_TARGET_OPENGLES + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +readonly buffer InstanceInfo { + vec4 colors[]; +} +instance_info; + +in vec2 vtx; + +out vec4 v_color; + +void main() { + gl_Position = + frame_info.mvp * vec4(vtx.x + 105.0 * gl_InstanceIndex, + vtx.y + 105.0 * gl_InstanceIndex, 0.0, 1.0); + v_color = instance_info.colors[gl_InstanceIndex]; +} + +#endif // IMPELLER_TARGET_OPENGLES diff --git a/flutter/engine/src/flutter/impeller/fixtures/kalimba.jpg b/flutter/engine/src/flutter/impeller/fixtures/kalimba.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d0242ead728c27088f9c3014b0a998f21d069985 Binary files /dev/null and b/flutter/engine/src/flutter/impeller/fixtures/kalimba.jpg differ diff --git a/flutter/engine/src/flutter/impeller/fixtures/mipmaps.frag b/flutter/engine/src/flutter/impeller/fixtures/mipmaps.frag new file mode 100644 index 0000000000000000000000000000000000000000..05114fdda4d91e34fb2a89a5393fb4bc4d1afc18 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/mipmaps.frag @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FragInfo { + float lod; +} +frag_info; + +uniform sampler2D tex; + +in vec2 v_uv; + +out vec4 frag_color; + +void main() { + frag_color = textureLod(tex, v_uv, frag_info.lod); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/mipmaps.vert b/flutter/engine/src/flutter/impeller/fixtures/mipmaps.vert new file mode 100644 index 0000000000000000000000000000000000000000..eab582c732aee56b3a0d8a004556fa30a9721882 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/mipmaps.vert @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 vertex_position; +in vec2 uv; + +out vec2 v_uv; + +void main() { + gl_Position = frame_info.mvp * vec4(vertex_position, 0.0, 1.0); + v_uv = uv; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/multiple_stages.hlsl b/flutter/engine/src/flutter/impeller/fixtures/multiple_stages.hlsl new file mode 100644 index 0000000000000000000000000000000000000000..93e7073b24304e0150b015c77ebf6a1ff0dc7e33 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/multiple_stages.hlsl @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +struct VertexInput { + float3 position : POSITION; +}; + +struct VertexOutput { + float4 position : SV_POSITION; +}; + +VertexOutput VertexShader(VertexInput input) { + VertexOutput output; + output.position = float4(input.position, 1.0); + return output; +} + +float4 FragmentShader(VertexOutput input) { + return input.position; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/nine_patch_corners.png b/flutter/engine/src/flutter/impeller/fixtures/nine_patch_corners.png new file mode 100644 index 0000000000000000000000000000000000000000..6f48981f51b407b00a1916d319b8f5294db8956f Binary files /dev/null and b/flutter/engine/src/flutter/impeller/fixtures/nine_patch_corners.png differ diff --git a/flutter/engine/src/flutter/impeller/fixtures/ordering/shader_with_samplers.frag b/flutter/engine/src/flutter/impeller/fixtures/ordering/shader_with_samplers.frag new file mode 100644 index 0000000000000000000000000000000000000000..2900797d22d000a852764bb3dcd94d9964f28bca --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/ordering/shader_with_samplers.frag @@ -0,0 +1,15 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Declare samplers in different order than usage. +uniform sampler2D textureA; +uniform sampler2D textureB; + +out vec4 frag_color; + +void main() { + vec4 sample_1 = texture(textureB, vec2(1.0)); + vec4 sample_2 = texture(textureA, vec2(1.0)); + frag_color = sample_1 + sample_2; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/planet.frag b/flutter/engine/src/flutter/impeller/fixtures/planet.frag new file mode 100644 index 0000000000000000000000000000000000000000..2e687e415dc931feca6b16eaeeeb151c97c47c44 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/planet.frag @@ -0,0 +1,486 @@ +uniform FragInfo { + vec2 resolution; + float time; + float speed; + float planet_size; + float show_normals; + float show_noise; + float seed_value; +} +frag_info; + +in vec2 v_screen_position; +out vec4 frag_color; + +float inverseLerp(float v, float min_value, float max_value) { + return (v - min_value) / (max_value - min_value); +} + +float remap(float v, float in_min, float in_max, float out_min, float out_max) { + float t = inverseLerp(v, in_min, in_max); + return mix(out_min, out_max, t); +} + +float saturate(float x) { + return clamp(x, 0.0, 1.0); +} + +// Copyright (C) 2011 by Ashima Arts (Simplex noise) +// Copyright (C) 2011-2016 by Stefan Gustavson (Classic noise and others) +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: The above copyright +// notice and this permission notice shall be included in all copies or +// substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", +// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +// THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// https://github.com/ashima/webgl-noise/tree/master/src +vec3 mod289(vec3 x) { + return x - floor(x / 289.0) * 289.0; +} + +vec4 mod289(vec4 x) { + return x - floor(x / 289.0) * 289.0; +} + +vec4 permute(vec4 x) { + return mod289((x * 34.0 + 1.0) * x); +} + +vec4 taylorInvSqrt(vec4 r) { + return 1.79284291400159 - r * 0.85373472095314; +} + +vec4 snoise(vec3 v) { + const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0); + + // First corner + vec3 i = floor(v + dot(v, vec3(C.y))); + vec3 x0 = v - i + dot(i, vec3(C.x)); + + // Other corners + vec3 g = step(x0.yzx, x0.xyz); + vec3 l = 1.0 - g; + vec3 i1 = min(g.xyz, l.zxy); + vec3 i2 = max(g.xyz, l.zxy); + + vec3 x1 = x0 - i1 + C.x; + vec3 x2 = x0 - i2 + C.y; + vec3 x3 = x0 - 0.5; + + // Permutations + i = mod289(i); // Avoid truncation effects in permutation + vec4 p = permute(permute(permute(i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + + vec4(0.0, i1.y, i2.y, 1.0)) + + i.x + vec4(0.0, i1.x, i2.x, 1.0)); + + // Gradients: 7x7 points over a square, mapped onto an octahedron. + // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) + vec4 j = p - 49.0 * floor(p / 49.0); // mod(p,7*7) + + vec4 x_ = floor(j / 7.0); + vec4 y_ = floor(j - 7.0 * x_); + + vec4 x = (x_ * 2.0 + 0.5) / 7.0 - 1.0; + vec4 y = (y_ * 2.0 + 0.5) / 7.0 - 1.0; + + vec4 h = 1.0 - abs(x) - abs(y); + + vec4 b0 = vec4(x.xy, y.xy); + vec4 b1 = vec4(x.zw, y.zw); + + vec4 s0 = floor(b0) * 2.0 + 1.0; + vec4 s1 = floor(b1) * 2.0 + 1.0; + vec4 sh = -step(h, vec4(0.0)); + + vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; + vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; + + vec3 g0 = vec3(a0.xy, h.x); + vec3 g1 = vec3(a0.zw, h.y); + vec3 g2 = vec3(a1.xy, h.z); + vec3 g3 = vec3(a1.zw, h.w); + + // Normalize gradients + vec4 norm = + taylorInvSqrt(vec4(dot(g0, g0), dot(g1, g1), dot(g2, g2), dot(g3, g3))); + g0 *= norm.x; + g1 *= norm.y; + g2 *= norm.z; + g3 *= norm.w; + + // Compute noise and gradient at P + vec4 m = + max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); + vec4 m2 = m * m; + vec4 m3 = m2 * m; + vec4 m4 = m2 * m2; + vec3 grad = -6.0 * m3.x * x0 * dot(x0, g0) + m4.x * g0 + + -6.0 * m3.y * x1 * dot(x1, g1) + m4.y * g1 + + -6.0 * m3.z * x2 * dot(x2, g2) + m4.z * g2 + + -6.0 * m3.w * x3 * dot(x3, g3) + m4.w * g3; + vec4 px = vec4(dot(x0, g0), dot(x1, g1), dot(x2, g2), dot(x3, g3)); + return 42.0 * vec4(grad, dot(m4, px)); +} + +// The MIT License +// Copyright © 2013 Inigo Quilez +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: The above copyright +// notice and this permission notice shall be included in all copies or +// substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", +// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +// THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// https://www.youtube.com/c/InigoQuilez +// https://iquilezles.org/ +// +// https://www.shadertoy.com/view/Xsl3Dl +vec3 hash3(vec3 p) // replace this by something better +{ + p = vec3(dot(p, vec3(127.1, 311.7, 74.7)), dot(p, vec3(269.5, 183.3, 246.1)), + dot(p, vec3(113.5, 271.9, 124.6))); + + return -1.0 + 2.0 * fract(sin(p) * 43758.5453123); +} + +float noise(in vec3 p) { + vec3 i = floor(p); + vec3 f = fract(p); + + vec3 u = f * f * (3.0 - 2.0 * f); + + return mix( + mix(mix(dot(hash3(i + vec3(0.0, 0.0, 0.0)), f - vec3(0.0, 0.0, 0.0)), + dot(hash3(i + vec3(1.0, 0.0, 0.0)), f - vec3(1.0, 0.0, 0.0)), + u.x), + mix(dot(hash3(i + vec3(0.0, 1.0, 0.0)), f - vec3(0.0, 1.0, 0.0)), + dot(hash3(i + vec3(1.0, 1.0, 0.0)), f - vec3(1.0, 1.0, 0.0)), + u.x), + u.y), + mix(mix(dot(hash3(i + vec3(0.0, 0.0, 1.0)), f - vec3(0.0, 0.0, 1.0)), + dot(hash3(i + vec3(1.0, 0.0, 1.0)), f - vec3(1.0, 0.0, 1.0)), + u.x), + mix(dot(hash3(i + vec3(0.0, 1.0, 1.0)), f - vec3(0.0, 1.0, 1.0)), + dot(hash3(i + vec3(1.0, 1.0, 1.0)), f - vec3(1.0, 1.0, 1.0)), + u.x), + u.y), + u.z); +} + +float fbm6(vec3 p, float persistence, float lacunarity, float exponentiation) { + float amplitude = 0.5; + float frequency = 1.0; + float total = 0.0; + float normalization = 0.0; + + p = p + frag_info.seed_value; + for (int i = 0; i < 6; ++i) { + float noiseValue = snoise(p * frequency).w; + total += noiseValue * amplitude; + normalization += amplitude; + amplitude *= persistence; + frequency *= lacunarity; + } + + total /= normalization; + total = total * 0.5 + 0.5; + total = pow(total, exponentiation); + + return total; +} + +float fbm2(vec3 p, float persistence, float lacunarity, float exponentiation) { + float amplitude = 0.5; + float frequency = 1.0; + float total = 0.0; + float normalization = 0.0; + p = p + frag_info.seed_value; + + for (int i = 0; i < 2; ++i) { + float noiseValue = snoise(p * frequency).w; + total += noiseValue * amplitude; + normalization += amplitude; + amplitude *= persistence; + frequency *= lacunarity; + } + + total /= normalization; + total = total * 0.5 + 0.5; + total = pow(total, exponentiation); + + return total; +} + +vec3 GenerateStarGrid(vec2 pixel_coords, + float cell_width, + float star_radius, + float seed, + bool twinkle) { + // fract() gives you 0.0 to 1.0 for the cell_width + // - 0.5 will move the origin from the bottom left to the cetner + vec2 cell_coords = fract(pixel_coords / cell_width) - 0.5; + // "each cell is now scaled in terms of pixels" + cell_coords *= cell_width; + + vec2 cell_id = (floor(pixel_coords / cell_width) + seed) / 100.0; // "(x,y)" + vec3 cell_hash_value = + hash3(vec3(cell_id, 0.0)); // [-1, 1] - note; "z" is unused right now. + + // Hash gives you -1 to 1; saturate clamps to 0,1. This will effectivly + // kill some of the stars (wanted) vs remap giving you a star per-cell + float starBrighness = saturate(cell_hash_value.z); // -1,1 -> 0->1 + + // Get a star position and + vec2 star_position = vec2(0.0); + star_position += cell_hash_value.xy * (cell_width * 0.5 - star_radius * 4.0); + + // float distance_to_star = length(cell_coords); // stars in the middle + float distance_to_star = length(cell_coords + star_position); + + // better falloff + float glow = exp(-2.0 * distance_to_star / star_radius); + + if (twinkle) { + // verticle and horizontal flare + float noise_sample = noise(vec3(cell_id, frag_info.time * 1.5)); + float twinkle_size = + remap(noise_sample, -1.0, 1.0, 1.0, 0.1) * star_radius * 6.0; + + vec2 abs_distance = + abs(cell_coords - star_position); // manhattan distance to cell center. + + // horizontal + float twinkleValue = smoothstep(star_radius * 0.25, 0.0, abs_distance.y) * + smoothstep(twinkle_size, 0.0, abs_distance.x); + // vertical + twinkleValue += smoothstep(star_radius * 0.25, 0.0, abs_distance.x) * + smoothstep(twinkle_size, 0.0, abs_distance.y); + + glow += twinkleValue; + } + + return vec3(glow * starBrighness); +} + +vec3 GenerateStars(vec2 pixel_coords) { + vec3 stars = vec3(0.0); + float size = 4.0; + float cell_width = 500.0; + for (float i = 0.0; i <= 2.0; i++) { + stars += GenerateStarGrid(pixel_coords, cell_width, size, + i + frag_info.seed_value, true); + size *= 0.5; + cell_width *= 0.35; + } + + for (float i = 3.0; i <= 5.0; i++) { + stars += GenerateStarGrid(pixel_coords, cell_width, size, + i + frag_info.seed_value, false); + size *= 0.5; + cell_width *= 0.35; + } + return stars; +} + +// 2D circle +float sdfCircle(vec2 p, float r) { + return length(p) - r; +} + +float map(vec3 pos) { + return fbm6(pos, 0.5, 2.0, 4.0); +} + +vec3 calcNormal(vec3 pos, vec3 n) { + // if you sample the noise field along each axis, a small amount of distance + // away from the position you're interested, you'll get a gradient + vec2 e = vec2(0.0001, 0.0); + /* -500.0 was added without comment, but it gives bump */ + return normalize(n + -500.0 * vec3(map(pos + e.xyy) - map(pos - e.xyy), + map(pos + e.yxy) - map(pos - e.yxy), + map(pos + e.yyx) - map(pos - e.yyx))); +} + +mat3 rotateY(float radians) { + float s = sin(radians); + float c = cos(radians); + return mat3( // split + c, 0.0, s, // 1 + 0.0, 1.0, 0.0, // 2 + -s, 0.0, c); // 3 +} + +vec3 DrawPlanet(vec2 pixel_coords, + vec3 color, + float planet_size, + float atmosphere_thickness, + float rotation_speed) { + vec3 planet_color = vec3(1.0); + + // Get a nice big 2D circle and the distance to the edge. + float d = sdfCircle(pixel_coords, planet_size); + + if (d <= 0.0) { + // inside the planet. + float x = pixel_coords.x / planet_size; + float y = pixel_coords.y / planet_size; + + // surface area of a sphere is x^2 + y^2 + z^2 = 1, so... + // z = 1 - x^2 - y^2 + float z = sqrt(1.0 - x * x - y * y); + + // sping around; right round... + mat3 planet_rotation = rotateY(frag_info.time * rotation_speed); + + // veiw space normal; + vec3 view_normal = vec3(x, y, z); + vec3 worldspace_position = planet_rotation * view_normal; + vec3 worldspace_normal = planet_rotation * normalize(worldspace_position); + vec3 wsViewDir = planet_rotation * vec3(0.0, 0.0, 1.0); + + vec3 noise_coord = worldspace_position * 2.0; + float noise_sample = fbm6(noise_coord, 0.5, 2.0, 4.0); + float moistureMap = fbm2(noise_coord * 0.5 + vec3(20.0), 0.5, 2.0, 4.0); + + vec3 shallowWaterColor = vec3(0.01, 0.09, 0.55); // light blue + vec3 deepWater = vec3(0.09, 0.26, 0.57); + vec3 waterColor = + mix(shallowWaterColor, deepWater, + smoothstep(0.02 /*deep*/, 0.06 /* shallow */, noise_sample)); + + vec3 coast_land = vec3(0.5, 1.0, 0.3); + vec3 jungle_land = vec3(0.0, 0.7, 0.0); + vec3 land_color = + mix(coast_land, jungle_land, smoothstep(0.05, 0.1, noise_sample)); + + vec3 sandyColor = vec3(1.0, 1.0, 0.5); + land_color = + mix(sandyColor, land_color, smoothstep(0.05, 0.1, moistureMap)); + + // Put in some mountains and snow... + vec3 mountainColor = vec3(0.5); + land_color = + mix(land_color, mountainColor, smoothstep(0.1, 0.2, noise_sample)); + + vec3 snowColor = vec3(1.0); + land_color = + mix(land_color, snowColor, smoothstep(0.15, 0.3, noise_sample)); + + // Take care of the poles... + land_color = + mix(land_color, vec3(0.9), smoothstep(0.6, 0.9, abs(view_normal.y))); + + planet_color = + mix(waterColor, land_color, smoothstep(0.05, 0.06, noise_sample)); + + // Lighting + // Check out the previous sections on lighting. + + // specularity of water vs land is different. + float water_selector = smoothstep(0.05, 0.06, noise_sample); + vec2 spec_params = mix(vec2(0.5, 32.0), // land + vec2(0.01, 2.0), // sea + water_selector); + + vec3 worldspace_light_direction = + planet_rotation * normalize(vec3(0.5, 1.0, 0.5)); + + // update: make water flat - though from space we should see some waves + // (to-do) + vec3 worldspace_surface_normal = + mix(worldspace_normal, calcNormal(noise_coord, worldspace_normal), + water_selector); + + if (frag_info.show_normals > 0.0) { + planet_color = worldspace_surface_normal; + } + float wrap = 0.05; + // float dp = max(0.0, dot(worldspace_light_direction, + // worldspace_surface_normal)); // dot product nvida surface scattering + // trick + float dp = max( + 0.0, + (dot(worldspace_light_direction, worldspace_surface_normal) + wrap) / + (1.0 + wrap)); + + vec3 darkRed = vec3(0.25, 0.0, 0.0); + vec3 lightColor = mix(darkRed, vec3(0.75), smoothstep(0.05, 0.5, dp)); + + vec3 ambient = vec3(0.002); // lets not have complete darkness + vec3 diffuse = lightColor * dp; + + vec3 r = normalize( + reflect(-worldspace_light_direction, worldspace_surface_normal)); + float phongValue = max(0.0, dot(wsViewDir, r)); + phongValue = pow(phongValue, spec_params.y); + + vec3 specular = vec3(phongValue) * spec_params.x * diffuse; + + vec3 planetShading = planet_color * (diffuse + ambient) + specular; + planet_color = planetShading; + + // Fresnel for atmosphere + float fresnel = smoothstep(1.0, 0.1, view_normal.z); // z == from camera. + // "blue halo goes around the dark side of the planet + // fresnel = pow(fresnel, 8.0); + fresnel = pow(fresnel, 8.0) * dp; + planet_color = mix(planet_color, vec3(0.0, 0.5, 1.0), fresnel); + + if (frag_info.show_noise > 0.0) { + planet_color = vec3(noise_sample); + } + } + // (color -> planet_color) when "d" is between 0 and -1 (inside the circle) + color = mix(color, planet_color, smoothstep(0.0, -1.0, d)); + + // Atmospheric glow + // 40 pixels outside the planet + if (d < atmosphere_thickness && d >= -1.0) { + // color = vec3(1.0); // draw the halo + float planetSizeAtmos = planet_size + atmosphere_thickness; + mat3 planet_rotation = rotateY(frag_info.time * rotation_speed); + + float x = pixel_coords.x / planetSizeAtmos; + float y = pixel_coords.y / planetSizeAtmos; + float z = sqrt(1.0 - x * x - y * y); + vec3 normal = planet_rotation * vec3(x, y, z); + + float lighting = dot(normal, normalize(vec3(0.5, 1.0, 0.5))); + lighting = + smoothstep(-0.15, 1.0, lighting); // same as above; just no wrap. + + vec3 glow_color = + vec3(0.05, 0.3, 0.9) * exp(-0.01 * d * d) * lighting * 0.75; + color += glow_color; + } + + return color; +} + +void main() { + vec2 vUvs = (gl_FragCoord.xy - 0.5) / frag_info.resolution; + vUvs.y = 1.0 - vUvs.y; // flip flutter's upside down. + vec2 pixel_coords = (vUvs - 0.5) * frag_info.resolution; + + vec3 color = vec3(0.0); + color = GenerateStars(pixel_coords); + color = DrawPlanet(pixel_coords, color, frag_info.planet_size, + frag_info.planet_size * 0.1, frag_info.speed); + + frag_color = vec4(pow(color, vec3(1.0 / 2.2)), 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/planet.vert b/flutter/engine/src/flutter/impeller/fixtures/planet.vert new file mode 100644 index 0000000000000000000000000000000000000000..3aa5bec5b8a927c12fb482be05ca4847426a47bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/planet.vert @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 vertex_position; +out vec2 v_screen_position; + +void main() { + v_screen_position = vertex_position; + gl_Position = frame_info.mvp * vec4(vertex_position, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/resources_limit.vert b/flutter/engine/src/flutter/impeller/fixtures/resources_limit.vert new file mode 100644 index 0000000000000000000000000000000000000000..f3f9db8c3a504f012589ad820b1e902538bf51b6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/resources_limit.vert @@ -0,0 +1,8 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform sampler1D tex; +void main() { + vec4 x = textureOffset(tex, 1.0, -10); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_example.frag b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_example.frag new file mode 100644 index 0000000000000000000000000000000000000000..66159e94156de2cb722c9db88676473b04a0fe2e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_example.frag @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform vec2 iResolution; +uniform float iTime; + +out vec4 fragColor; + +void main() { + vec2 uv = FlutterFragCoord() / iResolution; + float t = 4 * iTime; + vec3 col = 0.5 + 0.5 * cos(t + uv.xyx + vec3(0, 1, 4)); + fragColor = vec4(col, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_filter_example.frag b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_filter_example.frag new file mode 100644 index 0000000000000000000000000000000000000000..83b8a4f2145bccbbe1b31473c1ec0fee6b1326e2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_filter_example.frag @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform vec2 u_size; +uniform sampler2D u_texture; + +out vec4 frag_color; + +void main() { + frag_color = texture(u_texture, FlutterFragCoord().xy / u_size) * + (sin(FlutterFragCoord().y / u_size.y * 3.14) * + cos(FlutterFragCoord().x / u_size.x * 3.14)); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_position.frag b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_position.frag new file mode 100644 index 0000000000000000000000000000000000000000..aee7f895094661abbdc66b756051834942a92cba --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_position.frag @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +uniform vec4 ltrb; + +out vec4 frag_color; + +// Output solid red if frag position is within LTRB rectangle. +void main() { + if (FlutterFragCoord().x >= ltrb.x && FlutterFragCoord().x <= ltrb.z && + FlutterFragCoord().y >= ltrb.y && FlutterFragCoord().y <= ltrb.w) { + frag_color = vec4(1.0, 0.0, 0.0, 1.0); + } else { + frag_color = vec4(0.0); + } +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_simple.frag b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_simple.frag new file mode 100644 index 0000000000000000000000000000000000000000..38b00be8d32b122f9855cefa613e956e60cf7b58 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/runtime_stage_simple.frag @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec4 frag_color; + +void main() { + frag_color = vec4(1.0, 0.0, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sa%m#ple.vert b/flutter/engine/src/flutter/impeller/fixtures/sa%m#ple.vert new file mode 100644 index 0000000000000000000000000000000000000000..746824ec0adee4ca2da148bbcc856105941eb1e4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sa%m#ple.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "types.h" + +uniform UniformBufferObject { + Uniforms uniforms; +} +ubo; + +uniform sampler2D world; + +in vec2 inPosition; +in vec3 inPosition22; +in vec4 inAnotherPosition; +in float stuff; + +out vec4 outStuff; + +void main() { + gl_Position = ubo.uniforms.projection * ubo.uniforms.view * + ubo.uniforms.model * vec4(inPosition22, 1.0) * + inAnotherPosition; + outStuff = texture(world, inPosition); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sample.comp b/flutter/engine/src/flutter/impeller/fixtures/sample.comp new file mode 100644 index 0000000000000000000000000000000000000000..c5dc05d743c22270d5b3443d405e84e923e14307 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sample.comp @@ -0,0 +1,49 @@ +layout(local_size_x = 128) in; +layout(std430) buffer; + +struct SomeStruct { + vec2 vf; + uint i; +}; + +layout(binding = 0) writeonly buffer Output { + vec4 elements[]; +} +output_data; + +layout(binding = 1) readonly buffer Input0 { + int some_int; + ivec2 fixed_array[3]; + vec4 elements[]; +} +input_data0; + +layout(binding = 2) readonly buffer Input1 { + SomeStruct some_struct; + uvec2 fixed_array[4]; + vec4 elements[]; +} +input_data1; + +uniform Info { + uint count; +} +info; + +void main() { + uint ident = gl_GlobalInvocationID.x; + // TODO(dnfield): https://github.com/flutter/flutter/issues/112683 + // We should be able to use length here instead of an extra arrgument. + if (ident >= info.count) { + return; + } + + output_data.elements[ident] = + input_data0.elements[ident] * input_data1.elements[ident]; + output_data.elements[ident].x += + input_data0.fixed_array[1].x + input_data1.some_struct.i; + output_data.elements[ident].y += + input_data1.fixed_array[0].y + input_data1.some_struct.vf.x; + output_data.elements[ident].z += + input_data0.some_int + input_data1.some_struct.vf.y; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sample.frag b/flutter/engine/src/flutter/impeller/fixtures/sample.frag new file mode 100644 index 0000000000000000000000000000000000000000..5d9c83604dd68c4fb7a0101b8058f9788594628a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sample.frag @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FragInfo { + vec4 color; +} +frag_info; + +out vec4 frag_color; + +void main() { + frag_color = frag_info.color; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sample.vert b/flutter/engine/src/flutter/impeller/fixtures/sample.vert new file mode 100644 index 0000000000000000000000000000000000000000..746824ec0adee4ca2da148bbcc856105941eb1e4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sample.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "types.h" + +uniform UniformBufferObject { + Uniforms uniforms; +} +ubo; + +uniform sampler2D world; + +in vec2 inPosition; +in vec3 inPosition22; +in vec4 inAnotherPosition; +in float stuff; + +out vec4 outStuff; + +void main() { + gl_Position = ubo.uniforms.projection * ubo.uniforms.view * + ubo.uniforms.model * vec4(inPosition22, 1.0) * + inAnotherPosition; + outStuff = texture(world, inPosition); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sample_with_binding.vert b/flutter/engine/src/flutter/impeller/fixtures/sample_with_binding.vert new file mode 100644 index 0000000000000000000000000000000000000000..97c01fe8359aaf1b9de2df30f714bbc474e45a5f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sample_with_binding.vert @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "types.h" + +layout(set = 3, binding = 17) uniform UniformBufferObject { + Uniforms uniforms; +} +ubo; + +uniform sampler2D world; + +in vec2 inPosition; +in vec3 inPosition22; +in vec4 inAnotherPosition; +in float stuff; + +out vec4 outStuff; + +void main() { + gl_Position = ubo.uniforms.projection * ubo.uniforms.view * + ubo.uniforms.model * vec4(inPosition22, 1.0) * + inAnotherPosition; + outStuff = texture(world, inPosition); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sepia.frag b/flutter/engine/src/flutter/impeller/fixtures/sepia.frag new file mode 100644 index 0000000000000000000000000000000000000000..1379a5f4f533b3a336b184e2d7cb5850737298d8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sepia.frag @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec4 frag_color; + +layout(input_attachment_index = 0) uniform subpassInputMS subpass_input; + +void main() { + // https://github.com/chinmaygarde/merle/blob/3eecb311ac8862c41f0c53a5d9b360be923142bb/src/texture.cc#L195 + const mat4 sepia_matrix = mat4(0.3588, 0.2990, 0.2392, 0.0000, // + 0.7044, 0.5870, 0.4696, 0.0000, // + 0.1368, 0.1140, 0.0912, 0.0000, // + 0.0000, 0.0000, 0.0000, 1.0000 // + ); + frag_color = sepia_matrix * subpassLoad(subpass_input, 0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/sepia.vert b/flutter/engine/src/flutter/impeller/fixtures/sepia.vert new file mode 100644 index 0000000000000000000000000000000000000000..b8b09eeaae0e8e74b0456c357ffeac39da629416 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/sepia.vert @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform UniformBuffer { + mat4 mvp; +} +uniform_buffer; + +in vec3 vertex_position; + +void main() { + gl_Position = uniform_buffer.mvp * vec4(vertex_position, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/simple.vert b/flutter/engine/src/flutter/impeller/fixtures/simple.vert new file mode 100644 index 0000000000000000000000000000000000000000..122bf0630576fb8994a50672f7390d34a360f9e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/simple.vert @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec2 v_position; + +void main() { + gl_Position = vec4(1.0); + v_position = vec2(1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/simple.vert.hlsl b/flutter/engine/src/flutter/impeller/fixtures/simple.vert.hlsl new file mode 100644 index 0000000000000000000000000000000000000000..09c11039671900cc1c8fcfd581c7174051c815c1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/simple.vert.hlsl @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +struct VertexInput { + float3 position : POSITION; +}; + +struct VertexOutput { + float4 position : SV_POSITION; +}; + +VertexOutput main(VertexInput input) { + VertexOutput output; + output.position = float4(input.position, 1.0); + return output; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/spec_constant.frag b/flutter/engine/src/flutter/impeller/fixtures/spec_constant.frag new file mode 100644 index 0000000000000000000000000000000000000000..844d5c42cd76ca736a0fd45304cd72cb4c37356c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/spec_constant.frag @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec4 v_color; +in vec4 v_color2; + +layout(constant_id = 0) const float some_fraction = 1.0; + +out vec4 frag_color; + +uniform FragInfo { + float time; +} +frag_info; + +void main() { + frag_color = mix(v_color, v_color2, some_fraction); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/spec_constant.vert b/flutter/engine/src/flutter/impeller/fixtures/spec_constant.vert new file mode 100644 index 0000000000000000000000000000000000000000..d9ff2b6d892231c1fa70aadcca2c8136f0458655 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/spec_constant.vert @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec2 position; +in vec4 color; +in vec4 color2; + +out vec4 v_color; +out vec4 v_color2; + +void main() { + gl_Position = vec4(position, 0.0, 1.0); + v_color = color; + v_color2 = color2; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/stage1.comp b/flutter/engine/src/flutter/impeller/fixtures/stage1.comp new file mode 100644 index 0000000000000000000000000000000000000000..9c39e3f5a95a06352837edc1be716a62d15de785 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/stage1.comp @@ -0,0 +1,29 @@ +layout(local_size_x = 128) in; +layout(std430) buffer; + +layout(binding = 0) writeonly buffer Output { + uint count; + uint elements[]; +} +output_data; + +layout(binding = 1) readonly buffer Input { + uint count; + uint elements[]; +} +input_data; + +void main() { + uint ident = gl_GlobalInvocationID.x; + + if (ident >= input_data.count) { + return; + } + + uint out_slot = ident * 2; + + output_data.count = input_data.count * 2; + + output_data.elements[out_slot] = input_data.elements[ident] * 2; + output_data.elements[out_slot + 1] = input_data.elements[ident] * 3; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/stage2.comp b/flutter/engine/src/flutter/impeller/fixtures/stage2.comp new file mode 100644 index 0000000000000000000000000000000000000000..ed51278da16f8c7d248b4c8132bfe22cdfd3086c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/stage2.comp @@ -0,0 +1,26 @@ +layout(local_size_x = 128) in; +layout(std430) buffer; + +layout(binding = 0) writeonly buffer Output { + uint count; + uint elements[]; +} +output_data; + +layout(binding = 1) readonly buffer Input { + uint count; + uint elements[]; +} +input_data; + +void main() { + uint ident = gl_GlobalInvocationID.x; + + if (ident >= input_data.count) { + return; + } + + output_data.count = input_data.count; + + output_data.elements[ident] = input_data.elements[ident] * 2; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/struct_def_bug.vert b/flutter/engine/src/flutter/impeller/fixtures/struct_def_bug.vert new file mode 100644 index 0000000000000000000000000000000000000000..69d5eb063652e3677b37970d62a40f1fa67bdbec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/struct_def_bug.vert @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; + vec2 atlas_size; + vec4 text_color; +} +frame_info; + +in vec2 unit_vertex; +in mat4 + glyph_position; // <--- Causes multiple slots to be used and is a failure. +in vec2 destination_size; +in vec2 source_position; +in vec2 source_glyph_size; + +out vec2 v_unit_vertex; +out vec2 v_source_position; +out vec2 v_source_glyph_size; +out vec2 v_atlas_size; +out vec4 v_text_color; + +void main() { + gl_Position = frame_info.mvp * glyph_position * + vec4(unit_vertex.x * destination_size.x, + unit_vertex.y * destination_size.y, 0.0, 1.0); + + v_unit_vertex = unit_vertex; + v_source_position = source_position; + v_source_glyph_size = source_glyph_size; + v_atlas_size = frame_info.atlas_size; + v_text_color = frame_info.text_color; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/struct_internal.frag b/flutter/engine/src/flutter/impeller/fixtures/struct_internal.frag new file mode 100644 index 0000000000000000000000000000000000000000..5cc75950ee39cf1960ec9c9e70641b51a531ac6b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/struct_internal.frag @@ -0,0 +1,16 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec4 frag_color; + +struct TestStruct { + float a; + float b; + float c; +}; + +void main() { + TestStruct ts = TestStruct(1.0, 0.5, 0.25); + frag_color = vec4(ts.c, ts.b, ts.a, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/swizzle.frag b/flutter/engine/src/flutter/impeller/fixtures/swizzle.frag new file mode 100644 index 0000000000000000000000000000000000000000..63d793e3ead9994d354aae452f99f6cdeb8bfb13 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/swizzle.frag @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec4 frag_color; + +layout(input_attachment_index = 0) uniform subpassInputMS subpass_input; + +void main() { + frag_color = subpassLoad(subpass_input, 0).gbra; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/table_mountain_px.png b/flutter/engine/src/flutter/impeller/fixtures/table_mountain_px.png new file mode 100644 index 0000000000000000000000000000000000000000..c4fff0d223e4093414e117e6b103ee0a4220a0c9 Binary files /dev/null and b/flutter/engine/src/flutter/impeller/fixtures/table_mountain_px.png differ diff --git a/flutter/engine/src/flutter/impeller/fixtures/table_mountain_py.png b/flutter/engine/src/flutter/impeller/fixtures/table_mountain_py.png new file mode 100644 index 0000000000000000000000000000000000000000..34ca6f74348aa41a3791d143e856aa6c3bf6c18e Binary files /dev/null and b/flutter/engine/src/flutter/impeller/fixtures/table_mountain_py.png differ diff --git a/flutter/engine/src/flutter/impeller/fixtures/test_texture.frag b/flutter/engine/src/flutter/impeller/fixtures/test_texture.frag new file mode 100644 index 0000000000000000000000000000000000000000..778163ed04f29cace46766f5cdec95c6530b1b87 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/test_texture.frag @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +out vec4 frag_color; + +void main() { + frag_color = vec4(1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/test_texture.vert b/flutter/engine/src/flutter/impeller/fixtures/test_texture.vert new file mode 100644 index 0000000000000000000000000000000000000000..0b8c99e7f7fb9c2643098b435dd648f91f70fb78 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/test_texture.vert @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform FrameInfo { + mat4 mvp; +} +frame_info; + +in vec2 vtx; + +void main() { + gl_Position = frame_info.mvp * vec4(vtx, 0.0, 1.0); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/texture.frag b/flutter/engine/src/flutter/impeller/fixtures/texture.frag new file mode 100644 index 0000000000000000000000000000000000000000..1e95b0f8f8ade297f6feda753cf8871879d7f100 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/texture.frag @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec2 interpolated_texture_coordinates; + +out vec4 frag_color; + +uniform sampler2D texture_contents; + +void main() { + frag_color = texture(texture_contents, interpolated_texture_coordinates); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/texture.vert b/flutter/engine/src/flutter/impeller/fixtures/texture.vert new file mode 100644 index 0000000000000000000000000000000000000000..fd65238d83de787c88af318e317453bd4bbecb31 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/texture.vert @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform UniformBuffer { + mat4 mvp; +} +uniform_buffer; + +in vec3 vertex_position; +in vec2 texture_coordinates; + +out vec2 interpolated_texture_coordinates; + +void main() { + gl_Position = uniform_buffer.mvp * vec4(vertex_position, 1.0); + interpolated_texture_coordinates = texture_coordinates; +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/texture_lookup.frag b/flutter/engine/src/flutter/impeller/fixtures/texture_lookup.frag new file mode 100644 index 0000000000000000000000000000000000000000..cbf7d5db7136df2cc9f93d5d96b85080a7c52f1c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/texture_lookup.frag @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform sampler2D textureA; + +out vec4 frag_color; + +void main() { + frag_color = texture(textureA, vec2(1.0) + gl_FragCoord.xy); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/types.h b/flutter/engine/src/flutter/impeller/fixtures/types.h new file mode 100644 index 0000000000000000000000000000000000000000..e26dbee0682bd97e93cb52c6da09d0643930fb1c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/types.h @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_FIXTURES_TYPES_H_ +#define FLUTTER_IMPELLER_FIXTURES_TYPES_H_ + +struct Uniforms { + mat4 model; + mat4 view; + mat4 projection; +}; + +#endif // FLUTTER_IMPELLER_FIXTURES_TYPES_H_ diff --git a/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_1.frag b/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_1.frag new file mode 100644 index 0000000000000000000000000000000000000000..196ff621764ed159dd439f8fc6045c49fc53e1f0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_1.frag @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// sampler is specifically ordered before color. +uniform sampler2D u_texture; +uniform vec4 u_color; + +out vec4 frag_color; + +void main() { + frag_color = u_color + texture(u_texture, vec2(0.5, 0.5)); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_2.frag b/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_2.frag new file mode 100644 index 0000000000000000000000000000000000000000..77706675594cf2d73460f2b81c66f223f90a390b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/fixtures/uniforms_and_sampler_2.frag @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform vec4 u_color; +// sampler is specifically ordered after color. +uniform sampler2D u_texture; + +out vec4 frag_color; + +void main() { + frag_color = u_color + texture(u_texture, vec2(0.5, 0.5)); +} diff --git a/flutter/engine/src/flutter/impeller/fixtures/wtf.otf b/flutter/engine/src/flutter/impeller/fixtures/wtf.otf new file mode 100644 index 0000000000000000000000000000000000000000..ae0c62c61a728bbf4ae8952dc8134a727dc634ac Binary files /dev/null and b/flutter/engine/src/flutter/impeller/fixtures/wtf.otf differ diff --git a/flutter/engine/src/flutter/impeller/geometry/BUILD.gn b/flutter/engine/src/flutter/impeller/geometry/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dde58e907ea7d811e5cde83c3595bc4376214735 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/BUILD.gn @@ -0,0 +1,112 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("geometry") { + sources = [ + "color.cc", + "color.h", + "constants.cc", + "constants.h", + "gradient.cc", + "gradient.h", + "half.h", + "matrix.cc", + "matrix.h", + "matrix_decomposition.cc", + "matrix_decomposition.h", + "path.cc", + "path.h", + "path_builder.cc", + "path_builder.h", + "path_component.cc", + "path_component.h", + "point.cc", + "point.h", + "quaternion.cc", + "quaternion.h", + "rational.cc", + "rational.h", + "rect.cc", + "rect.h", + "round_rect.cc", + "round_rect.h", + "round_superellipse.cc", + "round_superellipse.h", + "round_superellipse_param.cc", + "round_superellipse_param.h", + "rounding_radii.cc", + "rounding_radii.h", + "rstransform.cc", + "rstransform.h", + "saturated_math.h", + "scalar.h", + "separated_vector.cc", + "separated_vector.h", + "shear.cc", + "shear.h", + "sigma.cc", + "sigma.h", + "size.cc", + "size.h", + "trig.cc", + "trig.h", + "type_traits.cc", + "type_traits.h", + "vector.cc", + "vector.h", + "wangs_formula.cc", + "wangs_formula.h", + ] + + deps = [ + "../base", + "//flutter/fml", + ] +} + +impeller_component("geometry_asserts") { + testonly = true + sources = [ "geometry_asserts.h" ] + deps = [ + ":geometry", + "//flutter/testing:testing_lib", + ] +} + +impeller_component("geometry_unittests") { + testonly = true + sources = [ + "geometry_unittests.cc", + "matrix_unittests.cc", + "path_unittests.cc", + "rational_unittests.cc", + "rect_unittests.cc", + "round_rect_unittests.cc", + "round_superellipse_unittests.cc", + "rounding_radii_unittests.cc", + "rstransform_unittests.cc", + "saturated_math_unittests.cc", + "size_unittests.cc", + "trig_unittests.cc", + ] + + deps = [ + ":geometry", + ":geometry_asserts", + "//flutter/testing:testing_lib", + ] +} + +executable("geometry_benchmarks") { + testonly = true + sources = [ "geometry_benchmarks.cc" ] + deps = [ + ":geometry", + "../entity", + "../tessellator:tessellator_libtess", + "//flutter/benchmarking", + ] +} diff --git a/flutter/engine/src/flutter/impeller/geometry/README.md b/flutter/engine/src/flutter/impeller/geometry/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c58c4af1e0e227bb1da3c47ad1530222e2db8cd5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/README.md @@ -0,0 +1,8 @@ +# The Impeller Geometry Library + +Set of utilities used by most graphics operations. While the utilities +themselves are rendering backend agnostic, the layout and packing of the various +POD structs is arranged such that these can be copied into device memory +directly. The supported operations also mimic GLSL to some extent. For this +reason, the Impeller shader compiler and reflector uses these utilities in +generated code. diff --git a/flutter/engine/src/flutter/impeller/geometry/color.cc b/flutter/engine/src/flutter/impeller/geometry/color.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa77cda7e680959e602744474fdd5796a7d22256 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/color.cc @@ -0,0 +1,342 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/color.h" + +#include +#include +#include +#include +#include + +#include "impeller/base/strings.h" +#include "impeller/geometry/constants.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/vector.h" + +namespace impeller { + +#define _IMPELLER_ASSERT_BLEND_MODE(blend_mode) \ + auto enum_##blend_mode = static_cast>( \ + BlendMode::k##blend_mode); \ + if (i != enum_##blend_mode) { \ + return false; \ + } \ + ++i; + +static constexpr inline bool ValidateBlendModes() { + std::underlying_type_t i = 0; + // Ensure the order of the blend modes match. + IMPELLER_FOR_EACH_BLEND_MODE(_IMPELLER_ASSERT_BLEND_MODE) + // Ensure the total number of blend modes match. + if (i - 1 != + static_cast>(BlendMode::kLastMode)) { + return false; + } + return true; +} +static_assert(ValidateBlendModes(), + "IMPELLER_FOR_EACH_BLEND_MODE must match impeller::BlendMode."); + +#define _IMPELLER_BLEND_MODE_NAME_LIST(blend_mode) #blend_mode, + +static constexpr const char* kBlendModeNames[] = { + IMPELLER_FOR_EACH_BLEND_MODE(_IMPELLER_BLEND_MODE_NAME_LIST)}; + +const char* BlendModeToString(BlendMode blend_mode) { + return kBlendModeNames[static_cast>( + blend_mode)]; +} + +Color::Color(const Vector4& value) + : red(value.x), green(value.y), blue(value.z), alpha(value.w) {} + +static constexpr inline Color Min(Color c, float threshold) { + return Color(std::min(c.red, threshold), std::min(c.green, threshold), + std::min(c.blue, threshold), std::min(c.alpha, threshold)); +} + +// The following HSV utilities correspond to the W3C blend definitions +// implemented in: impeller/compiler/shader_lib/impeller/blending.glsl + +static constexpr inline Scalar Luminosity(Vector3 color) { + return color.x * 0.3f + color.y * 0.59f + color.z * 0.11f; +} + +static constexpr inline Vector3 ClipColor(Vector3 color) { + Scalar lum = Luminosity(color); + Scalar mn = std::min(std::min(color.x, color.y), color.z); + Scalar mx = std::max(std::max(color.x, color.y), color.z); + // `lum - mn` and `mx - lum` will always be >= 0 in the following conditions, + // so adding a tiny value is enough to make these divisions safe. + if (mn < 0.0f) { + color = lum + (((color - lum) * lum) / (lum - mn + kEhCloseEnough)); + } + if (mx > 1.0) { + color = + lum + (((color - lum) * (1.0f - lum)) / (mx - lum + kEhCloseEnough)); + } + return color; +} + +static constexpr inline Vector3 SetLuminosity(Vector3 color, + Scalar luminosity) { + Scalar relative_lum = luminosity - Luminosity(color); + return ClipColor(color + relative_lum); +} + +static constexpr inline Scalar Saturation(Vector3 color) { + return std::max(std::max(color.x, color.y), color.z) - + std::min(std::min(color.x, color.y), color.z); +} + +static constexpr inline Vector3 SetSaturation(Vector3 color, + Scalar saturation) { + Scalar mn = std::min(std::min(color.x, color.y), color.z); + Scalar mx = std::max(std::max(color.x, color.y), color.z); + return (mn < mx) ? ((color - mn) * saturation) / (mx - mn) : Vector3(); +} + +static constexpr inline Vector3 ComponentChoose(Vector3 a, + Vector3 b, + Vector3 value, + Scalar cutoff) { + return Vector3(value.x > cutoff ? b.x : a.x, // + value.y > cutoff ? b.y : a.y, // + value.z > cutoff ? b.z : a.z // + ); +} + +static constexpr inline Vector3 ToRGB(Color color) { + return {color.red, color.green, color.blue}; +} + +static constexpr inline Color FromRGB(Vector3 color, Scalar alpha) { + return {color.x, color.y, color.z, alpha}; +} + +/// Composite a blended color onto the destination. +/// All three parameters are unpremultiplied. Returns a premultiplied result. +/// +/// This routine is the same as `IPApplyBlendedColor` in the Impeller shader +/// library. +static constexpr inline Color ApplyBlendedColor(Color dst, + Color src, + Vector3 blend_result) { + dst = dst.Premultiply(); + src = + // Use the blended color for areas where the source and destination + // colors overlap. + FromRGB(blend_result, src.alpha * dst.alpha).Premultiply() + + // Use the original source color for any remaining non-overlapping areas. + src.Premultiply() * (1.0f - dst.alpha); + + // Source-over composite the blended source color atop the destination. + return src + dst * (1.0f - src.alpha); +} + +static constexpr inline Color DoColorBlend( + Color dst, + Color src, + const std::function& blend_rgb_func) { + const Vector3 blend_result = blend_rgb_func(ToRGB(dst), ToRGB(src)); + return ApplyBlendedColor(dst, src, blend_result).Unpremultiply(); +} + +static constexpr inline Color DoColorBlendComponents( + Color dst, + Color src, + const std::function& blend_func) { + Vector3 blend_result = Vector3(blend_func(dst.red, src.red), // + blend_func(dst.green, src.green), // + blend_func(dst.blue, src.blue)); // + return ApplyBlendedColor(dst, src, blend_result).Unpremultiply(); +} + +Color Color::Blend(Color src, BlendMode blend_mode) const { + Color dst = *this; + + switch (blend_mode) { + case BlendMode::kClear: + return Color::BlackTransparent(); + case BlendMode::kSrc: + return src; + case BlendMode::kDst: + return dst; + case BlendMode::kSrcOver: + // r = s + (1-sa)*d + return (src.Premultiply() + dst.Premultiply() * (1 - src.alpha)) + .Unpremultiply(); + case BlendMode::kDstOver: + // r = d + (1-da)*s + return (dst.Premultiply() + src.Premultiply() * (1 - dst.alpha)) + .Unpremultiply(); + case BlendMode::kSrcIn: + // r = s * da + return (src.Premultiply() * dst.alpha).Unpremultiply(); + case BlendMode::kDstIn: + // r = d * sa + return (dst.Premultiply() * src.alpha).Unpremultiply(); + case BlendMode::kSrcOut: + // r = s * ( 1- da) + return (src.Premultiply() * (1 - dst.alpha)).Unpremultiply(); + case BlendMode::kDstOut: + // r = d * (1-sa) + return (dst.Premultiply() * (1 - src.alpha)).Unpremultiply(); + case BlendMode::kSrcATop: + // r = s*da + d*(1-sa) + return (src.Premultiply() * dst.alpha + + dst.Premultiply() * (1 - src.alpha)) + .Unpremultiply(); + case BlendMode::kDstATop: + // r = d*sa + s*(1-da) + return (dst.Premultiply() * src.alpha + + src.Premultiply() * (1 - dst.alpha)) + .Unpremultiply(); + case BlendMode::kXor: + // r = s*(1-da) + d*(1-sa) + return (src.Premultiply() * (1 - dst.alpha) + + dst.Premultiply() * (1 - src.alpha)) + .Unpremultiply(); + case BlendMode::kPlus: + // r = min(s + d, 1) + return (Min(src.Premultiply() + dst.Premultiply(), 1)).Unpremultiply(); + case BlendMode::kModulate: + // r = s*d + return (src.Premultiply() * dst.Premultiply()).Unpremultiply(); + case BlendMode::kScreen: { + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return s + d - s * d; + }); + } + case BlendMode::kOverlay: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + // The same as HardLight, but with the source and destination reversed. + Vector3 screen_src = 2.0 * d - 1.0; + Vector3 screen = screen_src + s - screen_src * s; + return ComponentChoose(s * (2.0 * d), // + screen, // + d, // + 0.5); + }); + case BlendMode::kDarken: + return DoColorBlend( + dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d.Min(s); }); + case BlendMode::kLighten: + return DoColorBlend( + dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d.Max(s); }); + case BlendMode::kColorDodge: + return DoColorBlendComponents(dst, src, [](Scalar d, Scalar s) -> Scalar { + if (d < kEhCloseEnough) { + return 0.0f; + } + if (1.0 - s < kEhCloseEnough) { + return 1.0f; + } + return std::min(1.0f, d / (1.0f - s)); + }); + case BlendMode::kColorBurn: + return DoColorBlendComponents(dst, src, [](Scalar d, Scalar s) -> Scalar { + if (1.0 - d < kEhCloseEnough) { + return 1.0f; + } + if (s < kEhCloseEnough) { + return 0.0f; + } + return 1.0f - std::min(1.0f, (1.0f - d) / s); + }); + case BlendMode::kHardLight: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + Vector3 screen_src = 2.0 * s - 1.0; + Vector3 screen = screen_src + d - screen_src * d; + return ComponentChoose(d * (2.0 * s), // + screen, // + s, // + 0.5); + }); + case BlendMode::kSoftLight: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + Vector3 D = ComponentChoose(((16.0 * d - 12.0) * d + 4.0) * d, // + Vector3(std::sqrt(d.x), std::sqrt(d.y), + std::sqrt(d.z)), // + d, // + 0.25); + return ComponentChoose(d - (1.0 - 2.0 * s) * d * (1.0 - d), // + d + (2.0 * s - 1.0) * (D - d), // + s, // + 0.5); + }); + case BlendMode::kDifference: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return (d - s).Abs(); + }); + case BlendMode::kExclusion: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return d + s - 2.0f * d * s; + }); + case BlendMode::kMultiply: + return DoColorBlend( + dst, src, [](Vector3 d, Vector3 s) -> Vector3 { return d * s; }); + case BlendMode::kHue: { + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return SetLuminosity(SetSaturation(s, Saturation(d)), Luminosity(d)); + }); + } + case BlendMode::kSaturation: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return SetLuminosity(SetSaturation(d, Saturation(s)), Luminosity(d)); + }); + case BlendMode::kColor: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return SetLuminosity(s, Luminosity(d)); + }); + case BlendMode::kLuminosity: + return DoColorBlend(dst, src, [](Vector3 d, Vector3 s) -> Vector3 { + return SetLuminosity(d, Luminosity(s)); + }); + } +} + +Color Color::ApplyColorMatrix(const ColorMatrix& color_matrix) const { + auto* c = color_matrix.array; + return Color( + c[0] * red + c[1] * green + c[2] * blue + c[3] * alpha + c[4], + c[5] * red + c[6] * green + c[7] * blue + c[8] * alpha + c[9], + c[10] * red + c[11] * green + c[12] * blue + c[13] * alpha + c[14], + c[15] * red + c[16] * green + c[17] * blue + c[18] * alpha + c[19]) + .Clamp01(); +} + +Color Color::LinearToSRGB() const { + static auto conversion = [](Scalar component) { + if (component <= 0.0031308) { + return component * 12.92; + } + return 1.055 * pow(component, (1.0 / 2.4)) - 0.055; + }; + + return Color(conversion(red), conversion(green), conversion(blue), alpha); +} + +Color Color::SRGBToLinear() const { + static auto conversion = [](Scalar component) { + if (component <= 0.04045) { + return component / 12.92; + } + return pow((component + 0.055) / 1.055, 2.4); + }; + + return Color(conversion(red), conversion(green), conversion(blue), alpha); +} + +std::string ColorToString(const Color& color) { + return SPrintF("R=%.1f,G=%.1f,B=%.1f,A=%.1f", // + color.red, // + color.green, // + color.blue, // + color.alpha // + ); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/color.h b/flutter/engine/src/flutter/impeller/geometry/color.h new file mode 100644 index 0000000000000000000000000000000000000000..57c7c88e0c553aab2386b2abbe7578e6f8c7d0dd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/color.h @@ -0,0 +1,941 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_COLOR_H_ +#define FLUTTER_IMPELLER_GEOMETRY_COLOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/type_traits.h" + +#define IMPELLER_FOR_EACH_BLEND_MODE(V) \ + V(Clear) \ + V(Src) \ + V(Dst) \ + V(SrcOver) \ + V(DstOver) \ + V(SrcIn) \ + V(DstIn) \ + V(SrcOut) \ + V(DstOut) \ + V(SrcATop) \ + V(DstATop) \ + V(Xor) \ + V(Plus) \ + V(Modulate) \ + V(Screen) \ + V(Overlay) \ + V(Darken) \ + V(Lighten) \ + V(ColorDodge) \ + V(ColorBurn) \ + V(HardLight) \ + V(SoftLight) \ + V(Difference) \ + V(Exclusion) \ + V(Multiply) \ + V(Hue) \ + V(Saturation) \ + V(Color) \ + V(Luminosity) + +namespace impeller { + +struct Vector4; + +enum class YUVColorSpace { kBT601LimitedRange, kBT601FullRange }; + +/// All blend modes assume that both the source (fragment output) and +/// destination (first color attachment) have colors with premultiplied alpha. +enum class BlendMode : uint8_t { + // The following blend modes are able to be used as pipeline blend modes or + // via `BlendFilterContents`. + kClear = 0, + kSrc, + kDst, + kSrcOver, + kDstOver, + kSrcIn, + kDstIn, + kSrcOut, + kDstOut, + kSrcATop, + kDstATop, + kXor, + kPlus, + kModulate, + + // The following blend modes use equations that are not available for + // pipelines on most graphics devices without extensions, and so they are + // only able to be used via `BlendFilterContents`. + kScreen, + kOverlay, + kDarken, + kLighten, + kColorDodge, + kColorBurn, + kHardLight, + kSoftLight, + kDifference, + kExclusion, + kMultiply, + kHue, + kSaturation, + kColor, + kLuminosity, + + kLastMode = kLuminosity, + kDefaultMode = kSrcOver, +}; + +const char* BlendModeToString(BlendMode blend_mode); + +/// 4x5 matrix for transforming the color and alpha components of a Bitmap. +/// +/// [ a, b, c, d, e, +/// f, g, h, i, j, +/// k, l, m, n, o, +/// p, q, r, s, t ] +/// +/// When applied to a color [R, G, B, A], the resulting color is computed as: +/// +/// R’ = a*R + b*G + c*B + d*A + e; +/// G’ = f*R + g*G + h*B + i*A + j; +/// B’ = k*R + l*G + m*B + n*A + o; +/// A’ = p*R + q*G + r*B + s*A + t; +/// +/// That resulting color [R’, G’, B’, A’] then has each channel clamped to the 0 +/// to 1 range. +struct ColorMatrix { + Scalar array[20]; +}; + +/** + * Represents a RGBA color + */ +struct Color { + /** + * The red color component (0 to 1) + */ + Scalar red = 0.0; + + /** + * The green color component (0 to 1) + */ + Scalar green = 0.0; + + /** + * The blue color component (0 to 1) + */ + Scalar blue = 0.0; + + /** + * The alpha component of the color (0 to 1) + */ + Scalar alpha = 0.0; + + constexpr Color() {} + + explicit Color(const Vector4& value); + + constexpr Color(Scalar r, Scalar g, Scalar b, Scalar a) + : red(r), green(g), blue(b), alpha(a) {} + + static constexpr Color MakeRGBA8(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + return Color( + static_cast(r) / 255.0f, static_cast(g) / 255.0f, + static_cast(b) / 255.0f, static_cast(a) / 255.0f); + } + + /// @brief Convert this color to a 32-bit representation. + static constexpr uint32_t ToIColor(Color color) { + return (((std::lround(color.alpha * 255.0f) & 0xff) << 24) | + ((std::lround(color.red * 255.0f) & 0xff) << 16) | + ((std::lround(color.green * 255.0f) & 0xff) << 8) | + ((std::lround(color.blue * 255.0f) & 0xff) << 0)) & + 0xFFFFFFFF; + } + + constexpr inline bool operator==(const Color& c) const { + return ScalarNearlyEqual(red, c.red) && ScalarNearlyEqual(green, c.green) && + ScalarNearlyEqual(blue, c.blue) && ScalarNearlyEqual(alpha, c.alpha); + } + + constexpr inline Color operator+(const Color& c) const { + return {red + c.red, green + c.green, blue + c.blue, alpha + c.alpha}; + } + + template >> + constexpr inline Color operator+(T value) const { + auto v = static_cast(value); + return {red + v, green + v, blue + v, alpha + v}; + } + + constexpr inline Color operator-(const Color& c) const { + return {red - c.red, green - c.green, blue - c.blue, alpha - c.alpha}; + } + + template >> + constexpr inline Color operator-(T value) const { + auto v = static_cast(value); + return {red - v, green - v, blue - v, alpha - v}; + } + + constexpr inline Color operator*(const Color& c) const { + return {red * c.red, green * c.green, blue * c.blue, alpha * c.alpha}; + } + + template >> + constexpr inline Color operator*(T value) const { + auto v = static_cast(value); + return {red * v, green * v, blue * v, alpha * v}; + } + + constexpr inline Color operator/(const Color& c) const { + return {red * c.red, green * c.green, blue * c.blue, alpha * c.alpha}; + } + + template >> + constexpr inline Color operator/(T value) const { + auto v = static_cast(value); + return {red / v, green / v, blue / v, alpha / v}; + } + + constexpr Color Premultiply() const { + return {red * alpha, green * alpha, blue * alpha, alpha}; + } + + constexpr Color Unpremultiply() const { + if (ScalarNearlyEqual(alpha, 0.0f)) { + return Color::BlackTransparent(); + } + return {red / alpha, green / alpha, blue / alpha, alpha}; + } + + /** + * @brief Return a color that is linearly interpolated between colors a + * and b, according to the value of t. + * + * @param a The lower color. + * @param b The upper color. + * @param t A value between 0.0f and 1.0f, inclusive. + * @return constexpr Color + */ + constexpr static Color Lerp(Color a, Color b, Scalar t) { + return a + (b - a) * t; + } + + constexpr Color Clamp01() const { + return Color(std::clamp(red, 0.0f, 1.0f), std::clamp(green, 0.0f, 1.0f), + std::clamp(blue, 0.0f, 1.0f), std::clamp(alpha, 0.0f, 1.0f)); + } + + /** + * @brief Convert to R8G8B8A8 representation. + * + * @return constexpr std::array + */ + constexpr std::array ToR8G8B8A8() const { + uint8_t r = std::round(red * 255.0f); + uint8_t g = std::round(green * 255.0f); + uint8_t b = std::round(blue * 255.0f); + uint8_t a = std::round(alpha * 255.0f); + return {r, g, b, a}; + } + + /** + * @brief Convert to ARGB 32 bit color. + * + * @return constexpr uint32_t + */ + constexpr uint32_t ToARGB() const { + std::array result = ToR8G8B8A8(); + return result[3] << 24 | result[0] << 16 | result[1] << 8 | result[2]; + } + + static constexpr Color White() { return {1.0f, 1.0f, 1.0f, 1.0f}; } + + static constexpr Color Black() { return {0.0f, 0.0f, 0.0f, 1.0f}; } + + static constexpr Color WhiteTransparent() { return {1.0f, 1.0f, 1.0f, 0.0f}; } + + static constexpr Color BlackTransparent() { return {0.0f, 0.0f, 0.0f, 0.0f}; } + + static constexpr Color Red() { return {1.0f, 0.0f, 0.0f, 1.0f}; } + + static constexpr Color Green() { return {0.0f, 1.0f, 0.0f, 1.0f}; } + + static constexpr Color Blue() { return {0.0f, 0.0f, 1.0f, 1.0f}; } + + constexpr Color WithAlpha(Scalar new_alpha) const { + return {red, green, blue, new_alpha}; + } + + static constexpr Color AliceBlue() { + return {240.0f / 255.0f, 248.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color AntiqueWhite() { + return {250.0f / 255.0f, 235.0f / 255.0f, 215.0f / 255.0f, 1.0f}; + } + + static constexpr Color Aqua() { + return {0.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color AquaMarine() { + return {127.0f / 255.0f, 255.0f / 255.0f, 212.0f / 255.0f, 1.0f}; + } + + static constexpr Color Azure() { + return {240.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color Beige() { + return {245.0f / 255.0f, 245.0f / 255.0f, 220.0f / 255.0f, 1.0f}; + } + + static constexpr Color Bisque() { + return {255.0f / 255.0f, 228.0f / 255.0f, 196.0f / 255.0f, 1.0f}; + } + + static constexpr Color BlanchedAlmond() { + return {255.0f / 255.0f, 235.0f / 255.0f, 205.0f / 255.0f, 1.0f}; + } + + static constexpr Color BlueViolet() { + return {138.0f / 255.0f, 43.0f / 255.0f, 226.0f / 255.0f, 1.0f}; + } + + static constexpr Color Brown() { + return {165.0f / 255.0f, 42.0f / 255.0f, 42.0f / 255.0f, 1.0f}; + } + + static constexpr Color BurlyWood() { + return {222.0f / 255.0f, 184.0f / 255.0f, 135.0f / 255.0f, 1.0f}; + } + + static constexpr Color CadetBlue() { + return {95.0f / 255.0f, 158.0f / 255.0f, 160.0f / 255.0f, 1.0f}; + } + + static constexpr Color Chartreuse() { + return {127.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color Chocolate() { + return {210.0f / 255.0f, 105.0f / 255.0f, 30.0f / 255.0f, 1.0f}; + } + + static constexpr Color Coral() { + return {255.0f / 255.0f, 127.0f / 255.0f, 80.0f / 255.0f, 1.0f}; + } + + static constexpr Color CornflowerBlue() { + return {100.0f / 255.0f, 149.0f / 255.0f, 237.0f / 255.0f, 1.0f}; + } + + static constexpr Color Cornsilk() { + return {255.0f / 255.0f, 248.0f / 255.0f, 220.0f / 255.0f, 1.0f}; + } + + static constexpr Color Crimson() { + return {220.0f / 255.0f, 20.0f / 255.0f, 60.0f / 255.0f, 1.0f}; + } + + static constexpr Color Cyan() { + return {0.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkBlue() { + return {0.0f / 255.0f, 0.0f / 255.0f, 139.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkCyan() { + return {0.0f / 255.0f, 139.0f / 255.0f, 139.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkGoldenrod() { + return {184.0f / 255.0f, 134.0f / 255.0f, 11.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkGray() { + return {169.0f / 255.0f, 169.0f / 255.0f, 169.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkGreen() { + return {0.0f / 255.0f, 100.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkGrey() { + return {169.0f / 255.0f, 169.0f / 255.0f, 169.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkKhaki() { + return {189.0f / 255.0f, 183.0f / 255.0f, 107.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkMagenta() { + return {139.0f / 255.0f, 0.0f / 255.0f, 139.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkOliveGreen() { + return {85.0f / 255.0f, 107.0f / 255.0f, 47.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkOrange() { + return {255.0f / 255.0f, 140.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkOrchid() { + return {153.0f / 255.0f, 50.0f / 255.0f, 204.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkRed() { + return {139.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkSalmon() { + return {233.0f / 255.0f, 150.0f / 255.0f, 122.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkSeagreen() { + return {143.0f / 255.0f, 188.0f / 255.0f, 143.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkSlateBlue() { + return {72.0f / 255.0f, 61.0f / 255.0f, 139.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkSlateGray() { + return {47.0f / 255.0f, 79.0f / 255.0f, 79.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkSlateGrey() { + return {47.0f / 255.0f, 79.0f / 255.0f, 79.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkTurquoise() { + return {0.0f / 255.0f, 206.0f / 255.0f, 209.0f / 255.0f, 1.0f}; + } + + static constexpr Color DarkViolet() { + return {148.0f / 255.0f, 0.0f / 255.0f, 211.0f / 255.0f, 1.0f}; + } + + static constexpr Color DeepPink() { + return {255.0f / 255.0f, 20.0f / 255.0f, 147.0f / 255.0f, 1.0f}; + } + + static constexpr Color DeepSkyBlue() { + return {0.0f / 255.0f, 191.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color DimGray() { + return {105.0f / 255.0f, 105.0f / 255.0f, 105.0f / 255.0f, 1.0f}; + } + + static constexpr Color DimGrey() { + return {105.0f / 255.0f, 105.0f / 255.0f, 105.0f / 255.0f, 1.0f}; + } + + static constexpr Color DodgerBlue() { + return {30.0f / 255.0f, 144.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color Firebrick() { + return {178.0f / 255.0f, 34.0f / 255.0f, 34.0f / 255.0f, 1.0f}; + } + + static constexpr Color FloralWhite() { + return {255.0f / 255.0f, 250.0f / 255.0f, 240.0f / 255.0f, 1.0f}; + } + + static constexpr Color ForestGreen() { + return {34.0f / 255.0f, 139.0f / 255.0f, 34.0f / 255.0f, 1.0f}; + } + + static constexpr Color Fuchsia() { + return {255.0f / 255.0f, 0.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color Gainsboro() { + return {220.0f / 255.0f, 220.0f / 255.0f, 220.0f / 255.0f, 1.0f}; + } + + static constexpr Color Ghostwhite() { + return {248.0f / 255.0f, 248.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color Gold() { + return {255.0f / 255.0f, 215.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color Goldenrod() { + return {218.0f / 255.0f, 165.0f / 255.0f, 32.0f / 255.0f, 1.0f}; + } + + static constexpr Color Gray() { + return {128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color GreenYellow() { + return {173.0f / 255.0f, 255.0f / 255.0f, 47.0f / 255.0f, 1.0f}; + } + + static constexpr Color Grey() { + return {128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color Honeydew() { + return {240.0f / 255.0f, 255.0f / 255.0f, 240.0f / 255.0f, 1.0f}; + } + + static constexpr Color HotPink() { + return {255.0f / 255.0f, 105.0f / 255.0f, 180.0f / 255.0f, 1.0f}; + } + + static constexpr Color IndianRed() { + return {205.0f / 255.0f, 92.0f / 255.0f, 92.0f / 255.0f, 1.0f}; + } + + static constexpr Color Indigo() { + return {75.0f / 255.0f, 0.0f / 255.0f, 130.0f / 255.0f, 1.0f}; + } + + static constexpr Color Ivory() { + return {255.0f / 255.0f, 255.0f / 255.0f, 240.0f / 255.0f, 1.0f}; + } + + static constexpr Color Khaki() { + return {240.0f / 255.0f, 230.0f / 255.0f, 140.0f / 255.0f, 1.0f}; + } + + static constexpr Color Lavender() { + return {230.0f / 255.0f, 230.0f / 255.0f, 250.0f / 255.0f, 1.0f}; + } + + static constexpr Color LavenderBlush() { + return {255.0f / 255.0f, 240.0f / 255.0f, 245.0f / 255.0f, 1.0f}; + } + + static constexpr Color LawnGreen() { + return {124.0f / 255.0f, 252.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color LemonChiffon() { + return {255.0f / 255.0f, 250.0f / 255.0f, 205.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightBlue() { + return {173.0f / 255.0f, 216.0f / 255.0f, 230.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightCoral() { + return {240.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightCyan() { + return {224.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightGoldenrodYellow() { + return {50.0f / 255.0f, 250.0f / 255.0f, 210.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightGray() { + return {211.0f / 255.0f, 211.0f / 255.0f, 211.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightGreen() { + return {144.0f / 255.0f, 238.0f / 255.0f, 144.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightGrey() { + return {211.0f / 255.0f, 211.0f / 255.0f, 211.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightPink() { + return {255.0f / 255.0f, 182.0f / 255.0f, 193.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSalmon() { + return {255.0f / 255.0f, 160.0f / 255.0f, 122.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSeaGreen() { + return {32.0f / 255.0f, 178.0f / 255.0f, 170.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSkyBlue() { + return {135.0f / 255.0f, 206.0f / 255.0f, 250.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSlateGray() { + return {119.0f / 255.0f, 136.0f / 255.0f, 153.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSlateGrey() { + return {119.0f / 255.0f, 136.0f / 255.0f, 153.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightSteelBlue() { + return {176.0f / 255.0f, 196.0f / 255.0f, 222.0f / 255.0f, 1.0f}; + } + + static constexpr Color LightYellow() { + return {255.0f / 255.0f, 255.0f / 255.0f, 224.0f / 255.0f, 1.0f}; + } + + static constexpr Color Lime() { + return {0.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color LimeGreen() { + return {50.0f / 255.0f, 205.0f / 255.0f, 50.0f / 255.0f, 1.0f}; + } + + static constexpr Color Linen() { + return {250.0f / 255.0f, 240.0f / 255.0f, 230.0f / 255.0f, 1.0f}; + } + + static constexpr Color Magenta() { + return {255.0f / 255.0f, 0.0f / 255.0f, 255.0f / 255.0f, 1.0f}; + } + + static constexpr Color Maroon() { + return {128.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumAquamarine() { + return {102.0f / 255.0f, 205.0f / 255.0f, 170.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumBlue() { + return {0.0f / 255.0f, 0.0f / 255.0f, 205.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumOrchid() { + return {186.0f / 255.0f, 85.0f / 255.0f, 211.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumPurple() { + return {147.0f / 255.0f, 112.0f / 255.0f, 219.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumSeagreen() { + return {60.0f / 255.0f, 179.0f / 255.0f, 113.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumSlateBlue() { + return {123.0f / 255.0f, 104.0f / 255.0f, 238.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumSpringGreen() { + return {0.0f / 255.0f, 250.0f / 255.0f, 154.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumTurquoise() { + return {72.0f / 255.0f, 209.0f / 255.0f, 204.0f / 255.0f, 1.0f}; + } + + static constexpr Color MediumVioletRed() { + return {199.0f / 255.0f, 21.0f / 255.0f, 133.0f / 255.0f, 1.0f}; + } + + static constexpr Color MidnightBlue() { + return {25.0f / 255.0f, 25.0f / 255.0f, 112.0f / 255.0f, 1.0f}; + } + + static constexpr Color MintCream() { + return {245.0f / 255.0f, 255.0f / 255.0f, 250.0f / 255.0f, 1.0f}; + } + + static constexpr Color MistyRose() { + return {255.0f / 255.0f, 228.0f / 255.0f, 225.0f / 255.0f, 1.0f}; + } + + static constexpr Color Moccasin() { + return {255.0f / 255.0f, 228.0f / 255.0f, 181.0f / 255.0f, 1.0f}; + } + + static constexpr Color NavajoWhite() { + return {255.0f / 255.0f, 222.0f / 255.0f, 173.0f / 255.0f, 1.0f}; + } + + static constexpr Color Navy() { + return {0.0f / 255.0f, 0.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color OldLace() { + return {253.0f / 255.0f, 245.0f / 255.0f, 230.0f / 255.0f, 1.0f}; + } + + static constexpr Color Olive() { + return {128.0f / 255.0f, 128.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color OliveDrab() { + return {107.0f / 255.0f, 142.0f / 255.0f, 35.0f / 255.0f, 1.0f}; + } + + static constexpr Color Orange() { + return {255.0f / 255.0f, 165.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color OrangeRed() { + return {255.0f / 255.0f, 69.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color Orchid() { + return {218.0f / 255.0f, 112.0f / 255.0f, 214.0f / 255.0f, 1.0f}; + } + + static constexpr Color PaleGoldenrod() { + return {238.0f / 255.0f, 232.0f / 255.0f, 170.0f / 255.0f, 1.0f}; + } + + static constexpr Color PaleGreen() { + return {152.0f / 255.0f, 251.0f / 255.0f, 152.0f / 255.0f, 1.0f}; + } + + static constexpr Color PaleTurquoise() { + return {175.0f / 255.0f, 238.0f / 255.0f, 238.0f / 255.0f, 1.0f}; + } + + static constexpr Color PaleVioletRed() { + return {219.0f / 255.0f, 112.0f / 255.0f, 147.0f / 255.0f, 1.0f}; + } + + static constexpr Color PapayaWhip() { + return {255.0f / 255.0f, 239.0f / 255.0f, 213.0f / 255.0f, 1.0f}; + } + + static constexpr Color Peachpuff() { + return {255.0f / 255.0f, 218.0f / 255.0f, 185.0f / 255.0f, 1.0f}; + } + + static constexpr Color Peru() { + return {205.0f / 255.0f, 133.0f / 255.0f, 63.0f / 255.0f, 1.0f}; + } + + static constexpr Color Pink() { + return {255.0f / 255.0f, 192.0f / 255.0f, 203.0f / 255.0f, 1.0f}; + } + + static constexpr Color Plum() { + return {221.0f / 255.0f, 160.0f / 255.0f, 221.0f / 255.0f, 1.0f}; + } + + static constexpr Color PowderBlue() { + return {176.0f / 255.0f, 224.0f / 255.0f, 230.0f / 255.0f, 1.0f}; + } + + static constexpr Color Purple() { + return {128.0f / 255.0f, 0.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color RosyBrown() { + return {188.0f / 255.0f, 143.0f / 255.0f, 143.0f / 255.0f, 1.0f}; + } + + static constexpr Color RoyalBlue() { + return {65.0f / 255.0f, 105.0f / 255.0f, 225.0f / 255.0f, 1.0f}; + } + + static constexpr Color SaddleBrown() { + return {139.0f / 255.0f, 69.0f / 255.0f, 19.0f / 255.0f, 1.0f}; + } + + static constexpr Color Salmon() { + return {250.0f / 255.0f, 128.0f / 255.0f, 114.0f / 255.0f, 1.0f}; + } + + static constexpr Color SandyBrown() { + return {244.0f / 255.0f, 164.0f / 255.0f, 96.0f / 255.0f, 1.0f}; + } + + static constexpr Color Seagreen() { + return {46.0f / 255.0f, 139.0f / 255.0f, 87.0f / 255.0f, 1.0f}; + } + + static constexpr Color Seashell() { + return {255.0f / 255.0f, 245.0f / 255.0f, 238.0f / 255.0f, 1.0f}; + } + + static constexpr Color Sienna() { + return {160.0f / 255.0f, 82.0f / 255.0f, 45.0f / 255.0f, 1.0f}; + } + + static constexpr Color Silver() { + return {192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f, 1.0f}; + } + + static constexpr Color SkyBlue() { + return {135.0f / 255.0f, 206.0f / 255.0f, 235.0f / 255.0f, 1.0f}; + } + + static constexpr Color SlateBlue() { + return {106.0f / 255.0f, 90.0f / 255.0f, 205.0f / 255.0f, 1.0f}; + } + + static constexpr Color SlateGray() { + return {112.0f / 255.0f, 128.0f / 255.0f, 144.0f / 255.0f, 1.0f}; + } + + static constexpr Color SlateGrey() { + return {112.0f / 255.0f, 128.0f / 255.0f, 144.0f / 255.0f, 1.0f}; + } + + static constexpr Color Snow() { + return {255.0f / 255.0f, 250.0f / 255.0f, 250.0f / 255.0f, 1.0f}; + } + + static constexpr Color SpringGreen() { + return {0.0f / 255.0f, 255.0f / 255.0f, 127.0f / 255.0f, 1.0f}; + } + + static constexpr Color SteelBlue() { + return {70.0f / 255.0f, 130.0f / 255.0f, 180.0f / 255.0f, 1.0f}; + } + + static constexpr Color Tan() { + return {210.0f / 255.0f, 180.0f / 255.0f, 140.0f / 255.0f, 1.0f}; + } + + static constexpr Color Teal() { + return {0.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f, 1.0f}; + } + + static constexpr Color Thistle() { + return {216.0f / 255.0f, 191.0f / 255.0f, 216.0f / 255.0f, 1.0f}; + } + + static constexpr Color Tomato() { + return {255.0f / 255.0f, 99.0f / 255.0f, 71.0f / 255.0f, 1.0f}; + } + + static constexpr Color Turquoise() { + return {64.0f / 255.0f, 224.0f / 255.0f, 208.0f / 255.0f, 1.0f}; + } + + static constexpr Color Violet() { + return {238.0f / 255.0f, 130.0f / 255.0f, 238.0f / 255.0f, 1.0f}; + } + + static constexpr Color Wheat() { + return {245.0f / 255.0f, 222.0f / 255.0f, 179.0f / 255.0f, 1.0f}; + } + + static constexpr Color Whitesmoke() { + return {245.0f / 255.0f, 245.0f / 255.0f, 245.0f / 255.0f, 1.0f}; + } + + static constexpr Color Yellow() { + return {255.0f / 255.0f, 255.0f / 255.0f, 0.0f / 255.0f, 1.0f}; + } + + static constexpr Color YellowGreen() { + return {154.0f / 255.0f, 205.0f / 255.0f, 50.0f / 255.0f, 1.0f}; + } + + static Color Random() { + return { + // This method is not used for cryptographic purposes. + // NOLINTBEGIN(clang-analyzer-security.insecureAPI.rand) + static_cast((std::rand() % 255) / 255.0f), // + static_cast((std::rand() % 255) / 255.0f), // + static_cast((std::rand() % 255) / 255.0f), // + // NOLINTEND(clang-analyzer-security.insecureAPI.rand) + 1.0f // + + }; + } + + /// @brief Blends an unpremultiplied destination color into a given + /// unpremultiplied source color to form a new unpremultiplied color. + /// + /// If either the source or destination are premultiplied, the result + /// will be incorrect. + Color Blend(Color source, BlendMode blend_mode) const; + + /// @brief A color filter that transforms colors through a 4x5 color matrix. + /// + /// This filter can be used to change the saturation of pixels, convert + /// from YUV to RGB, etc. + /// + /// Each channel of the output color is clamped to the 0 to 1 range. + /// + /// @see `ColorMatrix` + Color ApplyColorMatrix(const ColorMatrix& color_matrix) const; + + /// @brief Convert the color from linear space to sRGB space. + /// + /// The color is assumed to be unpremultiplied. If the color is + /// premultipled, the conversion output will be incorrect. + Color LinearToSRGB() const; + + /// @brief Convert the color from sRGB space to linear space. + /// + /// The color is assumed to be unpremultiplied. If the color is + /// premultipled, the conversion output will be incorrect. + Color SRGBToLinear() const; + + constexpr bool IsTransparent() const { return alpha == 0.0f; } + + constexpr bool IsOpaque() const { return alpha == 1.0f; } +}; + +template >> +constexpr inline Color operator+(T value, const Color& c) { + return c + static_cast(value); +} + +template >> +constexpr inline Color operator-(T value, const Color& c) { + auto v = static_cast(value); + return {v - c.red, v - c.green, v - c.blue, v - c.alpha}; +} + +template >> +constexpr inline Color operator*(T value, const Color& c) { + return c * static_cast(value); +} + +template >> +constexpr inline Color operator/(T value, const Color& c) { + auto v = static_cast(value); + return {v / c.red, v / c.green, v / c.blue, v / c.alpha}; +} + +std::string ColorToString(const Color& color); + +static_assert(sizeof(Color) == 4 * sizeof(Scalar)); + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, const impeller::Color& c) { + out << "(" << c.red << ", " << c.green << ", " << c.blue << ", " << c.alpha + << ")"; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const impeller::BlendMode& mode) { + out << "BlendMode::k" << BlendModeToString(mode); + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_COLOR_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/constants.cc b/flutter/engine/src/flutter/impeller/geometry/constants.cc new file mode 100644 index 0000000000000000000000000000000000000000..115a24da4a3d1e80bc04129cfe86d43e28e14557 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/constants.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/constants.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/constants.h b/flutter/engine/src/flutter/impeller/geometry/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..3630f64ad3600e36089b1829e400ca66db10ea09 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/constants.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_CONSTANTS_H_ +#define FLUTTER_IMPELLER_GEOMETRY_CONSTANTS_H_ + +namespace impeller { + +// e +constexpr float kE = 2.7182818284590452354f; + +// log_2 e +constexpr float kLog2E = 1.4426950408889634074f; + +// log_10 e +constexpr float kLog10E = 0.43429448190325182765f; + +// log_e 2 +constexpr float kLogE2 = 0.69314718055994530942f; + +// log_e 10 +constexpr float kLogE10 = 2.30258509299404568402f; + +// pi +constexpr float kPi = 3.14159265358979323846f; + +// pi*2 +constexpr float k2Pi = 6.28318530717958647693f; + +// pi/2 +constexpr float kPiOver2 = 1.57079632679489661923f; + +// pi/4 +constexpr float kPiOver4 = 0.78539816339744830962f; + +// 1/pi +constexpr float k1OverPi = 0.31830988618379067154f; + +// 2/pi +constexpr float k2OverPi = 0.63661977236758134308f; + +// 2/sqrt(pi) +constexpr float k2OverSqrtPi = 1.12837916709551257390f; + +// sqrt(2) +constexpr float kSqrt2 = 1.41421356237309504880f; + +// sqrt(2) / 2 == 1/sqrt(2) +constexpr float k1OverSqrt2 = 0.70710678118654752440f; +constexpr float kSqrt2Over2 = 0.70710678118654752440f; + +// phi +constexpr float kPhi = 1.61803398874989484820f; + +// 0.001 +constexpr float kEhCloseEnough = 1e-3f; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_CONSTANTS_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/geometry_asserts.h b/flutter/engine/src/flutter/impeller/geometry/geometry_asserts.h new file mode 100644 index 0000000000000000000000000000000000000000..f5ad45b67f764a5fe8ac46dd9450a92d69275242 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/geometry_asserts.h @@ -0,0 +1,213 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_ +#define FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_ + +#include +#include + +#include "gtest/gtest.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/size.h" +#include "impeller/geometry/vector.h" + +inline bool NumberNear(double a, double b) { + if (a == b) { + return true; + } + if (std::isnan(a) || std::isnan(b)) { + return false; + } + + // We used to compare based on an absolute difference of 1e-3 which + // would allow up to 10 bits of mantissa difference in a float + // (leaving 14 bits of accuracy being tested). Some numbers in the tests + // will fail with a bit difference of up to 19 (a little over 4 bits) even + // though the numbers print out identically using the float ostream output + // at the default output precision. Choosing a max "units of least precision" + // of 32 allows up to 5 bits of imprecision. + static constexpr float kImpellerTestingMaxULP = 32; + + // We also impose a minimum step size so that cases of comparing numbers + // very close to 0.0 don't compute a huge number of ULPs due to the ever + // increasing precision near 0. This value is approximately the step size + // of numbers going less than 1.0f. + static constexpr float kMinimumULPStep = (1.0f / (1 << 24)); + + auto adjust_step = [](float v) { + return (std::abs(v) < kMinimumULPStep) ? std::copysignf(kMinimumULPStep, v) + : v; + }; + + float step_ab = adjust_step(a - std::nexttowardf(a, b)); + float step_ba = adjust_step(b - std::nexttowardf(b, a)); + + float ab_ulps = (a - b) / step_ab; + float ba_ulps = (b - a) / step_ba; + FML_CHECK(ab_ulps >= 0 && ba_ulps >= 0); + + return (std::min(ab_ulps, ba_ulps) < kImpellerTestingMaxULP); +} + +inline ::testing::AssertionResult MatrixNear(impeller::Matrix a, + impeller::Matrix b) { + auto equal = NumberNear(a.m[0], b.m[0]) // + && NumberNear(a.m[1], b.m[1]) // + && NumberNear(a.m[2], b.m[2]) // + && NumberNear(a.m[3], b.m[3]) // + && NumberNear(a.m[4], b.m[4]) // + && NumberNear(a.m[5], b.m[5]) // + && NumberNear(a.m[6], b.m[6]) // + && NumberNear(a.m[7], b.m[7]) // + && NumberNear(a.m[8], b.m[8]) // + && NumberNear(a.m[9], b.m[9]) // + && NumberNear(a.m[10], b.m[10]) // + && NumberNear(a.m[11], b.m[11]) // + && NumberNear(a.m[12], b.m[12]) // + && NumberNear(a.m[13], b.m[13]) // + && NumberNear(a.m[14], b.m[14]) // + && NumberNear(a.m[15], b.m[15]); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() + << "Matrixes are not equal " << a << " " << b; +} + +inline ::testing::AssertionResult QuaternionNear(impeller::Quaternion a, + impeller::Quaternion b) { + auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y) && + NumberNear(a.z, b.z) && NumberNear(a.w, b.w); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Quaternions are not equal."; +} + +inline ::testing::AssertionResult RectNear(impeller::Rect a, impeller::Rect b) { + auto equal = NumberNear(a.GetLeft(), b.GetLeft()) && + NumberNear(a.GetTop(), b.GetTop()) && + NumberNear(a.GetRight(), b.GetRight()) && + NumberNear(a.GetBottom(), b.GetBottom()); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() + << "Rects are not equal (" << a << " " << b << ")"; +} + +inline ::testing::AssertionResult ColorNear(impeller::Color a, + impeller::Color b) { + auto equal = NumberNear(a.red, b.red) && NumberNear(a.green, b.green) && + NumberNear(a.blue, b.blue) && NumberNear(a.alpha, b.alpha); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Colors are not equal."; +} + +inline ::testing::AssertionResult PointNear(impeller::Point a, + impeller::Point b) { + auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() + << "Points are not equal (" << a << " " << b << ")."; +} + +inline ::testing::AssertionResult Vector3Near(impeller::Vector3 a, + impeller::Vector3 b) { + auto equal = + NumberNear(a.x, b.x) && NumberNear(a.y, b.y) && NumberNear(a.z, b.z); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Vector3s are not equal."; +} + +inline ::testing::AssertionResult Vector4Near(impeller::Vector4 a, + impeller::Vector4 b) { + auto equal = NumberNear(a.x, b.x) && NumberNear(a.y, b.y) && + NumberNear(a.z, b.z) && NumberNear(a.w, b.w); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Vector4s are not equal."; +} + +inline ::testing::AssertionResult SizeNear(impeller::Size a, impeller::Size b) { + auto equal = NumberNear(a.width, b.width) && NumberNear(a.height, b.height); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Sizes are not equal."; +} + +inline ::testing::AssertionResult Array4Near(std::array a, + std::array b) { + auto equal = NumberNear(a[0], b[0]) && NumberNear(a[1], b[1]) && + NumberNear(a[2], b[2]) && NumberNear(a[3], b[3]); + + return equal ? ::testing::AssertionSuccess() + : ::testing::AssertionFailure() << "Arrays are not equal."; +} + +inline ::testing::AssertionResult ColorBufferNear( + std::vector a, + std::vector b) { + if (a.size() != b.size() * 4) { + return ::testing::AssertionFailure() + << "Color buffer length does not match"; + } + for (auto i = 0u; i < b.size(); i++) { + auto right = b[i].Premultiply().ToR8G8B8A8(); + auto j = i * 4; + auto equal = NumberNear(a[j], right[0]) && NumberNear(a[j + 1], right[1]) && + NumberNear(a[j + 2], right[2]) && + NumberNear(a[j + 3], right[3]); + if (!equal) { + ::testing::AssertionFailure() << "Color buffers are not equal."; + } + } + return ::testing::AssertionSuccess(); +} + +inline ::testing::AssertionResult ColorsNear(std::vector a, + std::vector b) { + if (a.size() != b.size()) { + return ::testing::AssertionFailure() << "Colors length does not match"; + } + for (auto i = 0u; i < b.size(); i++) { + auto equal = + NumberNear(a[i].red, b[i].red) && NumberNear(a[i].green, b[i].green) && + NumberNear(a[i].blue, b[i].blue) && NumberNear(a[i].alpha, b[i].alpha); + + if (!equal) { + ::testing::AssertionFailure() << "Colors are not equal."; + } + } + return ::testing::AssertionSuccess(); +} + +#define ASSERT_MATRIX_NEAR(a, b) ASSERT_PRED2(&::MatrixNear, a, b) +#define ASSERT_QUATERNION_NEAR(a, b) ASSERT_PRED2(&::QuaternionNear, a, b) +#define ASSERT_RECT_NEAR(a, b) ASSERT_PRED2(&::RectNear, a, b) +#define ASSERT_COLOR_NEAR(a, b) ASSERT_PRED2(&::ColorNear, a, b) +#define ASSERT_POINT_NEAR(a, b) ASSERT_PRED2(&::PointNear, a, b) +#define ASSERT_VECTOR3_NEAR(a, b) ASSERT_PRED2(&::Vector3Near, a, b) +#define ASSERT_VECTOR4_NEAR(a, b) ASSERT_PRED2(&::Vector4Near, a, b) +#define ASSERT_SIZE_NEAR(a, b) ASSERT_PRED2(&::SizeNear, a, b) +#define ASSERT_ARRAY_4_NEAR(a, b) ASSERT_PRED2(&::Array4Near, a, b) +#define ASSERT_COLOR_BUFFER_NEAR(a, b) ASSERT_PRED2(&::ColorBufferNear, a, b) +#define ASSERT_COLORS_NEAR(a, b) ASSERT_PRED2(&::ColorsNear, a, b) + +#define EXPECT_MATRIX_NEAR(a, b) EXPECT_PRED2(&::MatrixNear, a, b) +#define EXPECT_QUATERNION_NEAR(a, b) EXPECT_PRED2(&::QuaternionNear, a, b) +#define EXPECT_RECT_NEAR(a, b) EXPECT_PRED2(&::RectNear, a, b) +#define EXPECT_COLOR_NEAR(a, b) EXPECT_PRED2(&::ColorNear, a, b) +#define EXPECT_POINT_NEAR(a, b) EXPECT_PRED2(&::PointNear, a, b) +#define EXPECT_VECTOR3_NEAR(a, b) EXPECT_PRED2(&::Vector3Near, a, b) +#define EXPECT_VECTOR4_NEAR(a, b) EXPECT_PRED2(&::Vector4Near, a, b) +#define EXPECT_SIZE_NEAR(a, b) EXPECT_PRED2(&::SizeNear, a, b) +#define EXPECT_ARRAY_4_NEAR(a, b) EXPECT_PRED2(&::Array4Near, a, b) +#define EXPECT_COLOR_BUFFER_NEAR(a, b) EXPECT_PRED2(&::ColorBufferNear, a, b) +#define EXPECT_COLORS_NEAR(a, b) EXPECT_PRED2(&::ColorsNear, a, b) + +#endif // FLUTTER_IMPELLER_GEOMETRY_GEOMETRY_ASSERTS_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/geometry_benchmarks.cc b/flutter/engine/src/flutter/impeller/geometry/geometry_benchmarks.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa3128c605970e443eb9876f5692da1dacd6765f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/geometry_benchmarks.cc @@ -0,0 +1,468 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/benchmarking/benchmarking.h" + +#include "impeller/entity/geometry/stroke_path_geometry.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/tessellator/tessellator_libtess.h" + +namespace impeller { + +class ImpellerBenchmarkAccessor { + public: + static std::vector GenerateSolidStrokeVertices( + const Path::Polyline& polyline, + Scalar stroke_width, + Scalar miter_limit, + Join stroke_join, + Cap stroke_cap, + Scalar scale) { + return StrokePathGeometry::GenerateSolidStrokeVertices( + polyline, stroke_width, miter_limit, stroke_join, stroke_cap, scale); + } +}; + +namespace { +/// A path with many connected cubic components, including +/// overlaps/self-intersections/multi-contour. +Path CreateCubic(bool closed); +/// Similar to the path above, but with all cubics replaced by quadratics. +Path CreateQuadratic(bool closed); +/// Create a rounded rect. +Path CreateRRect(); +/// Create a rounded superellipse. +Path CreateRSuperellipse(); +} // namespace + +static TessellatorLibtess tess; + +template +static void BM_Polyline(benchmark::State& state, Args&&... args) { + auto args_tuple = std::make_tuple(std::move(args)...); + auto path = std::get(args_tuple); + + size_t point_count = 0u; + size_t single_point_count = 0u; + auto points = std::make_unique>(); + points->reserve(2048); + while (state.KeepRunning()) { + auto polyline = path.CreatePolyline( + // Clang-tidy doesn't know that the points get moved back before + // getting moved again in this loop. + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + 1.0f, std::move(points), + [&points](Path::Polyline::PointBufferPtr reclaimed) { + points = std::move(reclaimed); + }); + single_point_count = polyline.points->size(); + point_count += single_point_count; + } + state.counters["SinglePointCount"] = single_point_count; + state.counters["TotalPointCount"] = point_count; +} + +template +static void BM_StrokePolyline(benchmark::State& state, Args&&... args) { + auto args_tuple = std::make_tuple(std::move(args)...); + auto path = std::get(args_tuple); + auto cap = std::get(args_tuple); + auto join = std::get(args_tuple); + + const Scalar stroke_width = 5.0f; + const Scalar miter_limit = 10.0f; + const Scalar scale = 1.0f; + + auto points = std::make_unique>(); + points->reserve(2048); + auto polyline = + path.CreatePolyline(1.0f, std::move(points), + [&points](Path::Polyline::PointBufferPtr reclaimed) { + points = std::move(reclaimed); + }); + + size_t point_count = 0u; + size_t single_point_count = 0u; + while (state.KeepRunning()) { + auto vertices = ImpellerBenchmarkAccessor::GenerateSolidStrokeVertices( + polyline, stroke_width, miter_limit, join, cap, scale); + single_point_count = vertices.size(); + point_count += single_point_count; + } + state.counters["SinglePointCount"] = single_point_count; + state.counters["TotalPointCount"] = point_count; +} + +template +static void BM_Convex(benchmark::State& state, Args&&... args) { + auto args_tuple = std::make_tuple(std::move(args)...); + auto path = std::get(args_tuple); + + size_t point_count = 0u; + size_t single_point_count = 0u; + auto points = std::make_unique>(); + auto indices = std::make_unique>(); + points->reserve(2048); + while (state.KeepRunning()) { + points->clear(); + indices->clear(); + Tessellator::TessellateConvexInternal(path, *points, *indices, 1.0f); + single_point_count = indices->size(); + point_count += indices->size(); + } + state.counters["SinglePointCount"] = single_point_count; + state.counters["TotalPointCount"] = point_count; +} + +#define MAKE_STROKE_BENCHMARK_CAPTURE(path, cap, join, closed) \ + BENCHMARK_CAPTURE(BM_StrokePolyline, stroke_##path##_##cap##_##join, \ + Create##path(closed), Cap::k##cap, Join::k##join) + +#define MAKE_STROKE_BENCHMARK_CAPTURE_ALL_CAPS_JOINS(path, closed) \ + MAKE_STROKE_BENCHMARK_CAPTURE(path, Butt, Bevel, closed); \ + MAKE_STROKE_BENCHMARK_CAPTURE(path, Butt, Miter, closed); \ + MAKE_STROKE_BENCHMARK_CAPTURE(path, Butt, Round, closed); \ + MAKE_STROKE_BENCHMARK_CAPTURE(path, Square, Bevel, closed); \ + MAKE_STROKE_BENCHMARK_CAPTURE(path, Round, Bevel, closed) + +BENCHMARK_CAPTURE(BM_Polyline, cubic_polyline, CreateCubic(true)); +BENCHMARK_CAPTURE(BM_Polyline, unclosed_cubic_polyline, CreateCubic(false)); +MAKE_STROKE_BENCHMARK_CAPTURE_ALL_CAPS_JOINS(Cubic, false); + +BENCHMARK_CAPTURE(BM_Polyline, quad_polyline, CreateQuadratic(true)); +BENCHMARK_CAPTURE(BM_Polyline, unclosed_quad_polyline, CreateQuadratic(false)); +MAKE_STROKE_BENCHMARK_CAPTURE_ALL_CAPS_JOINS(Quadratic, false); + +BENCHMARK_CAPTURE(BM_Convex, rrect_convex, CreateRRect(), true); +// A round rect has no ends so we don't need to try it with all cap values +// but it does have joins and even though they should all be almost +// colinear, we run the benchmark against all 3 join values. +MAKE_STROKE_BENCHMARK_CAPTURE(RRect, Butt, Bevel, ); +MAKE_STROKE_BENCHMARK_CAPTURE(RRect, Butt, Miter, ); +MAKE_STROKE_BENCHMARK_CAPTURE(RRect, Butt, Round, ); + +// Same as RRect +BENCHMARK_CAPTURE(BM_Convex, rse_convex, CreateRSuperellipse(), true); +MAKE_STROKE_BENCHMARK_CAPTURE(RSuperellipse, Butt, Bevel, ); +MAKE_STROKE_BENCHMARK_CAPTURE(RSuperellipse, Butt, Miter, ); +MAKE_STROKE_BENCHMARK_CAPTURE(RSuperellipse, Butt, Round, ); + +namespace { + +Path CreateRRect() { + return PathBuilder{} + .AddRoundRect( + RoundRect::MakeRectXY(Rect::MakeLTRB(0, 0, 400, 400), 16, 16)) + .TakePath(); +} + +Path CreateRSuperellipse() { + return PathBuilder{} + .AddRoundSuperellipse( + RoundSuperellipse::MakeRectXY(Rect::MakeLTRB(0, 0, 400, 400), 16, 16)) + .TakePath(); +} + +Path CreateCubic(bool closed) { + auto builder = PathBuilder{}; + builder // + .MoveTo({359.934, 96.6335}) + .CubicCurveTo({358.189, 96.7055}, {356.436, 96.7908}, {354.673, 96.8895}) + .CubicCurveTo({354.571, 96.8953}, {354.469, 96.9016}, {354.367, 96.9075}) + .CubicCurveTo({352.672, 97.0038}, {350.969, 97.113}, {349.259, 97.2355}) + .CubicCurveTo({349.048, 97.2506}, {348.836, 97.2678}, {348.625, 97.2834}) + .CubicCurveTo({347.019, 97.4014}, {345.407, 97.5299}, {343.789, 97.6722}) + .CubicCurveTo({343.428, 97.704}, {343.065, 97.7402}, {342.703, 97.7734}) + .CubicCurveTo({341.221, 97.9086}, {339.736, 98.0505}, {338.246, 98.207}) + .CubicCurveTo({337.702, 98.2642}, {337.156, 98.3292}, {336.612, 98.3894}) + .CubicCurveTo({335.284, 98.5356}, {333.956, 98.6837}, {332.623, 98.8476}) + .CubicCurveTo({332.495, 98.8635}, {332.366, 98.8818}, {332.237, 98.8982}) + .LineTo({332.237, 102.601}) + .LineTo({321.778, 102.601}) + .LineTo({321.778, 100.382}) + .CubicCurveTo({321.572, 100.413}, {321.367, 100.442}, {321.161, 100.476}) + .CubicCurveTo({319.22, 100.79}, {317.277, 101.123}, {315.332, 101.479}) + .CubicCurveTo({315.322, 101.481}, {315.311, 101.482}, {315.301, 101.484}) + .LineTo({310.017, 105.94}) + .LineTo({309.779, 105.427}) + .LineTo({314.403, 101.651}) + .CubicCurveTo({314.391, 101.653}, {314.379, 101.656}, {314.368, 101.658}) + .CubicCurveTo({312.528, 102.001}, {310.687, 102.366}, {308.846, 102.748}) + .CubicCurveTo({307.85, 102.955}, {306.855, 103.182}, {305.859, 103.4}) + .CubicCurveTo({305.048, 103.579}, {304.236, 103.75}, {303.425, 103.936}) + .LineTo({299.105, 107.578}) + .LineTo({298.867, 107.065}) + .LineTo({302.394, 104.185}) + .LineTo({302.412, 104.171}) + .CubicCurveTo({301.388, 104.409}, {300.366, 104.67}, {299.344, 104.921}) + .CubicCurveTo({298.618, 105.1}, {297.89, 105.269}, {297.165, 105.455}) + .CubicCurveTo({295.262, 105.94}, {293.36, 106.445}, {291.462, 106.979}) + .CubicCurveTo({291.132, 107.072}, {290.802, 107.163}, {290.471, 107.257}) + .CubicCurveTo({289.463, 107.544}, {288.455, 107.839}, {287.449, 108.139}) + .CubicCurveTo({286.476, 108.431}, {285.506, 108.73}, {284.536, 109.035}) + .CubicCurveTo({283.674, 109.304}, {282.812, 109.579}, {281.952, 109.859}) + .CubicCurveTo({281.177, 110.112}, {280.406, 110.377}, {279.633, 110.638}) + .CubicCurveTo({278.458, 111.037}, {277.256, 111.449}, {276.803, 111.607}) + .CubicCurveTo({276.76, 111.622}, {276.716, 111.637}, {276.672, 111.653}) + .CubicCurveTo({275.017, 112.239}, {273.365, 112.836}, {271.721, 113.463}) + .LineTo({271.717, 113.449}) + .CubicCurveTo({271.496, 113.496}, {271.238, 113.559}, {270.963, 113.628}) + .CubicCurveTo({270.893, 113.645}, {270.822, 113.663}, {270.748, 113.682}) + .CubicCurveTo({270.468, 113.755}, {270.169, 113.834}, {269.839, 113.926}) + .CubicCurveTo({269.789, 113.94}, {269.732, 113.957}, {269.681, 113.972}) + .CubicCurveTo({269.391, 114.053}, {269.081, 114.143}, {268.756, 114.239}) + .CubicCurveTo({268.628, 114.276}, {268.5, 114.314}, {268.367, 114.354}) + .CubicCurveTo({268.172, 114.412}, {267.959, 114.478}, {267.752, 114.54}) + .CubicCurveTo({263.349, 115.964}, {258.058, 117.695}, {253.564, 119.252}) + .CubicCurveTo({253.556, 119.255}, {253.547, 119.258}, {253.538, 119.261}) + .CubicCurveTo({251.844, 119.849}, {250.056, 120.474}, {248.189, 121.131}) + .CubicCurveTo({248, 121.197}, {247.812, 121.264}, {247.621, 121.331}) + .CubicCurveTo({247.079, 121.522}, {246.531, 121.715}, {245.975, 121.912}) + .CubicCurveTo({245.554, 122.06}, {245.126, 122.212}, {244.698, 122.364}) + .CubicCurveTo({244.071, 122.586}, {243.437, 122.811}, {242.794, 123.04}) + .CubicCurveTo({242.189, 123.255}, {241.58, 123.472}, {240.961, 123.693}) + .CubicCurveTo({240.659, 123.801}, {240.357, 123.909}, {240.052, 124.018}) + .CubicCurveTo({239.12, 124.351}, {238.18, 124.687}, {237.22, 125.032}) + .LineTo({237.164, 125.003}) + .CubicCurveTo({236.709, 125.184}, {236.262, 125.358}, {235.81, 125.538}) + .CubicCurveTo({235.413, 125.68}, {234.994, 125.832}, {234.592, 125.977}) + .CubicCurveTo({234.592, 125.977}, {234.591, 125.977}, {234.59, 125.977}) + .CubicCurveTo({222.206, 130.435}, {207.708, 135.753}, {192.381, 141.429}) + .CubicCurveTo({162.77, 151.336}, {122.17, 156.894}, {84.1123, 160}) + .LineTo({360, 160}) + .LineTo({360, 119.256}) + .LineTo({360, 106.332}) + .LineTo({360, 96.6307}) + .CubicCurveTo({359.978, 96.6317}, {359.956, 96.6326}, {359.934, 96.6335}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({337.336, 124.143}) + .CubicCurveTo({337.274, 122.359}, {338.903, 121.511}, {338.903, 121.511}) + .CubicCurveTo({338.903, 121.511}, {338.96, 123.303}, {337.336, 124.143}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({340.082, 121.849}) + .CubicCurveTo({340.074, 121.917}, {340.062, 121.992}, {340.046, 122.075}) + .CubicCurveTo({340.039, 122.109}, {340.031, 122.142}, {340.023, 122.177}) + .CubicCurveTo({340.005, 122.26}, {339.98, 122.346}, {339.952, 122.437}) + .CubicCurveTo({339.941, 122.473}, {339.931, 122.507}, {339.918, 122.544}) + .CubicCurveTo({339.873, 122.672}, {339.819, 122.804}, {339.75, 122.938}) + .CubicCurveTo({339.747, 122.944}, {339.743, 122.949}, {339.74, 122.955}) + .CubicCurveTo({339.674, 123.08}, {339.593, 123.205}, {339.501, 123.328}) + .CubicCurveTo({339.473, 123.366}, {339.441, 123.401}, {339.41, 123.438}) + .CubicCurveTo({339.332, 123.534}, {339.243, 123.625}, {339.145, 123.714}) + .CubicCurveTo({339.105, 123.75}, {339.068, 123.786}, {339.025, 123.821}) + .CubicCurveTo({338.881, 123.937}, {338.724, 124.048}, {338.539, 124.143}) + .CubicCurveTo({338.532, 123.959}, {338.554, 123.79}, {338.58, 123.626}) + .CubicCurveTo({338.58, 123.625}, {338.58, 123.625}, {338.58, 123.625}) + .CubicCurveTo({338.607, 123.455}, {338.65, 123.299}, {338.704, 123.151}) + .CubicCurveTo({338.708, 123.14}, {338.71, 123.127}, {338.714, 123.117}) + .CubicCurveTo({338.769, 122.971}, {338.833, 122.838}, {338.905, 122.712}) + .CubicCurveTo({338.911, 122.702}, {338.916, 122.69200000000001}, + {338.922, 122.682}) + .CubicCurveTo({338.996, 122.557}, {339.072, 122.444}, {339.155, 122.34}) + .CubicCurveTo({339.161, 122.333}, {339.166, 122.326}, {339.172, 122.319}) + .CubicCurveTo({339.256, 122.215}, {339.339, 122.12}, {339.425, 122.037}) + .CubicCurveTo({339.428, 122.033}, {339.431, 122.03}, {339.435, 122.027}) + .CubicCurveTo({339.785, 121.687}, {340.106, 121.511}, {340.106, 121.511}) + .CubicCurveTo({340.106, 121.511}, {340.107, 121.645}, {340.082, 121.849}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({340.678, 113.245}) + .CubicCurveTo({340.594, 113.488}, {340.356, 113.655}, {340.135, 113.775}) + .CubicCurveTo({339.817, 113.948}, {339.465, 114.059}, {339.115, 114.151}) + .CubicCurveTo({338.251, 114.379}, {337.34, 114.516}, {336.448, 114.516}) + .CubicCurveTo({335.761, 114.516}, {335.072, 114.527}, {334.384, 114.513}) + .CubicCurveTo({334.125, 114.508}, {333.862, 114.462}, {333.605, 114.424}) + .CubicCurveTo({332.865, 114.318}, {332.096, 114.184}, {331.41, 113.883}) + .CubicCurveTo({330.979, 113.695}, {330.442, 113.34}, {330.672, 112.813}) + .CubicCurveTo({331.135, 111.755}, {333.219, 112.946}, {334.526, 113.833}) + .CubicCurveTo({334.54, 113.816}, {334.554, 113.8}, {334.569, 113.784}) + .CubicCurveTo({333.38, 112.708}, {331.749, 110.985}, {332.76, 110.402}) + .CubicCurveTo({333.769, 109.82}, {334.713, 111.93}, {335.228, 113.395}) + .CubicCurveTo({334.915, 111.889}, {334.59, 109.636}, {335.661, 109.592}) + .CubicCurveTo({336.733, 109.636}, {336.408, 111.889}, {336.07, 113.389}) + .CubicCurveTo({336.609, 111.93}, {337.553, 109.82}, {338.563, 110.402}) + .CubicCurveTo({339.574, 110.984}, {337.942, 112.708}, {336.753, 113.784}) + .CubicCurveTo({336.768, 113.8}, {336.782, 113.816}, {336.796, 113.833}) + .CubicCurveTo({338.104, 112.946}, {340.187, 111.755}, {340.65, 112.813}) + .CubicCurveTo({340.71, 112.95}, {340.728, 113.102}, {340.678, 113.245}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({346.357, 106.771}) + .CubicCurveTo({346.295, 104.987}, {347.924, 104.139}, {347.924, 104.139}) + .CubicCurveTo({347.924, 104.139}, {347.982, 105.931}, {346.357, 106.771}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({347.56, 106.771}) + .CubicCurveTo({347.498, 104.987}, {349.127, 104.139}, {349.127, 104.139}) + .CubicCurveTo({349.127, 104.139}, {349.185, 105.931}, {347.56, 106.771}); + if (closed) { + builder.Close(); + } + return builder.TakePath(); +} + +Path CreateQuadratic(bool closed) { + auto builder = PathBuilder{}; + builder // + .MoveTo({359.934, 96.6335}) + .QuadraticCurveTo({358.189, 96.7055}, {354.673, 96.8895}) + .QuadraticCurveTo({354.571, 96.8953}, {354.367, 96.9075}) + .QuadraticCurveTo({352.672, 97.0038}, {349.259, 97.2355}) + .QuadraticCurveTo({349.048, 97.2506}, {348.625, 97.2834}) + .QuadraticCurveTo({347.019, 97.4014}, {343.789, 97.6722}) + .QuadraticCurveTo({343.428, 97.704}, {342.703, 97.7734}) + .QuadraticCurveTo({341.221, 97.9086}, {338.246, 98.207}) + .QuadraticCurveTo({337.702, 98.2642}, {336.612, 98.3894}) + .QuadraticCurveTo({335.284, 98.5356}, {332.623, 98.8476}) + .QuadraticCurveTo({332.495, 98.8635}, {332.237, 98.8982}) + .LineTo({332.237, 102.601}) + .LineTo({321.778, 102.601}) + .LineTo({321.778, 100.382}) + .QuadraticCurveTo({321.572, 100.413}, {321.161, 100.476}) + .QuadraticCurveTo({319.22, 100.79}, {315.332, 101.479}) + .QuadraticCurveTo({315.322, 101.481}, {315.301, 101.484}) + .LineTo({310.017, 105.94}) + .LineTo({309.779, 105.427}) + .LineTo({314.403, 101.651}) + .QuadraticCurveTo({314.391, 101.653}, {314.368, 101.658}) + .QuadraticCurveTo({312.528, 102.001}, {308.846, 102.748}) + .QuadraticCurveTo({307.85, 102.955}, {305.859, 103.4}) + .QuadraticCurveTo({305.048, 103.579}, {303.425, 103.936}) + .LineTo({299.105, 107.578}) + .LineTo({298.867, 107.065}) + .LineTo({302.394, 104.185}) + .LineTo({302.412, 104.171}) + .QuadraticCurveTo({301.388, 104.409}, {299.344, 104.921}) + .QuadraticCurveTo({298.618, 105.1}, {297.165, 105.455}) + .QuadraticCurveTo({295.262, 105.94}, {291.462, 106.979}) + .QuadraticCurveTo({291.132, 107.072}, {290.471, 107.257}) + .QuadraticCurveTo({289.463, 107.544}, {287.449, 108.139}) + .QuadraticCurveTo({286.476, 108.431}, {284.536, 109.035}) + .QuadraticCurveTo({283.674, 109.304}, {281.952, 109.859}) + .QuadraticCurveTo({281.177, 110.112}, {279.633, 110.638}) + .QuadraticCurveTo({278.458, 111.037}, {276.803, 111.607}) + .QuadraticCurveTo({276.76, 111.622}, {276.672, 111.653}) + .QuadraticCurveTo({275.017, 112.239}, {271.721, 113.463}) + .LineTo({271.717, 113.449}) + .QuadraticCurveTo({271.496, 113.496}, {270.963, 113.628}) + .QuadraticCurveTo({270.893, 113.645}, {270.748, 113.682}) + .QuadraticCurveTo({270.468, 113.755}, {269.839, 113.926}) + .QuadraticCurveTo({269.789, 113.94}, {269.681, 113.972}) + .QuadraticCurveTo({269.391, 114.053}, {268.756, 114.239}) + .QuadraticCurveTo({268.628, 114.276}, {268.367, 114.354}) + .QuadraticCurveTo({268.172, 114.412}, {267.752, 114.54}) + .QuadraticCurveTo({263.349, 115.964}, {253.564, 119.252}) + .QuadraticCurveTo({253.556, 119.255}, {253.538, 119.261}) + .QuadraticCurveTo({251.844, 119.849}, {248.189, 121.131}) + .QuadraticCurveTo({248, 121.197}, {247.621, 121.331}) + .QuadraticCurveTo({247.079, 121.522}, {245.975, 121.912}) + .QuadraticCurveTo({245.554, 122.06}, {244.698, 122.364}) + .QuadraticCurveTo({244.071, 122.586}, {242.794, 123.04}) + .QuadraticCurveTo({242.189, 123.255}, {240.961, 123.693}) + .QuadraticCurveTo({240.659, 123.801}, {240.052, 124.018}) + .QuadraticCurveTo({239.12, 124.351}, {237.22, 125.032}) + .LineTo({237.164, 125.003}) + .QuadraticCurveTo({236.709, 125.184}, {235.81, 125.538}) + .QuadraticCurveTo({235.413, 125.68}, {234.592, 125.977}) + .QuadraticCurveTo({234.592, 125.977}, {234.59, 125.977}) + .QuadraticCurveTo({222.206, 130.435}, {192.381, 141.429}) + .QuadraticCurveTo({162.77, 151.336}, {84.1123, 160}) + .LineTo({360, 160}) + .LineTo({360, 119.256}) + .LineTo({360, 106.332}) + .LineTo({360, 96.6307}) + .QuadraticCurveTo({359.978, 96.6317}, {359.934, 96.6335}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({337.336, 124.143}) + .QuadraticCurveTo({337.274, 122.359}, {338.903, 121.511}) + .QuadraticCurveTo({338.903, 121.511}, {337.336, 124.143}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({340.082, 121.849}) + .QuadraticCurveTo({340.074, 121.917}, {340.046, 122.075}) + .QuadraticCurveTo({340.039, 122.109}, {340.023, 122.177}) + .QuadraticCurveTo({340.005, 122.26}, {339.952, 122.437}) + .QuadraticCurveTo({339.941, 122.473}, {339.918, 122.544}) + .QuadraticCurveTo({339.873, 122.672}, {339.75, 122.938}) + .QuadraticCurveTo({339.747, 122.944}, {339.74, 122.955}) + .QuadraticCurveTo({339.674, 123.08}, {339.501, 123.328}) + .QuadraticCurveTo({339.473, 123.366}, {339.41, 123.438}) + .QuadraticCurveTo({339.332, 123.534}, {339.145, 123.714}) + .QuadraticCurveTo({339.105, 123.75}, {339.025, 123.821}) + .QuadraticCurveTo({338.881, 123.937}, {338.539, 124.143}) + .QuadraticCurveTo({338.532, 123.959}, {338.58, 123.626}) + .QuadraticCurveTo({338.58, 123.625}, {338.58, 123.625}) + .QuadraticCurveTo({338.607, 123.455}, {338.704, 123.151}) + .QuadraticCurveTo({338.708, 123.14}, {338.714, 123.117}) + .QuadraticCurveTo({338.769, 122.971}, {338.905, 122.712}) + .QuadraticCurveTo({338.911, 122.702}, {338.922, 122.682}) + .QuadraticCurveTo({338.996, 122.557}, {339.155, 122.34}) + .QuadraticCurveTo({339.161, 122.333}, {339.172, 122.319}) + .QuadraticCurveTo({339.256, 122.215}, {339.425, 122.037}) + .QuadraticCurveTo({339.428, 122.033}, {339.435, 122.027}) + .QuadraticCurveTo({339.785, 121.687}, {340.106, 121.511}) + .QuadraticCurveTo({340.106, 121.511}, {340.082, 121.849}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({340.678, 113.245}) + .QuadraticCurveTo({340.594, 113.488}, {340.135, 113.775}) + .QuadraticCurveTo({339.817, 113.948}, {339.115, 114.151}) + .QuadraticCurveTo({338.251, 114.379}, {336.448, 114.516}) + .QuadraticCurveTo({335.761, 114.516}, {334.384, 114.513}) + .QuadraticCurveTo({334.125, 114.508}, {333.605, 114.424}) + .QuadraticCurveTo({332.865, 114.318}, {331.41, 113.883}) + .QuadraticCurveTo({330.979, 113.695}, {330.672, 112.813}) + .QuadraticCurveTo({331.135, 111.755}, {334.526, 113.833}) + .QuadraticCurveTo({334.54, 113.816}, {334.569, 113.784}) + .QuadraticCurveTo({333.38, 112.708}, {332.76, 110.402}) + .QuadraticCurveTo({333.769, 109.82}, {335.228, 113.395}) + .QuadraticCurveTo({334.915, 111.889}, {335.661, 109.592}) + .QuadraticCurveTo({336.733, 109.636}, {336.07, 113.389}) + .QuadraticCurveTo({336.609, 111.93}, {338.563, 110.402}) + .QuadraticCurveTo({339.574, 110.984}, {336.753, 113.784}) + .QuadraticCurveTo({336.768, 113.8}, {336.796, 113.833}) + .QuadraticCurveTo({338.104, 112.946}, {340.65, 112.813}) + .QuadraticCurveTo({340.71, 112.95}, {340.678, 113.245}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({346.357, 106.771}) + .QuadraticCurveTo({346.295, 104.987}, {347.924, 104.139}) + .QuadraticCurveTo({347.924, 104.139}, {346.357, 106.771}); + if (closed) { + builder.Close(); + } + builder // + .MoveTo({347.56, 106.771}) + .QuadraticCurveTo({347.498, 104.987}, {349.127, 104.139}) + .QuadraticCurveTo({349.127, 104.139}, {347.56, 106.771}); + if (closed) { + builder.Close(); + } + return builder.TakePath(); +} + +} // namespace +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/geometry_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/geometry_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e85fb6c6fc202f6fb7109405d6a55fcb65351b7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/geometry_unittests.cc @@ -0,0 +1,1931 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" +#include "impeller/geometry/geometry_asserts.h" + +#include +#include +#include +#include + +#include "flutter/fml/build_config.h" +#include "flutter/testing/testing.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/constants.h" +#include "impeller/geometry/gradient.h" +#include "impeller/geometry/half.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/separated_vector.h" +#include "impeller/geometry/size.h" + +// TODO(zanderso): https://github.com/flutter/flutter/issues/127701 +// NOLINTBEGIN(bugprone-unchecked-optional-access) + +namespace impeller { +namespace testing { + +TEST(GeometryTest, ScalarNearlyEqual) { + ASSERT_FALSE(ScalarNearlyEqual(0.0021f, 0.001f)); + ASSERT_TRUE(ScalarNearlyEqual(0.0019f, 0.001f)); + ASSERT_TRUE(ScalarNearlyEqual(0.002f, 0.001f, 0.0011f)); + ASSERT_FALSE(ScalarNearlyEqual(0.002f, 0.001f, 0.0009f)); + ASSERT_TRUE(ScalarNearlyEqual( + 1.0f, 1.0f + std::numeric_limits::epsilon() * 4)); +} + +TEST(GeometryTest, MakeColumn) { + auto matrix = Matrix::MakeColumn(1, 2, 3, 4, // + 5, 6, 7, 8, // + 9, 10, 11, 12, // + 13, 14, 15, 16); + + auto expect = Matrix{1, 2, 3, 4, // + 5, 6, 7, 8, // + 9, 10, 11, 12, // + 13, 14, 15, 16}; + + ASSERT_TRUE(matrix == expect); +} + +TEST(GeometryTest, MakeRow) { + auto matrix = Matrix::MakeRow(1, 2, 3, 4, // + 5, 6, 7, 8, // + 9, 10, 11, 12, // + 13, 14, 15, 16); + + auto expect = Matrix{1, 5, 9, 13, // + 2, 6, 10, 14, // + 3, 7, 11, 15, // + 4, 8, 12, 16}; + + ASSERT_TRUE(matrix == expect); +} + +TEST(GeometryTest, RotationMatrix) { + auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4}); + // clang-format off + auto expect = Matrix{k1OverSqrt2, k1OverSqrt2, 0, 0, + -k1OverSqrt2, k1OverSqrt2, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1}; + // clang-format on + ASSERT_MATRIX_NEAR(rotation, expect); +} + +TEST(GeometryTest, InvertMultMatrix) { + { + auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4}); + auto invert = rotation.Invert(); + // clang-format off + auto expect = Matrix{k1OverSqrt2, -k1OverSqrt2, 0, 0, + k1OverSqrt2, k1OverSqrt2, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1}; + // clang-format on + ASSERT_MATRIX_NEAR(invert, expect); + } + { + auto scale = Matrix::MakeScale(Vector2{2, 4}); + auto invert = scale.Invert(); + auto expect = Matrix{0.5, 0, 0, 0, // + 0, 0.25, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 0, 1}; + ASSERT_MATRIX_NEAR(invert, expect); + } +} + +TEST(GeometryTest, MatrixBasis) { + auto matrix = Matrix{1, 2, 3, 4, // + 5, 6, 7, 8, // + 9, 10, 11, 12, // + 13, 14, 15, 16}; + auto basis = matrix.Basis(); + auto expect = Matrix{1, 2, 3, 0, // + 5, 6, 7, 0, // + 9, 10, 11, 0, // + 0, 0, 0, 1}; + ASSERT_MATRIX_NEAR(basis, expect); +} + +TEST(GeometryTest, MutliplicationMatrix) { + auto rotation = Matrix::MakeRotationZ(Radians{kPiOver4}); + auto invert = rotation.Invert(); + ASSERT_MATRIX_NEAR(rotation * invert, Matrix{}); +} + +TEST(GeometryTest, DeterminantTest) { + auto matrix = Matrix{3, 4, 14, 155, 2, 1, 3, 4, 2, 3, 2, 1, 1, 2, 4, 2}; + ASSERT_EQ(matrix.GetDeterminant(), -1889); +} + +TEST(GeometryTest, InvertMatrix) { + auto inverted = Matrix{10, -9, -12, 8, // + 7, -12, 11, 22, // + -10, 10, 3, 6, // + -2, 22, 2, 1} + .Invert(); + + auto result = Matrix{ + 438.0 / 85123.0, 1751.0 / 85123.0, -7783.0 / 85123.0, 4672.0 / 85123.0, + 393.0 / 85123.0, -178.0 / 85123.0, -570.0 / 85123.0, 4192 / 85123.0, + -5230.0 / 85123.0, 2802.0 / 85123.0, -3461.0 / 85123.0, 962.0 / 85123.0, + 2690.0 / 85123.0, 1814.0 / 85123.0, 3896.0 / 85123.0, 319.0 / 85123.0}; + + ASSERT_MATRIX_NEAR(inverted, result); +} + +TEST(GeometryTest, TestDecomposition) { + auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4}); + + auto result = rotated.Decompose(); + + ASSERT_TRUE(result.has_value()); + + MatrixDecomposition res = result.value(); + + auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4}; + ASSERT_QUATERNION_NEAR(res.rotation, quaternion); +} + +TEST(GeometryTest, TestDecomposition2) { + auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4}); + auto scaled = Matrix::MakeScale({2.0, 3.0, 1.0}); + auto translated = Matrix::MakeTranslation({-200, 750, 20}); + + auto result = (translated * rotated * scaled).Decompose(); + + ASSERT_TRUE(result.has_value()); + + MatrixDecomposition res = result.value(); + + auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4}; + + ASSERT_QUATERNION_NEAR(res.rotation, quaternion); + + ASSERT_FLOAT_EQ(res.translation.x, -200); + ASSERT_FLOAT_EQ(res.translation.y, 750); + ASSERT_FLOAT_EQ(res.translation.z, 20); + + ASSERT_FLOAT_EQ(res.scale.x, 2); + ASSERT_FLOAT_EQ(res.scale.y, 3); + ASSERT_FLOAT_EQ(res.scale.z, 1); +} + +TEST(GeometryTest, TestRecomposition) { + /* + * Decomposition. + */ + auto rotated = Matrix::MakeRotationZ(Radians{kPiOver4}); + + auto result = rotated.Decompose(); + + ASSERT_TRUE(result.has_value()); + + MatrixDecomposition res = result.value(); + + auto quaternion = Quaternion{{0.0, 0.0, 1.0}, kPiOver4}; + + ASSERT_QUATERNION_NEAR(res.rotation, quaternion); + + /* + * Recomposition. + */ + ASSERT_MATRIX_NEAR(rotated, Matrix{res}); +} + +TEST(GeometryTest, TestRecomposition2) { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver4}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + + auto result = matrix.Decompose(); + + ASSERT_TRUE(result.has_value()); + + ASSERT_MATRIX_NEAR(matrix, Matrix{result.value()}); +} + +TEST(GeometryTest, MatrixVectorMultiplication) { + { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Vector4(10, 20, 30, 2); + + Vector4 result = matrix * vector; + auto expected = Vector4(160, 220, 260, 2); + ASSERT_VECTOR4_NEAR(result, expected); + } + + { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Vector3(10, 20, 30); + + Vector3 result = matrix * vector; + auto expected = Vector3(60, 120, 160); + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Point(10, 20); + + Point result = matrix * vector; + auto expected = Point(60, 120); + ASSERT_POINT_NEAR(result, expected); + } + + // Matrix Vector ops should respect perspective transforms. + { + auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100); + auto vector = Vector3(3, 3, -3); + + Vector3 result = matrix * vector; + auto expected = Vector3(-1, -1, 1.3468); + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100) * + Matrix::MakeTranslation(Vector3(0, 0, -3)); + auto point = Point(3, 3); + + Point result = matrix * point; + auto expected = Point(-1, -1); + ASSERT_POINT_NEAR(result, expected); + } + + // Resolves to 0 on perspective singularity. + { + auto matrix = Matrix::MakePerspective(Radians(kPiOver2), 1, 1, 100); + auto point = Point(3, 3); + + Point result = matrix * point; + auto expected = Point(0, 0); + ASSERT_POINT_NEAR(result, expected); + } +} + +TEST(GeometryTest, MatrixMakeRotationFromQuaternion) { + { + auto matrix = Matrix::MakeRotation(Quaternion({1, 0, 0}, kPiOver2)); + auto expected = Matrix::MakeRotationX(Radians(kPiOver2)); + ASSERT_MATRIX_NEAR(matrix, expected); + } + + { + auto matrix = Matrix::MakeRotation(Quaternion({0, 1, 0}, kPiOver2)); + auto expected = Matrix::MakeRotationY(Radians(kPiOver2)); + ASSERT_MATRIX_NEAR(matrix, expected); + } + + { + auto matrix = Matrix::MakeRotation(Quaternion({0, 0, 1}, kPiOver2)); + auto expected = Matrix::MakeRotationZ(Radians(kPiOver2)); + ASSERT_MATRIX_NEAR(matrix, expected); + } +} + +TEST(GeometryTest, MatrixTransformDirection) { + { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Vector4(10, 20, 30, 2); + + Vector4 result = matrix.TransformDirection(vector); + auto expected = Vector4(-40, 20, 60, 2); + ASSERT_VECTOR4_NEAR(result, expected); + } + + { + auto matrix = Matrix::MakeTranslation({100, 100, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Vector3(10, 20, 30); + + Vector3 result = matrix.TransformDirection(vector); + auto expected = Vector3(-40, 20, 60); + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + auto matrix = Matrix::MakeTranslation({0, -0.4, 100}) * + Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale({2.0, 2.0, 2.0}); + auto vector = Point(10, 20); + + Point result = matrix.TransformDirection(vector); + auto expected = Point(-40, 20); + ASSERT_POINT_NEAR(result, expected); + } +} + +TEST(GeometryTest, MatrixGetMaxBasisLengthXY) { + { + auto m = Matrix::MakeScale({3, 1, 1}); + ASSERT_EQ(m.GetMaxBasisLengthXY(), 3); + + m = m * Matrix::MakeSkew(0, 4); + ASSERT_EQ(m.GetMaxBasisLengthXY(), 5); + } + + { + auto m = Matrix::MakeScale({-3, 4, 7}); + ASSERT_EQ(m.GetMaxBasisLengthXY(), 4); + } + + { + // clang-format off + auto m = Matrix::MakeColumn( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 4.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + // clang-format on + ASSERT_EQ(m.GetMaxBasisLengthXY(), 1.0f); + } +} + +TEST(GeometryTest, MatrixMakeOrthographic) { + { + auto m = Matrix::MakeOrthographic(Size(100, 200)); + auto expect = Matrix{ + 0.02, 0, 0, 0, // + 0, -0.01, 0, 0, // + 0, 0, 0, 0, // + -1, 1, 0.5, 1, // + }; + ASSERT_MATRIX_NEAR(m, expect); + } + + { + auto m = Matrix::MakeOrthographic(Size(400, 100)); + auto expect = Matrix{ + 0.005, 0, 0, 0, // + 0, -0.02, 0, 0, // + 0, 0, 0, 0, // + -1, 1, 0.5, 1, // + }; + ASSERT_MATRIX_NEAR(m, expect); + } +} + +TEST(GeometryTest, MatrixMakePerspective) { + { + auto m = Matrix::MakePerspective(Degrees(60), Size(100, 200), 1, 10); + auto expect = Matrix{ + 3.4641, 0, 0, 0, // + 0, 1.73205, 0, 0, // + 0, 0, 1.11111, 1, // + 0, 0, -1.11111, 0, // + }; + ASSERT_MATRIX_NEAR(m, expect); + } + + { + auto m = Matrix::MakePerspective(Radians(1), 2, 10, 20); + auto expect = Matrix{ + 0.915244, 0, 0, 0, // + 0, 1.83049, 0, 0, // + 0, 0, 2, 1, // + 0, 0, -20, 0, // + }; + ASSERT_MATRIX_NEAR(m, expect); + } +} + +TEST(GeometryTest, MatrixGetBasisVectors) { + { + auto m = Matrix(); + Vector3 x = m.GetBasisX(); + Vector3 y = m.GetBasisY(); + Vector3 z = m.GetBasisZ(); + ASSERT_VECTOR3_NEAR(x, Vector3(1, 0, 0)); + ASSERT_VECTOR3_NEAR(y, Vector3(0, 1, 0)); + ASSERT_VECTOR3_NEAR(z, Vector3(0, 0, 1)); + } + + { + auto m = Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeRotationX(Radians{kPiOver2}) * + Matrix::MakeScale(Vector3(2, 3, 4)); + Vector3 x = m.GetBasisX(); + Vector3 y = m.GetBasisY(); + Vector3 z = m.GetBasisZ(); + ASSERT_VECTOR3_NEAR(x, Vector3(0, 2, 0)); + ASSERT_VECTOR3_NEAR(y, Vector3(0, 0, 3)); + ASSERT_VECTOR3_NEAR(z, Vector3(4, 0, 0)); + } +} + +TEST(GeometryTest, MatrixGetDirectionScale) { + { + auto m = Matrix(); + Scalar result = m.GetDirectionScale(Vector3{1, 0, 0}); + ASSERT_FLOAT_EQ(result, 1); + } + + { + auto m = Matrix::MakeRotationX(Degrees{10}) * + Matrix::MakeRotationY(Degrees{83}) * + Matrix::MakeRotationZ(Degrees{172}); + Scalar result = m.GetDirectionScale(Vector3{0, 1, 0}); + ASSERT_FLOAT_EQ(result, 1); + } + + { + auto m = Matrix::MakeRotationZ(Radians{kPiOver2}) * + Matrix::MakeScale(Vector3(3, 4, 5)); + Scalar result = m.GetDirectionScale(Vector3{2, 0, 0}); + ASSERT_FLOAT_EQ(result, 8); + } +} + +TEST(GeometryTest, MatrixTranslationScaleOnly) { + { + auto m = Matrix(); + bool result = m.IsTranslationScaleOnly(); + ASSERT_TRUE(result); + } + + { + auto m = Matrix::MakeScale(Vector3(2, 3, 4)); + bool result = m.IsTranslationScaleOnly(); + ASSERT_TRUE(result); + } + + { + auto m = Matrix::MakeTranslation(Vector3(2, 3, 4)); + bool result = m.IsTranslationScaleOnly(); + ASSERT_TRUE(result); + } + + { + auto m = Matrix::MakeRotationZ(Degrees(10)); + bool result = m.IsTranslationScaleOnly(); + ASSERT_FALSE(result); + } +} + +TEST(GeometryTest, MatrixLookAt) { + { + auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1), + Vector3(0, 1, 0)); + auto expected = Matrix{ + 1, 0, 0, 0, // + 0, 1, 0, 0, // + 0, 0, 1, 0, // + 0, 0, 1, 1, // + }; + ASSERT_MATRIX_NEAR(m, expected); + } + + // Sideways tilt. + { + auto m = Matrix::MakeLookAt(Vector3(0, 0, -1), Vector3(0, 0, 1), + Vector3(1, 1, 0).Normalize()); + + // clang-format off + auto expected = Matrix{ + k1OverSqrt2, k1OverSqrt2, 0, 0, + -k1OverSqrt2, k1OverSqrt2, 0, 0, + 0, 0, 1, 0, + 0, 0, 1, 1, + }; + // clang-format on + ASSERT_MATRIX_NEAR(m, expected); + } + + // Half way between +x and -y, yaw 90 + { + auto m = + Matrix::MakeLookAt(Vector3(), Vector3(10, -10, 0), Vector3(0, 0, -1)); + + // clang-format off + auto expected = Matrix{ + -k1OverSqrt2, 0, k1OverSqrt2, 0, + -k1OverSqrt2, 0, -k1OverSqrt2, 0, + 0, -1, 0, 0, + 0, 0, 0, 1, + }; + // clang-format on + ASSERT_MATRIX_NEAR(m, expected); + } +} + +TEST(GeometryTest, QuaternionLerp) { + auto q1 = Quaternion{{0.0, 0.0, 1.0}, 0.0}; + auto q2 = Quaternion{{0.0, 0.0, 1.0}, kPiOver4}; + + auto q3 = q1.Slerp(q2, 0.5); + + auto expected = Quaternion{{0.0, 0.0, 1.0}, kPiOver4 / 2.0}; + + ASSERT_QUATERNION_NEAR(q3, expected); +} + +TEST(GeometryTest, QuaternionVectorMultiply) { + { + Quaternion q({0, 0, 1}, 0); + Vector3 v(0, 1, 0); + + Vector3 result = q * v; + Vector3 expected(0, 1, 0); + + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + Quaternion q({0, 0, 1}, k2Pi); + Vector3 v(1, 0, 0); + + Vector3 result = q * v; + Vector3 expected(1, 0, 0); + + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + Quaternion q({0, 0, 1}, kPiOver4); + Vector3 v(0, 1, 0); + + Vector3 result = q * v; + Vector3 expected(-k1OverSqrt2, k1OverSqrt2, 0); + + ASSERT_VECTOR3_NEAR(result, expected); + } + + { + Quaternion q(Vector3(1, 0, 1).Normalize(), kPi); + Vector3 v(0, 0, -1); + + Vector3 result = q * v; + Vector3 expected(-1, 0, 0); + + ASSERT_VECTOR3_NEAR(result, expected); + } +} + +TEST(GeometryTest, CanGenerateMipCounts) { + EXPECT_EQ((Size{128, 128}.MipCount()), 7u); + EXPECT_EQ((Size{128, 256}.MipCount()), 7u); + EXPECT_EQ((Size{128, 130}.MipCount()), 7u); + EXPECT_EQ((Size{128, 257}.MipCount()), 7u); + EXPECT_EQ((Size{257, 128}.MipCount()), 7u); + EXPECT_EQ((Size{128, 0}.MipCount()), 1u); + EXPECT_EQ((Size{128, -25}.MipCount()), 1u); + EXPECT_EQ((Size{-128, 25}.MipCount()), 1u); + EXPECT_EQ((Size{1, 1}.MipCount()), 1u); + EXPECT_EQ((Size{0, 0}.MipCount()), 1u); +} + +TEST(GeometryTest, CanConvertTTypesExplicitly) { + { + Point p1(1.0, 2.0); + IPoint p2 = static_cast(p1); + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 2u); + } + + { + Size s1(1.0, 2.0); + ISize s2 = static_cast(s1); + ASSERT_EQ(s2.width, 1u); + ASSERT_EQ(s2.height, 2u); + } + + { + Size s1(1.0, 2.0); + Point p1 = static_cast(s1); + ASSERT_EQ(p1.x, 1u); + ASSERT_EQ(p1.y, 2u); + } +} + +TEST(GeometryTest, CanPerformAlgebraicPointOps) { + { + IPoint p1(1, 2); + IPoint p2 = p1 + IPoint(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(3, 6); + IPoint p2 = p1 - IPoint(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(1, 2); + IPoint p2 = p1 * IPoint(2, 3); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 6u); + } + + { + IPoint p1(2, 6); + IPoint p2 = p1 / IPoint(2, 3); + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 2u); + } +} + +TEST(GeometryTest, CanPerformAlgebraicPointOpsWithArithmeticTypes) { + // LHS + { + IPoint p1(1, 2); + IPoint p2 = p1 * 2.0f; + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(2, 6); + IPoint p2 = p1 / 2.0f; + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 3u); + } + + // RHS + { + IPoint p1(1, 2); + IPoint p2 = 2.0f * p1; + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(2, 6); + IPoint p2 = 12.0f / p1; + ASSERT_EQ(p2.x, 6u); + ASSERT_EQ(p2.y, 2u); + } +} + +TEST(GeometryTest, PointIntegerCoercesToFloat) { + // Integer on LHS, float on RHS + { + IPoint p1(1, 2); + Point p2 = p1 + Point(1, 2); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 4u); + } + + { + IPoint p1(3, 6); + Point p2 = p1 - Point(1, 2); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 4u); + } + + { + IPoint p1(1, 2); + Point p2 = p1 * Point(2, 3); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 6u); + } + + { + IPoint p1(2, 6); + Point p2 = p1 / Point(2, 3); + ASSERT_FLOAT_EQ(p2.x, 1u); + ASSERT_FLOAT_EQ(p2.y, 2u); + } + + // Float on LHS, integer on RHS + { + Point p1(1, 2); + Point p2 = p1 + IPoint(1, 2); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 4u); + } + + { + Point p1(3, 6); + Point p2 = p1 - IPoint(1, 2); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 4u); + } + + { + Point p1(1, 2); + Point p2 = p1 * IPoint(2, 3); + ASSERT_FLOAT_EQ(p2.x, 2u); + ASSERT_FLOAT_EQ(p2.y, 6u); + } + + { + Point p1(2, 6); + Point p2 = p1 / IPoint(2, 3); + ASSERT_FLOAT_EQ(p2.x, 1u); + ASSERT_FLOAT_EQ(p2.y, 2u); + } +} + +TEST(GeometryTest, SizeCoercesToPoint) { + // Point on LHS, Size on RHS + { + IPoint p1(1, 2); + IPoint p2 = p1 + ISize(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(3, 6); + IPoint p2 = p1 - ISize(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + IPoint p1(1, 2); + IPoint p2 = p1 * ISize(2, 3); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 6u); + } + + { + IPoint p1(2, 6); + IPoint p2 = p1 / ISize(2, 3); + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 2u); + } + + // Size on LHS, Point on RHS + { + ISize p1(1, 2); + IPoint p2 = p1 + IPoint(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + ISize p1(3, 6); + IPoint p2 = p1 - IPoint(1, 2); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + } + + { + ISize p1(1, 2); + IPoint p2 = p1 * IPoint(2, 3); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 6u); + } + + { + ISize p1(2, 6); + IPoint p2 = p1 / IPoint(2, 3); + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 2u); + } +} + +TEST(GeometryTest, CanUsePointAssignmentOperators) { + // Point on RHS + { + IPoint p(1, 2); + p += IPoint(1, 2); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + } + + { + IPoint p(3, 6); + p -= IPoint(1, 2); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + } + + { + IPoint p(1, 2); + p *= IPoint(2, 3); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 6u); + } + + { + IPoint p(2, 6); + p /= IPoint(2, 3); + ASSERT_EQ(p.x, 1u); + ASSERT_EQ(p.y, 2u); + } + + // Size on RHS + { + IPoint p(1, 2); + p += ISize(1, 2); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + } + + { + IPoint p(3, 6); + p -= ISize(1, 2); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + } + + { + IPoint p(1, 2); + p *= ISize(2, 3); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 6u); + } + + { + IPoint p(2, 6); + p /= ISize(2, 3); + ASSERT_EQ(p.x, 1u); + ASSERT_EQ(p.y, 2u); + } + + // Arithmetic type on RHS + { + IPoint p(1, 2); + p *= 3; + ASSERT_EQ(p.x, 3u); + ASSERT_EQ(p.y, 6u); + } + + { + IPoint p(3, 6); + p /= 3; + ASSERT_EQ(p.x, 1u); + ASSERT_EQ(p.y, 2u); + } +} + +TEST(GeometryTest, PointDotProduct) { + { + Point p(1, 0); + Scalar s = p.Dot(Point(-1, 0)); + ASSERT_FLOAT_EQ(s, -1); + } + + { + Point p(0, -1); + Scalar s = p.Dot(Point(-1, 0)); + ASSERT_FLOAT_EQ(s, 0); + } + + { + Point p(1, 2); + Scalar s = p.Dot(Point(3, -4)); + ASSERT_FLOAT_EQ(s, -5); + } +} + +TEST(GeometryTest, PointCrossProduct) { + { + Point p(1, 0); + Scalar s = p.Cross(Point(-1, 0)); + ASSERT_FLOAT_EQ(s, 0); + } + + { + Point p(0, -1); + Scalar s = p.Cross(Point(-1, 0)); + ASSERT_FLOAT_EQ(s, -1); + } + + { + Point p(1, 2); + Scalar s = p.Cross(Point(3, -4)); + ASSERT_FLOAT_EQ(s, -10); + } +} + +TEST(GeometryTest, PointReflect) { + { + Point axis = Point(0, 1); + Point a(2, 3); + auto reflected = a.Reflect(axis); + auto expected = Point(2, -3); + ASSERT_POINT_NEAR(reflected, expected); + } + + { + Point axis = Point(1, 1).Normalize(); + Point a(1, 0); + auto reflected = a.Reflect(axis); + auto expected = Point(0, -1); + ASSERT_POINT_NEAR(reflected, expected); + } + + { + Point axis = Point(1, 1).Normalize(); + Point a(-1, -1); + auto reflected = a.Reflect(axis); + ASSERT_POINT_NEAR(reflected, -a); + } +} + +TEST(GeometryTest, PointAbs) { + Point a(-1, -2); + auto a_abs = a.Abs(); + auto expected = Point(1, 2); + ASSERT_POINT_NEAR(a_abs, expected); +} + +TEST(GeometryTest, PointRotate) { + { + Point a(1, 0); + auto rotated = a.Rotate(Radians{kPiOver2}); + auto expected = Point(0, 1); + ASSERT_POINT_NEAR(rotated, expected); + } + + { + Point a(1, 0); + auto rotated = a.Rotate(Radians{-kPiOver2}); + auto expected = Point(0, -1); + ASSERT_POINT_NEAR(rotated, expected); + } + + { + Point a(1, 0); + auto rotated = a.Rotate(Radians{kPi}); + auto expected = Point(-1, 0); + ASSERT_POINT_NEAR(rotated, expected); + } + + { + Point a(1, 0); + auto rotated = a.Rotate(Radians{kPi * 1.5}); + auto expected = Point(0, -1); + ASSERT_POINT_NEAR(rotated, expected); + } +} + +TEST(GeometryTest, PointAngleTo) { + // Negative result in the CCW (with up = -Y) direction. + { + Point a(1, 1); + Point b(1, -1); + Radians actual = a.AngleTo(b); + Radians expected = Radians{-kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } + + // Check the other direction to ensure the result is signed correctly. + { + Point a(1, -1); + Point b(1, 1); + Radians actual = a.AngleTo(b); + Radians expected = Radians{kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } + + // Differences in magnitude should have no impact on the result. + { + Point a(100, -100); + Point b(0.01, 0.01); + Radians actual = a.AngleTo(b); + Radians expected = Radians{kPi / 2}; + ASSERT_FLOAT_EQ(actual.radians, expected.radians); + } +} + +TEST(GeometryTest, PointMin) { + Point p(1, 2); + Point result = p.Min({0, 10}); + Point expected(0, 2); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4IsFinite) { + { + Vector4 v; + ASSERT_TRUE(v.IsFinite()); + v.x = std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.x = -std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.x = -std::numeric_limits::quiet_NaN(); + ASSERT_FALSE(v.IsFinite()); + } + + { + Vector4 v; + ASSERT_TRUE(v.IsFinite()); + v.y = std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.y = -std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.y = -std::numeric_limits::quiet_NaN(); + ASSERT_FALSE(v.IsFinite()); + } + + { + Vector4 v; + ASSERT_TRUE(v.IsFinite()); + v.z = std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.z = -std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.z = -std::numeric_limits::quiet_NaN(); + ASSERT_FALSE(v.IsFinite()); + } + + { + Vector4 v; + ASSERT_TRUE(v.IsFinite()); + v.w = std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.w = -std::numeric_limits::infinity(); + ASSERT_FALSE(v.IsFinite()); + v.w = -std::numeric_limits::quiet_NaN(); + ASSERT_FALSE(v.IsFinite()); + } +} + +TEST(GeometryTest, Vector3Min) { + Vector3 p(1, 2, 3); + Vector3 result = p.Min({0, 10, 2}); + Vector3 expected(0, 2, 2); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Min) { + Vector4 p(1, 2, 3, 4); + Vector4 result = p.Min({0, 10, 2, 1}); + Vector4 expected(0, 2, 2, 1); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, PointMax) { + Point p(1, 2); + Point result = p.Max({0, 10}); + Point expected(1, 10); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector3Max) { + Vector3 p(1, 2, 3); + Vector3 result = p.Max({0, 10, 2}); + Vector3 expected(1, 10, 3); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Max) { + Vector4 p(1, 2, 3, 4); + Vector4 result = p.Max({0, 10, 2, 1}); + Vector4 expected(1, 10, 3, 4); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, PointFloor) { + Point p(1.5, 2.3); + Point result = p.Floor(); + Point expected(1, 2); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector3Floor) { + Vector3 p(1.5, 2.3, 3.9); + Vector3 result = p.Floor(); + Vector3 expected(1, 2, 3); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Floor) { + Vector4 p(1.5, 2.3, 3.9, 4.0); + Vector4 result = p.Floor(); + Vector4 expected(1, 2, 3, 4); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, PointCeil) { + Point p(1.5, 2.3); + Point result = p.Ceil(); + Point expected(2, 3); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector3Ceil) { + Vector3 p(1.5, 2.3, 3.9); + Vector3 result = p.Ceil(); + Vector3 expected(2, 3, 4); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Ceil) { + Vector4 p(1.5, 2.3, 3.9, 4.0); + Vector4 result = p.Ceil(); + Vector4 expected(2, 3, 4, 4); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, PointRound) { + Point p(1.5, 2.3); + Point result = p.Round(); + Point expected(2, 2); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector3Round) { + Vector3 p(1.5, 2.3, 3.9); + Vector3 result = p.Round(); + Vector3 expected(2, 2, 4); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Round) { + Vector4 p(1.5, 2.3, 3.9, 4.0); + Vector4 result = p.Round(); + Vector4 expected(2, 2, 4, 4); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, PointLerp) { + Point p(1, 2); + Point result = p.Lerp({5, 10}, 0.75); + Point expected(4, 8); + ASSERT_POINT_NEAR(result, expected); +} + +TEST(GeometryTest, Vector3Lerp) { + Vector3 p(1, 2, 3); + Vector3 result = p.Lerp({5, 10, 15}, 0.75); + Vector3 expected(4, 8, 12); + ASSERT_VECTOR3_NEAR(result, expected); +} + +TEST(GeometryTest, Vector4Lerp) { + Vector4 p(1, 2, 3, 4); + Vector4 result = p.Lerp({5, 10, 15, 20}, 0.75); + Vector4 expected(4, 8, 12, 16); + ASSERT_VECTOR4_NEAR(result, expected); +} + +TEST(GeometryTest, SeparatedVector2NormalizesWithConstructor) { + SeparatedVector2 v(Vector2(10, 0)); + ASSERT_POINT_NEAR(v.direction, Vector2(1, 0)); + ASSERT_NEAR(v.magnitude, 10, kEhCloseEnough); +} + +TEST(GeometryTest, SeparatedVector2GetVector) { + SeparatedVector2 v(Vector2(10, 0)); + ASSERT_POINT_NEAR(v.GetVector(), Vector2(10, 0)); +} + +TEST(GeometryTest, SeparatedVector2GetAlignment) { + // Parallel + { + SeparatedVector2 v(Vector2(10, 0)); + Scalar actual = v.GetAlignment(SeparatedVector2(Vector2(5, 0))); + ASSERT_NEAR(actual, 1, kEhCloseEnough); + } + + // Perpendicular + { + SeparatedVector2 v(Vector2(10, 0)); + Scalar actual = v.GetAlignment(SeparatedVector2(Vector2(0, 5))); + ASSERT_NEAR(actual, 0, kEhCloseEnough); + } + + // Opposite parallel + { + SeparatedVector2 v(Vector2(0, 10)); + Scalar actual = v.GetAlignment(SeparatedVector2(Vector2(0, -5))); + ASSERT_NEAR(actual, -1, kEhCloseEnough); + } +} + +TEST(GeometryTest, SeparatedVector2AngleTo) { + { + SeparatedVector2 v(Vector2(10, 0)); + Radians actual = v.AngleTo(SeparatedVector2(Vector2(5, 0))); + Radians expected = Radians{0}; + ASSERT_NEAR(actual.radians, expected.radians, kEhCloseEnough); + } + + { + SeparatedVector2 v(Vector2(10, 0)); + Radians actual = v.AngleTo(SeparatedVector2(Vector2(0, -5))); + Radians expected = Radians{-kPi / 2}; + ASSERT_NEAR(actual.radians, expected.radians, kEhCloseEnough); + } +} + +TEST(GeometryTest, CanUseVector3AssignmentOperators) { + { + Vector3 p(1, 2, 4); + p += Vector3(1, 2, 4); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + ASSERT_EQ(p.z, 8u); + } + + { + Vector3 p(3, 6, 8); + p -= Vector3(1, 2, 3); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + ASSERT_EQ(p.z, 5u); + } + + { + Vector3 p(1, 2, 3); + p *= Vector3(2, 3, 4); + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 6u); + ASSERT_EQ(p.z, 12u); + } + + { + Vector3 p(1, 2, 3); + p *= 2; + ASSERT_EQ(p.x, 2u); + ASSERT_EQ(p.y, 4u); + ASSERT_EQ(p.z, 6u); + } + + { + Vector3 p(2, 6, 12); + p /= Vector3(2, 3, 4); + ASSERT_EQ(p.x, 1u); + ASSERT_EQ(p.y, 2u); + ASSERT_EQ(p.z, 3u); + } + + { + Vector3 p(2, 6, 12); + p /= 2; + ASSERT_EQ(p.x, 1u); + ASSERT_EQ(p.y, 3u); + ASSERT_EQ(p.z, 6u); + } +} + +TEST(GeometryTest, CanPerformAlgebraicVector3Ops) { + { + Vector3 p1(1, 2, 3); + Vector3 p2 = p1 + Vector3(1, 2, 3); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + ASSERT_EQ(p2.z, 6u); + } + + { + Vector3 p1(3, 6, 9); + Vector3 p2 = p1 - Vector3(1, 2, 3); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 4u); + ASSERT_EQ(p2.z, 6u); + } + + { + Vector3 p1(1, 2, 3); + Vector3 p2 = p1 * Vector3(2, 3, 4); + ASSERT_EQ(p2.x, 2u); + ASSERT_EQ(p2.y, 6u); + ASSERT_EQ(p2.z, 12u); + } + + { + Vector3 p1(2, 6, 12); + Vector3 p2 = p1 / Vector3(2, 3, 4); + ASSERT_EQ(p2.x, 1u); + ASSERT_EQ(p2.y, 2u); + ASSERT_EQ(p2.z, 3u); + } +} + +TEST(GeometryTest, CanPerformAlgebraicVector3OpsWithArithmeticTypes) { + // LHS + { + Vector3 p1(1, 2, 3); + Vector3 p2 = p1 + 2.0f; + ASSERT_EQ(p2.x, 3); + ASSERT_EQ(p2.y, 4); + ASSERT_EQ(p2.z, 5); + } + + { + Vector3 p1(1, 2, 3); + Vector3 p2 = p1 - 2.0f; + ASSERT_EQ(p2.x, -1); + ASSERT_EQ(p2.y, 0); + ASSERT_EQ(p2.z, 1); + } + + { + Vector3 p1(1, 2, 3); + Vector3 p2 = p1 * 2.0f; + ASSERT_EQ(p2.x, 2); + ASSERT_EQ(p2.y, 4); + ASSERT_EQ(p2.z, 6); + } + + { + Vector3 p1(2, 6, 12); + Vector3 p2 = p1 / 2.0f; + ASSERT_EQ(p2.x, 1); + ASSERT_EQ(p2.y, 3); + ASSERT_EQ(p2.z, 6); + } + + // RHS + { + Vector3 p1(1, 2, 3); + Vector3 p2 = 2.0f + p1; + ASSERT_EQ(p2.x, 3); + ASSERT_EQ(p2.y, 4); + ASSERT_EQ(p2.z, 5); + } + + { + Vector3 p1(1, 2, 3); + Vector3 p2 = 2.0f - p1; + ASSERT_EQ(p2.x, 1); + ASSERT_EQ(p2.y, 0); + ASSERT_EQ(p2.z, -1); + } + + { + Vector3 p1(1, 2, 3); + Vector3 p2 = 2.0f * p1; + ASSERT_EQ(p2.x, 2); + ASSERT_EQ(p2.y, 4); + ASSERT_EQ(p2.z, 6); + } + + { + Vector3 p1(2, 6, 12); + Vector3 p2 = 12.0f / p1; + ASSERT_EQ(p2.x, 6); + ASSERT_EQ(p2.y, 2); + ASSERT_EQ(p2.z, 1); + } +} + +TEST(GeometryTest, ColorPremultiply) { + { + Color a(1.0, 0.5, 0.2, 0.5); + Color premultiplied = a.Premultiply(); + Color expected = Color(0.5, 0.25, 0.1, 0.5); + ASSERT_COLOR_NEAR(premultiplied, expected); + } + + { + Color a(0.5, 0.25, 0.1, 0.5); + Color unpremultiplied = a.Unpremultiply(); + Color expected = Color(1.0, 0.5, 0.2, 0.5); + ASSERT_COLOR_NEAR(unpremultiplied, expected); + } + + { + Color a(0.5, 0.25, 0.1, 0.0); + Color unpremultiplied = a.Unpremultiply(); + Color expected = Color(0.0, 0.0, 0.0, 0.0); + ASSERT_COLOR_NEAR(unpremultiplied, expected); + } +} + +TEST(GeometryTest, ColorR8G8B8A8) { + { + Color a(1.0, 0.5, 0.2, 0.5); + std::array expected = {255, 128, 51, 128}; + ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected); + } + + { + Color a(0.0, 0.0, 0.0, 0.0); + std::array expected = {0, 0, 0, 0}; + ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected); + } + + { + Color a(1.0, 1.0, 1.0, 1.0); + std::array expected = {255, 255, 255, 255}; + ASSERT_ARRAY_4_NEAR(a.ToR8G8B8A8(), expected); + } +} + +TEST(GeometryTest, ColorLerp) { + { + Color a(0.0, 0.0, 0.0, 0.0); + Color b(1.0, 1.0, 1.0, 1.0); + + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.5), Color(0.5, 0.5, 0.5, 0.5)); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.0), a); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 1.0), b); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.2), Color(0.2, 0.2, 0.2, 0.2)); + } + + { + Color a(0.2, 0.4, 1.0, 0.5); + Color b(0.4, 1.0, 0.2, 0.3); + + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.5), Color(0.3, 0.7, 0.6, 0.4)); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.0), a); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 1.0), b); + ASSERT_COLOR_NEAR(Color::Lerp(a, b, 0.2), Color(0.24, 0.52, 0.84, 0.46)); + } +} + +TEST(GeometryTest, ColorClamp01) { + { + Color result = Color(0.5, 0.5, 0.5, 0.5).Clamp01(); + Color expected = Color(0.5, 0.5, 0.5, 0.5); + ASSERT_COLOR_NEAR(result, expected); + } + + { + Color result = Color(-1, -1, -1, -1).Clamp01(); + Color expected = Color(0, 0, 0, 0); + ASSERT_COLOR_NEAR(result, expected); + } + + { + Color result = Color(2, 2, 2, 2).Clamp01(); + Color expected = Color(1, 1, 1, 1); + ASSERT_COLOR_NEAR(result, expected); + } +} + +TEST(GeometryTest, ColorMakeRGBA8) { + { + Color a = Color::MakeRGBA8(0, 0, 0, 0); + Color b = Color::BlackTransparent(); + ASSERT_COLOR_NEAR(a, b); + } + + { + Color a = Color::MakeRGBA8(255, 255, 255, 255); + Color b = Color::White(); + ASSERT_COLOR_NEAR(a, b); + } + + { + Color a = Color::MakeRGBA8(63, 127, 191, 127); + Color b(0.247059, 0.498039, 0.74902, 0.498039); + ASSERT_COLOR_NEAR(a, b); + } +} + +TEST(GeometryTest, ColorApplyColorMatrix) { + { + ColorMatrix color_matrix = { + 1, 1, 1, 1, 1, // + 1, 1, 1, 1, 1, // + 1, 1, 1, 1, 1, // + 1, 1, 1, 1, 1, // + }; + auto result = Color::White().ApplyColorMatrix(color_matrix); + auto expected = Color(1, 1, 1, 1); + ASSERT_COLOR_NEAR(result, expected); + } + + { + ColorMatrix color_matrix = { + 0.1, 0, 0, 0, 0.01, // + 0, 0.2, 0, 0, 0.02, // + 0, 0, 0.3, 0, 0.03, // + 0, 0, 0, 0.4, 0.04, // + }; + auto result = Color::White().ApplyColorMatrix(color_matrix); + auto expected = Color(0.11, 0.22, 0.33, 0.44); + ASSERT_COLOR_NEAR(result, expected); + } +} + +TEST(GeometryTest, ColorLinearToSRGB) { + { + auto result = Color::White().LinearToSRGB(); + auto expected = Color(1, 1, 1, 1); + ASSERT_COLOR_NEAR(result, expected); + } + + { + auto result = Color::BlackTransparent().LinearToSRGB(); + auto expected = Color(0, 0, 0, 0); + ASSERT_COLOR_NEAR(result, expected); + } + + { + auto result = Color(0.2, 0.4, 0.6, 0.8).LinearToSRGB(); + auto expected = Color(0.484529, 0.665185, 0.797738, 0.8); + ASSERT_COLOR_NEAR(result, expected); + } +} + +TEST(GeometryTest, ColorSRGBToLinear) { + { + auto result = Color::White().SRGBToLinear(); + auto expected = Color(1, 1, 1, 1); + ASSERT_COLOR_NEAR(result, expected); + } + + { + auto result = Color::BlackTransparent().SRGBToLinear(); + auto expected = Color(0, 0, 0, 0); + ASSERT_COLOR_NEAR(result, expected); + } + + { + auto result = Color(0.2, 0.4, 0.6, 0.8).SRGBToLinear(); + auto expected = Color(0.0331048, 0.132868, 0.318547, 0.8); + ASSERT_COLOR_NEAR(result, expected); + } +} + +struct ColorBlendTestData { + static constexpr Color kDestinationColor = + Color::CornflowerBlue().WithAlpha(0.75); + static constexpr Color kSourceColors[] = {Color::White().WithAlpha(0.75), + Color::LimeGreen().WithAlpha(0.75), + Color::Black().WithAlpha(0.75)}; + + static const std::map + kExpectedResults[sizeof(kSourceColors)]; +}; + +// THIS RESULT TABLE IS GENERATED! +// +// Uncomment the `GenerateColorBlendResults` test below to print a new table +// after making changes to `Color::Blend`. +const std::map ColorBlendTestData::kExpectedResults[sizeof( + ColorBlendTestData::kSourceColors)] = { + { + {BlendMode::kClear, {0, 0, 0, 0}}, + {BlendMode::kSrc, {1, 1, 1, 0.75}}, + {BlendMode::kDst, {0.392157, 0.584314, 0.929412, 0.75}}, + {BlendMode::kSrcOver, {0.878431, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kDstOver, {0.513726, 0.667451, 0.943529, 0.9375}}, + {BlendMode::kSrcIn, {1, 1, 1, 0.5625}}, + {BlendMode::kDstIn, {0.392157, 0.584314, 0.929412, 0.5625}}, + {BlendMode::kSrcOut, {1, 1, 1, 0.1875}}, + {BlendMode::kDstOut, {0.392157, 0.584314, 0.929412, 0.1875}}, + {BlendMode::kSrcATop, {0.848039, 0.896078, 0.982353, 0.75}}, + {BlendMode::kDstATop, {0.544118, 0.688235, 0.947059, 0.75}}, + {BlendMode::kXor, {0.696078, 0.792157, 0.964706, 0.375}}, + {BlendMode::kPlus, {1, 1, 1, 1}}, + {BlendMode::kModulate, {0.392157, 0.584314, 0.929412, 0.5625}}, + {BlendMode::kScreen, {0.878431, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kOverlay, {0.74902, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kDarken, {0.513726, 0.667451, 0.943529, 0.9375}}, + {BlendMode::kLighten, {0.878431, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kColorDodge, {0.878431, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kColorBurn, {0.513725, 0.667451, 0.943529, 0.9375}}, + {BlendMode::kHardLight, {0.878431, 0.916863, 0.985882, 0.9375}}, + {BlendMode::kSoftLight, {0.654166, 0.775505, 0.964318, 0.9375}}, + {BlendMode::kDifference, {0.643137, 0.566275, 0.428235, 0.9375}}, + {BlendMode::kExclusion, {0.643137, 0.566275, 0.428235, 0.9375}}, + {BlendMode::kMultiply, {0.513726, 0.667451, 0.943529, 0.9375}}, + {BlendMode::kHue, {0.617208, 0.655639, 0.724659, 0.9375}}, + {BlendMode::kSaturation, {0.617208, 0.655639, 0.724659, 0.9375}}, + {BlendMode::kColor, {0.617208, 0.655639, 0.724659, 0.9375}}, + {BlendMode::kLuminosity, {0.878431, 0.916863, 0.985882, 0.9375}}, + }, + { + {BlendMode::kClear, {0, 0, 0, 0}}, + {BlendMode::kSrc, {0.196078, 0.803922, 0.196078, 0.75}}, + {BlendMode::kDst, {0.392157, 0.584314, 0.929412, 0.75}}, + {BlendMode::kSrcOver, {0.235294, 0.76, 0.342745, 0.9375}}, + {BlendMode::kDstOver, {0.352941, 0.628235, 0.782745, 0.9375}}, + {BlendMode::kSrcIn, {0.196078, 0.803922, 0.196078, 0.5625}}, + {BlendMode::kDstIn, {0.392157, 0.584314, 0.929412, 0.5625}}, + {BlendMode::kSrcOut, {0.196078, 0.803922, 0.196078, 0.1875}}, + {BlendMode::kDstOut, {0.392157, 0.584314, 0.929412, 0.1875}}, + {BlendMode::kSrcATop, {0.245098, 0.74902, 0.379412, 0.75}}, + {BlendMode::kDstATop, {0.343137, 0.639216, 0.746078, 0.75}}, + {BlendMode::kXor, {0.294118, 0.694118, 0.562745, 0.375}}, + {BlendMode::kPlus, {0.441176, 1, 0.844118, 1}}, + {BlendMode::kModulate, {0.0768935, 0.469742, 0.182238, 0.5625}}, + {BlendMode::kScreen, {0.424452, 0.828743, 0.79105, 0.9375}}, + {BlendMode::kOverlay, {0.209919, 0.779839, 0.757001, 0.9375}}, + {BlendMode::kDarken, {0.235294, 0.628235, 0.342745, 0.9375}}, + {BlendMode::kLighten, {0.352941, 0.76, 0.782745, 0.9375}}, + {BlendMode::kColorDodge, {0.41033, 0.877647, 0.825098, 0.9375}}, + {BlendMode::kColorBurn, {0.117647, 0.567403, 0.609098, 0.9375}}, + {BlendMode::kHardLight, {0.209919, 0.779839, 0.443783, 0.9375}}, + {BlendMode::kSoftLight, {0.266006, 0.693915, 0.758818, 0.9375}}, + {BlendMode::kDifference, {0.235294, 0.409412, 0.665098, 0.9375}}, + {BlendMode::kExclusion, {0.378316, 0.546897, 0.681707, 0.9375}}, + {BlendMode::kMultiply, {0.163783, 0.559493, 0.334441, 0.9375}}, + {BlendMode::kHue, {0.266235, 0.748588, 0.373686, 0.9375}}, + {BlendMode::kSaturation, {0.339345, 0.629787, 0.811502, 0.9375}}, + {BlendMode::kColor, {0.241247, 0.765953, 0.348698, 0.9375}}, + {BlendMode::kLuminosity, {0.346988, 0.622282, 0.776792, 0.9375}}, + }, + { + {BlendMode::kClear, {0, 0, 0, 0}}, + {BlendMode::kSrc, {0, 0, 0, 0.75}}, + {BlendMode::kDst, {0.392157, 0.584314, 0.929412, 0.75}}, + {BlendMode::kSrcOver, {0.0784314, 0.116863, 0.185882, 0.9375}}, + {BlendMode::kDstOver, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kSrcIn, {0, 0, 0, 0.5625}}, + {BlendMode::kDstIn, {0.392157, 0.584314, 0.929412, 0.5625}}, + {BlendMode::kSrcOut, {0, 0, 0, 0.1875}}, + {BlendMode::kDstOut, {0.392157, 0.584314, 0.929412, 0.1875}}, + {BlendMode::kSrcATop, {0.0980392, 0.146078, 0.232353, 0.75}}, + {BlendMode::kDstATop, {0.294118, 0.438235, 0.697059, 0.75}}, + {BlendMode::kXor, {0.196078, 0.292157, 0.464706, 0.375}}, + {BlendMode::kPlus, {0.294118, 0.438235, 0.697059, 1}}, + {BlendMode::kModulate, {0, 0, 0, 0.5625}}, + {BlendMode::kScreen, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kOverlay, {0.0784314, 0.218039, 0.701176, 0.9375}}, + {BlendMode::kDarken, {0.0784314, 0.116863, 0.185882, 0.9375}}, + {BlendMode::kLighten, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kColorDodge, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kColorBurn, {0.0784314, 0.116863, 0.185882, 0.9375}}, + {BlendMode::kHardLight, {0.0784314, 0.116863, 0.185882, 0.9375}}, + {BlendMode::kSoftLight, {0.170704, 0.321716, 0.704166, 0.9375}}, + {BlendMode::kDifference, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kExclusion, {0.313726, 0.467451, 0.743529, 0.9375}}, + {BlendMode::kMultiply, {0.0784314, 0.116863, 0.185882, 0.9375}}, + {BlendMode::kHue, {0.417208, 0.455639, 0.524659, 0.9375}}, + {BlendMode::kSaturation, {0.417208, 0.455639, 0.524659, 0.9375}}, + {BlendMode::kColor, {0.417208, 0.455639, 0.524659, 0.9375}}, + {BlendMode::kLuminosity, {0.0784314, 0.116863, 0.185882, 0.9375}}, + }, +}; + +/// To print a new ColorBlendTestData::kExpectedResults table, uncomment this +/// test and run with: +/// --gtest_filter="GeometryTest.GenerateColorBlendResults" +/* +TEST(GeometryTest, GenerateColorBlendResults) { + auto& o = std::cout; + using BlendT = std::underlying_type_t; + o << "{"; + for (const auto& source : ColorBlendTestData::kSourceColors) { + o << "{"; + for (BlendT blend_i = 0; + blend_i < static_cast(BlendMode::kLast) + 1; blend_i++) { + auto blend = static_cast(blend_i); + Color c = ColorBlendTestData::kDestinationColor.Blend(source, blend); + o << "{ BlendMode::k" << BlendModeToString(blend) << ", "; + o << "{" << c.red << "," << c.green << "," << c.blue << "," << c.alpha + << "}"; + o << "}," << std::endl; + } + o << "},"; + } + o << "};" << std::endl; +} +*/ + +#define _BLEND_MODE_RESULT_CHECK(blend_mode) \ + expected = ColorBlendTestData::kExpectedResults[source_i] \ + .find(BlendMode::k##blend_mode) \ + ->second; \ + EXPECT_COLOR_NEAR(dst.Blend(src, BlendMode::k##blend_mode), expected); + +TEST(GeometryTest, ColorBlendReturnsExpectedResults) { + Color dst = ColorBlendTestData::kDestinationColor; + for (size_t source_i = 0; + source_i < sizeof(ColorBlendTestData::kSourceColors) / sizeof(Color); + source_i++) { + Color src = ColorBlendTestData::kSourceColors[source_i]; + + Color expected; + IMPELLER_FOR_EACH_BLEND_MODE(_BLEND_MODE_RESULT_CHECK) + } +} + +#define _BLEND_MODE_NAME_CHECK(blend_mode) \ + case BlendMode::k##blend_mode: \ + ASSERT_STREQ(result, #blend_mode); \ + break; + +TEST(GeometryTest, BlendModeToString) { + using BlendT = std::underlying_type_t; + for (BlendT i = 0; i <= static_cast(BlendMode::kLastMode); i++) { + auto mode = static_cast(i); + auto result = BlendModeToString(mode); + switch (mode) { IMPELLER_FOR_EACH_BLEND_MODE(_BLEND_MODE_NAME_CHECK) } + } +} + +TEST(GeometryTest, CanConvertBetweenDegressAndRadians) { + { + auto deg = Degrees{90.0}; + Radians rad = deg; + ASSERT_FLOAT_EQ(rad.radians, kPiOver2); + } +} + +TEST(GeometryTest, MatrixPrinting) { + { + std::stringstream stream; + Matrix m; + stream << m; + ASSERT_EQ(stream.str(), R"(( + 1.000000, 0.000000, 0.000000, 0.000000, + 0.000000, 1.000000, 0.000000, 0.000000, + 0.000000, 0.000000, 1.000000, 0.000000, + 0.000000, 0.000000, 0.000000, 1.000000, +))"); + } + + { + std::stringstream stream; + Matrix m = Matrix::MakeTranslation(Vector3(10, 20, 30)); + stream << m; + + ASSERT_EQ(stream.str(), R"(( + 1.000000, 0.000000, 0.000000, 10.000000, + 0.000000, 1.000000, 0.000000, 20.000000, + 0.000000, 0.000000, 1.000000, 30.000000, + 0.000000, 0.000000, 0.000000, 1.000000, +))"); + } +} + +TEST(GeometryTest, PointPrinting) { + { + std::stringstream stream; + Point m; + stream << m; + ASSERT_EQ(stream.str(), "(0, 0)"); + } + + { + std::stringstream stream; + Point m(13, 37); + stream << m; + ASSERT_EQ(stream.str(), "(13, 37)"); + } +} + +TEST(GeometryTest, Vector3Printing) { + { + std::stringstream stream; + Vector3 m; + stream << m; + ASSERT_EQ(stream.str(), "(0, 0, 0)"); + } + + { + std::stringstream stream; + Vector3 m(1, 2, 3); + stream << m; + ASSERT_EQ(stream.str(), "(1, 2, 3)"); + } +} + +TEST(GeometryTest, Vector4Printing) { + { + std::stringstream stream; + Vector4 m; + stream << m; + ASSERT_EQ(stream.str(), "(0, 0, 0, 1)"); + } + + { + std::stringstream stream; + Vector4 m(1, 2, 3, 4); + stream << m; + ASSERT_EQ(stream.str(), "(1, 2, 3, 4)"); + } +} + +TEST(GeometryTest, ColorPrinting) { + { + std::stringstream stream; + Color m; + stream << m; + ASSERT_EQ(stream.str(), "(0, 0, 0, 0)"); + } + + { + std::stringstream stream; + Color m(1, 2, 3, 4); + stream << m; + ASSERT_EQ(stream.str(), "(1, 2, 3, 4)"); + } +} + +TEST(GeometryTest, ToIColor) { + ASSERT_EQ(Color::ToIColor(Color(0, 0, 0, 0)), 0u); + ASSERT_EQ(Color::ToIColor(Color(1.0, 1.0, 1.0, 1.0)), 0xFFFFFFFF); + ASSERT_EQ(Color::ToIColor(Color(0.5, 0.5, 1.0, 1.0)), 0xFF8080FF); +} + +TEST(GeometryTest, Gradient) { + { + // Simple 2 color gradient produces color buffer containing exactly those + // values. + std::vector colors = {Color::Red(), Color::Blue()}; + std::vector stops = {0.0, 1.0}; + + auto gradient = CreateGradientBuffer(colors, stops); + + ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, colors); + ASSERT_EQ(gradient.texture_size, 2u); + } + + { + // Gradient with duplicate stops does not create an empty texture. + std::vector colors = {Color::Red(), Color::Yellow(), Color::Black(), + Color::Blue()}; + std::vector stops = {0.0, 0.25, 0.25, 1.0}; + + auto gradient = CreateGradientBuffer(colors, stops); + ASSERT_EQ(gradient.texture_size, 5u); + } + + { + // Simple N color gradient produces color buffer containing exactly those + // values. + std::vector colors = {Color::Red(), Color::Blue(), Color::Green(), + Color::White()}; + std::vector stops = {0.0, 0.33, 0.66, 1.0}; + + auto gradient = CreateGradientBuffer(colors, stops); + + ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, colors); + ASSERT_EQ(gradient.texture_size, 4u); + } + + { + // Gradient with color stops will lerp and scale buffer. + std::vector colors = {Color::Red(), Color::Blue(), Color::Green()}; + std::vector stops = {0.0, 0.25, 1.0}; + + auto gradient = CreateGradientBuffer(colors, stops); + + std::vector lerped_colors = { + Color::Red(), + Color::Blue(), + Color::Lerp(Color::Blue(), Color::Green(), 0.3333), + Color::Lerp(Color::Blue(), Color::Green(), 0.6666), + Color::Green(), + }; + ASSERT_COLOR_BUFFER_NEAR(gradient.color_bytes, lerped_colors); + ASSERT_EQ(gradient.texture_size, 5u); + } + + { + // Gradient size is capped at 1024. + std::vector colors = {}; + std::vector stops = {}; + for (auto i = 0u; i < 1025; i++) { + colors.push_back(Color::Blue()); + stops.push_back(i / 1025.0); + } + + auto gradient = CreateGradientBuffer(colors, stops); + + ASSERT_EQ(gradient.texture_size, 1024u); + ASSERT_EQ(gradient.color_bytes.size(), 1024u * 4); + } +} + +TEST(GeometryTest, HalfConversions) { +#if defined(FML_OS_MACOSX) || defined(FML_OS_IOS) || \ + defined(FML_OS_IOS_SIMULATOR) + ASSERT_EQ(ScalarToHalf(0.0), 0.0f16); + ASSERT_EQ(ScalarToHalf(0.05), 0.05f16); + ASSERT_EQ(ScalarToHalf(2.43), 2.43f16); + ASSERT_EQ(ScalarToHalf(-1.45), -1.45f16); + + // 65504 is the largest possible half. + ASSERT_EQ(ScalarToHalf(65504.0f), 65504.0f16); + ASSERT_EQ(ScalarToHalf(65504.0f + 1), 65504.0f16); + + // Colors + ASSERT_EQ(HalfVector4(Color::Red()), + HalfVector4(1.0f16, 0.0f16, 0.0f16, 1.0f16)); + ASSERT_EQ(HalfVector4(Color::Green()), + HalfVector4(0.0f16, 1.0f16, 0.0f16, 1.0f16)); + ASSERT_EQ(HalfVector4(Color::Blue()), + HalfVector4(0.0f16, 0.0f16, 1.0f16, 1.0f16)); + ASSERT_EQ(HalfVector4(Color::Black().WithAlpha(0)), + HalfVector4(0.0f16, 0.0f16, 0.0f16, 0.0f16)); + + ASSERT_EQ(HalfVector3(Vector3(4.0, 6.0, -1.0)), + HalfVector3(4.0f16, 6.0f16, -1.0f16)); + ASSERT_EQ(HalfVector2(Vector2(4.0, 6.0)), HalfVector2(4.0f16, 6.0f16)); + + ASSERT_EQ(Half(0.5f), Half(0.5f16)); + ASSERT_EQ(Half(0.5), Half(0.5f16)); + ASSERT_EQ(Half(5), Half(5.0f16)); +#else + GTEST_SKIP() << "Half-precision floats (IEEE 754) are not portable and " + "only used on Apple platforms."; +#endif // FML_OS_MACOSX || FML_OS_IOS || FML_OS_IOS_SIMULATOR +} + +} // namespace testing +} // namespace impeller + +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/flutter/engine/src/flutter/impeller/geometry/gradient.cc b/flutter/engine/src/flutter/impeller/geometry/gradient.cc new file mode 100644 index 0000000000000000000000000000000000000000..8bdfbe2cb250788d1fde1fa6903b19b741cc8254 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/gradient.cc @@ -0,0 +1,101 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/fml/logging.h" +#include "impeller/geometry/gradient.h" + +namespace impeller { + +static void AppendColor(const Color& color, GradientData* data) { + auto converted = color.ToR8G8B8A8(); + data->color_bytes.push_back(converted[0]); + data->color_bytes.push_back(converted[1]); + data->color_bytes.push_back(converted[2]); + data->color_bytes.push_back(converted[3]); +} + +GradientData CreateGradientBuffer(const std::vector& colors, + const std::vector& stops) { + FML_DCHECK(stops.size() == colors.size()); + + uint32_t texture_size; + if (stops.size() == 2) { + texture_size = colors.size(); + } else { + auto minimum_delta = 1.0; + for (size_t i = 1; i < stops.size(); i++) { + auto value = stops[i] - stops[i - 1]; + // Smaller than kEhCloseEnough + if (value < 0.0001) { + continue; + } + if (value < minimum_delta) { + minimum_delta = value; + } + } + // Avoid creating textures that are absurdly large due to stops that are + // very close together. + // TODO(jonahwilliams): this should use a platform specific max texture + // size. + texture_size = std::min( + static_cast(std::round(1.0 / minimum_delta)) + 1, 1024u); + } + GradientData data = { + .color_bytes = {}, + .texture_size = texture_size, + }; + data.color_bytes.reserve(texture_size * 4); + + if (texture_size == colors.size() && colors.size() <= 1024) { + for (auto i = 0u; i < colors.size(); i++) { + AppendColor(colors[i], &data); + } + } else { + Color previous_color = colors[0]; + auto previous_stop = 0.0; + auto previous_color_index = 0; + + // The first index is always equal to the first color, exactly. + AppendColor(previous_color, &data); + + for (auto i = 1u; i < texture_size - 1; i++) { + auto scaled_i = i / (texture_size - 1.0); + Color next_color = colors[previous_color_index + 1]; + auto next_stop = stops[previous_color_index + 1]; + // We're almost exactly equal to the next stop. + if (ScalarNearlyEqual(scaled_i, next_stop)) { + AppendColor(next_color, &data); + + previous_color = next_color; + previous_stop = next_stop; + previous_color_index += 1; + } else if (scaled_i < next_stop) { + // We're still between the current stop and the next stop. + auto t = (scaled_i - previous_stop) / (next_stop - previous_stop); + auto mixed_color = Color::Lerp(previous_color, next_color, t); + + AppendColor(mixed_color, &data); + } else { + // We've slightly overshot the previous stop. + previous_color = next_color; + previous_stop = next_stop; + previous_color_index += 1; + next_color = colors[previous_color_index + 1]; + auto next_stop = stops[previous_color_index + 1]; + + auto t = (scaled_i - previous_stop) / (next_stop - previous_stop); + auto mixed_color = Color::Lerp(previous_color, next_color, t); + + AppendColor(mixed_color, &data); + } + } + // The last index is always equal to the last color, exactly. + AppendColor(colors.back(), &data); + } + return data; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/gradient.h b/flutter/engine/src/flutter/impeller/geometry/gradient.h new file mode 100644 index 0000000000000000000000000000000000000000..551ec129f0a2f135dde438edeff6e1eb9aaf7664 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/gradient.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_ +#define FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_ + +#include +#include + +#include "impeller/geometry/color.h" + +namespace impeller { + +// If texture_size is 0 then the gradient is invalid. +struct GradientData { + std::vector color_bytes; + uint32_t texture_size; +}; + +/** + * @brief Populate a vector with the interpolated color bytes for the linear + * gradient described by colors and stops. + * + * @param colors + * @param stops + * @return GradientData + */ +GradientData CreateGradientBuffer(const std::vector& colors, + const std::vector& stops); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_GRADIENT_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/half.h b/flutter/engine/src/flutter/impeller/geometry/half.h new file mode 100644 index 0000000000000000000000000000000000000000..1e819ce466856cb1b496daa9c05866f0dc8d9d54 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/half.h @@ -0,0 +1,196 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_HALF_H_ +#define FLUTTER_IMPELLER_GEOMETRY_HALF_H_ + +#include + +#include "flutter/fml/build_config.h" + +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/vector.h" + +// NOLINTBEGIN(google-explicit-constructor) + +#if defined(FML_OS_MACOSX) || defined(FML_OS_IOS) || \ + defined(FML_OS_IOS_SIMULATOR) +using InternalHalf = _Float16; +#else +using InternalHalf = uint16_t; +#endif + +namespace impeller { + +/// @brief Convert a scalar to a half precision float. +/// +/// See also: https://clang.llvm.org/docs/LanguageExtensions.html +/// This is not currently supported on Windows toolchains. +inline constexpr InternalHalf ScalarToHalf(Scalar f) { +#ifdef FML_OS_WIN + return static_cast(0); +#else + return static_cast(f); +#endif +} + +/// @brief A storage only class for half precision floating point. +struct Half { + InternalHalf x = 0; + + constexpr Half() {} + + constexpr Half(double value) : x(ScalarToHalf(static_cast(value))) {} + + constexpr Half(Scalar value) : x(ScalarToHalf(value)) {} + + constexpr Half(int value) : x(ScalarToHalf(static_cast(value))) {} + + constexpr Half(InternalHalf x) : x(x) {} + + constexpr bool operator==(const Half& v) const { return v.x == x; } + + constexpr bool operator!=(const Half& v) const { return v.x != x; } +}; + +/// @brief A storage only class for half precision floating point vector 4. +struct HalfVector4 { + union { + struct { + InternalHalf x = 0; + InternalHalf y = 0; + InternalHalf z = 0; + InternalHalf w = 0; + }; + InternalHalf e[4]; + }; + + constexpr HalfVector4() {} + + constexpr HalfVector4(const Color& a) + : x(ScalarToHalf(a.red)), + y(ScalarToHalf(a.green)), + z(ScalarToHalf(a.blue)), + w(ScalarToHalf(a.alpha)) {} + + constexpr HalfVector4(const Vector4& a) + : x(ScalarToHalf(a.x)), + y(ScalarToHalf(a.y)), + z(ScalarToHalf(a.z)), + w(ScalarToHalf(a.w)) {} + + constexpr HalfVector4(InternalHalf x, + InternalHalf y, + InternalHalf z, + InternalHalf w) + : x(x), y(y), z(z), w(w) {} + + constexpr bool operator==(const HalfVector4& v) const { + return v.x == x && v.y == y && v.z == z && v.w == w; + } + + constexpr bool operator!=(const HalfVector4& v) const { + return v.x != x || v.y != y || v.z != z || v.w != w; + } +}; + +/// @brief A storage only class for half precision floating point vector 3. +struct HalfVector3 { + union { + struct { + InternalHalf x = 0; + InternalHalf y = 0; + InternalHalf z = 0; + }; + InternalHalf e[3]; + }; + + constexpr HalfVector3() {} + + constexpr HalfVector3(const Vector3& a) + : x(ScalarToHalf(a.x)), y(ScalarToHalf(a.y)), z(ScalarToHalf(a.z)) {} + + constexpr HalfVector3(InternalHalf x, InternalHalf y, InternalHalf z) + : x(x), y(y), z(z) {} + + constexpr bool operator==(const HalfVector3& v) const { + return v.x == x && v.y == y && v.z == z; + } + + constexpr bool operator!=(const HalfVector3& v) const { + return v.x != x || v.y != y || v.z != z; + } +}; + +/// @brief A storage only class for half precision floating point vector 2. +struct HalfVector2 { + union { + struct { + InternalHalf x = 0; + InternalHalf y = 0; + }; + InternalHalf e[2]; + }; + + constexpr HalfVector2() {} + + constexpr HalfVector2(const Vector2& a) + : x(ScalarToHalf(a.x)), y(ScalarToHalf(a.y)) {} + + constexpr HalfVector2(InternalHalf x, InternalHalf y) : x(x), y(y){}; + + constexpr bool operator==(const HalfVector2& v) const { + return v.x == x && v.y == y; + } + + constexpr bool operator!=(const HalfVector2& v) const { + return v.x != x || v.y != y; + } +}; + +static_assert(sizeof(Half) == sizeof(uint16_t)); +static_assert(sizeof(HalfVector2) == 2 * sizeof(Half)); +static_assert(sizeof(HalfVector3) == 3 * sizeof(Half)); +static_assert(sizeof(HalfVector4) == 4 * sizeof(Half)); + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, const impeller::Half& p) { + out << "(" << static_cast(p.x) << ")"; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const impeller::HalfVector2& p) { + out << "(" << static_cast(p.x) << ", " + << static_cast(p.y) << ")"; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const impeller::HalfVector3& p) { + out << "(" << static_cast(p.x) << ", " + << static_cast(p.y) << ", " + << static_cast(p.z) << ")"; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, + const impeller::HalfVector4& p) { + out << "(" << static_cast(p.x) << ", " + << static_cast(p.y) << ", " + << static_cast(p.z) << ", " + << static_cast(p.w) << ")"; + return out; +} + +// NOLINTEND(google-explicit-constructor) + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_HALF_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/matrix.cc b/flutter/engine/src/flutter/impeller/geometry/matrix.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba49965498aa5cdd36c0a5f680c835591d3e2086 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/matrix.cc @@ -0,0 +1,392 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/matrix.h" + +#include +#include + +namespace impeller { + +Matrix::Matrix(const MatrixDecomposition& d) : Matrix() { + /* + * Apply perspective. + */ + for (int i = 0; i < 4; i++) { + e[i][3] = d.perspective.e[i]; + } + + /* + * Apply translation. + */ + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + e[3][i] += d.translation.e[j] * e[j][i]; + } + } + + /* + * Apply rotation. + */ + + Matrix rotation; + + const auto x = -d.rotation.x; + const auto y = -d.rotation.y; + const auto z = -d.rotation.z; + const auto w = d.rotation.w; + + /* + * Construct a composite rotation matrix from the quaternion values. + */ + + rotation.e[0][0] = 1.0 - 2.0 * (y * y + z * z); + rotation.e[0][1] = 2.0 * (x * y - z * w); + rotation.e[0][2] = 2.0 * (x * z + y * w); + rotation.e[1][0] = 2.0 * (x * y + z * w); + rotation.e[1][1] = 1.0 - 2.0 * (x * x + z * z); + rotation.e[1][2] = 2.0 * (y * z - x * w); + rotation.e[2][0] = 2.0 * (x * z - y * w); + rotation.e[2][1] = 2.0 * (y * z + x * w); + rotation.e[2][2] = 1.0 - 2.0 * (x * x + y * y); + + *this = *this * rotation; + + /* + * Apply shear. + */ + Matrix shear; + + if (d.shear.e[2] != 0) { + shear.e[2][1] = d.shear.e[2]; + *this = *this * shear; + } + + if (d.shear.e[1] != 0) { + shear.e[2][1] = 0.0; + shear.e[2][0] = d.shear.e[1]; + *this = *this * shear; + } + + if (d.shear.e[0] != 0) { + shear.e[2][0] = 0.0; + shear.e[1][0] = d.shear.e[0]; + *this = *this * shear; + } + + /* + * Apply scale. + */ + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + e[i][j] *= d.scale.e[i]; + } + } +} + +Matrix Matrix::operator+(const Matrix& o) const { + return Matrix( + m[0] + o.m[0], m[1] + o.m[1], m[2] + o.m[2], m[3] + o.m[3], // + m[4] + o.m[4], m[5] + o.m[5], m[6] + o.m[6], m[7] + o.m[7], // + m[8] + o.m[8], m[9] + o.m[9], m[10] + o.m[10], m[11] + o.m[11], // + m[12] + o.m[12], m[13] + o.m[13], m[14] + o.m[14], m[15] + o.m[15] // + ); +} + +Matrix Matrix::Invert() const { + Matrix tmp{ + m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10], + + -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - + m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10], + + m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6], + + -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - + m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6], + + -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - + m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10], + + m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10], + + -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - + m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6], + + m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6], + + m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9], + + -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - + m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9], + + m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5], + + -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - + m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5], + + -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - + m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9], + + m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9], + + -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - + m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5], + + m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]}; + + Scalar det = + m[0] * tmp.m[0] + m[1] * tmp.m[4] + m[2] * tmp.m[8] + m[3] * tmp.m[12]; + + if (det == 0) { + return {}; + } + + det = 1.0 / det; + + return {tmp.m[0] * det, tmp.m[1] * det, tmp.m[2] * det, tmp.m[3] * det, + tmp.m[4] * det, tmp.m[5] * det, tmp.m[6] * det, tmp.m[7] * det, + tmp.m[8] * det, tmp.m[9] * det, tmp.m[10] * det, tmp.m[11] * det, + tmp.m[12] * det, tmp.m[13] * det, tmp.m[14] * det, tmp.m[15] * det}; +} + +Scalar Matrix::GetDeterminant() const { + auto a00 = e[0][0]; + auto a01 = e[0][1]; + auto a02 = e[0][2]; + auto a03 = e[0][3]; + auto a10 = e[1][0]; + auto a11 = e[1][1]; + auto a12 = e[1][2]; + auto a13 = e[1][3]; + auto a20 = e[2][0]; + auto a21 = e[2][1]; + auto a22 = e[2][2]; + auto a23 = e[2][3]; + auto a30 = e[3][0]; + auto a31 = e[3][1]; + auto a32 = e[3][2]; + auto a33 = e[3][3]; + + auto b00 = a00 * a11 - a01 * a10; + auto b01 = a00 * a12 - a02 * a10; + auto b02 = a00 * a13 - a03 * a10; + auto b03 = a01 * a12 - a02 * a11; + auto b04 = a01 * a13 - a03 * a11; + auto b05 = a02 * a13 - a03 * a12; + auto b06 = a20 * a31 - a21 * a30; + auto b07 = a20 * a32 - a22 * a30; + auto b08 = a20 * a33 - a23 * a30; + auto b09 = a21 * a32 - a22 * a31; + auto b10 = a21 * a33 - a23 * a31; + auto b11 = a22 * a33 - a23 * a32; + + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +} + +/* + * Adapted for Impeller from Graphics Gems: + * http://www.realtimerendering.com/resources/GraphicsGems/gemsii/unmatrix.c + */ +std::optional Matrix::Decompose() const { + /* + * Normalize the matrix. + */ + Matrix self = *this; + + if (self.e[3][3] == 0) { + return std::nullopt; + } + + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + self.e[i][j] /= self.e[3][3]; + } + } + + /* + * `perspectiveMatrix` is used to solve for perspective, but it also provides + * an easy way to test for singularity of the upper 3x3 component. + */ + Matrix perpectiveMatrix = self; + for (int i = 0; i < 3; i++) { + perpectiveMatrix.e[i][3] = 0; + } + + perpectiveMatrix.e[3][3] = 1; + + if (!perpectiveMatrix.IsInvertible()) { + return std::nullopt; + } + + MatrixDecomposition result; + + /* + * ========================================================================== + * First, isolate perspective. + * ========================================================================== + */ + if (self.e[0][3] != 0.0 || self.e[1][3] != 0.0 || self.e[2][3] != 0.0) { + /* + * prhs is the right hand side of the equation. + */ + const Vector4 rightHandSide(self.e[0][3], // + self.e[1][3], // + self.e[2][3], // + self.e[3][3]); + + /* + * Solve the equation by inverting `perspectiveMatrix` and multiplying + * prhs by the inverse. + */ + + result.perspective = perpectiveMatrix.Invert().Transpose() * rightHandSide; + + /* + * Clear the perspective partition. + */ + self.e[0][3] = self.e[1][3] = self.e[2][3] = 0; + self.e[3][3] = 1; + } + + /* + * ========================================================================== + * Next, the translation. + * ========================================================================== + */ + result.translation = {self.e[3][0], self.e[3][1], self.e[3][2]}; + self.e[3][0] = self.e[3][1] = self.e[3][2] = 0.0; + + /* + * ========================================================================== + * Next, the scale and shear. + * ========================================================================== + */ + Vector3 row[3]; + for (int i = 0; i < 3; i++) { + row[i].x = self.e[i][0]; + row[i].y = self.e[i][1]; + row[i].z = self.e[i][2]; + } + + /* + * Compute X scale factor and normalize first row. + */ + result.scale.x = row[0].GetLength(); + row[0] = row[0].Normalize(); + + /* + * Compute XY shear factor and make 2nd row orthogonal to 1st. + */ + result.shear.xy = row[0].Dot(row[1]); + row[1] = Vector3::Combine(row[1], 1.0, row[0], -result.shear.xy); + + /* + * Compute Y scale and normalize 2nd row. + */ + result.scale.y = row[1].GetLength(); + row[1] = row[1].Normalize(); + result.shear.xy /= result.scale.y; + + /* + * Compute XZ and YZ shears, orthogonalize 3rd row. + */ + result.shear.xz = row[0].Dot(row[2]); + row[2] = Vector3::Combine(row[2], 1.0, row[0], -result.shear.xz); + result.shear.yz = row[1].Dot(row[2]); + row[2] = Vector3::Combine(row[2], 1.0, row[1], -result.shear.yz); + + /* + * Next, get Z scale and normalize 3rd row. + */ + result.scale.z = row[2].GetLength(); + row[2] = row[2].Normalize(); + + result.shear.xz /= result.scale.z; + result.shear.yz /= result.scale.z; + + /* + * At this point, the matrix (in rows[]) is orthonormal. + * Check for a coordinate system flip. If the determinant + * is -1, then negate the matrix and the scaling factors. + */ + if (row[0].Dot(row[1].Cross(row[2])) < 0) { + result.scale.x *= -1; + result.scale.y *= -1; + result.scale.z *= -1; + + for (int i = 0; i < 3; i++) { + row[i].x *= -1; + row[i].y *= -1; + row[i].z *= -1; + } + } + + /* + * ========================================================================== + * Finally, get the rotations out. + * ========================================================================== + */ + result.rotation.x = + 0.5 * sqrt(fmax(1.0 + row[0].x - row[1].y - row[2].z, 0.0)); + result.rotation.y = + 0.5 * sqrt(fmax(1.0 - row[0].x + row[1].y - row[2].z, 0.0)); + result.rotation.z = + 0.5 * sqrt(fmax(1.0 - row[0].x - row[1].y + row[2].z, 0.0)); + result.rotation.w = + 0.5 * sqrt(fmax(1.0 + row[0].x + row[1].y + row[2].z, 0.0)); + + if (row[2].y > row[1].z) { + result.rotation.x = -result.rotation.x; + } + if (row[0].z > row[2].x) { + result.rotation.y = -result.rotation.y; + } + if (row[1].x > row[0].y) { + result.rotation.z = -result.rotation.z; + } + + return result; +} + +uint64_t MatrixDecomposition::GetComponentsMask() const { + uint64_t mask = 0; + + Quaternion noRotation(0.0, 0.0, 0.0, 1.0); + if (rotation != noRotation) { + mask = mask | static_cast(Component::kRotation); + } + + Vector4 defaultPerspective(0.0, 0.0, 0.0, 1.0); + if (perspective != defaultPerspective) { + mask = mask | static_cast(Component::kPerspective); + } + + Shear noShear(0.0, 0.0, 0.0); + if (shear != noShear) { + mask = mask | static_cast(Component::kShear); + } + + Vector3 defaultScale(1.0, 1.0, 1.0); + if (scale != defaultScale) { + mask = mask | static_cast(Component::kScale); + } + + Vector3 defaultTranslation(0.0, 0.0, 0.0); + if (translation != defaultTranslation) { + mask = mask | static_cast(Component::kTranslation); + } + + return mask; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/matrix.h b/flutter/engine/src/flutter/impeller/geometry/matrix.h new file mode 100644 index 0000000000000000000000000000000000000000..eb032b292ba0e37ca986f272491d0188d7a26df0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/matrix.h @@ -0,0 +1,675 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_MATRIX_H_ +#define FLUTTER_IMPELLER_GEOMETRY_MATRIX_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/geometry/matrix_decomposition.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/quaternion.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/shear.h" +#include "impeller/geometry/size.h" +#include "impeller/geometry/vector.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A 4x4 matrix using column-major storage. +/// +/// Utility methods that need to make assumptions about normalized +/// device coordinates must use the following convention: +/// * Left-handed coordinate system. Positive rotation is +/// clockwise about axis of rotation. +/// * Lower left corner is -1.0f, -1.0. +/// * Upper right corner is 1.0f, 1.0. +/// * Visible z-space is from 0.0 to 1.0. +/// * This is NOT the same as OpenGL! Be careful. +/// * NDC origin is at (0.0f, 0.0f, 0.5f). +struct Matrix { + union { + Scalar m[16]; + Scalar e[4][4]; + Vector4 vec[4]; + }; + + //---------------------------------------------------------------------------- + /// Constructs a default identity matrix. + /// + constexpr Matrix() + // clang-format off + : vec{ Vector4(1.0f, 0.0f, 0.0f, 0.0f), + Vector4(0.0f, 1.0f, 0.0f, 0.0f), + Vector4(0.0f, 0.0f, 1.0f, 0.0f), + Vector4(0.0f, 0.0f, 0.0f, 1.0f)} {} + // clang-format on + + // clang-format off + constexpr Matrix(Scalar m0, Scalar m1, Scalar m2, Scalar m3, + Scalar m4, Scalar m5, Scalar m6, Scalar m7, + Scalar m8, Scalar m9, Scalar m10, Scalar m11, + Scalar m12, Scalar m13, Scalar m14, Scalar m15) + : vec{Vector4(m0, m1, m2, m3), + Vector4(m4, m5, m6, m7), + Vector4(m8, m9, m10, m11), + Vector4(m12, m13, m14, m15)} {} + // clang-format on + + explicit Matrix(const MatrixDecomposition& decomposition); + + // clang-format off + static constexpr Matrix MakeColumn( + Scalar m0, Scalar m1, Scalar m2, Scalar m3, + Scalar m4, Scalar m5, Scalar m6, Scalar m7, + Scalar m8, Scalar m9, Scalar m10, Scalar m11, + Scalar m12, Scalar m13, Scalar m14, Scalar m15){ + return Matrix(m0, m1, m2, m3, + m4, m5, m6, m7, + m8, m9, m10, m11, + m12, m13, m14, m15); + + } + // clang-format on + + // clang-format off + static constexpr Matrix MakeRow( + Scalar m0, Scalar m1, Scalar m2, Scalar m3, + Scalar m4, Scalar m5, Scalar m6, Scalar m7, + Scalar m8, Scalar m9, Scalar m10, Scalar m11, + Scalar m12, Scalar m13, Scalar m14, Scalar m15){ + return Matrix(m0, m4, m8, m12, + m1, m5, m9, m13, + m2, m6, m10, m14, + m3, m7, m11, m15); + } + // clang-format on + + static constexpr Matrix MakeTranslation(const Vector3& t) { + // clang-format off + return Matrix(1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + t.x, t.y, t.z, 1.0f); + // clang-format on + } + + static constexpr Matrix MakeScale(const Vector3& s) { + // clang-format off + return Matrix(s.x, 0.0f, 0.0f, 0.0f, + 0.0f, s.y, 0.0f, 0.0f, + 0.0f, 0.0f, s.z, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + // clang-format on + } + + static constexpr Matrix MakeTranslateScale(const Vector3& s, + const Vector3& t) { + // clang-format off + return Matrix(s.x, 0.0f, 0.0f, 0.0f, + 0.0f, s.y, 0.0f, 0.0f, + 0.0f, 0.0f, s.z, 0.0f, + t.x , t.y, t.z, 1.0f); + // clang-format on + } + + static constexpr Matrix MakeScale(const Vector2& s) { + return MakeScale(Vector3(s.x, s.y, 1.0f)); + } + + static constexpr Matrix MakeSkew(Scalar sx, Scalar sy) { + // clang-format off + return Matrix(1.0f, sy , 0.0f, 0.0f, + sx , 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + // clang-format on + } + + static Matrix MakeRotation(Quaternion q) { + // clang-format off + return Matrix( + 1.0f - 2.0f * q.y * q.y - 2.0f * q.z * q.z, + 2.0f * q.x * q.y + 2.0f * q.z * q.w, + 2.0f * q.x * q.z - 2.0f * q.y * q.w, + 0.0f, + + 2.0f * q.x * q.y - 2.0f * q.z * q.w, + 1.0f - 2.0f * q.x * q.x - 2.0f * q.z * q.z, + 2.0f * q.y * q.z + 2.0f * q.x * q.w, + 0.0f, + + 2.0f * q.x * q.z + 2.0f * q.y * q.w, + 2.0f * q.y * q.z - 2.0f * q.x * q.w, + 1.0f - 2.0f * q.x * q.x - 2.0f * q.y * q.y, + 0.0f, + + 0.0f, + 0.0f, + 0.0f, + 1.0f); + // clang-format on + } + + static Matrix MakeRotation(Radians radians, const Vector4& r) { + const Vector4 v = r.Normalize(); + + const Vector2 cos_sin = CosSin(radians); + const Scalar cosine = cos_sin.x; + const Scalar cosp = 1.0f - cosine; + const Scalar sine = cos_sin.y; + + // clang-format off + return Matrix( + cosine + cosp * v.x * v.x, + cosp * v.x * v.y + v.z * sine, + cosp * v.x * v.z - v.y * sine, + 0.0f, + + cosp * v.x * v.y - v.z * sine, + cosine + cosp * v.y * v.y, + cosp * v.y * v.z + v.x * sine, + 0.0f, + + cosp * v.x * v.z + v.y * sine, + cosp * v.y * v.z - v.x * sine, + cosine + cosp * v.z * v.z, + 0.0f, + + 0.0f, + 0.0f, + 0.0f, + 1.0f); + // clang-format on + } + + static Matrix MakeRotationX(Radians r) { + const Vector2 cos_sin = CosSin(r); + const Scalar cosine = cos_sin.x; + const Scalar sine = cos_sin.y; + + // clang-format off + return Matrix( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, cosine, sine, 0.0f, + 0.0f, -sine, cosine, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + // clang-format on + } + + static Matrix MakeRotationY(Radians r) { + const Vector2 cos_sin = CosSin(r); + const Scalar cosine = cos_sin.x; + const Scalar sine = cos_sin.y; + + // clang-format off + return Matrix( + cosine, 0.0f, -sine, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + sine, 0.0f, cosine, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + // clang-format on + } + + static Matrix MakeRotationZ(Radians r) { + const Vector2 cos_sin = CosSin(r); + const Scalar cosine = cos_sin.x; + const Scalar sine = cos_sin.y; + + // clang-format off + return Matrix ( + cosine, sine, 0.0f, 0.0f, + -sine, cosine, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0 + ); + // clang-format on + } + + /// The Matrix without its `w` components (without translation). + constexpr Matrix Basis() const { + // clang-format off + return Matrix( + m[0], m[1], m[2], 0.0f, + m[4], m[5], m[6], 0.0f, + m[8], m[9], m[10], 0.0f, + 0.0f, 0.0f, 0.0f, 1.0 + ); + // clang-format on + } + + // Converts the second row/col to identity to make this an equivalent + // to a Skia 3x3 Matrix. + constexpr Matrix To3x3() const { + // clang-format off + return Matrix( + m[0], m[1], 0, m[3], + m[4], m[5], 0, m[7], + 0, 0, 1, 0, + m[12], m[13], 0, m[15] + ); + // clang-format on + } + + constexpr Matrix Translate(const Vector3& t) const { + // clang-format off + return Matrix(m[0], m[1], m[2], m[3], + m[4], m[5], m[6], m[7], + m[8], m[9], m[10], m[11], + m[0] * t.x + m[4] * t.y + m[8] * t.z + m[12], + m[1] * t.x + m[5] * t.y + m[9] * t.z + m[13], + m[2] * t.x + m[6] * t.y + m[10] * t.z + m[14], + m[3] * t.x + m[7] * t.y + m[11] * t.z + m[15]); + // clang-format on + } + + constexpr Matrix Scale(const Vector3& s) const { + // clang-format off + return Matrix(m[0] * s.x, m[1] * s.x, m[2] * s.x, m[3] * s.x, + m[4] * s.y, m[5] * s.y, m[6] * s.y, m[7] * s.y, + m[8] * s.z, m[9] * s.z, m[10] * s.z, m[11] * s.z, + m[12] , m[13] , m[14] , m[15] ); + // clang-format on + } + + constexpr Matrix Multiply(const Matrix& o) const { + // clang-format off + return Matrix( + m[0] * o.m[0] + m[4] * o.m[1] + m[8] * o.m[2] + m[12] * o.m[3], + m[1] * o.m[0] + m[5] * o.m[1] + m[9] * o.m[2] + m[13] * o.m[3], + m[2] * o.m[0] + m[6] * o.m[1] + m[10] * o.m[2] + m[14] * o.m[3], + m[3] * o.m[0] + m[7] * o.m[1] + m[11] * o.m[2] + m[15] * o.m[3], + m[0] * o.m[4] + m[4] * o.m[5] + m[8] * o.m[6] + m[12] * o.m[7], + m[1] * o.m[4] + m[5] * o.m[5] + m[9] * o.m[6] + m[13] * o.m[7], + m[2] * o.m[4] + m[6] * o.m[5] + m[10] * o.m[6] + m[14] * o.m[7], + m[3] * o.m[4] + m[7] * o.m[5] + m[11] * o.m[6] + m[15] * o.m[7], + m[0] * o.m[8] + m[4] * o.m[9] + m[8] * o.m[10] + m[12] * o.m[11], + m[1] * o.m[8] + m[5] * o.m[9] + m[9] * o.m[10] + m[13] * o.m[11], + m[2] * o.m[8] + m[6] * o.m[9] + m[10] * o.m[10] + m[14] * o.m[11], + m[3] * o.m[8] + m[7] * o.m[9] + m[11] * o.m[10] + m[15] * o.m[11], + m[0] * o.m[12] + m[4] * o.m[13] + m[8] * o.m[14] + m[12] * o.m[15], + m[1] * o.m[12] + m[5] * o.m[13] + m[9] * o.m[14] + m[13] * o.m[15], + m[2] * o.m[12] + m[6] * o.m[13] + m[10] * o.m[14] + m[14] * o.m[15], + m[3] * o.m[12] + m[7] * o.m[13] + m[11] * o.m[14] + m[15] * o.m[15]); + // clang-format on + } + + constexpr Matrix Transpose() const { + // clang-format off + return { + m[0], m[4], m[8], m[12], + m[1], m[5], m[9], m[13], + m[2], m[6], m[10], m[14], + m[3], m[7], m[11], m[15], + }; + // clang-format on + } + + Matrix Invert() const; + + Scalar GetDeterminant() const; + + bool IsInvertible() const { return GetDeterminant() != 0; } + + constexpr Scalar GetMaxBasisLengthXY() const { + // The full basis computation requires computing the squared scaling factor + // for translate/scale only matrices. This substantially limits the range of + // precision for small and large scales. Instead, check for the common cases + // and directly return the max scaling factor. + if (e[0][1] == 0 && e[1][0] == 0) { + return std::max(std::abs(e[0][0]), std::abs(e[1][1])); + } + return std::sqrt(std::max(e[0][0] * e[0][0] + e[0][1] * e[0][1], + e[1][0] * e[1][0] + e[1][1] * e[1][1])); + } + + constexpr Vector3 GetBasisX() const { return Vector3(m[0], m[1], m[2]); } + + constexpr Vector3 GetBasisY() const { return Vector3(m[4], m[5], m[6]); } + + constexpr Vector3 GetBasisZ() const { return Vector3(m[8], m[9], m[10]); } + + constexpr Vector3 GetScale() const { + return Vector3(GetBasisX().GetLength(), GetBasisY().GetLength(), + GetBasisZ().GetLength()); + } + + constexpr Scalar GetDirectionScale(Vector3 direction) const { + return 1.0f / (this->Basis().Invert() * direction.Normalize()).GetLength() * + direction.GetLength(); + } + + constexpr bool IsFinite() const { + return vec[0].IsFinite() && vec[1].IsFinite() && vec[2].IsFinite() && + vec[3].IsFinite(); + } + + constexpr bool IsAffine() const { + return (m[2] == 0 && m[3] == 0 && m[6] == 0 && m[7] == 0 && m[8] == 0 && + m[9] == 0 && m[10] == 1 && m[11] == 0 && m[14] == 0 && m[15] == 1); + } + + constexpr bool HasPerspective2D() const { + return m[3] != 0 || m[7] != 0 || m[15] != 1; + } + + constexpr bool HasPerspective() const { + return m[3] != 0 || m[7] != 0 || m[11] != 0 || m[15] != 1; + } + + constexpr bool HasTranslation() const { return m[12] != 0 || m[13] != 0; } + + constexpr bool IsAligned2D(Scalar tolerance = 0) const { + if (HasPerspective2D()) { + return false; + } + if (ScalarNearlyZero(m[1], tolerance) && + ScalarNearlyZero(m[4], tolerance)) { + return true; + } + if (ScalarNearlyZero(m[0], tolerance) && + ScalarNearlyZero(m[5], tolerance)) { + return true; + } + return false; + } + + constexpr bool IsAligned(Scalar tolerance = 0) const { + if (HasPerspective()) { + return false; + } + int v[] = {!ScalarNearlyZero(m[0], tolerance), // + !ScalarNearlyZero(m[1], tolerance), // + !ScalarNearlyZero(m[2], tolerance), // + !ScalarNearlyZero(m[4], tolerance), // + !ScalarNearlyZero(m[5], tolerance), // + !ScalarNearlyZero(m[6], tolerance), // + !ScalarNearlyZero(m[8], tolerance), // + !ScalarNearlyZero(m[9], tolerance), // + !ScalarNearlyZero(m[10], tolerance)}; + // Check if all three basis vectors are aligned to an axis. + if (v[0] + v[1] + v[2] != 1 || // + v[3] + v[4] + v[5] != 1 || // + v[6] + v[7] + v[8] != 1) { + return false; + } + // Ensure that none of the basis vectors overlap. + if (v[0] + v[3] + v[6] != 1 || // + v[1] + v[4] + v[7] != 1 || // + v[2] + v[5] + v[8] != 1) { + return false; + } + return true; + } + + constexpr bool IsIdentity() const { + return ( + // clang-format off + m[0] == 1.0f && m[1] == 0.0f && m[2] == 0.0f && m[3] == 0.0f && + m[4] == 0.0f && m[5] == 1.0f && m[6] == 0.0f && m[7] == 0.0f && + m[8] == 0.0f && m[9] == 0.0f && m[10] == 1.0f && m[11] == 0.0f && + m[12] == 0.0f && m[13] == 0.0f && m[14] == 0.0f && m[15] == 1.0f + // clang-format on + ); + } + + /// @brief Returns true if the matrix has no entries other than translation + /// components. Note that an identity matrix meets this criteria. + constexpr bool IsTranslationOnly() const { + return ( + // clang-format off + m[0] == 1.0 && m[1] == 0.0 && m[2] == 0.0 && m[3] == 0.0 && + m[4] == 0.0 && m[5] == 1.0 && m[6] == 0.0 && m[7] == 0.0 && + m[8] == 0.0 && m[9] == 0.0 && m[10] == 1.0 && m[11] == 0.0 && + m[15] == 1.0 + // clang-format on + ); + } + + /// @brief Returns true if the matrix has a scale-only basis and is + /// non-projective. Note that an identity matrix meets this criteria. + constexpr bool IsTranslationScaleOnly() const { + return ( + // clang-format off + m[0] != 0.0 && m[1] == 0.0 && m[2] == 0.0 && m[3] == 0.0 && + m[4] == 0.0 && m[5] != 0.0 && m[6] == 0.0 && m[7] == 0.0 && + m[8] == 0.0 && m[9] == 0.0 && m[10] != 0.0 && m[11] == 0.0 && + m[15] == 1.0 + // clang-format on + ); + } + + std::optional Decompose() const; + + bool Equals(const Matrix& matrix, Scalar epsilon = 1e-5f) const { + const Scalar* a = m; + const Scalar* b = matrix.m; + return ScalarNearlyEqual(a[0], b[0], epsilon) && + ScalarNearlyEqual(a[1], b[1], epsilon) && + ScalarNearlyEqual(a[2], b[2], epsilon) && + ScalarNearlyEqual(a[3], b[3], epsilon) && + ScalarNearlyEqual(a[4], b[4], epsilon) && + ScalarNearlyEqual(a[5], b[5], epsilon) && + ScalarNearlyEqual(a[6], b[6], epsilon) && + ScalarNearlyEqual(a[7], b[7], epsilon) && + ScalarNearlyEqual(a[8], b[8], epsilon) && + ScalarNearlyEqual(a[9], b[9], epsilon) && + ScalarNearlyEqual(a[10], b[10], epsilon) && + ScalarNearlyEqual(a[11], b[11], epsilon) && + ScalarNearlyEqual(a[12], b[12], epsilon) && + ScalarNearlyEqual(a[13], b[13], epsilon) && + ScalarNearlyEqual(a[14], b[14], epsilon) && + ScalarNearlyEqual(a[15], b[15], epsilon); + } + + constexpr bool operator==(const Matrix& m) const { + // clang-format off + return vec[0] == m.vec[0] + && vec[1] == m.vec[1] + && vec[2] == m.vec[2] + && vec[3] == m.vec[3]; + // clang-format on + } + + constexpr bool operator!=(const Matrix& m) const { + // clang-format off + return vec[0] != m.vec[0] + || vec[1] != m.vec[1] + || vec[2] != m.vec[2] + || vec[3] != m.vec[3]; + // clang-format on + } + + Matrix operator+(const Vector3& t) const { return Translate(t); } + + Matrix operator-(const Vector3& t) const { return Translate(-t); } + + Matrix operator*(const Matrix& m) const { return Multiply(m); } + + Matrix operator+(const Matrix& m) const; + + constexpr Vector4 operator*(const Vector4& v) const { + return Vector4(v.x * m[0] + v.y * m[4] + v.z * m[8] + v.w * m[12], + v.x * m[1] + v.y * m[5] + v.z * m[9] + v.w * m[13], + v.x * m[2] + v.y * m[6] + v.z * m[10] + v.w * m[14], + v.x * m[3] + v.y * m[7] + v.z * m[11] + v.w * m[15]); + } + + constexpr Vector3 operator*(const Vector3& v) const { + Scalar w = v.x * m[3] + v.y * m[7] + v.z * m[11] + m[15]; + Vector3 result(v.x * m[0] + v.y * m[4] + v.z * m[8] + m[12], + v.x * m[1] + v.y * m[5] + v.z * m[9] + m[13], + v.x * m[2] + v.y * m[6] + v.z * m[10] + m[14]); + + // This is Skia's behavior, but it may be reasonable to allow UB for the w=0 + // case. + if (w) { + w = 1 / w; + } + return result * w; + } + + constexpr Point operator*(const Point& v) const { + Scalar w = v.x * m[3] + v.y * m[7] + m[15]; + Point result(v.x * m[0] + v.y * m[4] + m[12], + v.x * m[1] + v.y * m[5] + m[13]); + + // This is Skia's behavior, but it may be reasonable to allow UB for the w=0 + // case. + if (w) { + w = 1 / w; + } + return result * w; + } + + constexpr Vector3 TransformHomogenous(const Point& v) const { + return Vector3(v.x * m[0] + v.y * m[4] + m[12], + v.x * m[1] + v.y * m[5] + m[13], + v.x * m[3] + v.y * m[7] + m[15]); + } + + constexpr Vector4 TransformDirection(const Vector4& v) const { + return Vector4(v.x * m[0] + v.y * m[4] + v.z * m[8], + v.x * m[1] + v.y * m[5] + v.z * m[9], + v.x * m[2] + v.y * m[6] + v.z * m[10], v.w); + } + + constexpr Vector3 TransformDirection(const Vector3& v) const { + return Vector3(v.x * m[0] + v.y * m[4] + v.z * m[8], + v.x * m[1] + v.y * m[5] + v.z * m[9], + v.x * m[2] + v.y * m[6] + v.z * m[10]); + } + + constexpr Vector2 TransformDirection(const Vector2& v) const { + return Vector2(v.x * m[0] + v.y * m[4], v.x * m[1] + v.y * m[5]); + } + + constexpr Quad Transform(const Quad& quad) const { + return { + *this * quad[0], + *this * quad[1], + *this * quad[2], + *this * quad[3], + }; + } + + template + static constexpr Matrix MakeOrthographic(TSize size) { + // Per assumptions about NDC documented above. + const auto scale = + MakeScale({2.0f / static_cast(size.width), + -2.0f / static_cast(size.height), 0.0f}); + const auto translate = MakeTranslation({-1.0f, 1.0f, 0.5f}); + return translate * scale; + } + + static constexpr Matrix MakePerspective(Radians fov_y, + Scalar aspect_ratio, + Scalar z_near, + Scalar z_far) { + Scalar height = std::tan(fov_y.radians * 0.5f); + Scalar width = height * aspect_ratio; + + // clang-format off + return { + 1.0f / width, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f / height, 0.0f, 0.0f, + 0.0f, 0.0f, z_far / (z_far - z_near), 1.0f, + 0.0f, 0.0f, -(z_far * z_near) / (z_far - z_near), 0.0f, + }; + // clang-format on + } + + template + static constexpr Matrix MakePerspective(Radians fov_y, + TSize size, + Scalar z_near, + Scalar z_far) { + return MakePerspective(fov_y, static_cast(size.width) / size.height, + z_near, z_far); + } + + static constexpr Matrix MakeLookAt(Vector3 position, + Vector3 target, + Vector3 up) { + Vector3 forward = (target - position).Normalize(); + Vector3 right = up.Cross(forward); + up = forward.Cross(right); + + // clang-format off + return { + right.x, up.x, forward.x, 0.0f, + right.y, up.y, forward.y, 0.0f, + right.z, up.z, forward.z, 0.0f, + -right.Dot(position), -up.Dot(position), -forward.Dot(position), 1.0f + }; + // clang-format on + } + + static constexpr Vector2 CosSin(Radians radians) { + // The precision of a float around 1.0 is much lower than it is + // around 0.0, so we end up with cases on quadrant rotations where + // we get a +/-1.0 for one of the values and a non-zero value for + // the other. This happens around quadrant rotations which makes it + // especially common and results in unclean quadrant rotation + // matrices which do not return true from |IsAligned[2D]| even + // though that is exactly where you need them to exhibit that property. + // It also injects small floating point mantissa errors into the + // matrices whenever you concatenate them with a quadrant rotation. + // + // This issue is also exacerbated by the fact that, in radians, the + // angles for quadrant rotations are irrational numbers. The measuring + // error for representing 90 degree multiples is small enough that + // either sin or cos will return a value near +/-1.0, but not small + // enough that the other value will be a clean 0.0. + // + // Some geometry packages simply discard very small numbers from + // sin/cos, but the following approach specifically targets just the + // area around a quadrant rotation (where either the sin or cos are + // measuring as +/-1.0) for symmetry of precision. + + Scalar sin = std::sin(radians.radians); + if (std::abs(sin) == 1.0f) { + // 90 or 270 degrees (mod 360) + return {0.0f, sin}; + } else { + Scalar cos = std::cos(radians.radians); + if (std::abs(cos) == 1.0f) { + // 0 or 180 degrees (mod 360) + return {cos, 0.0f}; + } + return {cos, sin}; + } + } +}; + +static_assert(sizeof(struct Matrix) == sizeof(Scalar) * 16, + "The matrix must be of consistent size."); + +} // namespace impeller + +namespace std { +inline std::ostream& operator<<(std::ostream& out, const impeller::Matrix& m) { + out << "(" << std::endl << std::fixed; + for (size_t i = 0; i < 4u; i++) { + for (size_t j = 0; j < 4u; j++) { + out << std::setw(15) << m.e[j][i] << ","; + } + out << std::endl; + } + out << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_MATRIX_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.cc b/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.cc new file mode 100644 index 0000000000000000000000000000000000000000..a945345b30a369cb0e29f1cfb299e617bfc4235a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/matrix_decomposition.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.h b/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.h new file mode 100644 index 0000000000000000000000000000000000000000..a5b6592f26149272e41815e6bf49e9c1d84b6fc0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/matrix_decomposition.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_MATRIX_DECOMPOSITION_H_ +#define FLUTTER_IMPELLER_GEOMETRY_MATRIX_DECOMPOSITION_H_ + +#include "impeller/geometry/quaternion.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/shear.h" +#include "impeller/geometry/vector.h" + +namespace impeller { + +struct MatrixDecomposition { + Vector3 translation; + Vector3 scale; + Shear shear; + Vector4 perspective; + Quaternion rotation; + + enum class Component { + kTranslation = 1 << 0, + kScale = 1 << 1, + kShear = 1 << 2, + kPerspective = 1 << 3, + kRotation = 1 << 4, + }; + + uint64_t GetComponentsMask() const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_MATRIX_DECOMPOSITION_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/matrix_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/matrix_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..719affb438b8c25f7bd00619aba59425c2cef58d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/matrix_unittests.cc @@ -0,0 +1,326 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/matrix.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" +#include "impeller/geometry/constants.h" + +namespace impeller { +namespace testing { + +TEST(MatrixTest, Multiply) { + Matrix x(0.0, 0.0, 0.0, 1.0, // + 1.0, 0.0, 0.0, 1.0, // + 0.0, 1.0, 0.0, 1.0, // + 1.0, 1.0, 0.0, 1.0); + Matrix translate = Matrix::MakeTranslation({10, 20, 0}); + Matrix result = translate * x; + EXPECT_TRUE(MatrixNear(result, Matrix(10.0, 20.0, 0.0, 1.0, // + 11.0, 20.0, 0.0, 1.0, // + 10.0, 21.0, 0.0, 1.0, // + 11.0, 21.0, 0.0, 1.0))); +} + +TEST(MatrixTest, Equals) { + Matrix x; + Matrix y = x; + EXPECT_TRUE(x.Equals(y)); +} + +TEST(MatrixTest, NotEquals) { + Matrix x; + Matrix y = x.Translate({1, 0, 0}); + EXPECT_FALSE(x.Equals(y)); +} + +TEST(MatrixTest, HasPerspective2D) { + EXPECT_FALSE(Matrix().HasPerspective2D()); + + auto test = [](int index, bool expect) { + Matrix matrix; + EXPECT_FALSE(matrix.HasPerspective2D()); + matrix.m[index] = 0.5f; + EXPECT_EQ(matrix.HasPerspective2D(), expect) << "index: " << index; + }; + + // clang-format off + test( 0, false); test( 1, false); test( 2, false); test( 3, true); + test( 4, false); test( 5, false); test( 6, false); test( 7, true); + test( 8, false); test( 9, false); test(10, false); test(11, false); + test(12, false); test(13, false); test(14, false); test(15, true); + // clang-format on +} + +TEST(MatrixTest, HasPerspective) { + EXPECT_FALSE(Matrix().HasPerspective()); + + auto test = [](int index, bool expect) { + Matrix matrix; + EXPECT_FALSE(matrix.HasPerspective()); + matrix.m[index] = 0.5f; + EXPECT_EQ(matrix.HasPerspective(), expect) << "index: " << index; + }; + + // clang-format off + test( 0, false); test( 1, false); test( 2, false); test( 3, true); + test( 4, false); test( 5, false); test( 6, false); test( 7, true); + test( 8, false); test( 9, false); test(10, false); test(11, true); + test(12, false); test(13, false); test(14, false); test(15, true); + // clang-format on +} + +TEST(MatrixTest, HasTranslation) { + EXPECT_TRUE(Matrix::MakeTranslation({100, 100, 0}).HasTranslation()); + EXPECT_TRUE(Matrix::MakeTranslation({0, 100, 0}).HasTranslation()); + EXPECT_TRUE(Matrix::MakeTranslation({100, 0, 0}).HasTranslation()); + EXPECT_FALSE(Matrix().HasTranslation()); +} + +TEST(MatrixTest, IsTranslationOnly) { + EXPECT_TRUE(Matrix::MakeTranslation({100, 100, 0}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeTranslation({100, 100, 0}).IsTranslationScaleOnly()); + EXPECT_TRUE(Matrix::MakeTranslation({0, 100, 0}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeTranslation({0, 100, 0}).IsTranslationScaleOnly()); + EXPECT_TRUE(Matrix::MakeTranslation({100, 0, 0}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeTranslation({100, 0, 0}).IsTranslationScaleOnly()); + EXPECT_TRUE(Matrix().IsTranslationOnly()); + EXPECT_TRUE(Matrix().IsTranslationScaleOnly()); +} + +TEST(MatrixTest, IsTranslationScaleOnly) { + EXPECT_FALSE(Matrix::MakeScale({100, 100, 1}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeScale({100, 100, 1}).IsTranslationScaleOnly()); + EXPECT_FALSE(Matrix::MakeScale({1, 100, 1}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeScale({1, 100, 1}).IsTranslationScaleOnly()); + EXPECT_FALSE(Matrix::MakeScale({100, 1, 1}).IsTranslationOnly()); + EXPECT_TRUE(Matrix::MakeScale({100, 1, 1}).IsTranslationScaleOnly()); + EXPECT_TRUE(Matrix().IsTranslationOnly()); + EXPECT_TRUE(Matrix().IsTranslationScaleOnly()); +} + +TEST(MatrixTest, IsInvertibleGetDeterminant) { + EXPECT_TRUE(Matrix().IsInvertible()); + EXPECT_NE(Matrix().GetDeterminant(), 0.0f); + + EXPECT_TRUE(Matrix::MakeTranslation({100, 100, 0}).IsInvertible()); + EXPECT_NE(Matrix::MakeTranslation({100, 100, 0}).GetDeterminant(), 0.0f); + + EXPECT_TRUE(Matrix::MakeScale({100, 100, 1}).IsInvertible()); + EXPECT_NE(Matrix::MakeScale({100, 100, 1}).GetDeterminant(), 0.0f); + + EXPECT_TRUE(Matrix::MakeRotationX(Degrees(30)).IsInvertible()); + EXPECT_NE(Matrix::MakeRotationX(Degrees(30)).GetDeterminant(), 0.0f); + + EXPECT_TRUE(Matrix::MakeRotationY(Degrees(30)).IsInvertible()); + EXPECT_NE(Matrix::MakeRotationY(Degrees(30)).GetDeterminant(), 0.0f); + + EXPECT_TRUE(Matrix::MakeRotationZ(Degrees(30)).IsInvertible()); + EXPECT_NE(Matrix::MakeRotationZ(Degrees(30)).GetDeterminant(), 0.0f); + + EXPECT_FALSE(Matrix::MakeScale({0, 1, 1}).IsInvertible()); + EXPECT_EQ(Matrix::MakeScale({0, 1, 1}).GetDeterminant(), 0.0f); + EXPECT_FALSE(Matrix::MakeScale({1, 0, 1}).IsInvertible()); + EXPECT_EQ(Matrix::MakeScale({1, 0, 1}).GetDeterminant(), 0.0f); + EXPECT_FALSE(Matrix::MakeScale({1, 1, 0}).IsInvertible()); + EXPECT_EQ(Matrix::MakeScale({1, 1, 0}).GetDeterminant(), 0.0f); +} + +TEST(MatrixTest, IsFinite) { + EXPECT_TRUE(Matrix().IsFinite()); + + EXPECT_TRUE(Matrix::MakeTranslation({100, 100, 0}).IsFinite()); + EXPECT_TRUE(Matrix::MakeScale({100, 100, 1}).IsFinite()); + + EXPECT_TRUE(Matrix::MakeRotationX(Degrees(30)).IsFinite()); + EXPECT_TRUE(Matrix::MakeRotationY(Degrees(30)).IsFinite()); + EXPECT_TRUE(Matrix::MakeRotationZ(Degrees(30)).IsFinite()); + + EXPECT_TRUE(Matrix::MakeScale({0, 1, 1}).IsFinite()); + EXPECT_TRUE(Matrix::MakeScale({1, 0, 1}).IsFinite()); + EXPECT_TRUE(Matrix::MakeScale({1, 1, 0}).IsFinite()); + + for (int i = 0; i < 16; i++) { + { + Matrix matrix; + ASSERT_TRUE(matrix.IsFinite()); + matrix.m[i] = std::numeric_limits::infinity(); + ASSERT_FALSE(matrix.IsFinite()); + } + + { + Matrix matrix; + ASSERT_TRUE(matrix.IsFinite()); + matrix.m[i] = -std::numeric_limits::infinity(); + ASSERT_FALSE(matrix.IsFinite()); + } + + { + Matrix matrix; + ASSERT_TRUE(matrix.IsFinite()); + matrix.m[i] = -std::numeric_limits::quiet_NaN(); + ASSERT_FALSE(matrix.IsFinite()); + } + } +} + +TEST(MatrixTest, IsAligned2D) { + EXPECT_TRUE(Matrix().IsAligned2D()); + EXPECT_TRUE(Matrix::MakeScale({1.0f, 1.0f, 2.0f}).IsAligned2D()); + + auto test = [](int index, bool expect) { + Matrix matrix; + EXPECT_TRUE(matrix.IsAligned2D()); + matrix.m[index] = 0.5f; + EXPECT_EQ(matrix.IsAligned2D(), expect) << "index: " << index; + }; + + // clang-format off + test( 0, true); test( 1, false); test( 2, true); test( 3, false); + test( 4, false); test( 5, true); test( 6, true); test( 7, false); + test( 8, true); test( 9, true); test(10, true); test(11, true); + test(12, true); test(13, true); test(14, true); test(15, false); + // clang-format on + + // True for quadrant rotations from -250 to +250 full circles + for (int i = -1000; i < 1000; i++) { + Degrees d = Degrees(i * 90); + Matrix matrix = Matrix::MakeRotationZ(Degrees(d)); + EXPECT_TRUE(matrix.IsAligned2D()) << "degrees: " << d.degrees; + } + + // False for half degree rotations from -999.5 to +1000.5 degrees + for (int i = -1000; i < 1000; i++) { + Degrees d = Degrees(i + 0.5f); + Matrix matrix = Matrix::MakeRotationZ(Degrees(d)); + EXPECT_FALSE(matrix.IsAligned2D()) << "degrees: " << d.degrees; + } +} + +TEST(MatrixTest, IsAligned) { + EXPECT_TRUE(Matrix().IsAligned()); + EXPECT_TRUE(Matrix::MakeScale({1.0f, 1.0f, 2.0f}).IsAligned()); + + // Begin Legacy tests transferred over from geometry_unittests.cc + { + auto m = Matrix::MakeTranslation({1, 2, 3}); + bool result = m.IsAligned(); + ASSERT_TRUE(result); + } + + { + auto m = Matrix::MakeRotationZ(Degrees{123}); + bool result = m.IsAligned(); + ASSERT_FALSE(result); + } + // End Legacy tests transferred over from geometry_unittests.cc + + auto test = [](int index, bool expect) { + Matrix matrix; + EXPECT_TRUE(matrix.IsAligned()); + matrix.m[index] = 0.5f; + EXPECT_EQ(matrix.IsAligned(), expect) << "index: " << index; + }; + + // clang-format off + test( 0, true); test( 1, false); test( 2, false); test( 3, false); + test( 4, false); test( 5, true); test( 6, false); test( 7, false); + test( 8, false); test( 9, false); test(10, true); test(11, false); + test(12, true); test(13, true); test(14, true); test(15, false); + // clang-format on + + // True for quadrant rotations from -250 to +250 full circles + for (int i = -1000; i < 1000; i++) { + Degrees d = Degrees(i * 90); + Matrix matrix = Matrix::MakeRotationZ(Degrees(d)); + EXPECT_TRUE(matrix.IsAligned()) << "degrees: " << d.degrees; + } + + // False for half degree rotations from -999.5 to +1000.5 degrees + for (int i = -1000; i < 1000; i++) { + Degrees d = Degrees(i + 0.5f); + Matrix matrix = Matrix::MakeRotationZ(Degrees(d)); + EXPECT_FALSE(matrix.IsAligned()) << "degrees: " << d.degrees; + } +} + +TEST(MatrixTest, TransformHomogenous) { + Matrix matrix = Matrix::MakeColumn( + // clang-format off + 2.0f, 3.0f, 5.0f, 7.0f, + 11.0f, 13.0f, 17.0f, 19.0f, + 23.0f, 29.0f, 31.0f, 37.0f, + 41.0f, 43.0f, 47.0f, 53.0f + // clang-format on + ); + EXPECT_EQ(matrix.TransformHomogenous({1.0f, -1.0f}), + Vector3(32.0f, 33.0f, 41.0f)); +} + +TEST(MatrixTest, GetMaxBasisXYNegativeScale) { + Matrix m = Matrix::MakeScale({-2, 1, 1}); + + EXPECT_EQ(m.GetMaxBasisLengthXY(), 2); + + m = Matrix::MakeScale({1, -3, 1}); + + EXPECT_EQ(m.GetMaxBasisLengthXY(), 3); +} + +// Verifies a translate scale matrix doesn't need to compute sqrt(pow(scale, 2)) +TEST(MatrixTest, GetMaxBasisXYWithLargeAndSmallScalingFactor) { + Matrix m = Matrix::MakeScale({2.625e+20, 2.625e+20, 1}); + EXPECT_NEAR(m.GetMaxBasisLengthXY(), 2.625e+20, 1e+20); + + m = Matrix::MakeScale({2.625e-20, 2.625e-20, 1}); + EXPECT_NEAR(m.GetMaxBasisLengthXY(), 2.625e-20, 1e-20); +} + +TEST(MatrixTest, GetMaxBasisXYWithLargeAndSmallScalingFactorNonScaleTranslate) { + Matrix m = Matrix::MakeScale({2.625e+20, 2.625e+20, 1}); + m.e[0][1] = 2; + + EXPECT_TRUE(std::isinf(m.GetMaxBasisLengthXY())); +} + +TEST(MatrixTest, TranslateWithPerspective) { + Matrix m = Matrix::MakeRow(1.0, 0.0, 0.0, 10.0, // + 0.0, 1.0, 0.0, 20.0, // + 0.0, 0.0, 1.0, 0.0, // + 0.0, 2.0, 0.0, 30.0); + Matrix result = m.Translate({100, 200}); + EXPECT_TRUE(MatrixNear(result, Matrix::MakeRow(1.0, 0.0, 0.0, 110.0, // + 0.0, 1.0, 0.0, 220.0, // + 0.0, 0.0, 1.0, 0.0, // + 0.0, 2.0, 0.0, 430.0))); +} + +TEST(MatrixTest, MakeScaleTranslate) { + EXPECT_TRUE(MatrixNear( + Matrix::MakeTranslateScale({1, 1, 1.0 / 1024}, {10, 10, 1.0 / 1024}), + Matrix::MakeTranslation({10, 10, 1.0 / 1024}) * + Matrix::MakeScale({1, 1, 1.0 / 1024}))); + + EXPECT_TRUE(MatrixNear( + Matrix::MakeTranslateScale({2, 2, 2}, {10, 10, 0}), + Matrix::MakeTranslation({10, 10, 0}) * Matrix::MakeScale({2, 2, 2}))); + + EXPECT_TRUE(MatrixNear( + Matrix::MakeTranslateScale({0, 0, 0}, {0, 0, 0}), + Matrix::MakeTranslation({0, 0, 0}) * Matrix::MakeScale({0, 0, 0}))); +} + +TEST(MatrixTest, To3x3) { + Matrix x(1.0, 0.0, 4.0, 0.0, // + 0.0, 1.0, 4.0, 0.0, // + 6.0, 5.0, 111.0, 7.0, // + 0.0, 0.0, 9.0, 1.0); + + EXPECT_TRUE(MatrixNear(x.To3x3(), Matrix())); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/path.cc b/flutter/engine/src/flutter/impeller/geometry/path.cc new file mode 100644 index 0000000000000000000000000000000000000000..35539c543b7f1f2cade5c590849aa86a330be244 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path.cc @@ -0,0 +1,479 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/path.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/point.h" + +namespace impeller { + +Path::Path() : data_(new Data()) {} + +Path::Path(Data data) : data_(std::make_shared(std::move(data))) {} + +Path::~Path() = default; + +Path::ComponentType Path::ComponentIterator::type() const { + return path_.data_->components[component_index_]; +} + +#define CHECK_COMPONENT(type) \ + (component_index_ < path_.data_->components.size() && \ + path_.data_->components[component_index_] == type && \ + storage_offset_ + VerbToOffset(type) <= path_.data_->points.size()) + +const LinearPathComponent* Path::ComponentIterator::linear() const { + if (!CHECK_COMPONENT(Path::ComponentType::kLinear)) { + return nullptr; + } + const Point* points = &(path_.data_->points[storage_offset_]); + return reinterpret_cast(points); +} + +const QuadraticPathComponent* Path::ComponentIterator::quadratic() const { + if (!CHECK_COMPONENT(Path::ComponentType::kQuadratic)) { + return nullptr; + } + const Point* points = &(path_.data_->points[storage_offset_]); + return reinterpret_cast(points); +} + +const ConicPathComponent* Path::ComponentIterator::conic() const { + if (!CHECK_COMPONENT(Path::ComponentType::kConic)) { + return nullptr; + } + const Point* points = &(path_.data_->points[storage_offset_]); + return reinterpret_cast(points); +} + +const CubicPathComponent* Path::ComponentIterator::cubic() const { + if (!CHECK_COMPONENT(Path::ComponentType::kCubic)) { + return nullptr; + } + const Point* points = &(path_.data_->points[storage_offset_]); + return reinterpret_cast(points); +} + +const ContourComponent* Path::ComponentIterator::contour() const { + if (!CHECK_COMPONENT(Path::ComponentType::kContour)) { + return nullptr; + } + const Point* points = &(path_.data_->points[storage_offset_]); + return reinterpret_cast(points); +} + +Path::ComponentIterator& Path::ComponentIterator::operator++() { + auto components = path_.data_->components; + if (component_index_ < components.size()) { + storage_offset_ += VerbToOffset(path_.data_->components[component_index_]); + component_index_++; + } + return *this; +} + +std::tuple Path::Polyline::GetContourPointBounds( + size_t contour_index) const { + if (contour_index >= contours.size()) { + return {points->size(), points->size()}; + } + const size_t start_index = contours.at(contour_index).start_index; + const size_t end_index = (contour_index >= contours.size() - 1) + ? points->size() + : contours.at(contour_index + 1).start_index; + return std::make_tuple(start_index, end_index); +} + +size_t Path::GetComponentCount(std::optional type) const { + if (!type.has_value()) { + return data_->components.size(); + } + auto type_value = type.value(); + size_t count = 0u; + for (const auto& component : data_->components) { + if (component == type_value) { + count++; + } + } + return count; +} + +size_t Path::GetPointCount() const { + return data_->points.size(); +} + +FillType Path::GetFillType() const { + return data_->fill; +} + +bool Path::IsConvex() const { + return data_->convexity == Convexity::kConvex; +} + +bool Path::IsEmpty() const { + return data_->points.empty() || + (data_->components.size() == 1 && + data_->components[0] == ComponentType::kContour); +} + +bool Path::IsSingleContour() const { + return data_->single_contour; +} + +/// Determine required storage for points and indices. +std::pair Path::CountStorage(Scalar scale) const { + size_t points = 0; + size_t contours = 0; + + auto& path_components = data_->components; + auto& path_points = data_->points; + + size_t storage_offset = 0u; + for (size_t component_i = 0; component_i < path_components.size(); + component_i++) { + const auto& path_component = path_components[component_i]; + switch (path_component) { + case ComponentType::kLinear: { + points += 2; + break; + } + case ComponentType::kQuadratic: { + const QuadraticPathComponent* quad = + reinterpret_cast( + &path_points[storage_offset]); + points += quad->CountLinearPathComponents(scale); + break; + } + case ComponentType::kConic: { + const ConicPathComponent* conic = + reinterpret_cast( + &path_points[storage_offset]); + points += conic->CountLinearPathComponents(scale); + break; + } + case ComponentType::kCubic: { + const CubicPathComponent* cubic = + reinterpret_cast( + &path_points[storage_offset]); + points += cubic->CountLinearPathComponents(scale); + break; + } + case Path::ComponentType::kContour: + contours++; + } + storage_offset += VerbToOffset(path_component); + } + return std::make_pair(points, contours); +} + +void Path::WritePolyline(Scalar scale, VertexWriter& writer) const { + auto& path_components = data_->components; + auto& path_points = data_->points; + bool started_contour = false; + bool first_point = true; + + size_t storage_offset = 0u; + for (size_t component_i = 0; component_i < path_components.size(); + component_i++) { + const auto& path_component = path_components[component_i]; + switch (path_component) { + case ComponentType::kLinear: { + const LinearPathComponent* linear = + reinterpret_cast( + &path_points[storage_offset]); + if (first_point) { + writer.Write(linear->p1); + first_point = false; + } + writer.Write(linear->p2); + break; + } + case ComponentType::kQuadratic: { + const QuadraticPathComponent* quad = + reinterpret_cast( + &path_points[storage_offset]); + if (first_point) { + writer.Write(quad->p1); + first_point = false; + } + quad->ToLinearPathComponents(scale, writer); + break; + } + case ComponentType::kConic: { + const ConicPathComponent* conic = + reinterpret_cast( + &path_points[storage_offset]); + if (first_point) { + writer.Write(conic->p1); + first_point = false; + } + conic->ToLinearPathComponents(scale, writer); + break; + } + case ComponentType::kCubic: { + const CubicPathComponent* cubic = + reinterpret_cast( + &path_points[storage_offset]); + if (first_point) { + writer.Write(cubic->p1); + first_point = false; + } + cubic->ToLinearPathComponents(scale, writer); + break; + } + case Path::ComponentType::kContour: + if (component_i == path_components.size() - 1) { + // If the last component is a contour, that means it's an empty + // contour, so skip it. + continue; + } + // The contour component type is the first segment in a contour. + // Since this should contain the destination (if closed), we + // can start with this point. If there was already an open + // contour, or we've reached the end of the verb list, we + // also close the contour. + if (started_contour) { + writer.EndContour(); + } + started_contour = true; + first_point = true; + } + storage_offset += VerbToOffset(path_component); + } + if (started_contour) { + writer.EndContour(); + } +} + +Path::ComponentIterator Path::begin() const { + return ComponentIterator(*this, 0u, 0u); +} + +Path::ComponentIterator Path::end() const { + return ComponentIterator(*this, data_->components.size(), + data_->points.size()); +} + +Path::Polyline::Polyline(Path::Polyline::PointBufferPtr point_buffer, + Path::Polyline::ReclaimPointBufferCallback reclaim) + : points(std::move(point_buffer)), reclaim_points_(std::move(reclaim)) { + FML_DCHECK(points); +} + +Path::Polyline::Polyline(Path::Polyline&& other) { + points = std::move(other.points); + reclaim_points_ = std::move(other.reclaim_points_); + contours = std::move(other.contours); +} + +Path::Polyline::~Polyline() { + if (reclaim_points_) { + points->clear(); + reclaim_points_(std::move(points)); + } +} + +void Path::EndContour( + size_t storage_offset, + Polyline& polyline, + size_t component_index, + std::vector& poly_components) const { + auto& path_components = data_->components; + auto& path_points = data_->points; + // Whenever a contour has ended, extract the exact end direction from + // the last component. + if (polyline.contours.empty() || component_index == 0) { + return; + } + + auto& contour = polyline.contours.back(); + contour.end_direction = Vector2(0, 1); + contour.components = poly_components; + poly_components.clear(); + + size_t previous_index = component_index - 1; + storage_offset -= VerbToOffset(path_components[previous_index]); + + while (previous_index >= 0 && storage_offset >= 0) { + const auto& path_component = path_components[previous_index]; + switch (path_component) { + case ComponentType::kLinear: { + auto* linear = reinterpret_cast( + &path_points[storage_offset]); + auto maybe_end = linear->GetEndDirection(); + if (maybe_end.has_value()) { + contour.end_direction = maybe_end.value(); + return; + } + break; + } + case ComponentType::kQuadratic: { + auto* quad = reinterpret_cast( + &path_points[storage_offset]); + auto maybe_end = quad->GetEndDirection(); + if (maybe_end.has_value()) { + contour.end_direction = maybe_end.value(); + return; + } + break; + } + case ComponentType::kConic: { + auto* conic = reinterpret_cast( + &path_points[storage_offset]); + auto maybe_end = conic->GetEndDirection(); + if (maybe_end.has_value()) { + contour.end_direction = maybe_end.value(); + return; + } + break; + } + case ComponentType::kCubic: { + auto* cubic = reinterpret_cast( + &path_points[storage_offset]); + auto maybe_end = cubic->GetEndDirection(); + if (maybe_end.has_value()) { + contour.end_direction = maybe_end.value(); + return; + } + break; + } + case ComponentType::kContour: { + // Hit previous contour, return. + return; + }; + } + storage_offset -= VerbToOffset(path_component); + previous_index--; + } +}; + +Path::Polyline Path::CreatePolyline( + Scalar scale, + Path::Polyline::PointBufferPtr point_buffer, + Path::Polyline::ReclaimPointBufferCallback reclaim) const { + Polyline polyline(std::move(point_buffer), std::move(reclaim)); + + auto& path_components = data_->components; + auto& path_points = data_->points; + std::optional start_direction; + std::vector poly_components; + size_t storage_offset = 0u; + size_t component_i = 0; + + for (; component_i < path_components.size(); component_i++) { + auto path_component = path_components[component_i]; + switch (path_component) { + case ComponentType::kLinear: { + poly_components.push_back({ + .component_start_index = polyline.points->size() - 1, + .is_curve = false, + }); + auto* linear = reinterpret_cast( + &path_points[storage_offset]); + linear->AppendPolylinePoints(*polyline.points); + if (!start_direction.has_value()) { + start_direction = linear->GetStartDirection(); + } + break; + } + case ComponentType::kQuadratic: { + poly_components.push_back({ + .component_start_index = polyline.points->size() - 1, + .is_curve = true, + }); + auto* quad = reinterpret_cast( + &path_points[storage_offset]); + quad->AppendPolylinePoints(scale, *polyline.points); + if (!start_direction.has_value()) { + start_direction = quad->GetStartDirection(); + } + break; + } + case ComponentType::kConic: { + poly_components.push_back({ + .component_start_index = polyline.points->size() - 1, + .is_curve = true, + }); + auto* conic = reinterpret_cast( + &path_points[storage_offset]); + conic->AppendPolylinePoints(scale, *polyline.points); + if (!start_direction.has_value()) { + start_direction = conic->GetStartDirection(); + } + break; + } + case ComponentType::kCubic: { + poly_components.push_back({ + .component_start_index = polyline.points->size() - 1, + .is_curve = true, + }); + auto* cubic = reinterpret_cast( + &path_points[storage_offset]); + cubic->AppendPolylinePoints(scale, *polyline.points); + if (!start_direction.has_value()) { + start_direction = cubic->GetStartDirection(); + } + break; + } + case ComponentType::kContour: + if (component_i == path_components.size() - 1) { + // If the last component is a contour, that means it's an empty + // contour, so skip it. + break; + } + if (!polyline.contours.empty()) { + polyline.contours.back().start_direction = + start_direction.value_or(Vector2(0, -1)); + start_direction = std::nullopt; + } + EndContour(storage_offset, polyline, component_i, poly_components); + + auto* contour = reinterpret_cast( + &path_points[storage_offset]); + polyline.contours.push_back(PolylineContour{ + .start_index = polyline.points->size(), // + .is_closed = contour->IsClosed(), // + .start_direction = Vector2(0, -1), // + .components = poly_components // + }); + + polyline.points->push_back(contour->destination); + break; + } + storage_offset += VerbToOffset(path_component); + } + + // Subtract the last storage offset increment so that the storage lookup is + // correct, including potentially an empty contour as well. + if (component_i > 0 && path_components.back() == ComponentType::kContour) { + storage_offset -= VerbToOffset(ComponentType::kContour); + component_i--; + } + + if (!polyline.contours.empty()) { + polyline.contours.back().start_direction = + start_direction.value_or(Vector2(0, -1)); + } + EndContour(storage_offset, polyline, component_i, poly_components); + return polyline; +} + +std::optional Path::GetBoundingBox() const { + return data_->bounds; +} + +std::optional Path::GetTransformedBoundingBox( + const Matrix& transform) const { + auto bounds = GetBoundingBox(); + if (!bounds.has_value()) { + return std::nullopt; + } + return bounds->TransformBounds(transform); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/path.h b/flutter/engine/src/flutter/impeller/geometry/path.h new file mode 100644 index 0000000000000000000000000000000000000000..ce00424db09821646e2f889132d58a6d0ecacd4a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path.h @@ -0,0 +1,270 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_PATH_H_ +#define FLUTTER_IMPELLER_GEOMETRY_PATH_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +enum class Cap { + kButt, + kRound, + kSquare, +}; + +enum class Join { + kMiter, + kRound, + kBevel, +}; + +enum class FillType { + kNonZero, // The default winding order. + kOdd, +}; + +enum class Convexity { + kUnknown, + kConvex, +}; + +//------------------------------------------------------------------------------ +/// @brief Paths are lightweight objects that describe a collection of +/// linear, quadratic, or cubic segments. These segments may be +/// broken up by move commands, which are effectively linear +/// commands that pick up the pen rather than continuing to draw. +/// +/// All shapes supported by Impeller are paths either directly or +/// via approximation (in the case of circles). +/// +/// Paths are externally immutable once created, Creating paths must +/// be done using a path builder. +/// +class Path { + public: + enum class ComponentType { + kLinear, + kQuadratic, + kConic, + kCubic, + kContour, + }; + + class ComponentIterator { + public: + ComponentType type() const; + + // Return pointer to path component or null if the type is wrong or + // the iterator is past the end of the path. + const LinearPathComponent* linear() const; + const QuadraticPathComponent* quadratic() const; + const ConicPathComponent* conic() const; + const CubicPathComponent* cubic() const; + const ContourComponent* contour() const; + + ComponentIterator& operator++(); + bool operator==(const ComponentIterator& other) const { + return component_index_ == other.component_index_; + } + bool operator!=(const ComponentIterator& other) const { + return component_index_ != other.component_index_; + } + + private: + ComponentIterator(const Path& path, size_t index, size_t offset) + : path_(path), component_index_(index), storage_offset_(offset) {} + + const Path& path_; + size_t component_index_ = 0u; + size_t storage_offset_ = 0u; + + friend class Path; + }; + + static constexpr size_t VerbToOffset(Path::ComponentType verb) { + switch (verb) { + case Path::ComponentType::kLinear: + return 2u; + case Path::ComponentType::kQuadratic: + return 3u; + case Path::ComponentType::kConic: + return 4u; + case Path::ComponentType::kCubic: + return 4u; + case Path::ComponentType::kContour: + return 2u; + break; + } + FML_UNREACHABLE(); + } + + struct PolylineContour { + struct Component { + size_t component_start_index; + /// Denotes whether this component is a curve. + /// + /// This is set to true when this component is generated from + /// QuadraticComponent or CubicPathComponent. + bool is_curve; + }; + /// Index that denotes the first point of this contour. + size_t start_index; + + /// Denotes whether the last point of this contour is connected to the first + /// point of this contour or not. + bool is_closed; + + /// The direction of the contour's start cap. + Vector2 start_direction; + /// The direction of the contour's end cap. + Vector2 end_direction; + + /// Distinct components in this contour. + /// + /// If this contour is generated from multiple path components, each + /// path component forms a component in this vector. + std::vector components; + }; + + /// One or more contours represented as a series of points and indices in + /// the point vector representing the start of a new contour. + /// + /// Polylines are ephemeral and meant to be used by the tessellator. They do + /// not allocate their own point vectors to allow for optimizations around + /// allocation and reuse of arenas. + struct Polyline { + /// The signature of a method called when it is safe to reclaim the point + /// buffer provided to the constructor of this object. + using PointBufferPtr = std::unique_ptr>; + using ReclaimPointBufferCallback = std::function; + + /// The buffer will be cleared and returned at the destruction of this + /// polyline. + Polyline(PointBufferPtr point_buffer, ReclaimPointBufferCallback reclaim); + + Polyline(Polyline&& other); + ~Polyline(); + + /// Points in the polyline, which may represent multiple contours specified + /// by indices in |contours|. + PointBufferPtr points; + + Point& GetPoint(size_t index) const { return (*points)[index]; } + + /// Contours are disconnected pieces of a polyline, such as when a MoveTo + /// was issued on a PathBuilder. + std::vector contours; + + /// Convenience method to compute the start (inclusive) and end (exclusive) + /// point of the given contour index. + /// + /// The contour_index parameter is clamped to contours.size(). + std::tuple GetContourPointBounds( + size_t contour_index) const; + + private: + ReclaimPointBufferCallback reclaim_points_; + }; + + Path(); + + ~Path(); + + size_t GetComponentCount(std::optional type = {}) const; + + size_t GetPointCount() const; + + FillType GetFillType() const; + + bool IsConvex() const; + + bool IsEmpty() const; + + /// @brief Whether the line contains a single contour. + bool IsSingleContour() const; + + ComponentIterator begin() const; + ComponentIterator end() const; + + /// Callers must provide the scale factor for how this path will be + /// transformed. + /// + /// It is suitable to use the max basis length of the matrix used to transform + /// the path. If the provided scale is 0, curves will revert to straight + /// lines. + Polyline CreatePolyline( + Scalar scale, + Polyline::PointBufferPtr point_buffer = + std::make_unique>(), + Polyline::ReclaimPointBufferCallback reclaim = nullptr) const; + + void EndContour( + size_t storage_offset, + Polyline& polyline, + size_t component_index, + std::vector& poly_components) const; + + std::optional GetBoundingBox() const; + + std::optional GetTransformedBoundingBox(const Matrix& transform) const; + + /// Generate a polyline into the temporary storage held by the [writer]. + /// + /// It is suitable to use the max basis length of the matrix used to transform + /// the path. If the provided scale is 0, curves will revert to straight + /// lines. + void WritePolyline(Scalar scale, VertexWriter& writer) const; + + /// Determine required storage for points and number of contours. + std::pair CountStorage(Scalar scale) const; + + private: + friend class PathBuilder; + + // All of the data for the path is stored in this structure which is + // held by a shared_ptr. Since they all share the structure, the + // copy constructor for Path is very cheap and we don't need to deal + // with shared pointers for Path fields and method arguments. + // + // PathBuilder also uses this structure to accumulate the path data + // but the Path constructor used in |TakePath()| will clone the + // structure to prevent sharing and future modifications within the + // builder from affecting the existing taken paths. + struct Data { + Data() = default; + + Data(Data&& other) = default; + + Data(const Data& other) = default; + + ~Data() = default; + + FillType fill = FillType::kNonZero; + Convexity convexity = Convexity::kUnknown; + bool single_contour = true; + std::optional bounds; + std::vector points; + std::vector components; + }; + + explicit Path(Data data); + + std::shared_ptr data_; +}; + +static_assert(sizeof(Path) == sizeof(std::shared_ptr)); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_PATH_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/path_builder.cc b/flutter/engine/src/flutter/impeller/geometry/path_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe105a8f739b80542476830459f79a4f4059347f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path_builder.cc @@ -0,0 +1,665 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "path_builder.h" + +#include +#include + +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/round_superellipse_param.h" + +namespace impeller { + +PathBuilder::PathBuilder() { + AddContourComponent({}); +} + +PathBuilder::~PathBuilder() = default; + +Path PathBuilder::CopyPath(FillType fill) { + prototype_.fill = fill; + prototype_.single_contour = + current_contour_location_ == 0u || + (contour_count_ == 2 && + prototype_.components.back() == Path::ComponentType::kContour); + return Path(prototype_); +} + +Path PathBuilder::TakePath(FillType fill) { + prototype_.fill = fill; + UpdateBounds(); + prototype_.single_contour = + current_contour_location_ == 0u || + (contour_count_ == 2 && + prototype_.components.back() == Path::ComponentType::kContour); + current_contour_location_ = 0u; + contour_count_ = 1; + return Path(std::move(prototype_)); +} + +void PathBuilder::Reserve(size_t point_size, size_t verb_size) { + prototype_.points.reserve(point_size); + prototype_.components.reserve(verb_size); +} + +PathBuilder& PathBuilder::MoveTo(Point point, bool relative) { + current_ = relative ? current_ + point : point; + subpath_start_ = current_; + AddContourComponent(current_); + return *this; +} + +PathBuilder& PathBuilder::Close() { + // If the subpath start is the same as the current position, this + // is an empty contour and inserting a line segment will just + // confuse the tessellator. + if (subpath_start_ != current_) { + LineTo(subpath_start_); + } + SetContourClosed(true); + AddContourComponent(current_); + return *this; +} + +PathBuilder& PathBuilder::LineTo(Point point, bool relative) { + point = relative ? current_ + point : point; + AddLinearComponent(current_, point); + current_ = point; + return *this; +} + +PathBuilder& PathBuilder::HorizontalLineTo(Scalar x, bool relative) { + Point endpoint = + relative ? Point{current_.x + x, current_.y} : Point{x, current_.y}; + AddLinearComponent(current_, endpoint); + current_ = endpoint; + return *this; +} + +PathBuilder& PathBuilder::VerticalLineTo(Scalar y, bool relative) { + Point endpoint = + relative ? Point{current_.x, current_.y + y} : Point{current_.x, y}; + AddLinearComponent(current_, endpoint); + current_ = endpoint; + return *this; +} + +PathBuilder& PathBuilder::QuadraticCurveTo(Point controlPoint, + Point point, + bool relative) { + point = relative ? current_ + point : point; + controlPoint = relative ? current_ + controlPoint : controlPoint; + AddQuadraticComponent(current_, controlPoint, point); + current_ = point; + return *this; +} + +PathBuilder& PathBuilder::ConicCurveTo(Point controlPoint, + Point point, + Scalar weight, + bool relative) { + point = relative ? current_ + point : point; + controlPoint = relative ? current_ + controlPoint : controlPoint; + AddConicComponent(current_, controlPoint, point, weight); + current_ = point; + return *this; +} + +PathBuilder& PathBuilder::SetConvexity(Convexity value) { + prototype_.convexity = value; + return *this; +} + +PathBuilder& PathBuilder::CubicCurveTo(Point controlPoint1, + Point controlPoint2, + Point point, + bool relative) { + controlPoint1 = relative ? current_ + controlPoint1 : controlPoint1; + controlPoint2 = relative ? current_ + controlPoint2 : controlPoint2; + point = relative ? current_ + point : point; + AddCubicComponent(current_, controlPoint1, controlPoint2, point); + current_ = point; + return *this; +} + +PathBuilder& PathBuilder::AddQuadraticCurve(const Point& p1, + const Point& cp, + const Point& p2) { + MoveTo(p1); + AddQuadraticComponent(p1, cp, p2); + return *this; +} + +PathBuilder& PathBuilder::AddConicCurve(const Point& p1, + const Point& cp, + const Point& p2, + Scalar weight) { + MoveTo(p1); + AddConicComponent(p1, cp, p2, weight); + return *this; +} + +PathBuilder& PathBuilder::AddCubicCurve(const Point& p1, + const Point& cp1, + const Point& cp2, + const Point& p2) { + MoveTo(p1); + AddCubicComponent(p1, cp1, cp2, p2); + return *this; +} + +PathBuilder& PathBuilder::AddRect(const Rect& rect) { + auto origin = rect.GetOrigin(); + auto size = rect.GetSize(); + + auto tl = origin; + auto bl = origin + Point{0.0, size.height}; + auto br = origin + size; + auto tr = origin + Point{size.width, 0.0}; + + MoveTo(tl); + LineTo(tr); + LineTo(br); + LineTo(bl); + Close(); + + return *this; +} + +PathBuilder& PathBuilder::AddCircle(const Point& c, Scalar r) { + return AddOval(Rect::MakeXYWH(c.x - r, c.y - r, 2.0f * r, 2.0f * r)); +} + +PathBuilder& PathBuilder::AddRoundRect(RoundRect round_rect) { + auto rect = round_rect.GetBounds(); + auto radii = round_rect.GetRadii(); + if (radii.AreAllCornersEmpty()) { + return AddRect(rect); + } + + auto rect_origin = rect.GetOrigin(); + auto rect_size = rect.GetSize(); + + current_ = rect_origin + Point{radii.top_left.width, 0.0}; + + MoveTo({rect_origin.x + radii.top_left.width, rect_origin.y}); + + //---------------------------------------------------------------------------- + // Top line. + // + AddLinearComponentIfNeeded( + {rect_origin.x + radii.top_left.width, rect_origin.y}, + {rect_origin.x + rect_size.width - radii.top_right.width, rect_origin.y}); + + //---------------------------------------------------------------------------- + // Top right arc. + // + AddRoundedRectTopRight(rect, radii); + + //---------------------------------------------------------------------------- + // Right line. + // + AddLinearComponentIfNeeded( + {rect_origin.x + rect_size.width, rect_origin.y + radii.top_right.height}, + {rect_origin.x + rect_size.width, + rect_origin.y + rect_size.height - radii.bottom_right.height}); + + //---------------------------------------------------------------------------- + // Bottom right arc. + // + AddRoundedRectBottomRight(rect, radii); + + //---------------------------------------------------------------------------- + // Bottom line. + // + AddLinearComponentIfNeeded( + {rect_origin.x + rect_size.width - radii.bottom_right.width, + rect_origin.y + rect_size.height}, + {rect_origin.x + radii.bottom_left.width, + rect_origin.y + rect_size.height}); + + //---------------------------------------------------------------------------- + // Bottom left arc. + // + AddRoundedRectBottomLeft(rect, radii); + + //---------------------------------------------------------------------------- + // Left line. + // + AddLinearComponentIfNeeded( + {rect_origin.x, + rect_origin.y + rect_size.height - radii.bottom_left.height}, + {rect_origin.x, rect_origin.y + radii.top_left.height}); + + //---------------------------------------------------------------------------- + // Top left arc. + // + AddRoundedRectTopLeft(rect, radii); + + Close(); + + return *this; +} + +PathBuilder& PathBuilder::AddRoundSuperellipse(RoundSuperellipse rse) { + if (rse.IsRect()) { + AddRect(rse.GetBounds()); + } else if (rse.IsOval()) { + AddOval(rse.GetBounds()); + } else { + impeller::RoundSuperellipseParam::MakeBoundsRadii(rse.GetBounds(), + rse.GetRadii()) + .AddToPath(*this); + } + return *this; +} + +PathBuilder& PathBuilder::AddRoundedRectTopLeft(Rect rect, + RoundingRadii radii) { + const auto magic_top_left = radii.top_left * kArcApproximationMagic; + const auto corner = rect.GetOrigin(); + AddCubicComponent( + {corner.x, corner.y + radii.top_left.height}, + {corner.x, corner.y + radii.top_left.height - magic_top_left.height}, + {corner.x + radii.top_left.width - magic_top_left.width, corner.y}, + {corner.x + radii.top_left.width, corner.y}); + return *this; +} + +PathBuilder& PathBuilder::AddRoundedRectTopRight(Rect rect, + RoundingRadii radii) { + const auto magic_top_right = radii.top_right * kArcApproximationMagic; + const auto corner = rect.GetOrigin() + Point{rect.GetWidth(), 0}; + AddCubicComponent( + {corner.x - radii.top_right.width, corner.y}, + {corner.x - radii.top_right.width + magic_top_right.width, corner.y}, + {corner.x, corner.y + radii.top_right.height - magic_top_right.height}, + {corner.x, corner.y + radii.top_right.height}); + return *this; +} + +PathBuilder& PathBuilder::AddRoundedRectBottomRight(Rect rect, + RoundingRadii radii) { + const auto magic_bottom_right = radii.bottom_right * kArcApproximationMagic; + const auto corner = rect.GetOrigin() + rect.GetSize(); + AddCubicComponent( + {corner.x, corner.y - radii.bottom_right.height}, + {corner.x, + corner.y - radii.bottom_right.height + magic_bottom_right.height}, + {corner.x - radii.bottom_right.width + magic_bottom_right.width, + corner.y}, + {corner.x - radii.bottom_right.width, corner.y}); + return *this; +} + +PathBuilder& PathBuilder::AddRoundedRectBottomLeft(Rect rect, + RoundingRadii radii) { + const auto magic_bottom_left = radii.bottom_left * kArcApproximationMagic; + const auto corner = rect.GetOrigin() + Point{0, rect.GetHeight()}; + AddCubicComponent( + {corner.x + radii.bottom_left.width, corner.y}, + {corner.x + radii.bottom_left.width - magic_bottom_left.width, corner.y}, + {corner.x, + corner.y - radii.bottom_left.height + magic_bottom_left.height}, + {corner.x, corner.y - radii.bottom_left.height}); + return *this; +} + +void PathBuilder::AddContourComponent(const Point& destination, + bool is_closed) { + auto& components = prototype_.components; + auto& points = prototype_.points; + auto closed = is_closed ? Point{0, 0} : Point{1, 1}; + if (components.size() > 0 && + components.back() == Path::ComponentType::kContour) { + // Never insert contiguous contours. + points[current_contour_location_] = destination; + points[current_contour_location_ + 1] = closed; + } else { + current_contour_location_ = points.size(); + points.push_back(destination); + points.push_back(closed); + components.push_back(Path::ComponentType::kContour); + contour_count_ += 1; + } + prototype_.bounds.reset(); +} + +void PathBuilder::AddLinearComponentIfNeeded(const Point& p1, const Point& p2) { + if (ScalarNearlyEqual(p1.x, p2.x, 1e-4f) && + ScalarNearlyEqual(p1.y, p2.y, 1e-4f)) { + return; + } + AddLinearComponent(p1, p2); +} + +void PathBuilder::AddLinearComponent(const Point& p1, const Point& p2) { + auto& points = prototype_.points; + points.push_back(p1); + points.push_back(p2); + prototype_.components.push_back(Path::ComponentType::kLinear); + prototype_.bounds.reset(); +} + +void PathBuilder::AddQuadraticComponent(const Point& p1, + const Point& cp, + const Point& p2) { + auto& points = prototype_.points; + points.push_back(p1); + points.push_back(cp); + points.push_back(p2); + prototype_.components.push_back(Path::ComponentType::kQuadratic); + prototype_.bounds.reset(); +} + +void PathBuilder::AddConicComponent(const Point& p1, + const Point& cp, + const Point& p2, + Scalar weight) { + if (!std::isfinite(weight)) { + AddLinearComponent(p1, cp); + AddLinearComponent(cp, p2); + } else if (weight <= 0) { + AddLinearComponent(p1, p2); + } else if (weight == 1) { + AddQuadraticComponent(p1, cp, p2); + } else { + auto& points = prototype_.points; + points.push_back(p1); + points.push_back(cp); + points.push_back(p2); + points.emplace_back(weight, weight); + prototype_.components.push_back(Path::ComponentType::kConic); + prototype_.bounds.reset(); + } +} + +void PathBuilder::AddCubicComponent(const Point& p1, + const Point& cp1, + const Point& cp2, + const Point& p2) { + auto& points = prototype_.points; + points.push_back(p1); + points.push_back(cp1); + points.push_back(cp2); + points.push_back(p2); + prototype_.components.push_back(Path::ComponentType::kCubic); + prototype_.bounds.reset(); +} + +void PathBuilder::SetContourClosed(bool is_closed) { + prototype_.points[current_contour_location_ + 1] = + is_closed ? Point{0, 0} : Point{1, 1}; +} + +PathBuilder& PathBuilder::AddArc(const Rect& oval_bounds, + Radians start, + Radians sweep, + bool use_center) { + if (sweep.radians < 0) { + start.radians += sweep.radians; + sweep.radians *= -1; + } + sweep.radians = std::min(k2Pi, sweep.radians); + start.radians = std::fmod(start.radians, k2Pi); + + const Point center = oval_bounds.GetCenter(); + const Point radius = center - oval_bounds.GetOrigin(); + + Vector2 p1_unit(std::cos(start.radians), std::sin(start.radians)); + + if (use_center) { + MoveTo(center); + LineTo(center + p1_unit * radius); + } else { + MoveTo(center + p1_unit * radius); + } + + while (sweep.radians > 0) { + Vector2 p2_unit; + Scalar quadrant_angle; + if (sweep.radians < kPiOver2) { + quadrant_angle = sweep.radians; + p2_unit = Vector2(std::cos(start.radians + quadrant_angle), + std::sin(start.radians + quadrant_angle)); + } else { + quadrant_angle = kPiOver2; + p2_unit = Vector2(-p1_unit.y, p1_unit.x); + } + + Vector2 arc_cp_lengths = + (quadrant_angle / kPiOver2) * kArcApproximationMagic * radius; + + Point p1 = center + p1_unit * radius; + Point p2 = center + p2_unit * radius; + Point cp1 = p1 + Vector2(-p1_unit.y, p1_unit.x) * arc_cp_lengths; + Point cp2 = p2 + Vector2(p2_unit.y, -p2_unit.x) * arc_cp_lengths; + + AddCubicComponent(p1, cp1, cp2, p2); + current_ = p2; + + start.radians += quadrant_angle; + sweep.radians -= quadrant_angle; + p1_unit = p2_unit; + } + + if (use_center) { + Close(); + } + + return *this; +} + +PathBuilder& PathBuilder::AddOval(const Rect& container) { + const Point c = container.GetCenter(); + const Point r = c - container.GetOrigin(); + const Point m = r * kArcApproximationMagic; + + MoveTo({c.x, c.y - r.y}); + + //---------------------------------------------------------------------------- + // Top right arc. + // + AddCubicComponent({c.x, c.y - r.y}, // p1 + {c.x + m.x, c.y - r.y}, // cp1 + {c.x + r.x, c.y - m.y}, // cp2 + {c.x + r.x, c.y} // p2 + ); + + //---------------------------------------------------------------------------- + // Bottom right arc. + // + AddCubicComponent({c.x + r.x, c.y}, // p1 + {c.x + r.x, c.y + m.y}, // cp1 + {c.x + m.x, c.y + r.y}, // cp2 + {c.x, c.y + r.y} // p2 + ); + + //---------------------------------------------------------------------------- + // Bottom left arc. + // + AddCubicComponent({c.x, c.y + r.y}, // p1 + {c.x - m.x, c.y + r.y}, // cp1 + {c.x - r.x, c.y + m.y}, // cp2 + {c.x - r.x, c.y} // p2 + ); + + //---------------------------------------------------------------------------- + // Top left arc. + // + AddCubicComponent({c.x - r.x, c.y}, // p1 + {c.x - r.x, c.y - m.y}, // cp1 + {c.x - m.x, c.y - r.y}, // cp2 + {c.x, c.y - r.y} // p2 + ); + + Close(); + + return *this; +} + +PathBuilder& PathBuilder::AddLine(const Point& p1, const Point& p2) { + MoveTo(p1); + AddLinearComponent(p1, p2); + return *this; +} + +PathBuilder& PathBuilder::AddPath(const Path& path) { + auto& points = prototype_.points; + auto& components = prototype_.components; + size_t source_offset = points.size(); + + points.insert(points.end(), path.data_->points.begin(), + path.data_->points.end()); + components.insert(components.end(), path.data_->components.begin(), + path.data_->components.end()); + + for (auto component : path.data_->components) { + if (component == Path::ComponentType::kContour) { + current_contour_location_ = source_offset; + contour_count_ += 1; + } + source_offset += Path::VerbToOffset(component); + } + return *this; +} + +PathBuilder& PathBuilder::Shift(Point offset) { + auto& points = prototype_.points; + size_t storage_offset = 0u; + for (const auto& component : prototype_.components) { + switch (component) { + case Path::ComponentType::kLinear: { + auto* linear = + reinterpret_cast(&points[storage_offset]); + linear->p1 += offset; + linear->p2 += offset; + break; + } + case Path::ComponentType::kQuadratic: { + auto* quad = + reinterpret_cast(&points[storage_offset]); + quad->p1 += offset; + quad->p2 += offset; + quad->cp += offset; + } break; + case Path::ComponentType::kConic: { + auto* conic = + reinterpret_cast(&points[storage_offset]); + conic->p1 += offset; + conic->p2 += offset; + conic->cp += offset; + } break; + case Path::ComponentType::kCubic: { + auto* cubic = + reinterpret_cast(&points[storage_offset]); + cubic->p1 += offset; + cubic->p2 += offset; + cubic->cp1 += offset; + cubic->cp2 += offset; + } break; + case Path::ComponentType::kContour: + auto* contour = + reinterpret_cast(&points[storage_offset]); + contour->destination += offset; + break; + } + storage_offset += Path::VerbToOffset(component); + } + + prototype_.bounds.reset(); + return *this; +} + +PathBuilder& PathBuilder::SetBounds(Rect bounds) { + prototype_.bounds = bounds; + return *this; +} + +void PathBuilder::UpdateBounds() { + if (!prototype_.bounds.has_value()) { + auto min_max = GetMinMaxCoveragePoints(); + if (!min_max.has_value()) { + prototype_.bounds.reset(); + return; + } + auto min = min_max->first; + auto max = min_max->second; + const auto difference = max - min; + prototype_.bounds = + Rect::MakeXYWH(min.x, min.y, difference.x, difference.y); + } +} + +std::optional> PathBuilder::GetMinMaxCoveragePoints() + const { + auto& points = prototype_.points; + + if (points.empty()) { + return std::nullopt; + } + + std::optional min, max; + + auto clamp = [&min, &max](const Point& point) { + if (min.has_value()) { + min = min->Min(point); + } else { + min = point; + } + + if (max.has_value()) { + max = max->Max(point); + } else { + max = point; + } + }; + + size_t storage_offset = 0u; + for (const auto& component : prototype_.components) { + switch (component) { + case Path::ComponentType::kLinear: { + auto* linear = reinterpret_cast( + &points[storage_offset]); + clamp(linear->p1); + clamp(linear->p2); + break; + } + case Path::ComponentType::kQuadratic: + for (const auto& extrema : + reinterpret_cast( + &points[storage_offset]) + ->Extrema()) { + clamp(extrema); + } + break; + case Path::ComponentType::kConic: + for (const auto& extrema : reinterpret_cast( + &points[storage_offset]) + ->Extrema()) { + clamp(extrema); + } + break; + case Path::ComponentType::kCubic: + for (const auto& extrema : reinterpret_cast( + &points[storage_offset]) + ->Extrema()) { + clamp(extrema); + } + break; + case Path::ComponentType::kContour: + break; + } + storage_offset += Path::VerbToOffset(component); + } + + if (!min.has_value() || !max.has_value()) { + return std::nullopt; + } + + return std::make_pair(min.value(), max.value()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/path_builder.h b/flutter/engine/src/flutter/impeller/geometry/path_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..3569675884c603c9752a4c790bd93b5339e163c1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path_builder.h @@ -0,0 +1,183 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_PATH_BUILDER_H_ +#define FLUTTER_IMPELLER_GEOMETRY_PATH_BUILDER_H_ + +#include "impeller/geometry/path.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/round_rect.h" +#include "impeller/geometry/round_superellipse.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +class PathBuilder { + public: + /// Used for approximating quarter circle arcs with cubic curves. This is the + /// control point distance which results in the smallest possible unit circle + /// integration for a right angle arc. It can be used to approximate arcs less + /// than 90 degrees to great effect by simply reducing it proportionally to + /// the angle. However, accuracy rapidly diminishes if magnified for obtuse + /// angle arcs, and so multiple cubic curves should be used when approximating + /// arcs greater than 90 degrees. + constexpr static const Scalar kArcApproximationMagic = 0.551915024494f; + + PathBuilder(); + + ~PathBuilder(); + + Path CopyPath(FillType fill = FillType::kNonZero); + + Path TakePath(FillType fill = FillType::kNonZero); + + /// @brief Reserve [point_size] points and [verb_size] verbs in the underlying + /// path buffer. + void Reserve(size_t point_size, size_t verb_size); + + PathBuilder& SetConvexity(Convexity value); + + PathBuilder& MoveTo(Point point, bool relative = false); + + PathBuilder& Close(); + + /// @brief Insert a line from the current position to `point`. + /// + /// If `relative` is true, then `point` is relative to the current location. + PathBuilder& LineTo(Point point, bool relative = false); + + PathBuilder& HorizontalLineTo(Scalar x, bool relative = false); + + PathBuilder& VerticalLineTo(Scalar y, bool relative = false); + + /// @brief Insert a quadradic curve from the current position to `point` using + /// the control point `controlPoint`. + /// + /// If `relative` is true the `point` and `controlPoint` are relative to + /// current location. + PathBuilder& QuadraticCurveTo(Point controlPoint, + Point point, + bool relative = false); + + /// @brief Insert a conic curve from the current position to `point` using + /// the control point `controlPoint` and the weight `weight`. + /// + /// If `relative` is true the `point` and `controlPoint` are relative to + /// current location. + PathBuilder& ConicCurveTo(Point controlPoint, + Point point, + Scalar weight, + bool relative = false); + + /// @brief Insert a cubic curve from the curren position to `point` using the + /// control points `controlPoint1` and `controlPoint2`. + /// + /// If `relative` is true the `point`, `controlPoint1`, and `controlPoint2` + /// are relative to current location. + PathBuilder& CubicCurveTo(Point controlPoint1, + Point controlPoint2, + Point point, + bool relative = false); + + PathBuilder& AddRect(const Rect& rect); + + PathBuilder& AddCircle(const Point& center, Scalar radius); + + PathBuilder& AddArc(const Rect& oval_bounds, + Radians start, + Radians sweep, + bool use_center = false); + + PathBuilder& AddOval(const Rect& rect); + + /// @brief Move to point `p1`, then insert a line from `p1` to `p2`. + PathBuilder& AddLine(const Point& p1, const Point& p2); + + /// @brief Move to point `p1`, then insert a quadradic curve from `p1` to `p2` + /// with the control point `cp`. + PathBuilder& AddQuadraticCurve(const Point& p1, + const Point& cp, + const Point& p2); + + /// @brief Move to point `p1`, then insert a conic curve from `p1` to `p2` + /// with the control point `cp` and weight `weight`. + PathBuilder& AddConicCurve(const Point& p1, + const Point& cp, + const Point& p2, + Scalar weight); + + /// @brief Move to point `p1`, then insert a cubic curve from `p1` to `p2` + /// with control points `cp1` and `cp2`. + PathBuilder& AddCubicCurve(const Point& p1, + const Point& cp1, + const Point& cp2, + const Point& p2); + + /// @brief Transform the existing path segments and contours by the given + /// `offset`. + PathBuilder& Shift(Point offset); + + /// @brief Set the bounding box that will be used by `Path.GetBoundingBox` in + /// place of performing the computation. + /// + /// When Impeller recieves Skia Path objects, many of these already + /// have computed bounds. This method is used to avoid needlessly + /// recomputing these bounds. + PathBuilder& SetBounds(Rect bounds); + + PathBuilder& AddRoundRect(RoundRect rect); + + PathBuilder& AddRoundSuperellipse(RoundSuperellipse rse); + + PathBuilder& AddPath(const Path& path); + + private: + Point subpath_start_; + Point current_; + size_t current_contour_location_ = 0u; + size_t contour_count_ = 0u; + Path::Data prototype_; + + PathBuilder& AddRoundedRectTopLeft(Rect rect, RoundingRadii radii); + + PathBuilder& AddRoundedRectTopRight(Rect rect, RoundingRadii radii); + + PathBuilder& AddRoundedRectBottomRight(Rect rect, RoundingRadii radii); + + PathBuilder& AddRoundedRectBottomLeft(Rect rect, RoundingRadii radii); + + void AddContourComponent(const Point& destination, bool is_closed = false); + + void SetContourClosed(bool is_closed); + + void AddLinearComponent(const Point& p1, const Point& p2); + + void AddLinearComponentIfNeeded(const Point& p1, const Point& p2); + + void AddQuadraticComponent(const Point& p1, const Point& cp, const Point& p2); + + void AddConicComponent(const Point& p1, + const Point& cp, + const Point& p2, + Scalar weight); + + void AddCubicComponent(const Point& p1, + const Point& cp1, + const Point& cp2, + const Point& p2); + + /// Compute the bounds of the path unless they are already computed or + /// set by an external source, such as |SetBounds|. Any call which mutates + /// the path data can invalidate the computed/set bounds. + void UpdateBounds(); + + std::optional> GetMinMaxCoveragePoints() const; + + PathBuilder(const PathBuilder&) = delete; + PathBuilder& operator=(const PathBuilder&&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_PATH_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/path_component.cc b/flutter/engine/src/flutter/impeller/geometry/path_component.cc new file mode 100644 index 0000000000000000000000000000000000000000..cba5b58bb91e463b6c60de7d5abcc7bfd162bc6c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path_component.cc @@ -0,0 +1,610 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "path_component.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/impeller/geometry/scalar.h" +#include "flutter/impeller/geometry/wangs_formula.h" + +namespace impeller { + +/////////// FanVertexWriter /////////// + +FanVertexWriter::FanVertexWriter(Point* point_buffer, uint16_t* index_buffer) + : point_buffer_(point_buffer), index_buffer_(index_buffer) {} + +FanVertexWriter::~FanVertexWriter() = default; + +size_t FanVertexWriter::GetIndexCount() const { + return index_count_; +} + +void FanVertexWriter::EndContour() { + if (count_ == 0) { + return; + } + index_buffer_[index_count_++] = 0xFFFF; +} + +void FanVertexWriter::Write(Point point) { + index_buffer_[index_count_++] = count_; + point_buffer_[count_++] = point; +} + +/////////// StripVertexWriter /////////// + +StripVertexWriter::StripVertexWriter(Point* point_buffer, + uint16_t* index_buffer) + : point_buffer_(point_buffer), index_buffer_(index_buffer) {} + +StripVertexWriter::~StripVertexWriter() = default; + +size_t StripVertexWriter::GetIndexCount() const { + return index_count_; +} + +void StripVertexWriter::EndContour() { + if (count_ == 0u || contour_start_ == count_ - 1) { + // Empty or first contour. + return; + } + + size_t start = contour_start_; + size_t end = count_ - 1; + + index_buffer_[index_count_++] = start; + + size_t a = start + 1; + size_t b = end; + while (a < b) { + index_buffer_[index_count_++] = a; + index_buffer_[index_count_++] = b; + a++; + b--; + } + if (a == b) { + index_buffer_[index_count_++] = a; + } + + contour_start_ = count_; + index_buffer_[index_count_++] = 0xFFFF; +} + +void StripVertexWriter::Write(Point point) { + point_buffer_[count_++] = point; +} + +/////////// LineStripVertexWriter //////// + +LineStripVertexWriter::LineStripVertexWriter(std::vector& points) + : points_(points) {} + +void LineStripVertexWriter::EndContour() {} + +void LineStripVertexWriter::Write(Point point) { + if (offset_ >= points_.size()) { + overflow_.push_back(point); + } else { + points_[offset_++] = point; + } +} + +const std::vector& LineStripVertexWriter::GetOversizedBuffer() const { + return overflow_; +} + +std::pair LineStripVertexWriter::GetVertexCount() const { + return std::make_pair(offset_, overflow_.size()); +} + +/////////// GLESVertexWriter /////////// + +GLESVertexWriter::GLESVertexWriter(std::vector& points, + std::vector& indices) + : points_(points), indices_(indices) {} + +void GLESVertexWriter::EndContour() { + if (points_.size() == 0u || contour_start_ == points_.size() - 1) { + // Empty or first contour. + return; + } + + auto start = contour_start_; + auto end = points_.size() - 1; + // All filled paths are drawn as if they are closed, but if + // there is an explicit close then a lineTo to the origin + // is inserted. This point isn't strictly necesary to + // correctly render the shape and can be dropped. + if (points_[end] == points_[start]) { + end--; + } + + // Triangle strip break for subsequent contours + if (contour_start_ != 0) { + auto back = indices_.back(); + indices_.push_back(back); + indices_.push_back(start); + indices_.push_back(start); + + // If the contour has an odd number of points, insert an extra point when + // bridging to the next contour to preserve the correct triangle winding + // order. + if (previous_contour_odd_points_) { + indices_.push_back(start); + } + } else { + indices_.push_back(start); + } + + size_t a = start + 1; + size_t b = end; + while (a < b) { + indices_.push_back(a); + indices_.push_back(b); + a++; + b--; + } + if (a == b) { + indices_.push_back(a); + previous_contour_odd_points_ = false; + } else { + previous_contour_odd_points_ = true; + } + contour_start_ = points_.size(); +} + +void GLESVertexWriter::Write(Point point) { + points_.push_back(point); +} + +/* + * Based on: https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Specific_cases + */ + +static inline Scalar LinearSolve(Scalar t, Scalar p0, Scalar p1) { + return p0 + t * (p1 - p0); +} + +static inline Scalar QuadraticSolve(Scalar t, Scalar p0, Scalar p1, Scalar p2) { + return (1 - t) * (1 - t) * p0 + // + 2 * (1 - t) * t * p1 + // + t * t * p2; +} + +static inline Scalar QuadraticSolveDerivative(Scalar t, + Scalar p0, + Scalar p1, + Scalar p2) { + return 2 * (1 - t) * (p1 - p0) + // + 2 * t * (p2 - p1); +} + +static inline Scalar ConicSolve(Scalar t, + Scalar p0, + Scalar p1, + Scalar p2, + Scalar w) { + auto u = (1 - t); + auto coefficient_p0 = u * u; + auto coefficient_p1 = 2 * t * u * w; + auto coefficient_p2 = t * t; + + return ((p0 * coefficient_p0 + p1 * coefficient_p1 + p2 * coefficient_p2) / + (coefficient_p0 + coefficient_p1 + coefficient_p2)); +} + +static inline Scalar CubicSolve(Scalar t, + Scalar p0, + Scalar p1, + Scalar p2, + Scalar p3) { + return (1 - t) * (1 - t) * (1 - t) * p0 + // + 3 * (1 - t) * (1 - t) * t * p1 + // + 3 * (1 - t) * t * t * p2 + // + t * t * t * p3; +} + +static inline Scalar CubicSolveDerivative(Scalar t, + Scalar p0, + Scalar p1, + Scalar p2, + Scalar p3) { + return -3 * p0 * (1 - t) * (1 - t) + // + p1 * (3 * (1 - t) * (1 - t) - 6 * (1 - t) * t) + + p2 * (6 * (1 - t) * t - 3 * t * t) + // + 3 * p3 * t * t; +} + +Point LinearPathComponent::Solve(Scalar time) const { + return { + LinearSolve(time, p1.x, p2.x), // x + LinearSolve(time, p1.y, p2.y), // y + }; +} + +void LinearPathComponent::AppendPolylinePoints( + std::vector& points) const { + if (points.size() == 0 || points.back() != p2) { + points.push_back(p2); + } +} + +std::vector LinearPathComponent::Extrema() const { + return {p1, p2}; +} + +std::optional LinearPathComponent::GetStartDirection() const { + if (p1 == p2) { + return std::nullopt; + } + return (p1 - p2).Normalize(); +} + +std::optional LinearPathComponent::GetEndDirection() const { + if (p1 == p2) { + return std::nullopt; + } + return (p2 - p1).Normalize(); +} + +Point QuadraticPathComponent::Solve(Scalar time) const { + return { + QuadraticSolve(time, p1.x, cp.x, p2.x), // x + QuadraticSolve(time, p1.y, cp.y, p2.y), // y + }; +} + +Point QuadraticPathComponent::SolveDerivative(Scalar time) const { + return { + QuadraticSolveDerivative(time, p1.x, cp.x, p2.x), // x + QuadraticSolveDerivative(time, p1.y, cp.y, p2.y), // y + }; +} + +void QuadraticPathComponent::ToLinearPathComponents( + Scalar scale, + VertexWriter& writer) const { + Scalar line_count = std::ceilf(ComputeQuadradicSubdivisions(scale, *this)); + for (size_t i = 1; i < line_count; i += 1) { + writer.Write(Solve(i / line_count)); + } + writer.Write(p2); +} + +void QuadraticPathComponent::AppendPolylinePoints( + Scalar scale_factor, + std::vector& points) const { + ToLinearPathComponents(scale_factor, [&points](const Point& point) { + points.emplace_back(point); + }); +} + +void QuadraticPathComponent::ToLinearPathComponents( + Scalar scale_factor, + const PointProc& proc) const { + Scalar line_count = + std::ceilf(ComputeQuadradicSubdivisions(scale_factor, *this)); + for (size_t i = 1; i < line_count; i += 1) { + proc(Solve(i / line_count)); + } + proc(p2); +} + +size_t QuadraticPathComponent::CountLinearPathComponents(Scalar scale) const { + return std::ceilf(ComputeQuadradicSubdivisions(scale, *this)) + 2; +} + +std::vector QuadraticPathComponent::Extrema() const { + CubicPathComponent elevated(*this); + return elevated.Extrema(); +} + +std::optional QuadraticPathComponent::GetStartDirection() const { + if (p1 != cp) { + return (p1 - cp).Normalize(); + } + if (p1 != p2) { + return (p1 - p2).Normalize(); + } + return std::nullopt; +} + +std::optional QuadraticPathComponent::GetEndDirection() const { + if (p2 != cp) { + return (p2 - cp).Normalize(); + } + if (p2 != p1) { + return (p2 - p1).Normalize(); + } + return std::nullopt; +} + +Point ConicPathComponent::Solve(Scalar time) const { + return { + ConicSolve(time, p1.x, cp.x, p2.x, weight.x), // x + ConicSolve(time, p1.y, cp.y, p2.y, weight.y), // y + }; +} + +void ConicPathComponent::ToLinearPathComponents(Scalar scale_factor, + const PointProc& proc) const { + Scalar line_count = std::ceilf(ComputeConicSubdivisions(scale_factor, *this)); + for (size_t i = 1; i < line_count; i += 1) { + proc(Solve(i / line_count)); + } + proc(p2); +} + +void ConicPathComponent::AppendPolylinePoints( + Scalar scale_factor, + std::vector& points) const { + ToLinearPathComponents(scale_factor, [&points](const Point& point) { + if (point != points.back()) { + points.emplace_back(point); + } + }); +} + +void ConicPathComponent::ToLinearPathComponents(Scalar scale, + VertexWriter& writer) const { + Scalar line_count = std::ceilf(ComputeConicSubdivisions(scale, *this)); + for (size_t i = 1; i < line_count; i += 1) { + writer.Write(Solve(i / line_count)); + } + writer.Write(p2); +} + +size_t ConicPathComponent::CountLinearPathComponents(Scalar scale) const { + return std::ceilf(ComputeConicSubdivisions(scale, *this)) + 2; +} + +std::vector ConicPathComponent::Extrema() const { + std::vector points; + for (auto quad : ToQuadraticPathComponents()) { + auto quad_extrema = quad.Extrema(); + points.insert(points.end(), quad_extrema.begin(), quad_extrema.end()); + } + return points; +} + +std::optional ConicPathComponent::GetStartDirection() const { + if (p1 != cp) { + return (p1 - cp).Normalize(); + } + if (p1 != p2) { + return (p1 - p2).Normalize(); + } + return std::nullopt; +} + +std::optional ConicPathComponent::GetEndDirection() const { + if (p2 != cp) { + return (p2 - cp).Normalize(); + } + if (p2 != p1) { + return (p2 - p1).Normalize(); + } + return std::nullopt; +} + +void ConicPathComponent::SubdivideToQuadraticPoints( + std::array& points) const { + FML_DCHECK(weight.IsFinite() && weight.x > 0 && weight.y > 0); + + // Observe that scale will always be smaller than 1 because weight > 0. + const Scalar scale = 1.0f / (1.0f + weight.x); + + // The subdivided control points below are the sums of the following three + // terms. Because the terms are multiplied by something <1, and the resulting + // control points lie within the control points of the original then the + // terms and the sums below will not overflow. Note that weight * scale + // approaches 1 as weight becomes very large. + Point tp1 = p1 * scale; + Point tcp = cp * (weight.x * scale); + Point tp2 = p2 * scale; + + // Calculate the subdivided control points + Point sub_cp1 = tp1 + tcp; + Point sub_cp2 = tcp + tp2; + + // The middle point shared by the 2 sub-divisions, the interpolation of + // the original curve at its halfway point. + Point sub_mid = (tp1 + tcp + tcp + tp2) * 0.5f; + + FML_DCHECK(sub_cp1.IsFinite() && sub_mid.IsFinite() && sub_cp2.IsFinite()); + + points[0] = p1; + points[1] = sub_cp1; + points[2] = sub_mid; + points[3] = sub_cp2; + points[4] = p2; + + // Update w. + // Currently this method only subdivides a single time directly to 2 + // quadratics, but if we eventually want to keep the weights for further + // subdivision, this was the code that did it in Skia: + // sub_w1 = sub_w2 = SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf) +} + +std::array +ConicPathComponent::ToQuadraticPathComponents() const { + std::array points; + SubdivideToQuadraticPoints(points); + + return { + QuadraticPathComponent(points[0], points[1], points[2]), + QuadraticPathComponent(points[2], points[3], points[4]), + }; +} + +Point CubicPathComponent::Solve(Scalar time) const { + return { + CubicSolve(time, p1.x, cp1.x, cp2.x, p2.x), // x + CubicSolve(time, p1.y, cp1.y, cp2.y, p2.y), // y + }; +} + +Point CubicPathComponent::SolveDerivative(Scalar time) const { + return { + CubicSolveDerivative(time, p1.x, cp1.x, cp2.x, p2.x), // x + CubicSolveDerivative(time, p1.y, cp1.y, cp2.y, p2.y), // y + }; +} + +void CubicPathComponent::AppendPolylinePoints( + Scalar scale, + std::vector& points) const { + ToLinearPathComponents( + scale, [&points](const Point& point) { points.emplace_back(point); }); +} + +void CubicPathComponent::ToLinearPathComponents(Scalar scale, + VertexWriter& writer) const { + Scalar line_count = std::ceilf(ComputeCubicSubdivisions(scale, *this)); + for (size_t i = 1; i < line_count; i++) { + writer.Write(Solve(i / line_count)); + } + writer.Write(p2); +} + +size_t CubicPathComponent::CountLinearPathComponents(Scalar scale) const { + return std::ceilf(ComputeCubicSubdivisions(scale, *this)) + 2; +} + +inline QuadraticPathComponent CubicPathComponent::Lower() const { + return QuadraticPathComponent(3.0 * (cp1 - p1), 3.0 * (cp2 - cp1), + 3.0 * (p2 - cp2)); +} + +CubicPathComponent CubicPathComponent::Subsegment(Scalar t0, Scalar t1) const { + auto p0 = Solve(t0); + auto p3 = Solve(t1); + auto d = Lower(); + auto scale = (t1 - t0) * (1.0 / 3.0); + auto p1 = p0 + scale * d.Solve(t0); + auto p2 = p3 - scale * d.Solve(t1); + return CubicPathComponent(p0, p1, p2, p3); +} + +void CubicPathComponent::ToLinearPathComponents(Scalar scale, + const PointProc& proc) const { + Scalar line_count = std::ceilf(ComputeCubicSubdivisions(scale, *this)); + for (size_t i = 1; i < line_count; i++) { + proc(Solve(i / line_count)); + } + proc(p2); +} + +static inline bool NearEqual(Scalar a, Scalar b, Scalar epsilon) { + return (a > (b - epsilon)) && (a < (b + epsilon)); +} + +static inline bool NearZero(Scalar a) { + return NearEqual(a, 0.0, 1e-12); +} + +static void CubicPathBoundingPopulateValues(std::vector& values, + Scalar p1, + Scalar p2, + Scalar p3, + Scalar p4) { + const Scalar a = 3.0 * (-p1 + 3.0 * p2 - 3.0 * p3 + p4); + const Scalar b = 6.0 * (p1 - 2.0 * p2 + p3); + const Scalar c = 3.0 * (p2 - p1); + + /* + * Boundary conditions. + */ + if (NearZero(a)) { + if (NearZero(b)) { + return; + } + + Scalar t = -c / b; + if (t >= 0.0 && t <= 1.0) { + values.emplace_back(t); + } + return; + } + + Scalar b2Minus4AC = (b * b) - (4.0 * a * c); + + if (b2Minus4AC < 0.0) { + return; + } + + Scalar rootB2Minus4AC = ::sqrt(b2Minus4AC); + + /* From Numerical Recipes in C. + * + * q = -1/2 (b + sign(b) sqrt[b^2 - 4ac]) + * x1 = q / a + * x2 = c / q + */ + Scalar q = (b < 0) ? -(b - rootB2Minus4AC) / 2 : -(b + rootB2Minus4AC) / 2; + + { + Scalar t = q / a; + if (t >= 0.0 && t <= 1.0) { + values.emplace_back(t); + } + } + + { + Scalar t = c / q; + if (t >= 0.0 && t <= 1.0) { + values.emplace_back(t); + } + } +} + +std::vector CubicPathComponent::Extrema() const { + /* + * As described in: https://pomax.github.io/bezierinfo/#extremities + */ + std::vector values; + + CubicPathBoundingPopulateValues(values, p1.x, cp1.x, cp2.x, p2.x); + CubicPathBoundingPopulateValues(values, p1.y, cp1.y, cp2.y, p2.y); + + std::vector points = {p1, p2}; + + for (const auto& value : values) { + points.emplace_back(Solve(value)); + } + + return points; +} + +std::optional CubicPathComponent::GetStartDirection() const { + if (p1 != cp1) { + return (p1 - cp1).Normalize(); + } + if (p1 != cp2) { + return (p1 - cp2).Normalize(); + } + if (p1 != p2) { + return (p1 - p2).Normalize(); + } + return std::nullopt; +} + +std::optional CubicPathComponent::GetEndDirection() const { + if (p2 != cp2) { + return (p2 - cp2).Normalize(); + } + if (p2 != cp1) { + return (p2 - cp1).Normalize(); + } + if (p2 != p1) { + return (p2 - p1).Normalize(); + } + return std::nullopt; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/path_component.h b/flutter/engine/src/flutter/impeller/geometry/path_component.h new file mode 100644 index 0000000000000000000000000000000000000000..fb2be614aad099228f993cb26bddfe5d5629abe1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path_component.h @@ -0,0 +1,356 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_ +#define FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_ + +#include +#include +#include +#include +#include + +#include "impeller/geometry/point.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +/// @brief An interface for generating a multi contour polyline as a triangle +/// strip. +class VertexWriter { + public: + virtual void EndContour() = 0; + + virtual void Write(Point point) = 0; +}; + +/// @brief A vertex writer that generates a triangle fan and requires primitive +/// restart. +class FanVertexWriter : public VertexWriter { + public: + explicit FanVertexWriter(Point* point_buffer, uint16_t* index_buffer); + + ~FanVertexWriter(); + + size_t GetIndexCount() const; + + void EndContour() override; + + void Write(Point point) override; + + private: + size_t count_ = 0; + size_t index_count_ = 0; + Point* point_buffer_ = nullptr; + uint16_t* index_buffer_ = nullptr; +}; + +/// @brief A vertex writer that generates a triangle strip and requires +/// primitive restart. +class StripVertexWriter : public VertexWriter { + public: + explicit StripVertexWriter(Point* point_buffer, uint16_t* index_buffer); + + ~StripVertexWriter(); + + size_t GetIndexCount() const; + + void EndContour() override; + + void Write(Point point) override; + + private: + size_t count_ = 0; + size_t index_count_ = 0; + size_t contour_start_ = 0; + Point* point_buffer_ = nullptr; + uint16_t* index_buffer_ = nullptr; +}; + +/// @brief A vertex writer that generates a line strip topology. +class LineStripVertexWriter : public VertexWriter { + public: + explicit LineStripVertexWriter(std::vector& points); + + ~LineStripVertexWriter() = default; + + void EndContour() override; + + void Write(Point point) override; + + std::pair GetVertexCount() const; + + const std::vector& GetOversizedBuffer() const; + + private: + size_t offset_ = 0u; + std::vector& points_; + std::vector overflow_; +}; + +/// @brief A vertex writer that has no hardware requirements. +class GLESVertexWriter : public VertexWriter { + public: + explicit GLESVertexWriter(std::vector& points, + std::vector& indices); + + ~GLESVertexWriter() = default; + + void EndContour() override; + + void Write(Point point) override; + + private: + bool previous_contour_odd_points_ = false; + size_t contour_start_ = 0u; + std::vector& points_; + std::vector& indices_; +}; + +struct LinearPathComponent { + Point p1; + Point p2; + + LinearPathComponent() {} + + LinearPathComponent(Point ap1, Point ap2) : p1(ap1), p2(ap2) {} + + Point Solve(Scalar time) const; + + void AppendPolylinePoints(std::vector& points) const; + + std::vector Extrema() const; + + bool operator==(const LinearPathComponent& other) const { + return p1 == other.p1 && p2 == other.p2; + } + + std::optional GetStartDirection() const; + + std::optional GetEndDirection() const; +}; + +// A component that represets a Quadratic Bézier curve. +struct QuadraticPathComponent { + // Start point. + Point p1; + // Control point. + Point cp; + // End point. + Point p2; + + QuadraticPathComponent() {} + + QuadraticPathComponent(Point ap1, Point acp, Point ap2) + : p1(ap1), cp(acp), p2(ap2) {} + + Point Solve(Scalar time) const; + + Point SolveDerivative(Scalar time) const; + + void AppendPolylinePoints(Scalar scale_factor, + std::vector& points) const; + + using PointProc = std::function; + + void ToLinearPathComponents(Scalar scale_factor, const PointProc& proc) const; + + void ToLinearPathComponents(Scalar scale, VertexWriter& writer) const; + + size_t CountLinearPathComponents(Scalar scale) const; + + std::vector Extrema() const; + + bool operator==(const QuadraticPathComponent& other) const { + return p1 == other.p1 && cp == other.cp && p2 == other.p2; + } + + std::optional GetStartDirection() const; + + std::optional GetEndDirection() const; +}; + +// A component that represets a Conic section curve. +// +// A conic section is basically nearly a quadratic bezier curve, but it +// has an additional weight that is applied to the middle term (the control +// point term). +// +// Starting with the equation for a quadratic curve which is: +// (A) P1 * (1 - t) * (1 - t) +// + CP * 2 * t * (1 - t) +// + P2 * t * t +// One thing to note is that the quadratic coefficients always sum to 1: +// (B) (1-t)(1-t) + 2t(1-t) + tt +// == 1 - 2t + tt + 2t - 2tt + tt +// == 1 +// which means that the resulting point is always a weighted average of +// the 3 points without having to "divide by the sum of the coefficients" +// that is normally done when computing weighted averages. +// +// The conic equation, though, would then be: +// (C) P1 * (1 - t) * (1 - t) +// + CP * 2 * t * (1 - t) * w +// + P2 * t * t +// That would be the final equation, but if we look at the coefficients: +// (D) (1-t)(1-t) + 2wt(1-t) + tt +// == 1 - 2t + tt + 2wt - 2wtt + tt +// == 1 + (2w - 2)t + (2 - 2w)tt +// These only sum to 1 if the weight (w) is 1. In order for this math to +// produce a point that is the weighted average of the 3 points, we have +// to compute both and divide the equation (C) by the equation (D). +// +// Note that there are important potential optimizations we could apply. +// If w is 0, +// then this equation devolves into a straight line from P1 to P2. +// Note that the "progress" from P1 to P2, as a function of t, is +// quadratic if you compute it as the indicated numerator and denominator, +// but the actual points generated are all on the line from P1 to P2 +// If w is (sqrt(2) / 2), +// then this math is exactly an elliptical section, provided the 3 points +// P1, CP, P2 form a right angle, and a circular section if they are also +// of equal length (|P1,CP| == |CP,P2|) +// If w is 1, +// then we really don't need the division since the denominator will always +// be 1 and we could just treat that curve as a quadratic. +// If w is (infinity/large enough), +// then the equation devolves into 2 straight lines P1->CP->P2, but +// the straightforward math may encounter infinity/NaN values in the +// intermediate stages. The limit as w approaches infinity are those +// two lines. +// +// Some examples: https://fiddle.skia.org/c/986b521feb3b832f04cbdfeefc9fbc58 +// Note that the quadratic drawn in red in the center is identical to the +// conic with a weight of 1, drawn in green in the lower left. +struct ConicPathComponent { + // Start point. + Point p1; + // Control point. + Point cp; + // End point. + Point p2; + + // Weight + // + // We only need one value, but the underlying storage allocation is always + // a multiple of Point objects. To avoid confusion over which field the + // weight is stored in, and what the value of the other field may be, we + // store it in both x,y components of the |weight| field. + // + // This may also be an advantage eventually for code that can vectorize + // the conic calculations on both X & Y simultaneously. + Point weight; + + ConicPathComponent() {} + + ConicPathComponent(Point ap1, Point acp, Point ap2, Scalar weight) + : p1(ap1), cp(acp), p2(ap2), weight(weight, weight) {} + + Point Solve(Scalar time) const; + + void AppendPolylinePoints(Scalar scale_factor, + std::vector& points) const; + + using PointProc = std::function; + + void ToLinearPathComponents(Scalar scale_factor, const PointProc& proc) const; + + void ToLinearPathComponents(Scalar scale, VertexWriter& writer) const; + + size_t CountLinearPathComponents(Scalar scale) const; + + std::vector Extrema() const; + + bool operator==(const ConicPathComponent& other) const { + return p1 == other.p1 && cp == other.cp && p2 == other.p2 && + weight == other.weight; + } + + std::optional GetStartDirection() const; + + std::optional GetEndDirection() const; + + std::array ToQuadraticPathComponents() const; + + void SubdivideToQuadraticPoints(std::array& points) const; +}; + +// A component that represets a Cubic Bézier curve. +struct CubicPathComponent { + // Start point. + Point p1; + // The first control point. + Point cp1; + // The second control point. + Point cp2; + // End point. + Point p2; + + CubicPathComponent() {} + + explicit CubicPathComponent(const QuadraticPathComponent& q) + : p1(q.p1), + cp1(q.p1 + (q.cp - q.p1) * (2.0 / 3.0)), + cp2(q.p2 + (q.cp - q.p2) * (2.0 / 3.0)), + p2(q.p2) {} + + CubicPathComponent(Point ap1, Point acp1, Point acp2, Point ap2) + : p1(ap1), cp1(acp1), cp2(acp2), p2(ap2) {} + + Point Solve(Scalar time) const; + + Point SolveDerivative(Scalar time) const; + + void AppendPolylinePoints(Scalar scale, std::vector& points) const; + + std::vector Extrema() const; + + using PointProc = std::function; + + void ToLinearPathComponents(Scalar scale, const PointProc& proc) const; + + void ToLinearPathComponents(Scalar scale, VertexWriter& writer) const; + + size_t CountLinearPathComponents(Scalar scale) const; + + CubicPathComponent Subsegment(Scalar t0, Scalar t1) const; + + bool operator==(const CubicPathComponent& other) const { + return p1 == other.p1 && cp1 == other.cp1 && cp2 == other.cp2 && + p2 == other.p2; + } + + std::optional GetStartDirection() const; + + std::optional GetEndDirection() const; + + private: + QuadraticPathComponent Lower() const; +}; + +struct ContourComponent { + Point destination; + + // 0, 0 for closed, anything else for open. + Point closed = Point(1, 1); + + ContourComponent() {} + + constexpr bool IsClosed() const { return closed == Point{0, 0}; } + + explicit ContourComponent(Point p, Point closed) + : destination(p), closed(closed) {} + + bool operator==(const ContourComponent& other) const { + return destination == other.destination && IsClosed() == other.IsClosed(); + } +}; + +static_assert(!std::is_polymorphic::value); +static_assert(!std::is_polymorphic::value); +static_assert(!std::is_polymorphic::value); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_PATH_COMPONENT_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/path_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/path_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..8b7b5000de890eaa05b63cb0942f17c461a118f2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/path_unittests.cc @@ -0,0 +1,1297 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/testing/testing.h" +#include "impeller/geometry/geometry_asserts.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/round_rect.h" + +namespace impeller { +namespace testing { + +TEST(PathTest, CubicPathComponentPolylineDoesNotIncludePointOne) { + CubicPathComponent component({10, 10}, {20, 35}, {35, 20}, {40, 40}); + std::vector polyline; + component.AppendPolylinePoints(1.0f, polyline); + ASSERT_NE(polyline.front().x, 10); + ASSERT_NE(polyline.front().y, 10); + ASSERT_EQ(polyline.back().x, 40); + ASSERT_EQ(polyline.back().y, 40); +} + +TEST(PathTest, EmptyPathWithContour) { + PathBuilder builder; + auto path = builder.TakePath(); + + EXPECT_TRUE(path.IsEmpty()); +} + +TEST(PathTest, PathCreatePolyLineDoesNotDuplicatePoints) { + PathBuilder builder; + builder.MoveTo({10, 10}); + builder.LineTo({20, 20}); + builder.LineTo({30, 30}); + builder.MoveTo({40, 40}); + builder.LineTo({50, 50}); + + auto polyline = builder.TakePath().CreatePolyline(1.0f); + + ASSERT_EQ(polyline.contours.size(), 2u); + ASSERT_EQ(polyline.points->size(), 5u); + ASSERT_EQ(polyline.GetPoint(0).x, 10); + ASSERT_EQ(polyline.GetPoint(1).x, 20); + ASSERT_EQ(polyline.GetPoint(2).x, 30); + ASSERT_EQ(polyline.GetPoint(3).x, 40); + ASSERT_EQ(polyline.GetPoint(4).x, 50); +} + +TEST(PathTest, PathSingleContour) { + // Closed shapes. + { + Path path = PathBuilder{}.AddCircle({100, 100}, 50).TakePath(); + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = + PathBuilder{}.AddOval(Rect::MakeXYWH(100, 100, 100, 100)).TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = + PathBuilder{}.AddRect(Rect::MakeXYWH(100, 100, 100, 100)).TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundSuperellipse(RoundSuperellipse::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + // Open shapes. + { + Point p(100, 100); + Path path = PathBuilder{}.AddLine(p, {200, 100}).TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = + PathBuilder{} + .AddCubicCurve({100, 100}, {100, 50}, {100, 150}, {200, 100}) + .TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddQuadraticCurve({100, 100}, {100, 50}, {200, 100}) + .TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddConicCurve({100, 100}, {100, 50}, {200, 100}, 0.75f) + .TakePath(); + + EXPECT_TRUE(path.IsSingleContour()); + } +} + +TEST(PathTest, PathSingleContourDoubleShapes) { + // Closed shapes. + { + Path path = PathBuilder{} + .AddCircle({100, 100}, 50) + .AddCircle({100, 100}, 50) + .TakePath(); + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddOval(Rect::MakeXYWH(100, 100, 100, 100)) + .AddOval(Rect::MakeXYWH(100, 100, 100, 100)) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRect(Rect::MakeXYWH(100, 100, 100, 100)) + .AddRect(Rect::MakeXYWH(100, 100, 100, 100)) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .AddRoundRect(RoundRect::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundSuperellipse(RoundSuperellipse::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .AddRoundSuperellipse(RoundSuperellipse::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddRoundSuperellipse(RoundSuperellipse::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .AddRoundSuperellipse(RoundSuperellipse::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + // Open shapes. + { + Point p(100, 100); + Path path = + PathBuilder{}.AddLine(p, {200, 100}).AddLine(p, {200, 100}).TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = + PathBuilder{} + .AddCubicCurve({100, 100}, {100, 50}, {100, 150}, {200, 100}) + .AddCubicCurve({100, 100}, {100, 50}, {100, 150}, {200, 100}) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddQuadraticCurve({100, 100}, {100, 50}, {200, 100}) + .Close() + .AddQuadraticCurve({100, 100}, {100, 50}, {200, 100}) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } + + { + Path path = PathBuilder{} + .AddConicCurve({100, 100}, {100, 50}, {200, 100}, 0.75f) + .Close() + .AddConicCurve({100, 100}, {100, 50}, {200, 100}, 0.75f) + .TakePath(); + + EXPECT_FALSE(path.IsSingleContour()); + } +} + +TEST(PathTest, PathBuilderSetsCorrectContourPropertiesForAddCommands) { + // Closed shapes. + { + Path path = PathBuilder{}.AddCircle({100, 100}, 50).TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(100, 50)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = + PathBuilder{}.AddOval(Rect::MakeXYWH(100, 100, 100, 100)).TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(150, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = + PathBuilder{}.AddRect(Rect::MakeXYWH(100, 100, 100, 100)).TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(100, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(110, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(110, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddRoundSuperellipse(RoundSuperellipse::MakeRectRadius( + Rect::MakeXYWH(100, 100, 100, 100), 10)) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(150, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddRoundSuperellipse(RoundSuperellipse::MakeRectXY( + Rect::MakeXYWH(100, 100, 100, 100), Size(10, 20))) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(150, 100)); + EXPECT_TRUE(contour->IsClosed()); + } + + // Open shapes. + { + Point p(100, 100); + Path path = PathBuilder{}.AddLine(p, {200, 100}).TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, p); + EXPECT_FALSE(contour->IsClosed()); + } + + { + Path path = + PathBuilder{} + .AddCubicCurve({100, 100}, {100, 50}, {100, 150}, {200, 100}) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(100, 100)); + EXPECT_FALSE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddQuadraticCurve({100, 100}, {100, 50}, {200, 100}) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(100, 100)); + EXPECT_FALSE(contour->IsClosed()); + } + + { + Path path = PathBuilder{} + .AddConicCurve({100, 100}, {100, 50}, {200, 100}, 0.75f) + .TakePath(); + EXPECT_NE(path.begin(), path.end()); + EXPECT_EQ(path.begin().type(), Path::ComponentType::kContour); + auto contour = path.begin().contour(); + ASSERT_NE(contour, nullptr); + EXPECT_POINT_NEAR(contour->destination, Point(100, 100)); + EXPECT_FALSE(contour->IsClosed()); + } +} + +TEST(PathTest, PathCreatePolylineGeneratesCorrectContourData) { + Path::Polyline polyline = PathBuilder{} + .AddLine({100, 100}, {200, 100}) + .MoveTo({100, 200}) + .LineTo({150, 250}) + .LineTo({200, 200}) + .Close() + .TakePath() + .CreatePolyline(1.0f); + ASSERT_EQ(polyline.points->size(), 6u); + ASSERT_EQ(polyline.contours.size(), 2u); + ASSERT_EQ(polyline.contours[0].is_closed, false); + ASSERT_EQ(polyline.contours[0].start_index, 0u); + ASSERT_EQ(polyline.contours[1].is_closed, true); + ASSERT_EQ(polyline.contours[1].start_index, 2u); +} + +TEST(PathTest, PolylineGetContourPointBoundsReturnsCorrectRanges) { + Path::Polyline polyline = PathBuilder{} + .AddLine({100, 100}, {200, 100}) + .MoveTo({100, 200}) + .LineTo({150, 250}) + .LineTo({200, 200}) + .Close() + .TakePath() + .CreatePolyline(1.0f); + size_t a1, a2, b1, b2; + std::tie(a1, a2) = polyline.GetContourPointBounds(0); + std::tie(b1, b2) = polyline.GetContourPointBounds(1); + ASSERT_EQ(a1, 0u); + ASSERT_EQ(a2, 2u); + ASSERT_EQ(b1, 2u); + ASSERT_EQ(b2, 6u); +} + +TEST(PathTest, PathAddRectPolylineHasCorrectContourData) { + Path::Polyline polyline = PathBuilder{} + .AddRect(Rect::MakeLTRB(50, 60, 70, 80)) + .TakePath() + .CreatePolyline(1.0f); + ASSERT_EQ(polyline.contours.size(), 1u); + ASSERT_TRUE(polyline.contours[0].is_closed); + ASSERT_EQ(polyline.contours[0].start_index, 0u); + ASSERT_EQ(polyline.points->size(), 5u); + ASSERT_EQ(polyline.GetPoint(0), Point(50, 60)); + ASSERT_EQ(polyline.GetPoint(1), Point(70, 60)); + ASSERT_EQ(polyline.GetPoint(2), Point(70, 80)); + ASSERT_EQ(polyline.GetPoint(3), Point(50, 80)); + ASSERT_EQ(polyline.GetPoint(4), Point(50, 60)); +} + +TEST(PathTest, PathPolylineDuplicatesAreRemovedForSameContour) { + Path::Polyline polyline = + PathBuilder{} + .MoveTo({50, 50}) + .LineTo({50, 50}) // Insert duplicate at beginning of contour. + .LineTo({100, 50}) + .LineTo({100, 50}) // Insert duplicate at contour join. + .LineTo({100, 100}) + .Close() // Implicitly insert duplicate {50, 50} across contours. + .LineTo({0, 50}) + .LineTo({0, 100}) + .LineTo({0, 100}) // Insert duplicate at end of contour. + .TakePath() + .CreatePolyline(1.0f); + ASSERT_EQ(polyline.contours.size(), 2u); + ASSERT_EQ(polyline.contours[0].start_index, 0u); + ASSERT_TRUE(polyline.contours[0].is_closed); + ASSERT_EQ(polyline.contours[1].start_index, 4u); + ASSERT_FALSE(polyline.contours[1].is_closed); + ASSERT_EQ(polyline.points->size(), 7u); + ASSERT_EQ(polyline.GetPoint(0), Point(50, 50)); + ASSERT_EQ(polyline.GetPoint(1), Point(100, 50)); + ASSERT_EQ(polyline.GetPoint(2), Point(100, 100)); + ASSERT_EQ(polyline.GetPoint(3), Point(50, 50)); + ASSERT_EQ(polyline.GetPoint(4), Point(50, 50)); + ASSERT_EQ(polyline.GetPoint(5), Point(0, 50)); + ASSERT_EQ(polyline.GetPoint(6), Point(0, 100)); +} + +TEST(PathTest, PolylineBufferReuse) { + auto point_buffer = std::make_unique>(); + auto point_buffer_address = reinterpret_cast(point_buffer.get()); + Path::Polyline polyline = + PathBuilder{} + .MoveTo({50, 50}) + .LineTo({100, 100}) + .TakePath() + .CreatePolyline( + 1.0f, std::move(point_buffer), + [point_buffer_address]( + Path::Polyline::PointBufferPtr point_buffer) { + ASSERT_EQ(point_buffer->size(), 0u); + ASSERT_EQ(point_buffer_address, + reinterpret_cast(point_buffer.get())); + }); +} + +TEST(PathTest, PolylineFailsWithNullptrBuffer) { + EXPECT_DEATH_IF_SUPPORTED(PathBuilder{} + .MoveTo({50, 50}) + .LineTo({100, 100}) + .TakePath() + .CreatePolyline(1.0f, nullptr), + ""); +} + +TEST(PathTest, PathShifting) { + PathBuilder builder{}; + auto path = + builder.AddLine(Point(0, 0), Point(10, 10)) + .AddQuadraticCurve(Point(10, 10), Point(15, 15), Point(20, 20)) + .AddConicCurve(Point(10, 10), Point(15, 10), Point(15, 15), 0.75f) + .AddCubicCurve(Point(20, 20), Point(25, 25), Point(-5, -5), + Point(30, 30)) + .Close() + .Shift(Point(1, 1)) + .TakePath(); + + auto it = path.begin(); + + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kLinear); + const LinearPathComponent* linear = it.linear(); + ASSERT_NE(linear, nullptr); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kQuadratic); + const QuadraticPathComponent* quad = it.quadratic(); + ASSERT_NE(quad, nullptr); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kConic); + const ConicPathComponent* conic = it.conic(); + ASSERT_NE(conic, nullptr); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kCubic); + const CubicPathComponent* cubic = it.cubic(); + ASSERT_NE(cubic, nullptr); + ++it; + + // Close always opens a new contour, even if it isn't needed + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + EXPECT_EQ(it, path.end()); + + EXPECT_EQ(contour->destination, Point(1, 1)); + + EXPECT_EQ(linear->p1, Point(1, 1)); + EXPECT_EQ(linear->p2, Point(11, 11)); + + EXPECT_EQ(quad->cp, Point(16, 16)); + EXPECT_EQ(quad->p1, Point(11, 11)); + EXPECT_EQ(quad->p2, Point(21, 21)); + + EXPECT_EQ(cubic->cp1, Point(26, 26)); + EXPECT_EQ(cubic->cp2, Point(-4, -4)); + EXPECT_EQ(cubic->p1, Point(21, 21)); + EXPECT_EQ(cubic->p2, Point(31, 31)); +} + +TEST(PathTest, PathBuilderWillComputeBounds) { + PathBuilder builder; + auto path_1 = builder.AddLine({0, 0}, {1, 1}).TakePath(); + + ASSERT_EQ(path_1.GetBoundingBox().value_or(Rect::MakeMaximum()), + Rect::MakeLTRB(0, 0, 1, 1)); + + auto path_2 = builder.AddLine({-1, -1}, {1, 1}).TakePath(); + + // Verify that PathBuilder recomputes the bounds. + ASSERT_EQ(path_2.GetBoundingBox().value_or(Rect::MakeMaximum()), + Rect::MakeLTRB(-1, -1, 1, 1)); + + // PathBuilder can set the bounds to whatever it wants + auto path_3 = builder.AddLine({0, 0}, {1, 1}) + .SetBounds(Rect::MakeLTRB(0, 0, 100, 100)) + .TakePath(); + + ASSERT_EQ(path_3.GetBoundingBox().value_or(Rect::MakeMaximum()), + Rect::MakeLTRB(0, 0, 100, 100)); +} + +TEST(PathTest, PathHorizontalLine) { + PathBuilder builder; + auto path = builder.HorizontalLineTo(10).TakePath(); + + auto it = path.begin(); + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kLinear); + const LinearPathComponent* linear = it.linear(); + ASSERT_NE(linear, nullptr); + + EXPECT_EQ(linear->p1, Point(0, 0)); + EXPECT_EQ(linear->p2, Point(10, 0)); +} + +TEST(PathTest, PathVerticalLine) { + PathBuilder builder; + auto path = builder.VerticalLineTo(10).TakePath(); + + auto it = path.begin(); + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kLinear); + const LinearPathComponent* linear = it.linear(); + ASSERT_NE(linear, nullptr); + + EXPECT_EQ(linear->p1, Point(0, 0)); + EXPECT_EQ(linear->p2, Point(0, 10)); +} + +TEST(PathTest, QuadradicPath) { + PathBuilder builder; + auto path = builder.QuadraticCurveTo(Point(10, 10), Point(20, 20)).TakePath(); + + auto it = path.begin(); + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kQuadratic); + const QuadraticPathComponent* quad = it.quadratic(); + ASSERT_NE(quad, nullptr); + + EXPECT_EQ(quad->p1, Point(0, 0)); + EXPECT_EQ(quad->cp, Point(10, 10)); + EXPECT_EQ(quad->p2, Point(20, 20)); +} + +TEST(PathTest, ConicPath) { + PathBuilder builder; + auto path = + builder.ConicCurveTo(Point(10, 10), Point(20, 20), 0.75f).TakePath(); + + auto it = path.begin(); + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kConic); + const ConicPathComponent* conic = it.conic(); + ASSERT_NE(conic, nullptr); + + EXPECT_EQ(conic->p1, Point(0, 0)); + EXPECT_EQ(conic->cp, Point(10, 10)); + EXPECT_EQ(conic->p2, Point(20, 20)); + EXPECT_EQ(conic->weight, Point(0.75f, 0.75f)); +} + +TEST(PathTest, CubicPath) { + PathBuilder builder; + auto path = + builder.CubicCurveTo(Point(10, 10), Point(-10, -10), Point(20, 20)) + .TakePath(); + + auto it = path.begin(); + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + ++it; + + ASSERT_EQ(it.type(), Path::ComponentType::kCubic); + const CubicPathComponent* cubic = it.cubic(); + ASSERT_NE(cubic, nullptr); + + EXPECT_EQ(cubic->p1, Point(0, 0)); + EXPECT_EQ(cubic->cp1, Point(10, 10)); + EXPECT_EQ(cubic->cp2, Point(-10, -10)); + EXPECT_EQ(cubic->p2, Point(20, 20)); +} + +TEST(PathTest, BoundingBoxCubic) { + PathBuilder builder; + auto path = + builder.AddCubicCurve({120, 160}, {25, 200}, {220, 260}, {220, 40}) + .TakePath(); + auto box = path.GetBoundingBox(); + Rect expected = Rect::MakeXYWH(93.9101, 40, 126.09, 158.862); + ASSERT_TRUE(box.has_value()); + ASSERT_RECT_NEAR(box.value_or(Rect::MakeMaximum()), expected); +} + +TEST(PathTest, BoundingBoxOfCompositePathIsCorrect) { + PathBuilder builder; + builder.AddRoundRect( + RoundRect::MakeRectRadius(Rect::MakeXYWH(10, 10, 300, 300), 50)); + auto path = builder.TakePath(); + auto actual = path.GetBoundingBox(); + Rect expected = Rect::MakeXYWH(10, 10, 300, 300); + + ASSERT_TRUE(actual.has_value()); + ASSERT_RECT_NEAR(actual.value_or(Rect::MakeMaximum()), expected); +} + +TEST(PathTest, ExtremaOfCubicPathComponentIsCorrect) { + CubicPathComponent cubic{{11.769268, 252.883148}, + {-6.2857933, 204.356461}, + {-4.53997231, 156.552902}, + {17.0067291, 109.472488}}; + auto points = cubic.Extrema(); + + ASSERT_EQ(points.size(), static_cast(3)); + ASSERT_POINT_NEAR(points[2], cubic.Solve(0.455916)); +} + +TEST(PathTest, PathGetBoundingBoxForCubicWithNoDerivativeRootsIsCorrect) { + PathBuilder builder; + // Straight diagonal line. + builder.AddCubicCurve({0, 1}, {2, 3}, {4, 5}, {6, 7}); + auto path = builder.TakePath(); + auto actual = path.GetBoundingBox(); + auto expected = Rect::MakeLTRB(0, 1, 6, 7); + + ASSERT_TRUE(actual.has_value()); + ASSERT_RECT_NEAR(actual.value_or(Rect::MakeMaximum()), expected); +} + +TEST(PathTest, EmptyPath) { + auto path = PathBuilder{}.TakePath(); + ASSERT_EQ(path.GetComponentCount(), 1u); + + const ContourComponent* c = path.begin().contour(); + ASSERT_POINT_NEAR(c->destination, Point()); + + Path::Polyline polyline = path.CreatePolyline(1.0f); + ASSERT_TRUE(polyline.points->empty()); + ASSERT_TRUE(polyline.contours.empty()); +} + +TEST(PathTest, SimplePath) { + PathBuilder builder; + + auto path = builder.AddLine({0, 0}, {100, 100}) + .AddQuadraticCurve({100, 100}, {200, 200}, {300, 300}) + .AddConicCurve({100, 100}, {200, 200}, {300, 300}, 0.75f) + .AddCubicCurve({300, 300}, {400, 400}, {500, 500}, {600, 600}) + .TakePath(); + + EXPECT_EQ(path.GetComponentCount(), 8u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kLinear), 1u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kQuadratic), 1u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kConic), 1u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kCubic), 1u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kContour), 4u); + + auto it = path.begin(); + + { + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr); + ++it; + + Point p1(0, 0); + EXPECT_EQ(contour->destination, p1); + EXPECT_FALSE(contour->IsClosed()); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kLinear); + const LinearPathComponent* linear = it.linear(); + ASSERT_NE(linear, nullptr); + ++it; + + Point p1(0, 0); + Point p2(100, 100); + EXPECT_EQ(linear->p1, p1); + EXPECT_EQ(linear->p2, p2); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr); + ++it; + + Point p1(100, 100); + EXPECT_EQ(contour->destination, p1); + EXPECT_FALSE(contour->IsClosed()); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kQuadratic); + const QuadraticPathComponent* quad = it.quadratic(); + ASSERT_NE(quad, nullptr); + ++it; + + Point p1(100, 100); + Point cp(200, 200); + Point p2(300, 300); + EXPECT_EQ(quad->p1, p1); + EXPECT_EQ(quad->cp, cp); + EXPECT_EQ(quad->p2, p2); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr); + ++it; + + Point p1(100, 100); + EXPECT_EQ(contour->destination, p1); + EXPECT_FALSE(contour->IsClosed()); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kConic); + const ConicPathComponent* conic = it.conic(); + ASSERT_NE(conic, nullptr); + ++it; + + Point p1(100, 100); + Point cp(200, 200); + Point p2(300, 300); + Point weight(0.75f, 0.75f); + EXPECT_EQ(conic->p1, p1); + EXPECT_EQ(conic->cp, cp); + EXPECT_EQ(conic->p2, p2); + EXPECT_EQ(conic->weight, weight); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kContour); + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr); + ++it; + + Point p1(300, 300); + EXPECT_EQ(contour->destination, p1); + EXPECT_FALSE(contour->IsClosed()); + } + + { + ASSERT_EQ(it.type(), Path::ComponentType::kCubic); + const CubicPathComponent* cubic = it.cubic(); + ASSERT_NE(cubic, nullptr); + ++it; + + Point p1(300, 300); + Point cp1(400, 400); + Point cp2(500, 500); + Point p2(600, 600); + EXPECT_EQ(cubic->p1, p1); + EXPECT_EQ(cubic->cp1, cp1); + EXPECT_EQ(cubic->cp2, cp2); + EXPECT_EQ(cubic->p2, p2); + } + + EXPECT_EQ(it, path.end()); +} + +TEST(PathTest, RepeatCloseDoesNotAddNewLines) { + PathBuilder builder; + auto path = builder.LineTo({0, 10}) + .LineTo({10, 10}) + .Close() // Returns to (0, 0) + .Close() // No Op + .Close() // Still No op + .TakePath(); + + EXPECT_EQ(path.GetComponentCount(), 5u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kLinear), 3u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kContour), 2u); +} + +TEST(PathTest, CloseAfterMoveDoesNotAddNewLines) { + PathBuilder builder; + auto path = builder.LineTo({0, 10}) + .LineTo({10, 10}) + .MoveTo({30, 30}) // Moves to (30, 30) + .Close() // No Op + .Close() // Still No op + .TakePath(); + + EXPECT_EQ(path.GetComponentCount(), 4u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kLinear), 2u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kContour), 2u); +} + +TEST(PathTest, CloseAtOriginDoesNotAddNewLineSegment) { + PathBuilder builder; + // Create a path that has a current position at the origin when close is + // called. This should not insert a new line segment + auto path = builder.LineTo({10, 0}) + .LineTo({10, 10}) + .LineTo({0, 10}) + .LineTo({0, 0}) + .Close() + .TakePath(); + + EXPECT_EQ(path.GetComponentCount(), 6u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kLinear), 4u); + EXPECT_EQ(path.GetComponentCount(Path::ComponentType::kContour), 2u); +} + +TEST(PathTest, CanBeCloned) { + PathBuilder builder; + builder.MoveTo({10, 10}); + builder.LineTo({20, 20}); + builder.SetBounds(Rect::MakeLTRB(0, 0, 100, 100)); + builder.SetConvexity(Convexity::kConvex); + + auto path_a = builder.TakePath(FillType::kOdd); + // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) + auto path_b = path_a; + + EXPECT_EQ(path_a.GetBoundingBox(), path_b.GetBoundingBox()); + EXPECT_EQ(path_a.GetFillType(), path_b.GetFillType()); + EXPECT_EQ(path_a.IsConvex(), path_b.IsConvex()); + + auto poly_a = path_a.CreatePolyline(1.0); + auto poly_b = path_b.CreatePolyline(1.0); + + ASSERT_EQ(poly_a.points->size(), poly_b.points->size()); + ASSERT_EQ(poly_a.contours.size(), poly_b.contours.size()); + + for (auto i = 0u; i < poly_a.points->size(); i++) { + EXPECT_EQ((*poly_a.points)[i], (*poly_b.points)[i]); + } + + for (auto i = 0u; i < poly_a.contours.size(); i++) { + EXPECT_EQ(poly_a.contours[i].start_index, poly_b.contours[i].start_index); + EXPECT_EQ(poly_a.contours[i].start_direction, + poly_b.contours[i].start_direction); + } +} + +TEST(PathTest, FanTessellation) { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeLTRB(0, 0, 100, 100), 10)) + .TakePath(); + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + FanVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(writer.GetIndexCount(), index_storage.size()); + EXPECT_EQ(point_storage[0], Point(10, 0)); +} + +// Filled Paths without an explicit close should still be closed +TEST(PathTest, FanTessellationUnclosedPath) { + // Create a rectangle that lacks an explicit close. + Path path = PathBuilder{} + .LineTo({100, 0}) + .LineTo({100, 100}) + .LineTo({0, 100}) + .TakePath(); + + std::vector expected = {{0, 0}, {100, 0}, {100, 100}, + {0, 100}, {0, 0}, {0, 0}}; + std::vector expected_indices = {0, 1, 2, 3, 0xFFFF, 0}; + + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + FanVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(index_storage, expected_indices); + EXPECT_EQ(point_storage, expected); +} + +// Filled Paths without an explicit close should still be closed +TEST(PathTest, StripTessellationUnclosedPath) { + // Create a rectangle that lacks an explicit close. + Path path = PathBuilder{} + .LineTo({100, 0}) + .LineTo({100, 100}) + .LineTo({0, 100}) + .TakePath(); + + std::vector expected = {{0, 0}, {100, 0}, {100, 100}, + {0, 100}, {0, 0}, {0, 0}}; + std::vector expected_indices = {0, 1, 3, 2, 0xFFFF, 0}; + + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + StripVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(index_storage, expected_indices); + EXPECT_EQ(point_storage, expected); +} + +TEST(PathTest, FanTessellationMultiContour) { + PathBuilder builder{}; + for (auto i = 0; i < 10; i++) { + builder.AddRoundRect( + RoundRect::MakeRectRadius(Rect::MakeLTRB(0 + i, 0 + i, 100, 100), 10)); + } + auto path = builder.TakePath(); + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + FanVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(writer.GetIndexCount(), index_storage.size()); + EXPECT_EQ(point_storage[0], Point(10, 0)); +} + +TEST(PathTest, StripTessellation) { + Path path = PathBuilder{} + .AddRoundRect(RoundRect::MakeRectRadius( + Rect::MakeLTRB(0, 0, 100, 100), 10)) + .TakePath(); + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + StripVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(writer.GetIndexCount(), index_storage.size()); + EXPECT_EQ(point_storage[0], Point(10, 0)); +} + +TEST(PathTest, StripTessellationMultiContour) { + PathBuilder builder{}; + for (auto i = 0; i < 10; i++) { + builder.AddRoundRect( + RoundRect::MakeRectRadius(Rect::MakeLTRB(0 + i, 0 + i, 100, 100), 10)); + } + auto path = builder.TakePath(); + auto [points, contours] = path.CountStorage(1.0); + + std::vector point_storage(points); + std::vector index_storage(points + (contours - 1)); + + StripVertexWriter writer(point_storage.data(), index_storage.data()); + path.WritePolyline(1.0, writer); + + EXPECT_LE(writer.GetIndexCount(), index_storage.size()); + EXPECT_EQ(point_storage[0], Point(10, 0)); +} + +TEST(PathTest, PathBuilderAddPathBasher) { + PathBuilder test_path_builder; + test_path_builder.AddOval(Rect::MakeLTRB(10, 10, 50, 50)); + Path test_path = test_path_builder.TakePath(); + for (int i = 0; i < 2000; i++) { + PathBuilder path_builder; + for (int j = 0; j < 10; j++) { + path_builder.AddCircle(Point(50, 50), 25); + path_builder.AddOval(Rect::MakeLTRB(100, 100, 200, 200)); + path_builder.AddPath(test_path); + path_builder.AddRect(Rect::MakeLTRB(50, 50, 75, 57)); + path_builder.AddLine(Point(80, 70), Point(110, 95)); + path_builder.AddArc(Rect::MakeLTRB(50, 50, 100, 100), Degrees(20), + Degrees(100)); + path_builder.AddRoundRect(RoundRect::MakeRectXY( + Rect::MakeLTRB(70, 70, 130, 130), Size(10, 10))); + } + Path test_path = path_builder.TakePath(); + auto bounds = test_path.GetBoundingBox(); + EXPECT_TRUE(bounds.has_value()); + if (bounds.has_value()) { + EXPECT_EQ(bounds.value(), Rect::MakeLTRB(10, 10, 200, 200)); + } + } +} + +TEST(PathTest, PathBuilderDoesNotMutateCopiedPaths) { + auto test_isolation = + [](const std::function& mutator, + bool will_close, Point mutation_offset, const std::string& label) { + PathBuilder builder; + builder.MoveTo({10, 10}); + builder.LineTo({20, 20}); + builder.LineTo({20, 10}); + + auto verify_path = [](const Path& path, bool is_mutated, bool is_closed, + Point offset, const std::string& label) { + if (is_mutated) { + // We can only test the initial state before the mutator did + // its work. We have >= 3 components and the first 3 components + // will match what we saw before the mutation. + EXPECT_GE(path.GetComponentCount(), 3u) << label; + } else { + EXPECT_EQ(path.GetComponentCount(), 3u) << label; + } + auto it = path.begin(); + { + ASSERT_EQ(it.type(), Path::ComponentType::kContour) << label; + const ContourComponent* contour = it.contour(); + ASSERT_NE(contour, nullptr) << label; + ++it; + + EXPECT_EQ(contour->destination, offset + Point(10, 10)) << label; + EXPECT_EQ(contour->IsClosed(), is_closed) << label; + } + { + ASSERT_EQ(it.type(), Path::ComponentType::kLinear) << label; + const LinearPathComponent* line = it.linear(); + ASSERT_NE(line, nullptr) << label; + ++it; + + EXPECT_EQ(line->p1, offset + Point(10, 10)) << label; + EXPECT_EQ(line->p2, offset + Point(20, 20)) << label; + } + { + ASSERT_EQ(it.type(), Path::ComponentType::kLinear) << label; + const LinearPathComponent* line = it.linear(); + ASSERT_NE(line, nullptr) << label; + ++it; + + EXPECT_EQ(line->p1, offset + Point(20, 20)) << label; + EXPECT_EQ(line->p2, offset + Point(20, 10)) << label; + } + if (!is_mutated) { + EXPECT_EQ(it, path.end()) << label; + } + }; + + auto path1 = builder.CopyPath(); + verify_path(path1, false, false, {}, + "Initial Path1 state before " + label); + + for (int i = 0; i < 10; i++) { + auto path = builder.CopyPath(); + verify_path( + path, false, false, {}, + "Extra CopyPath #" + std::to_string(i + 1) + " for " + label); + } + mutator(builder); + verify_path(path1, false, false, {}, + "Path1 state after subsequent " + label); + + auto path2 = builder.CopyPath(); + verify_path(path1, false, false, {}, + "Path1 state after subsequent " + label + " and CopyPath"); + verify_path(path2, true, will_close, mutation_offset, + "Initial Path2 state with subsequent " + label); + }; + + test_isolation( + [](PathBuilder& builder) { // + builder.SetConvexity(Convexity::kConvex); + }, + false, {}, "SetConvex"); + + test_isolation( + [](PathBuilder& builder) { // + builder.SetConvexity(Convexity::kUnknown); + }, + false, {}, "SetUnknownConvex"); + + test_isolation( + [](PathBuilder& builder) { // + builder.Close(); + }, + true, {}, "Close"); + + test_isolation( + [](PathBuilder& builder) { + builder.MoveTo({20, 30}, false); + }, + false, {}, "Absolute MoveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.MoveTo({20, 30}, true); + }, + false, {}, "Relative MoveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.LineTo({20, 30}, false); + }, + false, {}, "Absolute LineTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.LineTo({20, 30}, true); + }, + false, {}, "Relative LineTo"); + + test_isolation( + [](PathBuilder& builder) { // + builder.HorizontalLineTo(100, false); + }, + false, {}, "Absolute HorizontalLineTo"); + + test_isolation( + [](PathBuilder& builder) { // + builder.HorizontalLineTo(100, true); + }, + false, {}, "Relative HorizontalLineTo"); + + test_isolation( + [](PathBuilder& builder) { // + builder.VerticalLineTo(100, false); + }, + false, {}, "Absolute VerticalLineTo"); + + test_isolation( + [](PathBuilder& builder) { // + builder.VerticalLineTo(100, true); + }, + false, {}, "Relative VerticalLineTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.QuadraticCurveTo({20, 30}, {30, 20}, false); + }, + false, {}, "Absolute QuadraticCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.QuadraticCurveTo({20, 30}, {30, 20}, true); + }, + false, {}, "Relative QuadraticCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.ConicCurveTo({20, 30}, {30, 20}, 0.75f, false); + }, + false, {}, "Absolute ConicCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.ConicCurveTo({20, 30}, {30, 20}, 0.75f, true); + }, + false, {}, "Relative ConicCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.CubicCurveTo({20, 30}, {30, 20}, {30, 30}, false); + }, + false, {}, "Absolute CubicCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.CubicCurveTo({20, 30}, {30, 20}, {30, 30}, true); + }, + false, {}, "Relative CubicCurveTo"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddLine({100, 100}, {150, 100}); + }, + false, {}, "AddLine"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddRect(Rect::MakeLTRB(100, 100, 120, 120)); + }, + false, {}, "AddRect"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddOval(Rect::MakeLTRB(100, 100, 120, 120)); + }, + false, {}, "AddOval"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddCircle({100, 100}, 20); + }, + false, {}, "AddCircle"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddArc(Rect::MakeLTRB(100, 100, 120, 120), Degrees(10), + Degrees(170)); + }, + false, {}, "AddArc"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddQuadraticCurve({100, 100}, {150, 100}, {150, 150}); + }, + false, {}, "AddQuadraticCurve"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddConicCurve({100, 100}, {150, 100}, {150, 150}, 0.75f); + }, + false, {}, "AddConicCurve"); + + test_isolation( + [](PathBuilder& builder) { + builder.AddCubicCurve({100, 100}, {150, 100}, {100, 150}, {150, 150}); + }, + false, {}, "AddCubicCurve"); + + test_isolation( + [](PathBuilder& builder) { + builder.Shift({23, 42}); + }, + false, {23, 42}, "Shift"); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/point.cc b/flutter/engine/src/flutter/impeller/geometry/point.cc new file mode 100644 index 0000000000000000000000000000000000000000..a00f1bf57cffb00e29c74ff3b72070d4e76c3110 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/point.cc @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "point.h" +#include + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/point.h b/flutter/engine/src/flutter/impeller/geometry/point.h new file mode 100644 index 0000000000000000000000000000000000000000..2c19467c6439b9f06cc6ac538aa67673f109d552 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/point.h @@ -0,0 +1,350 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_POINT_H_ +#define FLUTTER_IMPELLER_GEOMETRY_POINT_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/size.h" +#include "impeller/geometry/type_traits.h" + +namespace impeller { + +#define ONLY_ON_FLOAT_M(Modifiers, Return) \ + template \ + Modifiers std::enable_if_t, Return> +#define ONLY_ON_FLOAT(Return) DL_ONLY_ON_FLOAT_M(, Return) + +template +struct TPoint { + using Type = T; + + Type x = {}; + Type y = {}; + + constexpr TPoint() = default; + + template + explicit constexpr TPoint(const TPoint& other) + : TPoint(static_cast(other.x), static_cast(other.y)) {} + + template + explicit constexpr TPoint(const TSize& other) + : TPoint(static_cast(other.width), + static_cast(other.height)) {} + + constexpr TPoint(Type x, Type y) : x(x), y(y) {} + + static constexpr TPoint MakeXY(Type x, Type y) { return {x, y}; } + + template + static constexpr TPoint Round(const TPoint& other) { + return TPoint{static_cast(std::round(other.x)), + static_cast(std::round(other.y))}; + } + + constexpr bool operator==(const TPoint& p) const { + return p.x == x && p.y == y; + } + + constexpr bool operator!=(const TPoint& p) const { + return p.x != x || p.y != y; + } + + template + inline TPoint operator+=(const TPoint& p) { + x += static_cast(p.x); + y += static_cast(p.y); + return *this; + } + + template + inline TPoint operator+=(const TSize& s) { + x += static_cast(s.width); + y += static_cast(s.height); + return *this; + } + + template + inline TPoint operator-=(const TPoint& p) { + x -= static_cast(p.x); + y -= static_cast(p.y); + return *this; + } + + template + inline TPoint operator-=(const TSize& s) { + x -= static_cast(s.width); + y -= static_cast(s.height); + return *this; + } + + template + inline TPoint operator*=(const TPoint& p) { + x *= static_cast(p.x); + y *= static_cast(p.y); + return *this; + } + + template + inline TPoint operator*=(const TSize& s) { + x *= static_cast(s.width); + y *= static_cast(s.height); + return *this; + } + + template >> + inline TPoint operator*=(U scale) { + x *= static_cast(scale); + y *= static_cast(scale); + return *this; + } + + template + inline TPoint operator/=(const TPoint& p) { + x /= static_cast(p.x); + y /= static_cast(p.y); + return *this; + } + + template + inline TPoint operator/=(const TSize& s) { + x /= static_cast(s.width); + y /= static_cast(s.height); + return *this; + } + + template >> + inline TPoint operator/=(U scale) { + x /= static_cast(scale); + y /= static_cast(scale); + return *this; + } + + constexpr TPoint operator-() const { return {-x, -y}; } + + constexpr TPoint operator+(const TPoint& p) const { + return {x + p.x, y + p.y}; + } + + template + constexpr TPoint operator+(const TSize& s) const { + return {x + static_cast(s.width), y + static_cast(s.height)}; + } + + constexpr TPoint operator-(const TPoint& p) const { + return {x - p.x, y - p.y}; + } + + template + constexpr TPoint operator-(const TSize& s) const { + return {x - static_cast(s.width), y - static_cast(s.height)}; + } + + template >> + constexpr TPoint operator*(U scale) const { + return {static_cast(x * scale), static_cast(y * scale)}; + } + + constexpr TPoint operator*(const TPoint& p) const { + return {x * p.x, y * p.y}; + } + + template + constexpr TPoint operator*(const TSize& s) const { + return {x * static_cast(s.width), y * static_cast(s.height)}; + } + + template >> + constexpr TPoint operator/(U d) const { + return {static_cast(x / d), static_cast(y / d)}; + } + + constexpr TPoint operator/(const TPoint& p) const { + return {x / p.x, y / p.y}; + } + + template + constexpr TPoint operator/(const TSize& s) const { + return {x / static_cast(s.width), y / static_cast(s.height)}; + } + + constexpr Type GetDistanceSquared(const TPoint& p) const { + double dx = p.x - x; + double dy = p.y - y; + return dx * dx + dy * dy; + } + + constexpr TPoint Min(const TPoint& p) const { + return {std::min(x, p.x), std::min(y, p.y)}; + } + + constexpr TPoint Max(const TPoint& p) const { + return {std::max(x, p.x), std::max(y, p.y)}; + } + + constexpr TPoint Floor() const { return {std::floor(x), std::floor(y)}; } + + constexpr TPoint Ceil() const { return {std::ceil(x), std::ceil(y)}; } + + constexpr TPoint Round() const { return {std::round(x), std::round(y)}; } + + constexpr Type GetDistance(const TPoint& p) const { + return sqrt(GetDistanceSquared(p)); + } + + constexpr Type GetLengthSquared() const { return GetDistanceSquared({}); } + + constexpr Type GetLength() const { return GetDistance({}); } + + constexpr TPoint Normalize() const { + const auto length = GetLength(); + if (length == 0) { + return {1, 0}; + } + return {x / length, y / length}; + } + + constexpr TPoint Abs() const { return {std::fabs(x), std::fabs(y)}; } + + constexpr Type Cross(const TPoint& p) const { return (x * p.y) - (y * p.x); } + + constexpr Type Dot(const TPoint& p) const { return (x * p.x) + (y * p.y); } + + constexpr TPoint Reflect(const TPoint& axis) const { + return *this - axis * this->Dot(axis) * 2; + } + + constexpr TPoint Rotate(const Radians& angle) const { + const auto cos_a = std::cosf(angle.radians); + const auto sin_a = std::sinf(angle.radians); + return {x * cos_a - y * sin_a, x * sin_a + y * cos_a}; + } + + constexpr Radians AngleTo(const TPoint& p) const { + return Radians{std::atan2(this->Cross(p), this->Dot(p))}; + } + + constexpr TPoint Lerp(const TPoint& p, Scalar t) const { + return *this + (p - *this) * t; + } + + constexpr bool IsZero() const { return x == 0 && y == 0; } + + ONLY_ON_FLOAT_M(constexpr, bool) + IsFinite() const { return std::isfinite(x) && std::isfinite(y); } +}; + +// Specializations for mixed (float & integer) algebraic operations. + +template > +constexpr TPoint operator+(const TPoint& p1, const TPoint& p2) { + return {p1.x + static_cast(p2.x), p1.y + static_cast(p2.y)}; +} + +template > +constexpr TPoint operator+(const TPoint& p1, const TPoint& p2) { + return p2 + p1; +} + +template > +constexpr TPoint operator-(const TPoint& p1, const TPoint& p2) { + return {p1.x - static_cast(p2.x), p1.y - static_cast(p2.y)}; +} + +template > +constexpr TPoint operator-(const TPoint& p1, const TPoint& p2) { + return {static_cast(p1.x) - p2.x, static_cast(p1.y) - p2.y}; +} + +template > +constexpr TPoint operator*(const TPoint& p1, const TPoint& p2) { + return {p1.x * static_cast(p2.x), p1.y * static_cast(p2.y)}; +} + +template > +constexpr TPoint operator*(const TPoint& p1, const TPoint& p2) { + return p2 * p1; +} + +template > +constexpr TPoint operator/(const TPoint& p1, const TPoint& p2) { + return {p1.x / static_cast(p2.x), p1.y / static_cast(p2.y)}; +} + +template > +constexpr TPoint operator/(const TPoint& p1, const TPoint& p2) { + return {static_cast(p1.x) / p2.x, static_cast(p1.y) / p2.y}; +} + +// RHS algebraic operations with arithmetic types. + +template >> +constexpr TPoint operator*(U s, const TPoint& p) { + return p * s; +} + +template >> +constexpr TPoint operator/(U s, const TPoint& p) { + return {static_cast(s) / p.x, static_cast(s) / p.y}; +} + +// RHS algebraic operations with TSize. + +template +constexpr TPoint operator+(const TSize& s, const TPoint& p) { + return p + s; +} + +template +constexpr TPoint operator-(const TSize& s, const TPoint& p) { + return {static_cast(s.width) - p.x, static_cast(s.height) - p.y}; +} + +template +constexpr TPoint operator*(const TSize& s, const TPoint& p) { + return p * s; +} + +template +constexpr TPoint operator/(const TSize& s, const TPoint& p) { + return {static_cast(s.width) / p.x, static_cast(s.height) / p.y}; +} + +template +constexpr TPoint operator-(const TPoint& p, T v) { + return {p.x - v, p.y - v}; +} + +using Point = TPoint; +using IPoint = TPoint; +using IPoint32 = TPoint; +using UintPoint32 = TPoint; +using Vector2 = Point; +using Quad = std::array; + +#undef ONLY_ON_FLOAT +#undef ONLY_ON_FLOAT_M + +} // namespace impeller + +namespace std { + +template +inline std::ostream& operator<<(std::ostream& out, + const impeller::TPoint& p) { + out << "(" << p.x << ", " << p.y << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_POINT_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/quaternion.cc b/flutter/engine/src/flutter/impeller/geometry/quaternion.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c5a75b286b53153b51dc2151560c71437d01c09 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/quaternion.cc @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "quaternion.h" +#include + +namespace impeller { + +Quaternion Quaternion::Slerp(const Quaternion& to, double time) const { + double cosine = Dot(to); + if (fabs(cosine) < 1.0 - 1e-3 /* epsilon */) { + /* + * Spherical Interpolation. + */ + auto sine = sqrt(1.0 - cosine * cosine); + auto angle = atan2(sine, cosine); + auto sineInverse = 1.0 / sine; + auto c0 = sin((1.0 - time) * angle) * sineInverse; + auto c1 = sin(time * angle) * sineInverse; + return *this * c0 + to * c1; + } else { + /* + * Linear Interpolation. + */ + return (*this * (1.0 - time) + to * time).Normalize(); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/quaternion.h b/flutter/engine/src/flutter/impeller/geometry/quaternion.h new file mode 100644 index 0000000000000000000000000000000000000000..408f5c04edb6435de5b43515ccb2def2527b3ceb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/quaternion.h @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_ +#define FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_ + +#include + +#include "impeller/geometry/vector.h" + +namespace impeller { + +struct Quaternion { + union { + struct { + Scalar x = 0.0; + Scalar y = 0.0; + Scalar z = 0.0; + Scalar w = 1.0; + }; + Scalar e[4]; + }; + + Quaternion() {} + + Quaternion(Scalar px, Scalar py, Scalar pz, Scalar pw) + : x(px), y(py), z(pz), w(pw) {} + + Quaternion(const Vector3& axis, Scalar angle) { + const auto sine = sin(angle * 0.5f); + x = sine * axis.x; + y = sine * axis.y; + z = sine * axis.z; + w = cos(angle * 0.5f); + } + + Scalar Dot(const Quaternion& q) const { + return x * q.x + y * q.y + z * q.z + w * q.w; + } + + Scalar Length() const { return sqrt(x * x + y * y + z * z + w * w); } + + Quaternion Normalize() const { + auto m = 1.0f / Length(); + return {x * m, y * m, z * m, w * m}; + } + + Quaternion Invert() const { return {-x, -y, -z, w}; } + + Quaternion Slerp(const Quaternion& to, double time) const; + + Quaternion operator*(const Quaternion& o) const { + return { + w * o.x + x * o.w + y * o.z - z * o.y, + w * o.y + y * o.w + z * o.x - x * o.z, + w * o.z + z * o.w + x * o.y - y * o.x, + w * o.w - x * o.x - y * o.y - z * o.z, + }; + } + + Quaternion operator*(Scalar scale) const { + return {scale * x, scale * y, scale * z, scale * w}; + } + + Vector3 operator*(Vector3 vector) const { + Vector3 v(x, y, z); + return v * v.Dot(vector) * 2 + // + vector * (w * w - v.Dot(v)) + // + v.Cross(vector) * 2 * w; + } + + Quaternion operator+(const Quaternion& o) const { + return {x + o.x, y + o.y, z + o.z, w + o.w}; + } + + Quaternion operator-(const Quaternion& o) const { + return {x - o.x, y - o.y, z - o.z, w - o.w}; + } + + bool operator==(const Quaternion& o) const { + return x == o.x && y == o.y && z == o.z && w == o.w; + } + + bool operator!=(const Quaternion& o) const { + return x != o.x || y != o.y || z != o.z || w != o.w; + } +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::Quaternion& q) { + out << "(" << q.x << ", " << q.y << ", " << q.z << ", " << q.w << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_QUATERNION_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/rational.cc b/flutter/engine/src/flutter/impeller/geometry/rational.cc new file mode 100644 index 0000000000000000000000000000000000000000..57dc3705f378cd248facdccf74f1810f35fc8f26 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rational.cc @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/rational.h" + +#include +#include +#include + +namespace impeller { +namespace { +uint32_t AbsToUnsigned(int32_t x) { + return static_cast(std::abs(x)); +} +} // namespace + +bool Rational::operator==(const Rational& that) const { + if (den_ == that.den_) { + return num_ == that.num_; + } else if ((num_ >= 0) != (that.num_ >= 0)) { + return false; + } else { + return AbsToUnsigned(num_) * that.den_ == AbsToUnsigned(that.num_) * den_; + } +} + +bool Rational::operator!=(const Rational& that) const { + return !(*this == that); +} + +bool Rational::operator<(const Rational& that) const { + if (den_ == that.den_) { + return num_ < that.num_; + } else if ((num_ >= 0) != (that.num_ >= 0)) { + return num_ < that.num_; + } else { + return AbsToUnsigned(num_) * that.den_ < AbsToUnsigned(that.num_) * den_; + } +} + +uint64_t Rational::GetHash() const { + if (num_ == 0) { + return 0; + } + uint64_t gcd = std::gcd(num_, den_); + return ((num_ / gcd) << 32) | (den_ / gcd); +} + +Rational Rational::Invert() const { + if (num_ >= 0) { + return Rational(den_, num_); + } else { + return Rational(-1 * static_cast(den_), std::abs(num_)); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rational.h b/flutter/engine/src/flutter/impeller/geometry/rational.h new file mode 100644 index 0000000000000000000000000000000000000000..84f2914c32993cf67c2b3b92bafc43c2747ce741 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rational.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_RATIONAL_H_ +#define FLUTTER_IMPELLER_GEOMETRY_RATIONAL_H_ + +#include +#include "impeller/geometry/scalar.h" + +namespace impeller { + +class Rational { + public: + constexpr explicit Rational(int32_t num) : num_(num), den_(1) {} + + constexpr Rational(int32_t num, uint32_t den) : num_(num), den_(den) {} + + int32_t GetNumerator() const { return num_; } + + uint32_t GetDenominator() const { return den_; } + + bool operator==(const Rational& that) const; + + bool operator!=(const Rational& that) const; + + bool operator<(const Rational& that) const; + + uint64_t GetHash() const; + + explicit operator Scalar() const { return static_cast(num_) / den_; } + + Rational Invert() const; + + private: + int32_t num_; + uint32_t den_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_RATIONAL_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/rational_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/rational_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..f912965a57427b753cc18df3d346b5858ebf6370 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rational_unittests.cc @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/rational.h" + +#include "gtest/gtest.h" + +namespace impeller { + +TEST(RationalTest, Make) { + Rational value(1, 2); + EXPECT_EQ(value.GetNumerator(), 1); + EXPECT_EQ(value.GetDenominator(), 2u); +} + +TEST(RationalTest, EqualsSameDen) { + EXPECT_TRUE(Rational(1, 2) == Rational(1, 2)); +} + +TEST(RationalTest, NotEqualsSameDen) { + EXPECT_FALSE(Rational(3, 2) == Rational(1, 2)); +} + +TEST(RationalTest, EqualsDifferentDen) { + EXPECT_TRUE(Rational(1, 2) == Rational(2, 4)); +} + +TEST(RationalTest, NegationNotEquals) { + EXPECT_FALSE(Rational(1, 2) == Rational(-1, 2)); +} + +TEST(RationalTest, LessThanSameDen) { + EXPECT_TRUE(Rational(1, 2) < Rational(2, 2)); +} + +TEST(RationalTest, LessThanNegation) { + EXPECT_TRUE(Rational(-1, 2) < Rational(2, 23)); +} + +TEST(RationalTest, LessThanDifferentDen) { + EXPECT_TRUE(Rational(1, 2) < Rational(25, 23)); +} + +TEST(RationalTest, NotLessThanDifferentDen) { + EXPECT_FALSE(Rational(25, 23) < Rational(1, 2)); +} + +TEST(RationalTest, SameHashes) { + EXPECT_EQ(Rational(1, 2).GetHash(), Rational(2, 4).GetHash()); +} + +TEST(RationalTest, DifferentHashes) { + EXPECT_NE(Rational(2, 2).GetHash(), Rational(2, 4).GetHash()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rect.cc b/flutter/engine/src/flutter/impeller/geometry/rect.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b0192ad6f437e1629668a204ed116892415ef7a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rect.cc @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "rect.h" +#include + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rect.h b/flutter/engine/src/flutter/impeller/geometry/rect.h new file mode 100644 index 0000000000000000000000000000000000000000..703cd833b856f2be355ed92ee6cea97bb4bd6f01 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rect.h @@ -0,0 +1,813 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_RECT_H_ +#define FLUTTER_IMPELLER_GEOMETRY_RECT_H_ + +#include +#include +#include +#include + +#include "fml/logging.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/saturated_math.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +#define ONLY_ON_FLOAT_M(Modifiers, Return) \ + template \ + Modifiers std::enable_if_t, Return> +#define ONLY_ON_FLOAT(Return) DL_ONLY_ON_FLOAT_M(, Return) + +/// Templated struct for holding an axis-aligned rectangle. +/// +/// Rectangles are defined as 4 axis-aligned edges that might contain +/// space. They can be viewed as 2 X coordinates that define the +/// left and right edges and 2 Y coordinates that define the top and +/// bottom edges; or they can be viewed as an origin and horizontal +/// and vertical dimensions (width and height). +/// +/// When the left and right edges are equal or reversed (right <= left) +/// or the top and bottom edges are equal or reversed (bottom <= top), +/// the rectangle is considered empty. Considering the rectangle in XYWH +/// form, the width and/or the height would be negative or zero. Such +/// reversed/empty rectangles contain no space and act as such in the +/// methods that operate on them (Intersection, Union, IntersectsWithRect, +/// Contains, Cutout, etc.) +/// +/// Rectangles cannot be modified by any method and a new value can only +/// be stored into an existing rect using assignment. This keeps the API +/// clean compared to implementations that might have similar methods +/// that produce the answer in place, or construct a new object with +/// the answer, or place the result in an indicated result object. +/// +/// Methods that might fail to produce an answer will use |std::optional| +/// to indicate that success or failure (see |Intersection| and |CutOut|). +/// For convenience, |Intersection| and |Union| both have overloaded +/// variants that take |std::optional| arguments and treat them as if +/// the argument was an empty rect to allow chaining multiple such methods +/// and only needing to check the optional condition of the final result. +/// The primary methods also provide |...OrEmpty| overloaded variants that +/// translate an empty optional answer into a simple empty rectangle of the +/// same type. +/// +/// Rounding instance methods are not provided as the return value might +/// be wanted as another floating point rectangle or sometimes as an integer +/// rectangle. Instead a |RoundOut| factory, defined only for floating point +/// input rectangles, is provided to provide control over the result type. +/// +/// NaN and Infinity values +/// +/// Constructing an LTRB rectangle using Infinity values should work as +/// expected with either 0 or +Infinity returned as dimensions depending on +/// which side the Infinity values are on and the sign. +/// +/// Constructing an XYWH rectangle using Infinity values will usually +/// not work if the math requires the object to compute a right or bottom +/// edge from ([xy] -Infinity + [wh] +Infinity). Other combinations might +/// work. +/// +/// The special factory |MakeMaximum| is provided to construct a rectangle +/// of the indicated coordinate type that covers all finite coordinates. +/// It does not use infinity values, but rather the largest finite values +/// to avoid math that might produce a NaN value from various getters. +/// +/// Any rectangle that is constructed with, or computed to have a NaN value +/// will be considered the same as any empty rectangle. +/// +/// Empty Rectangle canonical results summary: +/// +/// Union will ignore any empty rects and return the other rect +/// Intersection will return nullopt if either rect is empty +/// IntersectsWithRect will return false if either rect is empty +/// Cutout will return the source rect if the argument is empty +/// Cutout will return nullopt if the source rectangle is empty +/// Contains(Point) will return false if the source rectangle is empty +/// Contains(Rect) will return false if the source rectangle is empty +/// Contains(Rect) will otherwise return true if the argument is empty +/// Specifically, EmptyRect.Contains(EmptyRect) returns false +/// +/// --------------- +/// Special notes on problems using the XYWH form of specifying rectangles: +/// +/// It is possible to have integer rectangles whose dimensions exceed +/// the maximum number that their coordinates can represent since +/// (MAX_INT - MIN_INT) overflows the representable positive numbers. +/// Floating point rectangles technically have a similar issue in that +/// overflow can occur, but it will be automatically converted into +/// either an infinity, or a finite-overflow value and still be +/// representable, just with little to no precision. +/// +/// Secondly, specifying a rectangle using XYWH leads to cases where the +/// math for (x+w) and/or (y+h) are also beyond the maximum representable +/// coordinates. For N-bit integer rectangles declared as XYWH, the +/// maximum right coordinate will require N+1 signed bits which cannot be +/// stored in storage that uses N-bit integers. +/// +/// Saturated math is used when constructing a rectangle from XYWH values +/// and when returning the dimensions of the rectangle. Constructing an +/// integer rectangle from values such that xy + wh is beyond the range +/// of the integer type will place the right or bottom edges at the maximum +/// value for the integer type. Similarly, constructing an integer rectangle +/// such that the distance from the left to the right (or top to bottom) is +/// greater than the range of the integer type will simply return the +/// maximum integer value as the dimension. Floating point rectangles are +/// naturally saturated by the rules of IEEE arithmetic. +template +struct TRect { + private: + using Type = T; + + public: + constexpr TRect() : left_(0), top_(0), right_(0), bottom_(0) {} + + constexpr static TRect MakeLTRB(Type left, + Type top, + Type right, + Type bottom) { + return TRect(left, top, right, bottom); + } + + constexpr static TRect MakeXYWH(Type x, Type y, Type width, Type height) { + return TRect(x, y, saturated::Add(x, width), saturated::Add(y, height)); + } + + constexpr static TRect MakeWH(Type width, Type height) { + return TRect(0, 0, width, height); + } + + constexpr static TRect MakeOriginSize(const TPoint& origin, + const TSize& size) { + return MakeXYWH(origin.x, origin.y, size.width, size.height); + } + + template + constexpr static TRect MakeSize(const TSize& size) { + return TRect(0.0, 0.0, size.width, size.height); + } + + /// Construct a floating point rect |Rect| from another Rect of a + /// potentially different storage type (eg. |IRect|). + template + constexpr static std::enable_if_t, TRect> Make( + const TRect& rect) { + return MakeLTRB( + static_cast(rect.GetLeft()), static_cast(rect.GetTop()), + static_cast(rect.GetRight()), static_cast(rect.GetBottom())); + } + + template + constexpr static std::optional MakePointBounds(const U& value) { + return MakePointBounds(value.begin(), value.end()); + } + + template + constexpr static std::optional MakePointBounds(const PointIter first, + const PointIter last) { + if (first == last) { + return std::nullopt; + } + auto left = first->x; + auto top = first->y; + auto right = first->x; + auto bottom = first->y; + for (auto it = first + 1; it < last; ++it) { + left = std::min(left, it->x); + top = std::min(top, it->y); + right = std::max(right, it->x); + bottom = std::max(bottom, it->y); + } + return TRect::MakeLTRB(left, top, right, bottom); + } + + [[nodiscard]] constexpr static TRect MakeMaximum() { + return TRect::MakeLTRB(std::numeric_limits::lowest(), + std::numeric_limits::lowest(), + std::numeric_limits::max(), + std::numeric_limits::max()); + } + + [[nodiscard]] constexpr bool operator==(const TRect& r) const { + return left_ == r.left_ && // + top_ == r.top_ && // + right_ == r.right_ && // + bottom_ == r.bottom_; + } + + [[nodiscard]] constexpr bool operator!=(const TRect& r) const { + return !(*this == r); + } + + [[nodiscard]] constexpr TRect Scale(Type scale) const { + return TRect(left_ * scale, // + top_ * scale, // + right_ * scale, // + bottom_ * scale); + } + + [[nodiscard]] constexpr TRect Scale(Type scale_x, Type scale_y) const { + return TRect(left_ * scale_x, // + top_ * scale_y, // + right_ * scale_x, // + bottom_ * scale_y); + } + + [[nodiscard]] constexpr TRect Scale(TPoint scale) const { + return Scale(scale.x, scale.y); + } + + [[nodiscard]] constexpr TRect Scale(TSize scale) const { + return Scale(scale.width, scale.height); + } + + /// @brief Returns true iff the provided point |p| is inside the + /// half-open interior of this rectangle. + /// + /// For purposes of containment, a rectangle contains points + /// along the top and left edges but not points along the + /// right and bottom edges so that a point is only ever + /// considered inside one of two abutting rectangles. + [[nodiscard]] constexpr bool Contains(const TPoint& p) const { + return !this->IsEmpty() && // + p.x >= left_ && // + p.y >= top_ && // + p.x < right_ && // + p.y < bottom_; + } + + /// @brief Returns true iff the provided point |p| is inside the + /// closed-range interior of this rectangle. + /// + /// Unlike the regular |Contains(TPoint)| method, this method + /// considers all points along the boundary of the rectangle + /// to be contained within the rectangle - useful for testing + /// if vertices that define a filled shape would carry the + /// interior of that shape outside the bounds of the rectangle. + /// Since both geometries are defining half-open spaces, their + /// defining geometry needs to consider their boundaries to + /// be equivalent with respect to interior and exterior. + [[nodiscard]] constexpr bool ContainsInclusive(const TPoint& p) const { + return !this->IsEmpty() && // + p.x >= left_ && // + p.y >= top_ && // + p.x <= right_ && // + p.y <= bottom_; + } + + /// @brief Returns true iff this rectangle is not empty and it also + /// contains every point considered inside the provided + /// rectangle |o| (as determined by |Contains(TPoint)|). + /// + /// This is similar to a definition where the result is true iff + /// the union of the two rectangles is equal to this rectangle, + /// ignoring precision issues with performing those operations + /// and assuming that empty rectangles are never equal. + /// + /// An empty rectangle can contain no other rectangle. + /// + /// An empty rectangle is, however, contained within any + /// other non-empy rectangle as the set of points it contains + /// is an empty set and so there are no points to fail the + /// containment criteria. + [[nodiscard]] constexpr bool Contains(const TRect& o) const { + return !this->IsEmpty() && // + (o.IsEmpty() || (o.left_ >= left_ && // + o.top_ >= top_ && // + o.right_ <= right_ && // + o.bottom_ <= bottom_)); + } + + /// @brief Returns true if all of the fields of this floating point + /// rectangle are finite. + /// + /// Note that the results of |GetWidth()| and |GetHeight()| may + /// still be infinite due to overflow even if the fields themselves + /// are finite. + ONLY_ON_FLOAT_M([[nodiscard]] constexpr, bool) + IsFinite() const { + return std::isfinite(left_) && // + std::isfinite(top_) && // + std::isfinite(right_) && // + std::isfinite(bottom_); + } + + /// @brief Returns true if either of the width or height are 0, negative, + /// or NaN. + [[nodiscard]] constexpr bool IsEmpty() const { + // Computing the non-empty condition and negating the result causes any + // NaN value to return true - i.e. is considered empty. + return !(left_ < right_ && top_ < bottom_); + } + + /// @brief Returns true if width and height are equal and neither is NaN. + [[nodiscard]] constexpr bool IsSquare() const { + // empty rectangles can technically be "square", but would be + // misleading to most callers. Using |IsEmpty| also prevents + // "non-empty and non-overflowing" computations from happening + // to be equal to "empty and overflowing" results. + // (Consider LTRB(10, 15, MAX-2, MIN+2) which is empty, but both + // w/h subtractions equal "5"). + return !IsEmpty() && (right_ - left_) == (bottom_ - top_); + } + + [[nodiscard]] constexpr bool IsMaximum() const { + return *this == MakeMaximum(); + } + + /// @brief Returns the upper left corner of the rectangle as specified + /// by the left/top or x/y values when it was constructed. + [[nodiscard]] constexpr TPoint GetOrigin() const { + return {left_, top_}; + } + + /// @brief Returns the size of the rectangle which may be negative in + /// either width or height and may have been clipped to the + /// maximum integer values for integer rects whose size overflows. + [[nodiscard]] constexpr TSize GetSize() const { + return {GetWidth(), GetHeight()}; + } + + /// @brief Returns the X coordinate of the upper left corner, equivalent + /// to |GetOrigin().x| + [[nodiscard]] constexpr Type GetX() const { return left_; } + + /// @brief Returns the Y coordinate of the upper left corner, equivalent + /// to |GetOrigin().y| + [[nodiscard]] constexpr Type GetY() const { return top_; } + + /// @brief Returns the width of the rectangle, equivalent to + /// |GetSize().width| + [[nodiscard]] constexpr Type GetWidth() const { + return saturated::Sub(right_, left_); + } + + /// @brief Returns the height of the rectangle, equivalent to + /// |GetSize().height| + [[nodiscard]] constexpr Type GetHeight() const { + return saturated::Sub(bottom_, top_); + } + + [[nodiscard]] constexpr auto GetLeft() const { return left_; } + + [[nodiscard]] constexpr auto GetTop() const { return top_; } + + [[nodiscard]] constexpr auto GetRight() const { return right_; } + + [[nodiscard]] constexpr auto GetBottom() const { return bottom_; } + + [[nodiscard]] constexpr TPoint GetLeftTop() const { // + return {left_, top_}; + } + + [[nodiscard]] constexpr TPoint GetRightTop() const { + return {right_, top_}; + } + + [[nodiscard]] constexpr TPoint GetLeftBottom() const { + return {left_, bottom_}; + } + + [[nodiscard]] constexpr TPoint GetRightBottom() const { + return {right_, bottom_}; + } + + /// @brief Get the area of the rectangle, equivalent to |GetSize().Area()| + [[nodiscard]] constexpr T Area() const { + // TODO(141710): Use saturated math to avoid overflow. + return IsEmpty() ? 0 : (right_ - left_) * (bottom_ - top_); + } + + /// @brief Get the center point as a |Point|. + [[nodiscard]] constexpr Point GetCenter() const { + return {saturated::AverageScalar(left_, right_), + saturated::AverageScalar(top_, bottom_)}; + } + + [[nodiscard]] constexpr std::array GetLTRB() const { + return {left_, top_, right_, bottom_}; + } + + /// @brief Get the x, y coordinates of the origin and the width and + /// height of the rectangle in an array. + [[nodiscard]] constexpr std::array GetXYWH() const { + return {left_, top_, GetWidth(), GetHeight()}; + } + + /// @brief Get a version of this rectangle that has a non-negative size. + [[nodiscard]] constexpr TRect GetPositive() const { + if (!IsEmpty()) { + return *this; + } + return { + std::min(left_, right_), + std::min(top_, bottom_), + std::max(left_, right_), + std::max(top_, bottom_), + }; + } + + /// @brief Get the points that represent the 4 corners of this rectangle + /// in a Z order that is compatible with triangle strips or a set + /// of all zero points if the rectangle is empty. + /// The order is: Top left, top right, bottom left, bottom right. + [[nodiscard]] constexpr std::array, 4> GetPoints() const { + if (IsEmpty()) { + return {}; + } + return { + TPoint{left_, top_}, + TPoint{right_, top_}, + TPoint{left_, bottom_}, + TPoint{right_, bottom_}, + }; + } + + [[nodiscard]] constexpr std::array, 4> GetTransformedPoints( + const Matrix& transform) const { + auto points = GetPoints(); + for (size_t i = 0; i < points.size(); i++) { + points[i] = transform * points[i]; + } + return points; + } + + /// @brief Creates a new bounding box that contains this transformed + /// rectangle, clipped against the near clipping plane if + /// necessary. + [[nodiscard]] constexpr TRect TransformAndClipBounds( + const Matrix& transform) const { + if (!transform.HasPerspective2D()) { + return TransformBounds(transform); + } + + if (IsEmpty()) { + return {}; + } + + auto ul = transform.TransformHomogenous({left_, top_}); + auto ur = transform.TransformHomogenous({right_, top_}); + auto ll = transform.TransformHomogenous({left_, bottom_}); + auto lr = transform.TransformHomogenous({right_, bottom_}); + + // It can probably be proven that we only ever have 5 points at most + // which happens when only 1 corner is clipped and we get 2 points + // in return for it as we interpolate against its neighbors. + Point points[8]; + int index = 0; + + // Process (clip and interpolate) each point against its 2 neighbors: + // left, pt, right + index = ClipAndInsert(points, index, ll, ul, ur); + index = ClipAndInsert(points, index, ul, ur, lr); + index = ClipAndInsert(points, index, ur, lr, ll); + index = ClipAndInsert(points, index, lr, ll, ul); + + auto bounds = TRect::MakePointBounds(points, points + index); + return bounds.value_or(TRect{}); + } + + /// @brief Creates a new bounding box that contains this transformed + /// rectangle. + [[nodiscard]] constexpr TRect TransformBounds(const Matrix& transform) const { + if (IsEmpty()) { + return {}; + } + auto points = GetTransformedPoints(transform); + auto bounds = TRect::MakePointBounds(points.begin(), points.end()); + if (bounds.has_value()) { + return bounds.value(); + } + FML_UNREACHABLE(); + } + + /// @brief Constructs a Matrix that will map all points in the coordinate + /// space of the rectangle into a new normalized coordinate space + /// where the upper left corner of the rectangle maps to (0, 0) + /// and the lower right corner of the rectangle maps to (1, 1). + /// + /// Empty and non-finite rectangles will return a zero-scaling + /// transform that maps all points to (0, 0). + [[nodiscard]] constexpr Matrix GetNormalizingTransform() const { + if (!IsEmpty()) { + Scalar sx = 1.0 / GetWidth(); + Scalar sy = 1.0 / GetHeight(); + Scalar tx = left_ * -sx; + Scalar ty = top_ * -sy; + + // Exclude NaN and infinities and either scale underflowing to zero + if (sx != 0.0 && sy != 0.0 && 0.0 * sx * sy * tx * ty == 0.0) { + // clang-format off + return Matrix( sx, 0.0f, 0.0f, 0.0f, + 0.0f, sy, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + tx, ty, 0.0f, 1.0f); + // clang-format on + } + } + + // Map all coordinates to the origin. + return Matrix::MakeScale({0.0f, 0.0f, 1.0f}); + } + + [[nodiscard]] constexpr TRect Union(const TRect& o) const { + if (IsEmpty()) { + return o; + } + if (o.IsEmpty()) { + return *this; + } + return { + std::min(left_, o.left_), + std::min(top_, o.top_), + std::max(right_, o.right_), + std::max(bottom_, o.bottom_), + }; + } + + [[nodiscard]] constexpr std::optional Intersection( + const TRect& o) const { + if (IntersectsWithRect(o)) { + return TRect{ + std::max(left_, o.left_), + std::max(top_, o.top_), + std::min(right_, o.right_), + std::min(bottom_, o.bottom_), + }; + } else { + return std::nullopt; + } + } + + [[nodiscard]] constexpr TRect IntersectionOrEmpty(const TRect& o) const { + return Intersection(o).value_or(TRect()); + } + + [[nodiscard]] constexpr bool IntersectsWithRect(const TRect& o) const { + return !IsEmpty() && // + !o.IsEmpty() && // + left_ < o.right_ && // + top_ < o.bottom_ && // + right_ > o.left_ && // + bottom_ > o.top_; + } + + /// @brief Returns the new boundary rectangle that would result from this + /// rectangle being cut out by the specified rectangle. + [[nodiscard]] constexpr std::optional> Cutout(const TRect& o) const { + if (IsEmpty()) { + // This test isn't just a short-circuit, it also prevents the concise + // math below from returning the wrong answer on empty rects. + // Once we know that this rectangle is not empty, the math below can + // only succeed in computing a value if o is also non-empty and non-nan. + // Otherwise, the method returns *this by default. + return std::nullopt; + } + + const auto& [a_left, a_top, a_right, a_bottom] = GetLTRB(); // Source rect. + const auto& [b_left, b_top, b_right, b_bottom] = o.GetLTRB(); // Cutout. + if (b_left <= a_left && b_right >= a_right) { + if (b_top <= a_top && b_bottom >= a_bottom) { + // Full cutout. + return std::nullopt; + } + if (b_top <= a_top && b_bottom > a_top) { + // Cuts off the top. + return TRect::MakeLTRB(a_left, b_bottom, a_right, a_bottom); + } + if (b_bottom >= a_bottom && b_top < a_bottom) { + // Cuts off the bottom. + return TRect::MakeLTRB(a_left, a_top, a_right, b_top); + } + } + if (b_top <= a_top && b_bottom >= a_bottom) { + if (b_left <= a_left && b_right > a_left) { + // Cuts off the left. + return TRect::MakeLTRB(b_right, a_top, a_right, a_bottom); + } + if (b_right >= a_right && b_left < a_right) { + // Cuts off the right. + return TRect::MakeLTRB(a_left, a_top, b_left, a_bottom); + } + } + + return *this; + } + + [[nodiscard]] constexpr TRect CutoutOrEmpty(const TRect& o) const { + return Cutout(o).value_or(TRect()); + } + + /// @brief Returns a new rectangle translated by the given offset. + [[nodiscard]] constexpr TRect Shift(T dx, T dy) const { + return { + saturated::Add(left_, dx), // + saturated::Add(top_, dy), // + saturated::Add(right_, dx), // + saturated::Add(bottom_, dy), // + }; + } + + /// @brief Returns a new rectangle translated by the given offset. + [[nodiscard]] constexpr TRect Shift(TPoint offset) const { + return Shift(offset.x, offset.y); + } + + /// @brief Returns a rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr TRect Expand(T left, + T top, + T right, + T bottom) const { + return { + saturated::Sub(left_, left), // + saturated::Sub(top_, top), // + saturated::Add(right_, right), // + saturated::Add(bottom_, bottom), // + }; + } + + /// @brief Returns a rectangle with expanded edges in all directions. + /// Negative expansion results in shrinking. + [[nodiscard]] constexpr TRect Expand(T amount) const { + return { + saturated::Sub(left_, amount), // + saturated::Sub(top_, amount), // + saturated::Add(right_, amount), // + saturated::Add(bottom_, amount), // + }; + } + + /// @brief Returns a rectangle with expanded edges in all directions. + /// Negative expansion results in shrinking. + [[nodiscard]] constexpr TRect Expand(T horizontal_amount, + T vertical_amount) const { + return { + saturated::Sub(left_, horizontal_amount), // + saturated::Sub(top_, vertical_amount), // + saturated::Add(right_, horizontal_amount), // + saturated::Add(bottom_, vertical_amount), // + }; + } + + /// @brief Returns a rectangle with expanded edges in all directions. + /// Negative expansion results in shrinking. + [[nodiscard]] constexpr TRect Expand(TPoint amount) const { + return Expand(amount.x, amount.y); + } + + /// @brief Returns a rectangle with expanded edges in all directions. + /// Negative expansion results in shrinking. + [[nodiscard]] constexpr TRect Expand(TSize amount) const { + return Expand(amount.width, amount.height); + } + + /// @brief Returns a new rectangle that represents the projection of the + /// source rectangle onto this rectangle. In other words, the source + /// rectangle is redefined in terms of the coordinate space of this + /// rectangle. + [[nodiscard]] constexpr TRect Project(TRect source) const { + if (IsEmpty()) { + return {}; + } + return source.Shift(-left_, -top_) + .Scale(1.0 / static_cast(GetWidth()), + 1.0 / static_cast(GetHeight())); + } + + ONLY_ON_FLOAT_M([[nodiscard]] constexpr static, TRect) + RoundOut(const TRect& r) { + return TRect::MakeLTRB(saturated::Cast(floor(r.GetLeft())), + saturated::Cast(floor(r.GetTop())), + saturated::Cast(ceil(r.GetRight())), + saturated::Cast(ceil(r.GetBottom()))); + } + + ONLY_ON_FLOAT_M([[nodiscard]] constexpr static, TRect) + RoundIn(const TRect& r) { + return TRect::MakeLTRB(saturated::Cast(ceil(r.GetLeft())), + saturated::Cast(ceil(r.GetTop())), + saturated::Cast(floor(r.GetRight())), + saturated::Cast(floor(r.GetBottom()))); + } + + ONLY_ON_FLOAT_M([[nodiscard]] constexpr static, TRect) + Round(const TRect& r) { + return TRect::MakeLTRB(saturated::Cast(round(r.GetLeft())), + saturated::Cast(round(r.GetTop())), + saturated::Cast(round(r.GetRight())), + saturated::Cast(round(r.GetBottom()))); + } + + [[nodiscard]] constexpr static TRect Union(const TRect& a, + const std::optional b) { + return b.has_value() ? a.Union(b.value()) : a; + } + + [[nodiscard]] constexpr static TRect Union(const std::optional a, + const TRect& b) { + return a.has_value() ? a->Union(b) : b; + } + + [[nodiscard]] constexpr static std::optional Union( + const std::optional a, + const std::optional b) { + return a.has_value() ? Union(a.value(), b) : b; + } + + [[nodiscard]] constexpr static std::optional Intersection( + const TRect& a, + const std::optional b) { + return b.has_value() ? a.Intersection(b.value()) : a; + } + + [[nodiscard]] constexpr static std::optional Intersection( + const std::optional a, + const TRect& b) { + return a.has_value() ? a->Intersection(b) : b; + } + + [[nodiscard]] constexpr static std::optional Intersection( + const std::optional a, + const std::optional b) { + return a.has_value() ? Intersection(a.value(), b) : b; + } + + private: + constexpr TRect(Type left, Type top, Type right, Type bottom) + : left_(left), top_(top), right_(right), bottom_(bottom) {} + + Type left_; + Type top_; + Type right_; + Type bottom_; + + static constexpr Scalar kMinimumHomogenous = 1.0f / (1 << 14); + + // Clip p against the near clipping plane (W = kMinimumHomogenous) + // and interpolate a crossing point against the nearby neighbors + // left and right if p is clipped and either of them is not. + // This method can produce 0, 1, or 2 points per call depending on + // how many of the points are clipped. + // 0 - all points are clipped + // 1 - p is unclipped OR + // p is clipped and exactly one of the neighbors is not + // 2 - p is clipped and both neighbors are not + static constexpr int ClipAndInsert(Point clipped[], + int index, + const Vector3& left, + const Vector3& p, + const Vector3& right) { + if (p.z >= kMinimumHomogenous) { + clipped[index++] = {p.x / p.z, p.y / p.z}; + } else { + index = InterpolateAndInsert(clipped, index, p, left); + index = InterpolateAndInsert(clipped, index, p, right); + } + return index; + } + + // Interpolate (a clipped) point p against one of its neighbors + // and insert the point into the array where the line between them + // veers from clipped space to unclipped, if such a point exists. + static constexpr int InterpolateAndInsert(Point clipped[], + int index, + const Vector3& p, + const Vector3& neighbor) { + if (neighbor.z >= kMinimumHomogenous) { + auto t = (kMinimumHomogenous - p.z) / (neighbor.z - p.z); + clipped[index++] = { + (t * p.x + (1.0f - t) * neighbor.x) / kMinimumHomogenous, + (t * p.y + (1.0f - t) * neighbor.y) / kMinimumHomogenous, + }; + } + return index; + } +}; + +using Rect = TRect; +using IRect32 = TRect; +using IRect64 = TRect; +using IRect = IRect64; + +#undef ONLY_ON_FLOAT +#undef ONLY_ON_FLOAT_M + +} // namespace impeller + +namespace std { + +template +inline std::ostream& operator<<(std::ostream& out, + const impeller::TRect& r) { + out << "(" << r.GetLeftTop() << " => " << r.GetRightBottom() << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_RECT_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/rect_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/rect_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..cb33c7debd49ff19cd2319e858b3b2fc33982281 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rect_unittests.cc @@ -0,0 +1,3247 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/rect.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +TEST(RectTest, RectEmptyDeclaration) { + Rect rect; + + EXPECT_EQ(rect.GetLeft(), 0.0f); + EXPECT_EQ(rect.GetTop(), 0.0f); + EXPECT_EQ(rect.GetRight(), 0.0f); + EXPECT_EQ(rect.GetBottom(), 0.0f); + EXPECT_EQ(rect.GetX(), 0.0f); + EXPECT_EQ(rect.GetY(), 0.0f); + EXPECT_EQ(rect.GetWidth(), 0.0f); + EXPECT_EQ(rect.GetHeight(), 0.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectEmptyDeclaration) { + IRect rect; + + EXPECT_EQ(rect.GetLeft(), 0); + EXPECT_EQ(rect.GetTop(), 0); + EXPECT_EQ(rect.GetRight(), 0); + EXPECT_EQ(rect.GetBottom(), 0); + EXPECT_EQ(rect.GetX(), 0); + EXPECT_EQ(rect.GetY(), 0); + EXPECT_EQ(rect.GetWidth(), 0); + EXPECT_EQ(rect.GetHeight(), 0); + EXPECT_TRUE(rect.IsEmpty()); + // EXPECT_TRUE(rect.IsFinite()); // should fail to compile +} + +TEST(RectTest, RectDefaultConstructor) { + Rect rect = Rect(); + + EXPECT_EQ(rect.GetLeft(), 0.0f); + EXPECT_EQ(rect.GetTop(), 0.0f); + EXPECT_EQ(rect.GetRight(), 0.0f); + EXPECT_EQ(rect.GetBottom(), 0.0f); + EXPECT_EQ(rect.GetX(), 0.0f); + EXPECT_EQ(rect.GetY(), 0.0f); + EXPECT_EQ(rect.GetWidth(), 0.0f); + EXPECT_EQ(rect.GetHeight(), 0.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectDefaultConstructor) { + IRect rect = IRect(); + + EXPECT_EQ(rect.GetLeft(), 0); + EXPECT_EQ(rect.GetTop(), 0); + EXPECT_EQ(rect.GetRight(), 0); + EXPECT_EQ(rect.GetBottom(), 0); + EXPECT_EQ(rect.GetX(), 0); + EXPECT_EQ(rect.GetY(), 0); + EXPECT_EQ(rect.GetWidth(), 0); + EXPECT_EQ(rect.GetHeight(), 0); + EXPECT_TRUE(rect.IsEmpty()); +} + +TEST(RectTest, RectSimpleLTRB) { + // Using fractional-power-of-2 friendly values for equality tests + Rect rect = Rect::MakeLTRB(5.125f, 10.25f, 20.625f, 25.375f); + + EXPECT_EQ(rect.GetLeft(), 5.125f); + EXPECT_EQ(rect.GetTop(), 10.25f); + EXPECT_EQ(rect.GetRight(), 20.625f); + EXPECT_EQ(rect.GetBottom(), 25.375f); + EXPECT_EQ(rect.GetX(), 5.125f); + EXPECT_EQ(rect.GetY(), 10.25f); + EXPECT_EQ(rect.GetWidth(), 15.5f); + EXPECT_EQ(rect.GetHeight(), 15.125f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectSimpleLTRB) { + IRect rect = IRect::MakeLTRB(5, 10, 20, 25); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), 20); + EXPECT_EQ(rect.GetBottom(), 25); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), 15); + EXPECT_EQ(rect.GetHeight(), 15); + EXPECT_FALSE(rect.IsEmpty()); +} + +TEST(RectTest, RectSimpleXYWH) { + // Using fractional-power-of-2 friendly values for equality tests + Rect rect = Rect::MakeXYWH(5.125f, 10.25f, 15.5f, 15.125f); + + EXPECT_EQ(rect.GetLeft(), 5.125f); + EXPECT_EQ(rect.GetTop(), 10.25f); + EXPECT_EQ(rect.GetRight(), 20.625f); + EXPECT_EQ(rect.GetBottom(), 25.375f); + EXPECT_EQ(rect.GetX(), 5.125f); + EXPECT_EQ(rect.GetY(), 10.25f); + EXPECT_EQ(rect.GetWidth(), 15.5f); + EXPECT_EQ(rect.GetHeight(), 15.125f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectSimpleXYWH) { + IRect rect = IRect::MakeXYWH(5, 10, 15, 16); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), 20); + EXPECT_EQ(rect.GetBottom(), 26); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), 15); + EXPECT_EQ(rect.GetHeight(), 16); + EXPECT_FALSE(rect.IsEmpty()); +} + +TEST(RectTest, RectSimpleWH) { + // Using fractional-power-of-2 friendly values for equality tests + Rect rect = Rect::MakeWH(15.5f, 15.125f); + + EXPECT_EQ(rect.GetLeft(), 0.0f); + EXPECT_EQ(rect.GetTop(), 0.0f); + EXPECT_EQ(rect.GetRight(), 15.5f); + EXPECT_EQ(rect.GetBottom(), 15.125f); + EXPECT_EQ(rect.GetX(), 0.0f); + EXPECT_EQ(rect.GetY(), 0.0f); + EXPECT_EQ(rect.GetWidth(), 15.5f); + EXPECT_EQ(rect.GetHeight(), 15.125f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectSimpleWH) { + // Using fractional-power-of-2 friendly values for equality tests + IRect rect = IRect::MakeWH(15, 25); + + EXPECT_EQ(rect.GetLeft(), 0); + EXPECT_EQ(rect.GetTop(), 0); + EXPECT_EQ(rect.GetRight(), 15); + EXPECT_EQ(rect.GetBottom(), 25); + EXPECT_EQ(rect.GetX(), 0); + EXPECT_EQ(rect.GetY(), 0); + EXPECT_EQ(rect.GetWidth(), 15); + EXPECT_EQ(rect.GetHeight(), 25); + EXPECT_FALSE(rect.IsEmpty()); +} + +TEST(RectTest, RectFromIRect) { + IRect irect = IRect::MakeLTRB(10, 20, 30, 40); + Rect rect = Rect::Make(irect); + + EXPECT_EQ(rect.GetLeft(), 10); + EXPECT_EQ(rect.GetTop(), 20); + EXPECT_EQ(rect.GetRight(), 30); + EXPECT_EQ(rect.GetBottom(), 40); + + // The following do not compile + // IRect irect2 = IRect::Make(rect); + // IRect irect2 = IRect::Make(irect); +} + +TEST(RectTest, RectOverflowXYWH) { + auto min = std::numeric_limits::lowest(); + auto max = std::numeric_limits::max(); + auto inf = std::numeric_limits::infinity(); + + // 8 cases: + // finite X, max W + // max X, max W + // finite Y, max H + // max Y, max H + // finite X, min W + // min X, min W + // finite Y, min H + // min Y, min H + + // a small finite value added to a max value will remain max + // a very large finite value (like max) added to max will go to infinity + + { + Rect rect = Rect::MakeXYWH(5.0, 10.0f, max, 15.0f); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), max); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), max); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(max, 10.0f, max, 15.0f); + + EXPECT_EQ(rect.GetLeft(), max); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), inf); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), max); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), inf); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_FALSE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(5.0f, 10.0f, 20.0f, max); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), 25.0f); + EXPECT_EQ(rect.GetBottom(), max); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), 20.0f); + EXPECT_EQ(rect.GetHeight(), max); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(5.0f, max, 20.0f, max); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), max); + EXPECT_EQ(rect.GetRight(), 25.0f); + EXPECT_EQ(rect.GetBottom(), inf); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), max); + EXPECT_EQ(rect.GetWidth(), 20.0f); + EXPECT_EQ(rect.GetHeight(), inf); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_FALSE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(5.0, 10.0f, min, 15.0f); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), min); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), min); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(min, 10.0f, min, 15.0f); + + EXPECT_EQ(rect.GetLeft(), min); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), -inf); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), min); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), -inf); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_FALSE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(5.0f, 10.0f, 20.0f, min); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), 25.0f); + EXPECT_EQ(rect.GetBottom(), min); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), 20.0f); + EXPECT_EQ(rect.GetHeight(), min); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeXYWH(5.0f, min, 20.0f, min); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), min); + EXPECT_EQ(rect.GetRight(), 25.0f); + EXPECT_EQ(rect.GetBottom(), -inf); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), min); + EXPECT_EQ(rect.GetWidth(), 20.0f); + EXPECT_EQ(rect.GetHeight(), -inf); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_FALSE(rect.IsFinite()); + } +} + +TEST(RectTest, IRectOverflowXYWH) { + auto min = std::numeric_limits::min(); + auto max = std::numeric_limits::max(); + + // 4 cases + // x near max, positive w takes it past max + // x near min, negative w takes it below min + // y near max, positive h takes it past max + // y near min, negative h takes it below min + + { + IRect rect = IRect::MakeXYWH(max - 5, 10, 10, 16); + + EXPECT_EQ(rect.GetLeft(), max - 5); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), max); + EXPECT_EQ(rect.GetBottom(), 26); + EXPECT_EQ(rect.GetX(), max - 5); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), 5); + EXPECT_EQ(rect.GetHeight(), 16); + EXPECT_FALSE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeXYWH(min + 5, 10, -10, 16); + + EXPECT_EQ(rect.GetLeft(), min + 5); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), min); + EXPECT_EQ(rect.GetBottom(), 26); + EXPECT_EQ(rect.GetX(), min + 5); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), -5); + EXPECT_EQ(rect.GetHeight(), 16); + EXPECT_TRUE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeXYWH(5, max - 10, 10, 16); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), max - 10); + EXPECT_EQ(rect.GetRight(), 15); + EXPECT_EQ(rect.GetBottom(), max); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), max - 10); + EXPECT_EQ(rect.GetWidth(), 10); + EXPECT_EQ(rect.GetHeight(), 10); + EXPECT_FALSE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeXYWH(5, min + 10, 10, -16); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), min + 10); + EXPECT_EQ(rect.GetRight(), 15); + EXPECT_EQ(rect.GetBottom(), min); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), min + 10); + EXPECT_EQ(rect.GetWidth(), 10); + EXPECT_EQ(rect.GetHeight(), -10); + EXPECT_TRUE(rect.IsEmpty()); + } +} + +TEST(RectTest, RectOverflowLTRB) { + auto min = std::numeric_limits::lowest(); + auto max = std::numeric_limits::max(); + auto inf = std::numeric_limits::infinity(); + + // 8 cases: + // finite negative X, max W + // ~min X, ~max W + // finite negative Y, max H + // ~min Y, ~max H + // finite positive X, min W + // ~min X, ~min W + // finite positive Y, min H + // ~min Y, ~min H + + // a small finite value subtracted from a max value will remain max + // a very large finite value (like min) subtracted from max will go to inf + + { + Rect rect = Rect::MakeLTRB(-5.0f, 10.0f, max, 25.0f); + + EXPECT_EQ(rect.GetLeft(), -5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), max); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), -5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), max); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(min + 5.0f, 10.0f, max - 5.0f, 25.0f); + + EXPECT_EQ(rect.GetLeft(), min + 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), max - 5.0f); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), min + 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), inf); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(5.0f, -10.0f, 20.0f, max); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), -10.0f); + EXPECT_EQ(rect.GetRight(), 20.0f); + EXPECT_EQ(rect.GetBottom(), max); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), -10.0f); + EXPECT_EQ(rect.GetWidth(), 15.0f); + EXPECT_EQ(rect.GetHeight(), max); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(5.0f, min + 10.0f, 20.0f, max - 15.0f); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), min + 10.0f); + EXPECT_EQ(rect.GetRight(), 20.0f); + EXPECT_EQ(rect.GetBottom(), max - 15.0f); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), min + 10.0f); + EXPECT_EQ(rect.GetWidth(), 15.0f); + EXPECT_EQ(rect.GetHeight(), inf); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(5.0f, 10.0f, min, 25.0f); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), min); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), min); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(max - 5.0f, 10.0f, min + 10.0f, 25.0f); + + EXPECT_EQ(rect.GetLeft(), max - 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), min + 10.0f); + EXPECT_EQ(rect.GetBottom(), 25.0f); + EXPECT_EQ(rect.GetX(), max - 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), -inf); + EXPECT_EQ(rect.GetHeight(), 15.0f); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(5.0f, 10.0f, 20.0f, min); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), 10.0f); + EXPECT_EQ(rect.GetRight(), 20.0f); + EXPECT_EQ(rect.GetBottom(), min); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), 10.0f); + EXPECT_EQ(rect.GetWidth(), 15.0f); + EXPECT_EQ(rect.GetHeight(), min); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } + + { + Rect rect = Rect::MakeLTRB(5.0f, max - 5.0f, 20.0f, min + 10.0f); + + EXPECT_EQ(rect.GetLeft(), 5.0f); + EXPECT_EQ(rect.GetTop(), max - 5.0f); + EXPECT_EQ(rect.GetRight(), 20.0f); + EXPECT_EQ(rect.GetBottom(), min + 10.0f); + EXPECT_EQ(rect.GetX(), 5.0f); + EXPECT_EQ(rect.GetY(), max - 5.0f); + EXPECT_EQ(rect.GetWidth(), 15.0f); + EXPECT_EQ(rect.GetHeight(), -inf); + EXPECT_TRUE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); + } +} + +TEST(RectTest, IRectOverflowLTRB) { + auto min = std::numeric_limits::min(); + auto max = std::numeric_limits::max(); + + // 4 cases + // negative l, r near max takes width past max + // positive l, r near min takes width below min + // negative t, b near max takes width past max + // positive t, b near min takes width below min + + { + IRect rect = IRect::MakeLTRB(-10, 10, max - 5, 26); + + EXPECT_EQ(rect.GetLeft(), -10); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), max - 5); + EXPECT_EQ(rect.GetBottom(), 26); + EXPECT_EQ(rect.GetX(), -10); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), max); + EXPECT_EQ(rect.GetHeight(), 16); + EXPECT_FALSE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeLTRB(10, 10, min + 5, 26); + + EXPECT_EQ(rect.GetLeft(), 10); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), min + 5); + EXPECT_EQ(rect.GetBottom(), 26); + EXPECT_EQ(rect.GetX(), 10); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), min); + EXPECT_EQ(rect.GetHeight(), 16); + EXPECT_TRUE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeLTRB(5, -10, 15, max - 5); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), -10); + EXPECT_EQ(rect.GetRight(), 15); + EXPECT_EQ(rect.GetBottom(), max - 5); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), -10); + EXPECT_EQ(rect.GetWidth(), 10); + EXPECT_EQ(rect.GetHeight(), max); + EXPECT_FALSE(rect.IsEmpty()); + } + + { + IRect rect = IRect::MakeLTRB(5, 10, 15, min + 5); + + EXPECT_EQ(rect.GetLeft(), 5); + EXPECT_EQ(rect.GetTop(), 10); + EXPECT_EQ(rect.GetRight(), 15); + EXPECT_EQ(rect.GetBottom(), min + 5); + EXPECT_EQ(rect.GetX(), 5); + EXPECT_EQ(rect.GetY(), 10); + EXPECT_EQ(rect.GetWidth(), 10); + EXPECT_EQ(rect.GetHeight(), min); + EXPECT_TRUE(rect.IsEmpty()); + } +} + +TEST(RectTest, RectMakeSize) { + { + Size s(100, 200); + Rect r = Rect::MakeSize(s); + Rect expected = Rect::MakeLTRB(0, 0, 100, 200); + EXPECT_RECT_NEAR(r, expected); + } + + { + ISize s(100, 200); + Rect r = Rect::MakeSize(s); + Rect expected = Rect::MakeLTRB(0, 0, 100, 200); + EXPECT_RECT_NEAR(r, expected); + } + + { + Size s(100, 200); + IRect r = IRect::MakeSize(s); + IRect expected = IRect::MakeLTRB(0, 0, 100, 200); + EXPECT_EQ(r, expected); + } + + { + ISize s(100, 200); + IRect r = IRect::MakeSize(s); + IRect expected = IRect::MakeLTRB(0, 0, 100, 200); + EXPECT_EQ(r, expected); + } +} + +TEST(RectTest, RectMakeMaximum) { + Rect rect = Rect::MakeMaximum(); + auto inf = std::numeric_limits::infinity(); + auto min = std::numeric_limits::lowest(); + auto max = std::numeric_limits::max(); + + EXPECT_EQ(rect.GetLeft(), min); + EXPECT_EQ(rect.GetTop(), min); + EXPECT_EQ(rect.GetRight(), max); + EXPECT_EQ(rect.GetBottom(), max); + EXPECT_EQ(rect.GetX(), min); + EXPECT_EQ(rect.GetY(), min); + EXPECT_EQ(rect.GetWidth(), inf); + EXPECT_EQ(rect.GetHeight(), inf); + EXPECT_FALSE(rect.IsEmpty()); + EXPECT_TRUE(rect.IsFinite()); +} + +TEST(RectTest, IRectMakeMaximum) { + IRect rect = IRect::MakeMaximum(); + auto min = std::numeric_limits::min(); + auto max = std::numeric_limits::max(); + + EXPECT_EQ(rect.GetLeft(), min); + EXPECT_EQ(rect.GetTop(), min); + EXPECT_EQ(rect.GetRight(), max); + EXPECT_EQ(rect.GetBottom(), max); + EXPECT_EQ(rect.GetX(), min); + EXPECT_EQ(rect.GetY(), min); + EXPECT_EQ(rect.GetWidth(), max); + EXPECT_EQ(rect.GetHeight(), max); + EXPECT_FALSE(rect.IsEmpty()); +} + +TEST(RectTest, RectFromRect) { + EXPECT_EQ(Rect(Rect::MakeXYWH(2, 3, 7, 15)), + Rect::MakeXYWH(2.0, 3.0, 7.0, 15.0)); + EXPECT_EQ(Rect(Rect::MakeLTRB(2, 3, 7, 15)), + Rect::MakeLTRB(2.0, 3.0, 7.0, 15.0)); +} + +TEST(RectTest, IRectFromIRect) { + EXPECT_EQ(IRect(IRect::MakeXYWH(2, 3, 7, 15)), // + IRect::MakeXYWH(2, 3, 7, 15)); + EXPECT_EQ(IRect(IRect::MakeLTRB(2, 3, 7, 15)), // + IRect::MakeLTRB(2, 3, 7, 15)); +} + +TEST(RectTest, RectCopy) { + // Using fractional-power-of-2 friendly values for equality tests + Rect rect = Rect::MakeLTRB(5.125f, 10.25f, 20.625f, 25.375f); + Rect copy = rect; + + EXPECT_EQ(rect, copy); + EXPECT_EQ(copy.GetLeft(), 5.125f); + EXPECT_EQ(copy.GetTop(), 10.25f); + EXPECT_EQ(copy.GetRight(), 20.625f); + EXPECT_EQ(copy.GetBottom(), 25.375f); + EXPECT_EQ(copy.GetX(), 5.125f); + EXPECT_EQ(copy.GetY(), 10.25f); + EXPECT_EQ(copy.GetWidth(), 15.5f); + EXPECT_EQ(copy.GetHeight(), 15.125f); + EXPECT_FALSE(copy.IsEmpty()); + EXPECT_TRUE(copy.IsFinite()); +} + +TEST(RectTest, IRectCopy) { + IRect rect = IRect::MakeLTRB(5, 10, 20, 25); + IRect copy = rect; + + EXPECT_EQ(rect, copy); + EXPECT_EQ(copy.GetLeft(), 5); + EXPECT_EQ(copy.GetTop(), 10); + EXPECT_EQ(copy.GetRight(), 20); + EXPECT_EQ(copy.GetBottom(), 25); + EXPECT_EQ(copy.GetX(), 5); + EXPECT_EQ(copy.GetY(), 10); + EXPECT_EQ(copy.GetWidth(), 15); + EXPECT_EQ(copy.GetHeight(), 15); + EXPECT_FALSE(copy.IsEmpty()); +} + +TEST(RectTest, RectOriginSizeXYWHGetters) { + { + Rect r = Rect::MakeOriginSize({10, 20}, {50, 40}); + EXPECT_EQ(r.GetOrigin(), Point(10, 20)); + EXPECT_EQ(r.GetSize(), Size(50, 40)); + EXPECT_EQ(r.GetX(), 10); + EXPECT_EQ(r.GetY(), 20); + EXPECT_EQ(r.GetWidth(), 50); + EXPECT_EQ(r.GetHeight(), 40); + auto expected_array = std::array{10, 20, 50, 40}; + EXPECT_EQ(r.GetXYWH(), expected_array); + } + + { + Rect r = Rect::MakeLTRB(10, 20, 50, 40); + EXPECT_EQ(r.GetOrigin(), Point(10, 20)); + EXPECT_EQ(r.GetSize(), Size(40, 20)); + EXPECT_EQ(r.GetX(), 10); + EXPECT_EQ(r.GetY(), 20); + EXPECT_EQ(r.GetWidth(), 40); + EXPECT_EQ(r.GetHeight(), 20); + auto expected_array = std::array{10, 20, 40, 20}; + EXPECT_EQ(r.GetXYWH(), expected_array); + } +} + +TEST(RectTest, IRectOriginSizeXYWHGetters) { + { + IRect r = IRect::MakeOriginSize({10, 20}, {50, 40}); + EXPECT_EQ(r.GetOrigin(), IPoint(10, 20)); + EXPECT_EQ(r.GetSize(), ISize(50, 40)); + EXPECT_EQ(r.GetX(), 10); + EXPECT_EQ(r.GetY(), 20); + EXPECT_EQ(r.GetWidth(), 50); + EXPECT_EQ(r.GetHeight(), 40); + auto expected_array = std::array{10, 20, 50, 40}; + EXPECT_EQ(r.GetXYWH(), expected_array); + } + + { + IRect r = IRect::MakeLTRB(10, 20, 50, 40); + EXPECT_EQ(r.GetOrigin(), IPoint(10, 20)); + EXPECT_EQ(r.GetSize(), ISize(40, 20)); + EXPECT_EQ(r.GetX(), 10); + EXPECT_EQ(r.GetY(), 20); + EXPECT_EQ(r.GetWidth(), 40); + EXPECT_EQ(r.GetHeight(), 20); + auto expected_array = std::array{10, 20, 40, 20}; + EXPECT_EQ(r.GetXYWH(), expected_array); + } +} + +TEST(RectTest, RectRoundOutEmpty) { + Rect rect; + + EXPECT_EQ(Rect::RoundOut(rect), Rect()); + + EXPECT_EQ(IRect::RoundOut(rect), IRect()); +} + +TEST(RectTest, RectRoundOutSimple) { + Rect rect = Rect::MakeLTRB(5.125f, 10.75f, 20.625f, 25.375f); + + EXPECT_EQ(Rect::RoundOut(rect), Rect::MakeLTRB(5.0f, 10.0f, 21.0f, 26.0f)); + + EXPECT_EQ(IRect::RoundOut(rect), IRect::MakeLTRB(5, 10, 21, 26)); +} + +TEST(RectTest, RectRoundOutToIRectHuge) { + auto test = [](int corners) { + EXPECT_TRUE(corners >= 0 && corners <= 0xf); + Scalar l, t, r, b; + int64_t il, it, ir, ib; + l = il = 50; + t = it = 50; + r = ir = 80; + b = ib = 80; + if ((corners & (1 << 0)) != 0) { + l = -1E20; + il = std::numeric_limits::min(); + } + if ((corners & (1 << 1)) != 0) { + t = -1E20; + it = std::numeric_limits::min(); + } + if ((corners & (1 << 2)) != 0) { + r = +1E20; + ir = std::numeric_limits::max(); + } + if ((corners & (1 << 3)) != 0) { + b = +1E20; + ib = std::numeric_limits::max(); + } + + Rect rect = Rect::MakeLTRB(l, t, r, b); + IRect irect = IRect::RoundOut(rect); + EXPECT_EQ(irect.GetLeft(), il) << corners; + EXPECT_EQ(irect.GetTop(), it) << corners; + EXPECT_EQ(irect.GetRight(), ir) << corners; + EXPECT_EQ(irect.GetBottom(), ib) << corners; + }; + + for (int corners = 0; corners <= 15; corners++) { + test(corners); + } +} + +TEST(RectTest, RectDoesNotIntersectEmpty) { + Rect rect = Rect::MakeLTRB(50, 50, 100, 100); + + auto test = [&rect](Scalar l, Scalar t, Scalar r, Scalar b, + const std::string& label) { + EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(l, b, r, t))) + << label << " with Top/Bottom swapped"; + EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(r, b, l, t))) + << label << " with Left/Right swapped"; + EXPECT_FALSE(rect.IntersectsWithRect(Rect::MakeLTRB(r, t, l, b))) + << label << " with all sides swapped"; + }; + + test(20, 20, 30, 30, "Above and Left"); + test(70, 20, 80, 30, "Above"); + test(120, 20, 130, 30, "Above and Right"); + test(120, 70, 130, 80, "Right"); + test(120, 120, 130, 130, "Below and Right"); + test(70, 120, 80, 130, "Below"); + test(20, 120, 30, 130, "Below and Left"); + test(20, 70, 30, 80, "Left"); + + test(70, 70, 80, 80, "Inside"); + + test(40, 70, 60, 80, "Straddling Left"); + test(70, 40, 80, 60, "Straddling Top"); + test(90, 70, 110, 80, "Straddling Right"); + test(70, 90, 80, 110, "Straddling Bottom"); +} + +TEST(RectTest, IRectDoesNotIntersectEmpty) { + IRect rect = IRect::MakeLTRB(50, 50, 100, 100); + + auto test = [&rect](int64_t l, int64_t t, int64_t r, int64_t b, + const std::string& label) { + EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(l, b, r, t))) + << label << " with Top/Bottom swapped"; + EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(r, b, l, t))) + << label << " with Left/Right swapped"; + EXPECT_FALSE(rect.IntersectsWithRect(IRect::MakeLTRB(r, t, l, b))) + << label << " with all sides swapped"; + }; + + test(20, 20, 30, 30, "Above and Left"); + test(70, 20, 80, 30, "Above"); + test(120, 20, 130, 30, "Above and Right"); + test(120, 70, 130, 80, "Right"); + test(120, 120, 130, 130, "Below and Right"); + test(70, 120, 80, 130, "Below"); + test(20, 120, 30, 130, "Below and Left"); + test(20, 70, 30, 80, "Left"); + + test(70, 70, 80, 80, "Inside"); + + test(40, 70, 60, 80, "Straddling Left"); + test(70, 40, 80, 60, "Straddling Top"); + test(90, 70, 110, 80, "Straddling Right"); + test(70, 90, 80, 110, "Straddling Bottom"); +} + +TEST(RectTest, EmptyRectDoesNotIntersect) { + Rect rect = Rect::MakeLTRB(50, 50, 100, 100); + + auto test = [&rect](Scalar l, Scalar t, Scalar r, Scalar b, + const std::string& label) { + EXPECT_FALSE(Rect::MakeLTRB(l, b, r, t).IntersectsWithRect(rect)) + << label << " with Top/Bottom swapped"; + EXPECT_FALSE(Rect::MakeLTRB(r, b, l, t).IntersectsWithRect(rect)) + << label << " with Left/Right swapped"; + EXPECT_FALSE(Rect::MakeLTRB(r, t, l, b).IntersectsWithRect(rect)) + << label << " with all sides swapped"; + }; + + test(20, 20, 30, 30, "Above and Left"); + test(70, 20, 80, 30, "Above"); + test(120, 20, 130, 30, "Above and Right"); + test(120, 70, 130, 80, "Right"); + test(120, 120, 130, 130, "Below and Right"); + test(70, 120, 80, 130, "Below"); + test(20, 120, 30, 130, "Below and Left"); + test(20, 70, 30, 80, "Left"); + + test(70, 70, 80, 80, "Inside"); + + test(40, 70, 60, 80, "Straddling Left"); + test(70, 40, 80, 60, "Straddling Top"); + test(90, 70, 110, 80, "Straddling Right"); + test(70, 90, 80, 110, "Straddling Bottom"); +} + +TEST(RectTest, EmptyIRectDoesNotIntersect) { + IRect rect = IRect::MakeLTRB(50, 50, 100, 100); + + auto test = [&rect](int64_t l, int64_t t, int64_t r, int64_t b, + const std::string& label) { + EXPECT_FALSE(IRect::MakeLTRB(l, b, r, t).IntersectsWithRect(rect)) + << label << " with Top/Bottom swapped"; + EXPECT_FALSE(IRect::MakeLTRB(r, b, l, t).IntersectsWithRect(rect)) + << label << " with Left/Right swapped"; + EXPECT_FALSE(IRect::MakeLTRB(r, t, l, b).IntersectsWithRect(rect)) + << label << " with all sides swapped"; + }; + + test(20, 20, 30, 30, "Above and Left"); + test(70, 20, 80, 30, "Above"); + test(120, 20, 130, 30, "Above and Right"); + test(120, 70, 130, 80, "Right"); + test(120, 120, 130, 130, "Below and Right"); + test(70, 120, 80, 130, "Below"); + test(20, 120, 30, 130, "Below and Left"); + test(20, 70, 30, 80, "Left"); + + test(70, 70, 80, 80, "Inside"); + + test(40, 70, 60, 80, "Straddling Left"); + test(70, 40, 80, 60, "Straddling Top"); + test(90, 70, 110, 80, "Straddling Right"); + test(70, 90, 80, 110, "Straddling Bottom"); +} + +TEST(RectTest, RectScale) { + auto test1 = [](Rect rect, Scalar scale) { + Rect expected = Rect::MakeXYWH(rect.GetX() * scale, // + rect.GetY() * scale, // + rect.GetWidth() * scale, // + rect.GetHeight() * scale); + + EXPECT_RECT_NEAR(rect.Scale(scale), expected) // + << rect << " * " << scale; + EXPECT_RECT_NEAR(rect.Scale(scale, scale), expected) // + << rect << " * " << scale; + EXPECT_RECT_NEAR(rect.Scale(Point(scale, scale)), expected) // + << rect << " * " << scale; + EXPECT_RECT_NEAR(rect.Scale(Size(scale, scale)), expected) // + << rect << " * " << scale; + }; + + auto test2 = [&test1](Rect rect, Scalar scale_x, Scalar scale_y) { + Rect expected = Rect::MakeXYWH(rect.GetX() * scale_x, // + rect.GetY() * scale_y, // + rect.GetWidth() * scale_x, // + rect.GetHeight() * scale_y); + + EXPECT_RECT_NEAR(rect.Scale(scale_x, scale_y), expected) // + << rect << " * " << scale_x << ", " << scale_y; + EXPECT_RECT_NEAR(rect.Scale(Point(scale_x, scale_y)), expected) // + << rect << " * " << scale_x << ", " << scale_y; + EXPECT_RECT_NEAR(rect.Scale(Size(scale_x, scale_y)), expected) // + << rect << " * " << scale_x << ", " << scale_y; + + test1(rect, scale_x); + test1(rect, scale_y); + }; + + test2(Rect::MakeLTRB(10, 15, 100, 150), 1.0, 0.0); + test2(Rect::MakeLTRB(10, 15, 100, 150), 0.0, 1.0); + test2(Rect::MakeLTRB(10, 15, 100, 150), 0.0, 0.0); + test2(Rect::MakeLTRB(10, 15, 100, 150), 2.5, 3.5); + test2(Rect::MakeLTRB(10, 15, 100, 150), 3.5, 2.5); + test2(Rect::MakeLTRB(10, 15, -100, 150), 2.5, 3.5); + test2(Rect::MakeLTRB(10, 15, 100, -150), 2.5, 3.5); + test2(Rect::MakeLTRB(10, 15, 100, 150), -2.5, 3.5); + test2(Rect::MakeLTRB(10, 15, 100, 150), 2.5, -3.5); +} + +TEST(RectTest, IRectScale) { + auto test1 = [](IRect rect, int64_t scale) { + IRect expected = IRect::MakeXYWH(rect.GetX() * scale, // + rect.GetY() * scale, // + rect.GetWidth() * scale, // + rect.GetHeight() * scale); + + EXPECT_EQ(rect.Scale(scale), expected) // + << rect << " * " << scale; + EXPECT_EQ(rect.Scale(scale, scale), expected) // + << rect << " * " << scale; + EXPECT_EQ(rect.Scale(IPoint(scale, scale)), expected) // + << rect << " * " << scale; + EXPECT_EQ(rect.Scale(ISize(scale, scale)), expected) // + << rect << " * " << scale; + }; + + auto test2 = [&test1](IRect rect, int64_t scale_x, int64_t scale_y) { + IRect expected = IRect::MakeXYWH(rect.GetX() * scale_x, // + rect.GetY() * scale_y, // + rect.GetWidth() * scale_x, // + rect.GetHeight() * scale_y); + + EXPECT_EQ(rect.Scale(scale_x, scale_y), expected) // + << rect << " * " << scale_x << ", " << scale_y; + EXPECT_EQ(rect.Scale(IPoint(scale_x, scale_y)), expected) // + << rect << " * " << scale_x << ", " << scale_y; + EXPECT_EQ(rect.Scale(ISize(scale_x, scale_y)), expected) // + << rect << " * " << scale_x << ", " << scale_y; + + test1(rect, scale_x); + test1(rect, scale_y); + }; + + test2(IRect::MakeLTRB(10, 15, 100, 150), 2, 3); + test2(IRect::MakeLTRB(10, 15, 100, 150), 3, 2); + test2(IRect::MakeLTRB(10, 15, -100, 150), 2, 3); + test2(IRect::MakeLTRB(10, 15, 100, -150), 2, 3); + test2(IRect::MakeLTRB(10, 15, 100, 150), -2, 3); + test2(IRect::MakeLTRB(10, 15, 100, 150), 2, -3); +} + +TEST(RectTest, RectArea) { + EXPECT_EQ(Rect::MakeXYWH(0, 0, 100, 200).Area(), 20000); + EXPECT_EQ(Rect::MakeXYWH(10, 20, 100, 200).Area(), 20000); + EXPECT_EQ(Rect::MakeXYWH(0, 0, 200, 100).Area(), 20000); + EXPECT_EQ(Rect::MakeXYWH(10, 20, 200, 100).Area(), 20000); + EXPECT_EQ(Rect::MakeXYWH(0, 0, 100, 100).Area(), 10000); + EXPECT_EQ(Rect::MakeXYWH(10, 20, 100, 100).Area(), 10000); +} + +TEST(RectTest, IRectArea) { + EXPECT_EQ(IRect::MakeXYWH(0, 0, 100, 200).Area(), 20000); + EXPECT_EQ(IRect::MakeXYWH(10, 20, 100, 200).Area(), 20000); + EXPECT_EQ(IRect::MakeXYWH(0, 0, 200, 100).Area(), 20000); + EXPECT_EQ(IRect::MakeXYWH(10, 20, 200, 100).Area(), 20000); + EXPECT_EQ(IRect::MakeXYWH(0, 0, 100, 100).Area(), 10000); + EXPECT_EQ(IRect::MakeXYWH(10, 20, 100, 100).Area(), 10000); +} + +TEST(RectTest, RectGetNormalizingTransform) { + { + // Checks for expected matrix values + + auto r = Rect::MakeXYWH(100, 200, 200, 400); + + EXPECT_EQ(r.GetNormalizingTransform(), + Matrix::MakeScale({0.005, 0.0025, 1.0}) * + Matrix::MakeTranslation({-100, -200})); + } + + { + // Checks for expected transform of points relative to the rect + + auto r = Rect::MakeLTRB(300, 500, 400, 700); + auto m = r.GetNormalizingTransform(); + + // The 4 corners of the rect => (0, 0) to (1, 1) + EXPECT_EQ(m * Point(300, 500), Point(0, 0)); + EXPECT_EQ(m * Point(400, 500), Point(1, 0)); + EXPECT_EQ(m * Point(400, 700), Point(1, 1)); + EXPECT_EQ(m * Point(300, 700), Point(0, 1)); + + // The center => (0.5, 0.5) + EXPECT_EQ(m * Point(350, 600), Point(0.5, 0.5)); + + // Outside the 4 corners => (-1, -1) to (2, 2) + EXPECT_EQ(m * Point(200, 300), Point(-1, -1)); + EXPECT_EQ(m * Point(500, 300), Point(2, -1)); + EXPECT_EQ(m * Point(500, 900), Point(2, 2)); + EXPECT_EQ(m * Point(200, 900), Point(-1, 2)); + } + + { + // Checks for behavior with empty rects + + auto zero = Matrix::MakeScale({0.0, 0.0, 1.0}); + + // Empty for width and/or height == 0 + EXPECT_EQ(Rect::MakeXYWH(10, 10, 0, 10).GetNormalizingTransform(), zero); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, 0).GetNormalizingTransform(), zero); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 0, 0).GetNormalizingTransform(), zero); + + // Empty for width and/or height < 0 + EXPECT_EQ(Rect::MakeXYWH(10, 10, -1, 10).GetNormalizingTransform(), zero); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, -1).GetNormalizingTransform(), zero); + EXPECT_EQ(Rect::MakeXYWH(10, 10, -1, -1).GetNormalizingTransform(), zero); + } + + { + // Checks for behavior with non-finite rects + + auto z = Matrix::MakeScale({0.0, 0.0, 1.0}); + auto nan = std::numeric_limits::quiet_NaN(); + auto inf = std::numeric_limits::infinity(); + + // Non-finite for width and/or height == nan + EXPECT_EQ(Rect::MakeXYWH(10, 10, nan, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, nan).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, nan, nan).GetNormalizingTransform(), z); + + // Non-finite for width and/or height == inf + EXPECT_EQ(Rect::MakeXYWH(10, 10, inf, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, inf).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, inf, inf).GetNormalizingTransform(), z); + + // Non-finite for width and/or height == -inf + EXPECT_EQ(Rect::MakeXYWH(10, 10, -inf, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, 10, -inf).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, 10, -inf, -inf).GetNormalizingTransform(), z); + + // Non-finite for origin X and/or Y == nan + EXPECT_EQ(Rect::MakeXYWH(nan, 10, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, nan, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(nan, nan, 10, 10).GetNormalizingTransform(), z); + + // Non-finite for origin X and/or Y == inf + EXPECT_EQ(Rect::MakeXYWH(inf, 10, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, inf, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(inf, inf, 10, 10).GetNormalizingTransform(), z); + + // Non-finite for origin X and/or Y == -inf + EXPECT_EQ(Rect::MakeXYWH(-inf, 10, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(10, -inf, 10, 10).GetNormalizingTransform(), z); + EXPECT_EQ(Rect::MakeXYWH(-inf, -inf, 10, 10).GetNormalizingTransform(), z); + } +} + +TEST(RectTest, IRectGetNormalizingTransform) { + { + // Checks for expected matrix values + + auto r = IRect::MakeXYWH(100, 200, 200, 400); + + EXPECT_EQ(r.GetNormalizingTransform(), + Matrix::MakeScale({0.005, 0.0025, 1.0}) * + Matrix::MakeTranslation({-100, -200})); + } + + { + // Checks for expected transform of points relative to the rect + + auto r = IRect::MakeLTRB(300, 500, 400, 700); + auto m = r.GetNormalizingTransform(); + + // The 4 corners of the rect => (0, 0) to (1, 1) + EXPECT_EQ(m * Point(300, 500), Point(0, 0)); + EXPECT_EQ(m * Point(400, 500), Point(1, 0)); + EXPECT_EQ(m * Point(400, 700), Point(1, 1)); + EXPECT_EQ(m * Point(300, 700), Point(0, 1)); + + // The center => (0.5, 0.5) + EXPECT_EQ(m * Point(350, 600), Point(0.5, 0.5)); + + // Outside the 4 corners => (-1, -1) to (2, 2) + EXPECT_EQ(m * Point(200, 300), Point(-1, -1)); + EXPECT_EQ(m * Point(500, 300), Point(2, -1)); + EXPECT_EQ(m * Point(500, 900), Point(2, 2)); + EXPECT_EQ(m * Point(200, 900), Point(-1, 2)); + } + + { + // Checks for behavior with empty rects + + auto zero = Matrix::MakeScale({0.0, 0.0, 1.0}); + + // Empty for width and/or height == 0 + EXPECT_EQ(IRect::MakeXYWH(10, 10, 0, 10).GetNormalizingTransform(), zero); + EXPECT_EQ(IRect::MakeXYWH(10, 10, 10, 0).GetNormalizingTransform(), zero); + EXPECT_EQ(IRect::MakeXYWH(10, 10, 0, 0).GetNormalizingTransform(), zero); + + // Empty for width and/or height < 0 + EXPECT_EQ(IRect::MakeXYWH(10, 10, -1, 10).GetNormalizingTransform(), zero); + EXPECT_EQ(IRect::MakeXYWH(10, 10, 10, -1).GetNormalizingTransform(), zero); + EXPECT_EQ(IRect::MakeXYWH(10, 10, -1, -1).GetNormalizingTransform(), zero); + } +} + +TEST(RectTest, RectXYWHIsEmpty) { + auto nan = std::numeric_limits::quiet_NaN(); + + // Non-empty + EXPECT_FALSE(Rect::MakeXYWH(1.5, 2.3, 10.5, 7.2).IsEmpty()); + + // Empty both width and height both 0 or negative, in all combinations + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, 0.0).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, -1.0).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, -1.0).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, 0.0).IsEmpty()); + + // Empty for 0 or negative width or height (but not both at the same time) + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, 0.0).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, -1.0).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 0.0, 7.2).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, -1.0, 7.2).IsEmpty()); + + // Empty for NaN in width or height or both + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, 10.5, nan).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, nan, 7.2).IsEmpty()); + EXPECT_TRUE(Rect::MakeXYWH(1.5, 2.3, nan, nan).IsEmpty()); +} + +TEST(RectTest, IRectXYWHIsEmpty) { + // Non-empty + EXPECT_FALSE(IRect::MakeXYWH(1, 2, 10, 7).IsEmpty()); + + // Empty both width and height both 0 or negative, in all combinations + EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, 0).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, -1).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, 0).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, -1).IsEmpty()); + + // Empty for 0 or negative width or height (but not both at the same time) + EXPECT_TRUE(IRect::MakeXYWH(1, 2, 10, 0).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, 10, -1).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, 0, 7).IsEmpty()); + EXPECT_TRUE(IRect::MakeXYWH(1, 2, -1, 7).IsEmpty()); +} + +TEST(RectTest, MakePointBoundsQuad) { + Quad quad = { + Point(10, 10), + Point(20, 10), + Point(10, 20), + Point(20, 20), + }; + std::optional bounds = Rect::MakePointBounds(quad); + EXPECT_TRUE(bounds.has_value()); + if (bounds.has_value()) { + EXPECT_TRUE(RectNear(bounds.value(), Rect::MakeLTRB(10, 10, 20, 20))); + } +} + +TEST(RectTest, IsSquare) { + EXPECT_TRUE(Rect::MakeXYWH(10, 30, 20, 20).IsSquare()); + EXPECT_FALSE(Rect::MakeXYWH(10, 30, 20, 19).IsSquare()); + EXPECT_FALSE(Rect::MakeXYWH(10, 30, 19, 20).IsSquare()); + EXPECT_TRUE(Rect::MakeMaximum().IsSquare()); + + EXPECT_TRUE(IRect::MakeXYWH(10, 30, 20, 20).IsSquare()); + EXPECT_FALSE(IRect::MakeXYWH(10, 30, 20, 19).IsSquare()); + EXPECT_FALSE(IRect::MakeXYWH(10, 30, 19, 20).IsSquare()); + EXPECT_TRUE(IRect::MakeMaximum().IsSquare()); +} + +TEST(RectTest, GetCenter) { + EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); + EXPECT_EQ(Rect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); + EXPECT_EQ(Rect::MakeMaximum().GetCenter(), Point(0, 0)); + + // Note that we expect a Point as the answer from an IRect + EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 20).GetCenter(), Point(20, 40)); + EXPECT_EQ(IRect::MakeXYWH(10, 30, 20, 19).GetCenter(), Point(20, 39.5)); + EXPECT_EQ(IRect::MakeMaximum().GetCenter(), Point(0, 0)); +} + +TEST(RectTest, RectExpand) { + auto rect = Rect::MakeLTRB(100, 100, 200, 200); + + // Expand(T amount) + EXPECT_EQ(rect.Expand(10), Rect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(-10), Rect::MakeLTRB(110, 110, 190, 190)); + + // Expand(amount, amount) + EXPECT_EQ(rect.Expand(10, 10), Rect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(10, -10), Rect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(-10, 10), Rect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(-10, -10), Rect::MakeLTRB(110, 110, 190, 190)); + + // Expand(amount, amount, amount, amount) + EXPECT_EQ(rect.Expand(10, 20, 30, 40), Rect::MakeLTRB(90, 80, 230, 240)); + EXPECT_EQ(rect.Expand(-10, 20, 30, 40), Rect::MakeLTRB(110, 80, 230, 240)); + EXPECT_EQ(rect.Expand(10, -20, 30, 40), Rect::MakeLTRB(90, 120, 230, 240)); + EXPECT_EQ(rect.Expand(10, 20, -30, 40), Rect::MakeLTRB(90, 80, 170, 240)); + EXPECT_EQ(rect.Expand(10, 20, 30, -40), Rect::MakeLTRB(90, 80, 230, 160)); + + // Expand(Point amount) + EXPECT_EQ(rect.Expand(Point{10, 10}), Rect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(Point{10, -10}), Rect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(Point{-10, 10}), Rect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(Point{-10, -10}), Rect::MakeLTRB(110, 110, 190, 190)); + + // Expand(Size amount) + EXPECT_EQ(rect.Expand(Size{10, 10}), Rect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(Size{10, -10}), Rect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(Size{-10, 10}), Rect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(Size{-10, -10}), Rect::MakeLTRB(110, 110, 190, 190)); +} + +TEST(RectTest, IRectExpand) { + auto rect = IRect::MakeLTRB(100, 100, 200, 200); + + // Expand(T amount) + EXPECT_EQ(rect.Expand(10), IRect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(-10), IRect::MakeLTRB(110, 110, 190, 190)); + + // Expand(amount, amount) + EXPECT_EQ(rect.Expand(10, 10), IRect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(10, -10), IRect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(-10, 10), IRect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(-10, -10), IRect::MakeLTRB(110, 110, 190, 190)); + + // Expand(amount, amount, amount, amount) + EXPECT_EQ(rect.Expand(10, 20, 30, 40), IRect::MakeLTRB(90, 80, 230, 240)); + EXPECT_EQ(rect.Expand(-10, 20, 30, 40), IRect::MakeLTRB(110, 80, 230, 240)); + EXPECT_EQ(rect.Expand(10, -20, 30, 40), IRect::MakeLTRB(90, 120, 230, 240)); + EXPECT_EQ(rect.Expand(10, 20, -30, 40), IRect::MakeLTRB(90, 80, 170, 240)); + EXPECT_EQ(rect.Expand(10, 20, 30, -40), IRect::MakeLTRB(90, 80, 230, 160)); + + // Expand(IPoint amount) + EXPECT_EQ(rect.Expand(IPoint{10, 10}), IRect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(IPoint{10, -10}), IRect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(IPoint{-10, 10}), IRect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(IPoint{-10, -10}), IRect::MakeLTRB(110, 110, 190, 190)); + + // Expand(ISize amount) + EXPECT_EQ(rect.Expand(ISize{10, 10}), IRect::MakeLTRB(90, 90, 210, 210)); + EXPECT_EQ(rect.Expand(ISize{10, -10}), IRect::MakeLTRB(90, 110, 210, 190)); + EXPECT_EQ(rect.Expand(ISize{-10, 10}), IRect::MakeLTRB(110, 90, 190, 210)); + EXPECT_EQ(rect.Expand(ISize{-10, -10}), IRect::MakeLTRB(110, 110, 190, 190)); +} + +TEST(RectTest, ContainsFloatingPoint) { + auto rect1 = + Rect::MakeXYWH(472.599945f, 440.999969f, 1102.80005f, 654.000061f); + auto rect2 = Rect::MakeXYWH(724.f, 618.f, 600.f, 300.f); + EXPECT_TRUE(rect1.Contains(rect2)); +} + +template +static constexpr inline R flip_lr(R rect) { + return R::MakeLTRB(rect.GetRight(), rect.GetTop(), // + rect.GetLeft(), rect.GetBottom()); +} + +template +static constexpr inline R flip_tb(R rect) { + return R::MakeLTRB(rect.GetLeft(), rect.GetBottom(), // + rect.GetRight(), rect.GetTop()); +} + +template +static constexpr inline R flip_lrtb(R rect) { + return flip_lr(flip_tb(rect)); +} + +static constexpr inline Rect swap_nan(const Rect& rect, int index) { + Scalar nan = std::numeric_limits::quiet_NaN(); + FML_DCHECK(index >= 0 && index <= 15); + Scalar l = ((index & (1 << 0)) != 0) ? nan : rect.GetLeft(); + Scalar t = ((index & (1 << 1)) != 0) ? nan : rect.GetTop(); + Scalar r = ((index & (1 << 2)) != 0) ? nan : rect.GetRight(); + Scalar b = ((index & (1 << 3)) != 0) ? nan : rect.GetBottom(); + return Rect::MakeLTRB(l, t, r, b); +} + +static constexpr inline Point swap_nan(const Point& point, int index) { + Scalar nan = std::numeric_limits::quiet_NaN(); + FML_DCHECK(index >= 0 && index <= 3); + Scalar x = ((index & (1 << 0)) != 0) ? nan : point.x; + Scalar y = ((index & (1 << 1)) != 0) ? nan : point.y; + return Point(x, y); +} + +TEST(RectTest, RectUnion) { + auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { + ASSERT_TRUE(a.IsFinite()) << label; + ASSERT_TRUE(b.IsFinite()) << label; + ASSERT_FALSE(a.Union(b).IsEmpty()); + + for (int i = 1; i < 16; i++) { + // NaN in a produces b + EXPECT_EQ(swap_nan(a, i).Union(b), b) << label << ", index = " << i; + // NaN in b produces a + EXPECT_EQ(a.Union(swap_nan(b, i)), a) << label << ", index = " << i; + // NaN in both is empty + for (int j = 1; j < 16; j++) { + EXPECT_TRUE(swap_nan(a, i).Union(swap_nan(b, j)).IsEmpty()) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& a, const Rect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_EQ(a.Union(flip_lr(b)), a) << label; + EXPECT_EQ(a.Union(flip_tb(b)), a) << label; + EXPECT_EQ(a.Union(flip_lrtb(b)), a) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_EQ(flip_lr(a).Union(b), b) << label; + EXPECT_EQ(flip_tb(a).Union(b), b) << label; + EXPECT_EQ(flip_lrtb(a).Union(b), b) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_TRUE(flip_lr(a).Union(flip_lr(b)).IsEmpty()) << label; + EXPECT_TRUE(flip_tb(a).Union(flip_tb(b)).IsEmpty()) << label; + EXPECT_TRUE(flip_lrtb(a).Union(flip_lrtb(b)).IsEmpty()) << label; + }; + + auto test = [&check_nans, &check_empty_flips](const Rect& a, const Rect& b, + const Rect& result) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_EQ(a.Union(b), result) << label; + EXPECT_EQ(b.Union(a), result) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 0, 0); + auto expected = Rect::MakeXYWH(100, 100, 100, 100); + test(a, b, expected); + } + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 1, 1); + auto expected = Rect::MakeXYWH(0, 0, 200, 200); + test(a, b, expected); + } + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 1, 1); + auto expected = Rect::MakeXYWH(10, 10, 190, 190); + test(a, b, expected); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 100, 100); + auto expected = Rect::MakeXYWH(0, 0, 110, 110); + test(a, b, expected); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(100, 100, 100, 100); + auto expected = Rect::MakeXYWH(0, 0, 200, 200); + test(a, b, expected); + } +} + +TEST(RectTest, OptRectUnion) { + auto a = Rect::MakeLTRB(0, 0, 100, 100); + auto b = Rect::MakeLTRB(100, 100, 200, 200); + auto c = Rect::MakeLTRB(100, 0, 200, 100); + + // NullOpt, NullOpt + EXPECT_FALSE(Rect::Union(std::nullopt, std::nullopt).has_value()); + EXPECT_EQ(Rect::Union(std::nullopt, std::nullopt), std::nullopt); + + auto test1 = [](const Rect& r) { + // Rect, NullOpt + EXPECT_EQ(Rect::Union(r, std::nullopt), r); + + // OptRect, NullOpt + EXPECT_TRUE(Rect::Union(std::optional(r), std::nullopt).has_value()); + EXPECT_EQ(Rect::Union(std::optional(r), std::nullopt).value(), r); + + // NullOpt, Rect + EXPECT_EQ(Rect::Union(std::nullopt, r), r); + + // NullOpt, OptRect + EXPECT_TRUE(Rect::Union(std::nullopt, std::optional(r)).has_value()); + EXPECT_EQ(Rect::Union(std::nullopt, std::optional(r)).value(), r); + }; + + test1(a); + test1(b); + test1(c); + + auto test2 = [](const Rect& a, const Rect& b, const Rect& u) { + ASSERT_EQ(a.Union(b), u); + + // Rect, OptRect + EXPECT_EQ(Rect::Union(a, std::optional(b)), u); + + // OptRect, Rect + EXPECT_EQ(Rect::Union(std::optional(a), b), u); + + // OptRect, OptRect + EXPECT_TRUE(Rect::Union(std::optional(a), std::optional(b)).has_value()); + EXPECT_EQ(Rect::Union(std::optional(a), std::optional(b)).value(), u); + }; + + test2(a, b, Rect::MakeLTRB(0, 0, 200, 200)); + test2(a, c, Rect::MakeLTRB(0, 0, 200, 100)); + test2(b, c, Rect::MakeLTRB(100, 0, 200, 200)); +} + +TEST(RectTest, IRectUnion) { + auto check_empty_flips = [](const IRect& a, const IRect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_EQ(a.Union(flip_lr(b)), a) << label; + EXPECT_EQ(a.Union(flip_tb(b)), a) << label; + EXPECT_EQ(a.Union(flip_lrtb(b)), a) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_EQ(flip_lr(a).Union(b), b) << label; + EXPECT_EQ(flip_tb(a).Union(b), b) << label; + EXPECT_EQ(flip_lrtb(a).Union(b), b) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_TRUE(flip_lr(a).Union(flip_lr(b)).IsEmpty()) << label; + EXPECT_TRUE(flip_tb(a).Union(flip_tb(b)).IsEmpty()) << label; + EXPECT_TRUE(flip_lrtb(a).Union(flip_lrtb(b)).IsEmpty()) << label; + }; + + auto test = [&check_empty_flips](const IRect& a, const IRect& b, + const IRect& result) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_EQ(a.Union(b), result) << label; + EXPECT_EQ(b.Union(a), result) << label; + check_empty_flips(a, b, label); + }; + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 0, 0); + auto expected = IRect::MakeXYWH(100, 100, 100, 100); + test(a, b, expected); + } + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 1, 1); + auto expected = IRect::MakeXYWH(0, 0, 200, 200); + test(a, b, expected); + } + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 1, 1); + auto expected = IRect::MakeXYWH(10, 10, 190, 190); + test(a, b, expected); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 100, 100); + auto expected = IRect::MakeXYWH(0, 0, 110, 110); + test(a, b, expected); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(100, 100, 100, 100); + auto expected = IRect::MakeXYWH(0, 0, 200, 200); + test(a, b, expected); + } +} + +TEST(RectTest, OptIRectUnion) { + auto a = IRect::MakeLTRB(0, 0, 100, 100); + auto b = IRect::MakeLTRB(100, 100, 200, 200); + auto c = IRect::MakeLTRB(100, 0, 200, 100); + + // NullOpt, NullOpt + EXPECT_FALSE(IRect::Union(std::nullopt, std::nullopt).has_value()); + EXPECT_EQ(IRect::Union(std::nullopt, std::nullopt), std::nullopt); + + auto test1 = [](const IRect& r) { + // Rect, NullOpt + EXPECT_EQ(IRect::Union(r, std::nullopt), r); + + // OptRect, NullOpt + EXPECT_TRUE(IRect::Union(std::optional(r), std::nullopt).has_value()); + EXPECT_EQ(IRect::Union(std::optional(r), std::nullopt).value(), r); + + // NullOpt, Rect + EXPECT_EQ(IRect::Union(std::nullopt, r), r); + + // NullOpt, OptRect + EXPECT_TRUE(IRect::Union(std::nullopt, std::optional(r)).has_value()); + EXPECT_EQ(IRect::Union(std::nullopt, std::optional(r)).value(), r); + }; + + test1(a); + test1(b); + test1(c); + + auto test2 = [](const IRect& a, const IRect& b, const IRect& u) { + ASSERT_EQ(a.Union(b), u); + + // Rect, OptRect + EXPECT_EQ(IRect::Union(a, std::optional(b)), u); + + // OptRect, Rect + EXPECT_EQ(IRect::Union(std::optional(a), b), u); + + // OptRect, OptRect + EXPECT_TRUE(IRect::Union(std::optional(a), std::optional(b)).has_value()); + EXPECT_EQ(IRect::Union(std::optional(a), std::optional(b)).value(), u); + }; + + test2(a, b, IRect::MakeLTRB(0, 0, 200, 200)); + test2(a, c, IRect::MakeLTRB(0, 0, 200, 100)); + test2(b, c, IRect::MakeLTRB(100, 0, 200, 200)); +} + +TEST(RectTest, RectIntersection) { + auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { + ASSERT_TRUE(a.IsFinite()) << label; + ASSERT_TRUE(b.IsFinite()) << label; + + for (int i = 1; i < 16; i++) { + // NaN in a produces empty + EXPECT_FALSE(swap_nan(a, i).Intersection(b).has_value()) + << label << ", index = " << i; + // NaN in b produces empty + EXPECT_FALSE(a.Intersection(swap_nan(b, i)).has_value()) + << label << ", index = " << i; + // NaN in both is empty + for (int j = 1; j < 16; j++) { + EXPECT_FALSE(swap_nan(a, i).Intersection(swap_nan(b, j)).has_value()) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& a, const Rect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_FALSE(a.Intersection(flip_lr(b)).has_value()) << label; + EXPECT_TRUE(a.IntersectionOrEmpty(flip_lr(b)).IsEmpty()) << label; + EXPECT_FALSE(a.Intersection(flip_tb(b)).has_value()) << label; + EXPECT_TRUE(a.IntersectionOrEmpty(flip_tb(b)).IsEmpty()) << label; + EXPECT_FALSE(a.Intersection(flip_lrtb(b)).has_value()) << label; + EXPECT_TRUE(a.IntersectionOrEmpty(flip_lrtb(b)).IsEmpty()) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_FALSE(flip_lr(a).Intersection(b).has_value()) << label; + EXPECT_TRUE(flip_lr(a).IntersectionOrEmpty(b).IsEmpty()) << label; + EXPECT_FALSE(flip_tb(a).Intersection(b).has_value()) << label; + EXPECT_TRUE(flip_tb(a).IntersectionOrEmpty(b).IsEmpty()) << label; + EXPECT_FALSE(flip_lrtb(a).Intersection(b).has_value()) << label; + EXPECT_TRUE(flip_lrtb(a).IntersectionOrEmpty(b).IsEmpty()) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).Intersection(flip_lr(b)).has_value()) << label; + EXPECT_TRUE(flip_lr(a).IntersectionOrEmpty(flip_lr(b)).IsEmpty()) << label; + EXPECT_FALSE(flip_tb(a).Intersection(flip_tb(b)).has_value()) << label; + EXPECT_TRUE(flip_tb(a).IntersectionOrEmpty(flip_tb(b)).IsEmpty()) << label; + EXPECT_FALSE(flip_lrtb(a).Intersection(flip_lrtb(b)).has_value()) << label; + EXPECT_TRUE(flip_lrtb(a).IntersectionOrEmpty(flip_lrtb(b)).IsEmpty()) + << label; + }; + + auto test_non_empty = [&check_nans, &check_empty_flips]( + const Rect& a, const Rect& b, const Rect& result) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.Intersection(b).has_value()) << label; + EXPECT_TRUE(b.Intersection(a).has_value()) << label; + EXPECT_EQ(a.Intersection(b), result) << label; + EXPECT_EQ(b.Intersection(a), result) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + auto test_empty = [&check_nans, &check_empty_flips](const Rect& a, + const Rect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.Intersection(b).has_value()) << label; + EXPECT_TRUE(a.IntersectionOrEmpty(b).IsEmpty()) << label; + EXPECT_FALSE(b.Intersection(a).has_value()) << label; + EXPECT_TRUE(b.IntersectionOrEmpty(a).IsEmpty()) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 0, 0); + + test_empty(a, b); + } + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 0, 0); + + test_empty(a, b); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 100, 100); + auto expected = Rect::MakeXYWH(10, 10, 90, 90); + + test_non_empty(a, b, expected); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(100, 100, 100, 100); + + test_empty(a, b); + } + + { + auto a = Rect::MakeMaximum(); + auto b = Rect::MakeXYWH(10, 10, 300, 300); + + test_non_empty(a, b, b); + } + + { + auto a = Rect::MakeMaximum(); + auto b = Rect::MakeMaximum(); + + test_non_empty(a, b, Rect::MakeMaximum()); + } +} + +TEST(RectTest, OptRectIntersection) { + auto a = Rect::MakeLTRB(0, 0, 110, 110); + auto b = Rect::MakeLTRB(100, 100, 200, 200); + auto c = Rect::MakeLTRB(100, 0, 200, 110); + + // NullOpt, NullOpt + EXPECT_FALSE(Rect::Intersection(std::nullopt, std::nullopt).has_value()); + EXPECT_EQ(Rect::Intersection(std::nullopt, std::nullopt), std::nullopt); + + auto test1 = [](const Rect& r) { + // Rect, NullOpt + EXPECT_TRUE(Rect::Intersection(r, std::nullopt).has_value()); + EXPECT_EQ(Rect::Intersection(r, std::nullopt).value(), r); + + // OptRect, NullOpt + EXPECT_TRUE(Rect::Intersection(std::optional(r), std::nullopt).has_value()); + EXPECT_EQ(Rect::Intersection(std::optional(r), std::nullopt).value(), r); + + // NullOpt, Rect + EXPECT_TRUE(Rect::Intersection(std::nullopt, r).has_value()); + EXPECT_EQ(Rect::Intersection(std::nullopt, r).value(), r); + + // NullOpt, OptRect + EXPECT_TRUE(Rect::Intersection(std::nullopt, std::optional(r)).has_value()); + EXPECT_EQ(Rect::Intersection(std::nullopt, std::optional(r)).value(), r); + }; + + test1(a); + test1(b); + test1(c); + + auto test2 = [](const Rect& a, const Rect& b, const Rect& i) { + ASSERT_EQ(a.Intersection(b), i); + + // Rect, OptRect + EXPECT_TRUE(Rect::Intersection(a, std::optional(b)).has_value()); + EXPECT_EQ(Rect::Intersection(a, std::optional(b)).value(), i); + + // OptRect, Rect + EXPECT_TRUE(Rect::Intersection(std::optional(a), b).has_value()); + EXPECT_EQ(Rect::Intersection(std::optional(a), b).value(), i); + + // OptRect, OptRect + EXPECT_TRUE( + Rect::Intersection(std::optional(a), std::optional(b)).has_value()); + EXPECT_EQ(Rect::Intersection(std::optional(a), std::optional(b)).value(), + i); + }; + + test2(a, b, Rect::MakeLTRB(100, 100, 110, 110)); + test2(a, c, Rect::MakeLTRB(100, 0, 110, 110)); + test2(b, c, Rect::MakeLTRB(100, 100, 200, 110)); +} + +TEST(RectTest, IRectIntersection) { + auto check_empty_flips = [](const IRect& a, const IRect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_FALSE(a.Intersection(flip_lr(b)).has_value()) << label; + EXPECT_FALSE(a.Intersection(flip_tb(b)).has_value()) << label; + EXPECT_FALSE(a.Intersection(flip_lrtb(b)).has_value()) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_FALSE(flip_lr(a).Intersection(b).has_value()) << label; + EXPECT_FALSE(flip_tb(a).Intersection(b).has_value()) << label; + EXPECT_FALSE(flip_lrtb(a).Intersection(b).has_value()) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).Intersection(flip_lr(b)).has_value()) << label; + EXPECT_FALSE(flip_tb(a).Intersection(flip_tb(b)).has_value()) << label; + EXPECT_FALSE(flip_lrtb(a).Intersection(flip_lrtb(b)).has_value()) << label; + }; + + auto test_non_empty = [&check_empty_flips](const IRect& a, const IRect& b, + const IRect& result) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.Intersection(b).has_value()) << label; + EXPECT_TRUE(b.Intersection(a).has_value()) << label; + EXPECT_EQ(a.Intersection(b), result) << label; + EXPECT_EQ(b.Intersection(a), result) << label; + check_empty_flips(a, b, label); + }; + + auto test_empty = [&check_empty_flips](const IRect& a, const IRect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.Intersection(b).has_value()) << label; + EXPECT_FALSE(b.Intersection(a).has_value()) << label; + check_empty_flips(a, b, label); + }; + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 0, 0); + + test_empty(a, b); + } + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 0, 0); + + test_empty(a, b); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 100, 100); + auto expected = IRect::MakeXYWH(10, 10, 90, 90); + + test_non_empty(a, b, expected); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(100, 100, 100, 100); + + test_empty(a, b); + } + + { + auto a = IRect::MakeMaximum(); + auto b = IRect::MakeXYWH(10, 10, 300, 300); + + test_non_empty(a, b, b); + } + + { + auto a = IRect::MakeMaximum(); + auto b = IRect::MakeMaximum(); + + test_non_empty(a, b, IRect::MakeMaximum()); + } +} + +TEST(RectTest, OptIRectIntersection) { + auto a = IRect::MakeLTRB(0, 0, 110, 110); + auto b = IRect::MakeLTRB(100, 100, 200, 200); + auto c = IRect::MakeLTRB(100, 0, 200, 110); + + // NullOpt, NullOpt + EXPECT_FALSE(IRect::Intersection(std::nullopt, std::nullopt).has_value()); + EXPECT_EQ(IRect::Intersection(std::nullopt, std::nullopt), std::nullopt); + + auto test1 = [](const IRect& r) { + // Rect, NullOpt + EXPECT_TRUE(IRect::Intersection(r, std::nullopt).has_value()); + EXPECT_EQ(IRect::Intersection(r, std::nullopt).value(), r); + + // OptRect, NullOpt + EXPECT_TRUE( + IRect::Intersection(std::optional(r), std::nullopt).has_value()); + EXPECT_EQ(IRect::Intersection(std::optional(r), std::nullopt).value(), r); + + // NullOpt, Rect + EXPECT_TRUE(IRect::Intersection(std::nullopt, r).has_value()); + EXPECT_EQ(IRect::Intersection(std::nullopt, r).value(), r); + + // NullOpt, OptRect + EXPECT_TRUE( + IRect::Intersection(std::nullopt, std::optional(r)).has_value()); + EXPECT_EQ(IRect::Intersection(std::nullopt, std::optional(r)).value(), r); + }; + + test1(a); + test1(b); + test1(c); + + auto test2 = [](const IRect& a, const IRect& b, const IRect& i) { + ASSERT_EQ(a.Intersection(b), i); + + // Rect, OptRect + EXPECT_TRUE(IRect::Intersection(a, std::optional(b)).has_value()); + EXPECT_EQ(IRect::Intersection(a, std::optional(b)).value(), i); + + // OptRect, Rect + EXPECT_TRUE(IRect::Intersection(std::optional(a), b).has_value()); + EXPECT_EQ(IRect::Intersection(std::optional(a), b).value(), i); + + // OptRect, OptRect + EXPECT_TRUE( + IRect::Intersection(std::optional(a), std::optional(b)).has_value()); + EXPECT_EQ(IRect::Intersection(std::optional(a), std::optional(b)).value(), + i); + }; + + test2(a, b, IRect::MakeLTRB(100, 100, 110, 110)); + test2(a, c, IRect::MakeLTRB(100, 0, 110, 110)); + test2(b, c, IRect::MakeLTRB(100, 100, 200, 110)); +} + +TEST(RectTest, RectIntersectsWithRect) { + auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { + ASSERT_TRUE(a.IsFinite()) << label; + ASSERT_TRUE(b.IsFinite()) << label; + + for (int i = 1; i < 16; i++) { + // NaN in a produces b + EXPECT_FALSE(swap_nan(a, i).IntersectsWithRect(b)) + << label << ", index = " << i; + // NaN in b produces a + EXPECT_FALSE(a.IntersectsWithRect(swap_nan(b, i))) + << label << ", index = " << i; + // NaN in both is empty + for (int j = 1; j < 16; j++) { + EXPECT_FALSE(swap_nan(a, i).IntersectsWithRect(swap_nan(b, j))) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& a, const Rect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_FALSE(a.IntersectsWithRect(flip_lr(b))) << label; + EXPECT_FALSE(a.IntersectsWithRect(flip_tb(b))) << label; + EXPECT_FALSE(a.IntersectsWithRect(flip_lrtb(b))) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_FALSE(flip_lr(a).IntersectsWithRect(b)) << label; + EXPECT_FALSE(flip_tb(a).IntersectsWithRect(b)) << label; + EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(b)) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).IntersectsWithRect(flip_lr(b))) << label; + EXPECT_FALSE(flip_tb(a).IntersectsWithRect(flip_tb(b))) << label; + EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(flip_lrtb(b))) << label; + }; + + auto test_non_empty = [&check_nans, &check_empty_flips](const Rect& a, + const Rect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.IntersectsWithRect(b)) << label; + EXPECT_TRUE(b.IntersectsWithRect(a)) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + auto test_empty = [&check_nans, &check_empty_flips](const Rect& a, + const Rect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.IntersectsWithRect(b)) << label; + EXPECT_FALSE(b.IntersectsWithRect(a)) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 0, 0); + + test_empty(a, b); + } + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 0, 0); + + test_empty(a, b); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(10, 10, 100, 100); + + test_non_empty(a, b); + } + + { + auto a = Rect::MakeXYWH(0, 0, 100, 100); + auto b = Rect::MakeXYWH(100, 100, 100, 100); + + test_empty(a, b); + } + + { + auto a = Rect::MakeMaximum(); + auto b = Rect::MakeXYWH(10, 10, 100, 100); + + test_non_empty(a, b); + } + + { + auto a = Rect::MakeMaximum(); + auto b = Rect::MakeMaximum(); + + test_non_empty(a, b); + } +} + +TEST(RectTest, IRectIntersectsWithRect) { + auto check_empty_flips = [](const IRect& a, const IRect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // b is allowed to be empty + + // unflipped a vs flipped (empty) b yields a + EXPECT_FALSE(a.IntersectsWithRect(flip_lr(b))) << label; + EXPECT_FALSE(a.IntersectsWithRect(flip_tb(b))) << label; + EXPECT_FALSE(a.IntersectsWithRect(flip_lrtb(b))) << label; + + // flipped (empty) a vs unflipped b yields b + EXPECT_FALSE(flip_lr(a).IntersectsWithRect(b)) << label; + EXPECT_FALSE(flip_tb(a).IntersectsWithRect(b)) << label; + EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(b)) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).IntersectsWithRect(flip_lr(b))) << label; + EXPECT_FALSE(flip_tb(a).IntersectsWithRect(flip_tb(b))) << label; + EXPECT_FALSE(flip_lrtb(a).IntersectsWithRect(flip_lrtb(b))) << label; + }; + + auto test_non_empty = [&check_empty_flips](const IRect& a, const IRect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.IntersectsWithRect(b)) << label; + EXPECT_TRUE(b.IntersectsWithRect(a)) << label; + check_empty_flips(a, b, label); + }; + + auto test_empty = [&check_empty_flips](const IRect& a, const IRect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // b is allowed to be empty + + std::stringstream stream; + stream << a << " union " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.IntersectsWithRect(b)) << label; + EXPECT_FALSE(b.IntersectsWithRect(a)) << label; + check_empty_flips(a, b, label); + }; + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 0, 0); + + test_empty(a, b); + } + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 0, 0); + + test_empty(a, b); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(10, 10, 100, 100); + + test_non_empty(a, b); + } + + { + auto a = IRect::MakeXYWH(0, 0, 100, 100); + auto b = IRect::MakeXYWH(100, 100, 100, 100); + + test_empty(a, b); + } + + { + auto a = IRect::MakeMaximum(); + auto b = IRect::MakeXYWH(10, 10, 100, 100); + + test_non_empty(a, b); + } + + { + auto a = IRect::MakeMaximum(); + auto b = IRect::MakeMaximum(); + + test_non_empty(a, b); + } +} + +TEST(RectTest, RectContainsPoint) { + auto check_nans = [](const Rect& rect, const Point& point, + const std::string& label) { + ASSERT_TRUE(rect.IsFinite()) << label; + ASSERT_TRUE(point.IsFinite()) << label; + + for (int i = 1; i < 16; i++) { + EXPECT_FALSE(swap_nan(rect, i).Contains(point)) + << label << ", index = " << i; + for (int j = 1; j < 4; j++) { + EXPECT_FALSE(swap_nan(rect, i).Contains(swap_nan(point, j))) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& rect, const Point& point, + const std::string& label) { + ASSERT_FALSE(rect.IsEmpty()); + + EXPECT_FALSE(flip_lr(rect).Contains(point)) << label; + EXPECT_FALSE(flip_tb(rect).Contains(point)) << label; + EXPECT_FALSE(flip_lrtb(rect).Contains(point)) << label; + }; + + auto test_inside = [&check_nans, &check_empty_flips](const Rect& rect, + const Point& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_TRUE(rect.Contains(point)) << label; + check_empty_flips(rect, point, label); + check_nans(rect, point, label); + }; + + auto test_outside = [&check_nans, &check_empty_flips](const Rect& rect, + const Point& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_FALSE(rect.Contains(point)) << label; + check_empty_flips(rect, point, label); + check_nans(rect, point, label); + }; + + { + // Origin is inclusive + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(100, 100); + + test_inside(r, p); + } + { + // Size is exclusive + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(200, 200); + + test_outside(r, p); + } + { + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(99, 99); + + test_outside(r, p); + } + { + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(199, 199); + + test_inside(r, p); + } + + { + auto r = Rect::MakeMaximum(); + auto p = Point(199, 199); + + test_inside(r, p); + } +} + +TEST(RectTest, IRectContainsIPoint) { + auto check_empty_flips = [](const IRect& rect, const IPoint& point, + const std::string& label) { + ASSERT_FALSE(rect.IsEmpty()); + + EXPECT_FALSE(flip_lr(rect).Contains(point)) << label; + EXPECT_FALSE(flip_tb(rect).Contains(point)) << label; + EXPECT_FALSE(flip_lrtb(rect).Contains(point)) << label; + }; + + auto test_inside = [&check_empty_flips](const IRect& rect, + const IPoint& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_TRUE(rect.Contains(point)) << label; + check_empty_flips(rect, point, label); + }; + + auto test_outside = [&check_empty_flips](const IRect& rect, + const IPoint& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_FALSE(rect.Contains(point)) << label; + check_empty_flips(rect, point, label); + }; + + { + // Origin is inclusive + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(100, 100); + + test_inside(r, p); + } + { + // Size is exclusive + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(200, 200); + + test_outside(r, p); + } + { + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(99, 99); + + test_outside(r, p); + } + { + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(199, 199); + + test_inside(r, p); + } + + { + auto r = IRect::MakeMaximum(); + auto p = IPoint(199, 199); + + test_inside(r, p); + } +} + +TEST(RectTest, RectContainsInclusivePoint) { + auto check_nans = [](const Rect& rect, const Point& point, + const std::string& label) { + ASSERT_TRUE(rect.IsFinite()) << label; + ASSERT_TRUE(point.IsFinite()) << label; + + for (int i = 1; i < 16; i++) { + EXPECT_FALSE(swap_nan(rect, i).ContainsInclusive(point)) + << label << ", index = " << i; + for (int j = 1; j < 4; j++) { + EXPECT_FALSE(swap_nan(rect, i).ContainsInclusive(swap_nan(point, j))) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& rect, const Point& point, + const std::string& label) { + ASSERT_FALSE(rect.IsEmpty()); + + EXPECT_FALSE(flip_lr(rect).ContainsInclusive(point)) << label; + EXPECT_FALSE(flip_tb(rect).ContainsInclusive(point)) << label; + EXPECT_FALSE(flip_lrtb(rect).ContainsInclusive(point)) << label; + }; + + auto test_inside = [&check_nans, &check_empty_flips](const Rect& rect, + const Point& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_TRUE(rect.ContainsInclusive(point)) << label; + check_empty_flips(rect, point, label); + check_nans(rect, point, label); + }; + + auto test_outside = [&check_nans, &check_empty_flips](const Rect& rect, + const Point& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_FALSE(rect.ContainsInclusive(point)) << label; + check_empty_flips(rect, point, label); + check_nans(rect, point, label); + }; + + { + // Origin is inclusive + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(100, 100); + + test_inside(r, p); + } + { + // Size is inclusive + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(200, 200); + + test_inside(r, p); + } + { + // Size + epsilon is exclusive + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(200 + kEhCloseEnough, 200 + kEhCloseEnough); + + test_outside(r, p); + } + { + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(99, 99); + + test_outside(r, p); + } + { + auto r = Rect::MakeXYWH(100, 100, 100, 100); + auto p = Point(199, 199); + + test_inside(r, p); + } + + { + auto r = Rect::MakeMaximum(); + auto p = Point(199, 199); + + test_inside(r, p); + } +} + +TEST(RectTest, IRectContainsInclusiveIPoint) { + auto check_empty_flips = [](const IRect& rect, const IPoint& point, + const std::string& label) { + ASSERT_FALSE(rect.IsEmpty()); + + EXPECT_FALSE(flip_lr(rect).ContainsInclusive(point)) << label; + EXPECT_FALSE(flip_tb(rect).ContainsInclusive(point)) << label; + EXPECT_FALSE(flip_lrtb(rect).ContainsInclusive(point)) << label; + }; + + auto test_inside = [&check_empty_flips](const IRect& rect, + const IPoint& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_TRUE(rect.ContainsInclusive(point)) << label; + check_empty_flips(rect, point, label); + }; + + auto test_outside = [&check_empty_flips](const IRect& rect, + const IPoint& point) { + ASSERT_FALSE(rect.IsEmpty()) << rect; + + std::stringstream stream; + stream << rect << " contains " << point; + auto label = stream.str(); + + EXPECT_FALSE(rect.ContainsInclusive(point)) << label; + check_empty_flips(rect, point, label); + }; + + { + // Origin is inclusive + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(100, 100); + + test_inside(r, p); + } + { + // Size is inclusive + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(200, 200); + + test_inside(r, p); + } + { + // Size + "epsilon" is exclusive + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(201, 201); + + test_outside(r, p); + } + { + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(99, 99); + + test_outside(r, p); + } + { + auto r = IRect::MakeXYWH(100, 100, 100, 100); + auto p = IPoint(199, 199); + + test_inside(r, p); + } + + { + auto r = IRect::MakeMaximum(); + auto p = IPoint(199, 199); + + test_inside(r, p); + } +} + +TEST(RectTest, RectContainsRect) { + auto check_nans = [](const Rect& a, const Rect& b, const std::string& label) { + ASSERT_TRUE(a.IsFinite()) << label; + ASSERT_TRUE(b.IsFinite()) << label; + ASSERT_FALSE(a.IsEmpty()); + + for (int i = 1; i < 16; i++) { + // NaN in a produces false + EXPECT_FALSE(swap_nan(a, i).Contains(b)) << label << ", index = " << i; + // NaN in b produces false + EXPECT_TRUE(a.Contains(swap_nan(b, i))) << label << ", index = " << i; + // NaN in both is false + for (int j = 1; j < 16; j++) { + EXPECT_FALSE(swap_nan(a, i).Contains(swap_nan(b, j))) + << label << ", indices = " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [](const Rect& a, const Rect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // test b rects are allowed to have 0 w/h, but not be backwards + ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); + + // unflipped a vs flipped (empty) b yields false + EXPECT_TRUE(a.Contains(flip_lr(b))) << label; + EXPECT_TRUE(a.Contains(flip_tb(b))) << label; + EXPECT_TRUE(a.Contains(flip_lrtb(b))) << label; + + // flipped (empty) a vs unflipped b yields false + EXPECT_FALSE(flip_lr(a).Contains(b)) << label; + EXPECT_FALSE(flip_tb(a).Contains(b)) << label; + EXPECT_FALSE(flip_lrtb(a).Contains(b)) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).Contains(flip_lr(b))) << label; + EXPECT_FALSE(flip_tb(a).Contains(flip_tb(b))) << label; + EXPECT_FALSE(flip_lrtb(a).Contains(flip_lrtb(b))) << label; + }; + + auto test_inside = [&check_nans, &check_empty_flips](const Rect& a, + const Rect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // test b rects are allowed to have 0 w/h, but not be backwards + ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); + + std::stringstream stream; + stream << a << " contains " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.Contains(b)) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + auto test_not_inside = [&check_nans, &check_empty_flips](const Rect& a, + const Rect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // If b was empty, it would be contained and should not be tested with + // this function - use |test_inside| instead. + ASSERT_FALSE(b.IsEmpty()) << b; + + std::stringstream stream; + stream << a << " contains " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.Contains(b)) << label; + check_empty_flips(a, b, label); + check_nans(a, b, label); + }; + + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + + test_inside(a, a); + } + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 0, 0); + + test_inside(a, b); + } + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(150, 150, 20, 20); + + test_inside(a, b); + } + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(150, 150, 100, 100); + + test_not_inside(a, b); + } + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(50, 50, 100, 100); + + test_not_inside(a, b); + } + { + auto a = Rect::MakeXYWH(100, 100, 100, 100); + auto b = Rect::MakeXYWH(0, 0, 300, 300); + + test_not_inside(a, b); + } + { + auto a = Rect::MakeMaximum(); + auto b = Rect::MakeXYWH(0, 0, 300, 300); + + test_inside(a, b); + } +} + +TEST(RectTest, IRectContainsIRect) { + auto check_empty_flips = [](const IRect& a, const IRect& b, + const std::string& label) { + ASSERT_FALSE(a.IsEmpty()); + // test b rects are allowed to have 0 w/h, but not be backwards + ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); + + // unflipped a vs flipped (empty) b yields true + EXPECT_TRUE(a.Contains(flip_lr(b))) << label; + EXPECT_TRUE(a.Contains(flip_tb(b))) << label; + EXPECT_TRUE(a.Contains(flip_lrtb(b))) << label; + + // flipped (empty) a vs unflipped b yields false + EXPECT_FALSE(flip_lr(a).Contains(b)) << label; + EXPECT_FALSE(flip_tb(a).Contains(b)) << label; + EXPECT_FALSE(flip_lrtb(a).Contains(b)) << label; + + // flipped (empty) a vs flipped (empty) b yields empty + EXPECT_FALSE(flip_lr(a).Contains(flip_lr(b))) << label; + EXPECT_FALSE(flip_tb(a).Contains(flip_tb(b))) << label; + EXPECT_FALSE(flip_lrtb(a).Contains(flip_lrtb(b))) << label; + }; + + auto test_inside = [&check_empty_flips](const IRect& a, const IRect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // test b rects are allowed to have 0 w/h, but not be backwards + ASSERT_FALSE(b.GetLeft() > b.GetRight() || b.GetTop() > b.GetBottom()); + + std::stringstream stream; + stream << a << " contains " << b; + auto label = stream.str(); + + EXPECT_TRUE(a.Contains(b)) << label; + check_empty_flips(a, b, label); + }; + + auto test_not_inside = [&check_empty_flips](const IRect& a, const IRect& b) { + ASSERT_FALSE(a.IsEmpty()) << a; + // If b was empty, it would be contained and should not be tested with + // this function - use |test_inside| instead. + ASSERT_FALSE(b.IsEmpty()) << b; + + std::stringstream stream; + stream << a << " contains " << b; + auto label = stream.str(); + + EXPECT_FALSE(a.Contains(b)) << label; + check_empty_flips(a, b, label); + }; + + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + + test_inside(a, a); + } + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 0, 0); + + test_inside(a, b); + } + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(150, 150, 20, 20); + + test_inside(a, b); + } + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(150, 150, 100, 100); + + test_not_inside(a, b); + } + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(50, 50, 100, 100); + + test_not_inside(a, b); + } + { + auto a = IRect::MakeXYWH(100, 100, 100, 100); + auto b = IRect::MakeXYWH(0, 0, 300, 300); + + test_not_inside(a, b); + } + { + auto a = IRect::MakeMaximum(); + auto b = IRect::MakeXYWH(0, 0, 300, 300); + + test_inside(a, b); + } +} + +TEST(RectTest, RectCutOut) { + Rect cull_rect = Rect::MakeLTRB(20, 20, 40, 40); + + auto check_nans = [&cull_rect](const Rect& diff_rect, + const std::string& label) { + EXPECT_TRUE(cull_rect.IsFinite()) << label; + EXPECT_TRUE(diff_rect.IsFinite()) << label; + + for (int i = 1; i < 16; i++) { + // NaN in cull_rect produces empty + EXPECT_FALSE(swap_nan(cull_rect, i).Cutout(diff_rect).has_value()) + << label << ", index " << i; + EXPECT_EQ(swap_nan(cull_rect, i).CutoutOrEmpty(diff_rect), Rect()) + << label << ", index " << i; + + // NaN in diff_rect is nop + EXPECT_TRUE(cull_rect.Cutout(swap_nan(diff_rect, i)).has_value()) + << label << ", index " << i; + EXPECT_EQ(cull_rect.CutoutOrEmpty(swap_nan(diff_rect, i)), cull_rect) + << label << ", index " << i; + + for (int j = 1; j < 16; j++) { + // NaN in both is also empty + EXPECT_FALSE( + swap_nan(cull_rect, i).Cutout(swap_nan(diff_rect, j)).has_value()) + << label << ", indices " << i << ", " << j; + EXPECT_EQ(swap_nan(cull_rect, i).CutoutOrEmpty(swap_nan(diff_rect, j)), + Rect()) + << label << ", indices " << i << ", " << j; + } + } + }; + + auto check_empty_flips = [&cull_rect](const Rect& diff_rect, + const std::string& label) { + EXPECT_FALSE(cull_rect.IsEmpty()) << label; + EXPECT_FALSE(diff_rect.IsEmpty()) << label; + + // unflipped cull_rect vs flipped(empty) diff_rect + // == cull_rect + EXPECT_TRUE(cull_rect.Cutout(flip_lr(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_lr(diff_rect)), cull_rect) << label; + EXPECT_TRUE(cull_rect.Cutout(flip_tb(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_tb(diff_rect)), cull_rect) << label; + EXPECT_TRUE(cull_rect.Cutout(flip_lrtb(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_lrtb(diff_rect)), cull_rect) << label; + + // flipped(empty) cull_rect vs unflipped diff_rect + // == empty + EXPECT_FALSE(flip_lr(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; + EXPECT_FALSE(flip_tb(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; + EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(diff_rect), Rect()) << label; + + // flipped(empty) cull_rect vs flipped(empty) diff_rect + // == empty + EXPECT_FALSE(flip_lr(cull_rect).Cutout(flip_lr(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(flip_lr(diff_rect)), Rect()) + << label; + EXPECT_FALSE(flip_tb(cull_rect).Cutout(flip_tb(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(flip_tb(diff_rect)), Rect()) + << label; + EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(flip_lrtb(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(flip_lrtb(diff_rect)), Rect()) + << label; + }; + + auto non_reducing = [&cull_rect, &check_empty_flips, &check_nans]( + const Rect& diff_rect, const std::string& label) { + EXPECT_EQ(cull_rect.Cutout(diff_rect), cull_rect) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), cull_rect) << label; + check_empty_flips(diff_rect, label); + check_nans(diff_rect, label); + }; + + auto reducing = [&cull_rect, &check_empty_flips, &check_nans]( + const Rect& diff_rect, const Rect& result_rect, + const std::string& label) { + EXPECT_TRUE(!result_rect.IsEmpty()); + EXPECT_EQ(cull_rect.Cutout(diff_rect), result_rect) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), result_rect) << label; + check_empty_flips(diff_rect, label); + check_nans(diff_rect, label); + }; + + auto emptying = [&cull_rect, &check_empty_flips, &check_nans]( + const Rect& diff_rect, const std::string& label) { + EXPECT_FALSE(cull_rect.Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), Rect()) << label; + check_empty_flips(diff_rect, label); + check_nans(diff_rect, label); + }; + + // Skim the corners and edge + non_reducing(Rect::MakeLTRB(10, 10, 20, 20), "outside UL corner"); + non_reducing(Rect::MakeLTRB(20, 10, 40, 20), "Above"); + non_reducing(Rect::MakeLTRB(40, 10, 50, 20), "outside UR corner"); + non_reducing(Rect::MakeLTRB(40, 20, 50, 40), "Right"); + non_reducing(Rect::MakeLTRB(40, 40, 50, 50), "outside LR corner"); + non_reducing(Rect::MakeLTRB(20, 40, 40, 50), "Below"); + non_reducing(Rect::MakeLTRB(10, 40, 20, 50), "outside LR corner"); + non_reducing(Rect::MakeLTRB(10, 20, 20, 40), "Left"); + + // Overlap corners + non_reducing(Rect::MakeLTRB(15, 15, 25, 25), "covering UL corner"); + non_reducing(Rect::MakeLTRB(35, 15, 45, 25), "covering UR corner"); + non_reducing(Rect::MakeLTRB(35, 35, 45, 45), "covering LR corner"); + non_reducing(Rect::MakeLTRB(15, 35, 25, 45), "covering LL corner"); + + // Overlap edges, but not across an entire side + non_reducing(Rect::MakeLTRB(20, 15, 39, 25), "Top edge left-biased"); + non_reducing(Rect::MakeLTRB(21, 15, 40, 25), "Top edge, right biased"); + non_reducing(Rect::MakeLTRB(35, 20, 45, 39), "Right edge, top-biased"); + non_reducing(Rect::MakeLTRB(35, 21, 45, 40), "Right edge, bottom-biased"); + non_reducing(Rect::MakeLTRB(20, 35, 39, 45), "Bottom edge, left-biased"); + non_reducing(Rect::MakeLTRB(21, 35, 40, 45), "Bottom edge, right-biased"); + non_reducing(Rect::MakeLTRB(15, 20, 25, 39), "Left edge, top-biased"); + non_reducing(Rect::MakeLTRB(15, 21, 25, 40), "Left edge, bottom-biased"); + + // Slice all the way through the middle + non_reducing(Rect::MakeLTRB(25, 15, 35, 45), "Vertical interior slice"); + non_reducing(Rect::MakeLTRB(15, 25, 45, 35), "Horizontal interior slice"); + + // Slice off each edge + reducing(Rect::MakeLTRB(20, 15, 40, 25), // + Rect::MakeLTRB(20, 25, 40, 40), // + "Slice off top"); + reducing(Rect::MakeLTRB(35, 20, 45, 40), // + Rect::MakeLTRB(20, 20, 35, 40), // + "Slice off right"); + reducing(Rect::MakeLTRB(20, 35, 40, 45), // + Rect::MakeLTRB(20, 20, 40, 35), // + "Slice off bottom"); + reducing(Rect::MakeLTRB(15, 20, 25, 40), // + Rect::MakeLTRB(25, 20, 40, 40), // + "Slice off left"); + + // cull rect contains diff rect + non_reducing(Rect::MakeLTRB(21, 21, 39, 39), "Contained, non-covering"); + + // cull rect equals diff rect + emptying(cull_rect, "Perfectly covering"); + + // diff rect contains cull rect + emptying(Rect::MakeLTRB(15, 15, 45, 45), "Smothering"); +} + +TEST(RectTest, IRectCutOut) { + IRect cull_rect = IRect::MakeLTRB(20, 20, 40, 40); + + auto check_empty_flips = [&cull_rect](const IRect& diff_rect, + const std::string& label) { + EXPECT_FALSE(diff_rect.IsEmpty()); + EXPECT_FALSE(cull_rect.IsEmpty()); + + // unflipped cull_rect vs flipped(empty) diff_rect + // == cull_rect + EXPECT_TRUE(cull_rect.Cutout(flip_lr(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_lr(diff_rect)), cull_rect) << label; + EXPECT_TRUE(cull_rect.Cutout(flip_tb(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_tb(diff_rect)), cull_rect) << label; + EXPECT_TRUE(cull_rect.Cutout(flip_lrtb(diff_rect)).has_value()) << label; + EXPECT_EQ(cull_rect.Cutout(flip_lrtb(diff_rect)), cull_rect) << label; + + // flipped(empty) cull_rect vs flipped(empty) diff_rect + // == empty + EXPECT_FALSE(flip_lr(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; + EXPECT_FALSE(flip_tb(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; + EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(diff_rect), IRect()) << label; + + // flipped(empty) cull_rect vs unflipped diff_rect + // == empty + EXPECT_FALSE(flip_lr(cull_rect).Cutout(flip_lr(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_lr(cull_rect).CutoutOrEmpty(flip_lr(diff_rect)), IRect()) + << label; + EXPECT_FALSE(flip_tb(cull_rect).Cutout(flip_tb(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_tb(cull_rect).CutoutOrEmpty(flip_tb(diff_rect)), IRect()) + << label; + EXPECT_FALSE(flip_lrtb(cull_rect).Cutout(flip_lrtb(diff_rect)).has_value()) + << label; + EXPECT_EQ(flip_lrtb(cull_rect).CutoutOrEmpty(flip_lrtb(diff_rect)), IRect()) + << label; + }; + + auto non_reducing = [&cull_rect, &check_empty_flips]( + const IRect& diff_rect, const std::string& label) { + EXPECT_EQ(cull_rect.Cutout(diff_rect), cull_rect) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), cull_rect) << label; + check_empty_flips(diff_rect, label); + }; + + auto reducing = [&cull_rect, &check_empty_flips](const IRect& diff_rect, + const IRect& result_rect, + const std::string& label) { + EXPECT_TRUE(!result_rect.IsEmpty()); + EXPECT_EQ(cull_rect.Cutout(diff_rect), result_rect) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), result_rect) << label; + check_empty_flips(diff_rect, label); + }; + + auto emptying = [&cull_rect, &check_empty_flips](const IRect& diff_rect, + const std::string& label) { + EXPECT_FALSE(cull_rect.Cutout(diff_rect).has_value()) << label; + EXPECT_EQ(cull_rect.CutoutOrEmpty(diff_rect), IRect()) << label; + check_empty_flips(diff_rect, label); + }; + + // Skim the corners and edge + non_reducing(IRect::MakeLTRB(10, 10, 20, 20), "outside UL corner"); + non_reducing(IRect::MakeLTRB(20, 10, 40, 20), "Above"); + non_reducing(IRect::MakeLTRB(40, 10, 50, 20), "outside UR corner"); + non_reducing(IRect::MakeLTRB(40, 20, 50, 40), "Right"); + non_reducing(IRect::MakeLTRB(40, 40, 50, 50), "outside LR corner"); + non_reducing(IRect::MakeLTRB(20, 40, 40, 50), "Below"); + non_reducing(IRect::MakeLTRB(10, 40, 20, 50), "outside LR corner"); + non_reducing(IRect::MakeLTRB(10, 20, 20, 40), "Left"); + + // Overlap corners + non_reducing(IRect::MakeLTRB(15, 15, 25, 25), "covering UL corner"); + non_reducing(IRect::MakeLTRB(35, 15, 45, 25), "covering UR corner"); + non_reducing(IRect::MakeLTRB(35, 35, 45, 45), "covering LR corner"); + non_reducing(IRect::MakeLTRB(15, 35, 25, 45), "covering LL corner"); + + // Overlap edges, but not across an entire side + non_reducing(IRect::MakeLTRB(20, 15, 39, 25), "Top edge left-biased"); + non_reducing(IRect::MakeLTRB(21, 15, 40, 25), "Top edge, right biased"); + non_reducing(IRect::MakeLTRB(35, 20, 45, 39), "Right edge, top-biased"); + non_reducing(IRect::MakeLTRB(35, 21, 45, 40), "Right edge, bottom-biased"); + non_reducing(IRect::MakeLTRB(20, 35, 39, 45), "Bottom edge, left-biased"); + non_reducing(IRect::MakeLTRB(21, 35, 40, 45), "Bottom edge, right-biased"); + non_reducing(IRect::MakeLTRB(15, 20, 25, 39), "Left edge, top-biased"); + non_reducing(IRect::MakeLTRB(15, 21, 25, 40), "Left edge, bottom-biased"); + + // Slice all the way through the middle + non_reducing(IRect::MakeLTRB(25, 15, 35, 45), "Vertical interior slice"); + non_reducing(IRect::MakeLTRB(15, 25, 45, 35), "Horizontal interior slice"); + + // Slice off each edge + reducing(IRect::MakeLTRB(20, 15, 40, 25), // + IRect::MakeLTRB(20, 25, 40, 40), // + "Slice off top"); + reducing(IRect::MakeLTRB(35, 20, 45, 40), // + IRect::MakeLTRB(20, 20, 35, 40), // + "Slice off right"); + reducing(IRect::MakeLTRB(20, 35, 40, 45), // + IRect::MakeLTRB(20, 20, 40, 35), // + "Slice off bottom"); + reducing(IRect::MakeLTRB(15, 20, 25, 40), // + IRect::MakeLTRB(25, 20, 40, 40), // + "Slice off left"); + + // cull rect contains diff rect + non_reducing(IRect::MakeLTRB(21, 21, 39, 39), "Contained, non-covering"); + + // cull rect equals diff rect + emptying(cull_rect, "Perfectly covering"); + + // diff rect contains cull rect + emptying(IRect::MakeLTRB(15, 15, 45, 45), "Smothering"); +} + +TEST(RectTest, RectGetPoints) { + { + Rect r = Rect::MakeXYWH(100, 200, 300, 400); + auto points = r.GetPoints(); + EXPECT_POINT_NEAR(points[0], Point(100, 200)); + EXPECT_POINT_NEAR(points[1], Point(400, 200)); + EXPECT_POINT_NEAR(points[2], Point(100, 600)); + EXPECT_POINT_NEAR(points[3], Point(400, 600)); + } + + { + Rect r = Rect::MakeMaximum(); + auto points = r.GetPoints(); + EXPECT_EQ(points[0], Point(std::numeric_limits::lowest(), + std::numeric_limits::lowest())); + EXPECT_EQ(points[1], Point(std::numeric_limits::max(), + std::numeric_limits::lowest())); + EXPECT_EQ(points[2], Point(std::numeric_limits::lowest(), + std::numeric_limits::max())); + EXPECT_EQ(points[3], Point(std::numeric_limits::max(), + std::numeric_limits::max())); + } +} + +TEST(RectTest, RectShift) { + auto r = Rect::MakeLTRB(0, 0, 100, 100); + + EXPECT_EQ(r.Shift(Point(10, 5)), Rect::MakeLTRB(10, 5, 110, 105)); + EXPECT_EQ(r.Shift(Point(-10, -5)), Rect::MakeLTRB(-10, -5, 90, 95)); +} + +TEST(RectTest, RectGetTransformedPoints) { + Rect r = Rect::MakeXYWH(100, 200, 300, 400); + auto points = r.GetTransformedPoints(Matrix::MakeTranslation({10, 20})); + EXPECT_POINT_NEAR(points[0], Point(110, 220)); + EXPECT_POINT_NEAR(points[1], Point(410, 220)); + EXPECT_POINT_NEAR(points[2], Point(110, 620)); + EXPECT_POINT_NEAR(points[3], Point(410, 620)); +} + +TEST(RectTest, RectMakePointBounds) { + { + std::vector points{{1, 5}, {4, -1}, {0, 6}}; + auto r = Rect::MakePointBounds(points.begin(), points.end()); + auto expected = Rect::MakeXYWH(0, -1, 4, 7); + EXPECT_TRUE(r.has_value()); + if (r.has_value()) { + EXPECT_RECT_NEAR(r.value(), expected); + } + } + { + std::vector points; + std::optional r = Rect::MakePointBounds(points.begin(), points.end()); + EXPECT_FALSE(r.has_value()); + } +} + +TEST(RectTest, RectGetPositive) { + { + Rect r = Rect::MakeXYWH(100, 200, 300, 400); + auto actual = r.GetPositive(); + EXPECT_RECT_NEAR(r, actual); + } + { + Rect r = Rect::MakeXYWH(100, 200, -100, -100); + auto actual = r.GetPositive(); + Rect expected = Rect::MakeXYWH(0, 100, 100, 100); + EXPECT_RECT_NEAR(expected, actual); + } +} + +TEST(RectTest, RectDirections) { + auto r = Rect::MakeLTRB(1, 2, 3, 4); + + EXPECT_EQ(r.GetLeft(), 1); + EXPECT_EQ(r.GetTop(), 2); + EXPECT_EQ(r.GetRight(), 3); + EXPECT_EQ(r.GetBottom(), 4); + + EXPECT_POINT_NEAR(r.GetLeftTop(), Point(1, 2)); + EXPECT_POINT_NEAR(r.GetRightTop(), Point(3, 2)); + EXPECT_POINT_NEAR(r.GetLeftBottom(), Point(1, 4)); + EXPECT_POINT_NEAR(r.GetRightBottom(), Point(3, 4)); +} + +TEST(RectTest, RectProject) { + { + auto r = Rect::MakeLTRB(-100, -100, 100, 100); + auto actual = r.Project(r); + auto expected = Rect::MakeLTRB(0, 0, 1, 1); + EXPECT_RECT_NEAR(expected, actual); + } + { + auto r = Rect::MakeLTRB(-100, -100, 100, 100); + auto actual = r.Project(Rect::MakeLTRB(0, 0, 100, 100)); + auto expected = Rect::MakeLTRB(0.5, 0.5, 1, 1); + EXPECT_RECT_NEAR(expected, actual); + } +} + +TEST(RectTest, RectRoundOut) { + { + auto r = Rect::MakeLTRB(-100, -200, 300, 400); + EXPECT_EQ(Rect::RoundOut(r), r); + } + { + auto r = Rect::MakeLTRB(-100.1, -200.1, 300.1, 400.1); + EXPECT_EQ(Rect::RoundOut(r), Rect::MakeLTRB(-101, -201, 301, 401)); + } +} + +TEST(RectTest, IRectRoundOut) { + { + auto r = Rect::MakeLTRB(-100, -200, 300, 400); + auto ir = IRect::MakeLTRB(-100, -200, 300, 400); + EXPECT_EQ(IRect::RoundOut(r), ir); + } + { + auto r = Rect::MakeLTRB(-100.1, -200.1, 300.1, 400.1); + auto ir = IRect::MakeLTRB(-101, -201, 301, 401); + EXPECT_EQ(IRect::RoundOut(r), ir); + } +} + +TEST(RectTest, RectRound) { + { + auto r = Rect::MakeLTRB(-100, -200, 300, 400); + EXPECT_EQ(Rect::Round(r), r); + } + { + auto r = Rect::MakeLTRB(-100.4, -200.4, 300.4, 400.4); + EXPECT_EQ(Rect::Round(r), Rect::MakeLTRB(-100, -200, 300, 400)); + } + { + auto r = Rect::MakeLTRB(-100.5, -200.5, 300.5, 400.5); + EXPECT_EQ(Rect::Round(r), Rect::MakeLTRB(-101, -201, 301, 401)); + } +} + +TEST(RectTest, IRectRound) { + { + auto r = Rect::MakeLTRB(-100, -200, 300, 400); + auto ir = IRect::MakeLTRB(-100, -200, 300, 400); + EXPECT_EQ(IRect::Round(r), ir); + } + { + auto r = Rect::MakeLTRB(-100.4, -200.4, 300.4, 400.4); + auto ir = IRect::MakeLTRB(-100, -200, 300, 400); + EXPECT_EQ(IRect::Round(r), ir); + } + { + auto r = Rect::MakeLTRB(-100.5, -200.5, 300.5, 400.5); + auto ir = IRect::MakeLTRB(-101, -201, 301, 401); + EXPECT_EQ(IRect::Round(r), ir); + } +} + +TEST(RectTest, TransformAndClipBounds) { + { + // This matrix should clip no corners. + auto matrix = impeller::Matrix::MakeColumn( + // clang-format off + 2.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 4.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 8.0f + // clang-format on + ); + Rect src = Rect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + // None of these should have a W<0 + EXPECT_EQ(matrix.TransformHomogenous(src.GetLeftTop()), + Vector3(200.0f, 400.0f, 8.0f)); + EXPECT_EQ(matrix.TransformHomogenous(src.GetRightTop()), + Vector3(400.0f, 400.0f, 8.0f)); + EXPECT_EQ(matrix.TransformHomogenous(src.GetLeftBottom()), + Vector3(200.0f, 800.0f, 8.0f)); + EXPECT_EQ(matrix.TransformHomogenous(src.GetRightBottom()), + Vector3(400.0f, 800.0f, 8.0f)); + + Rect expect = Rect::MakeLTRB(25.0f, 50.0f, 50.0f, 100.0f); + EXPECT_FALSE(src.TransformAndClipBounds(matrix).IsEmpty()); + EXPECT_EQ(src.TransformAndClipBounds(matrix), expect); + } + + { + // This matrix should clip one corner. + auto matrix = impeller::Matrix::MakeColumn( + // clang-format off + 2.0f, 0.0f, 0.0f, -0.01f, + 0.0f, 2.0f, 0.0f, -0.006f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 3.0f + // clang-format on + ); + Rect src = Rect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + // Exactly one of these should have a W<0 + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftTop()), + Vector3(200.0f, 200.0f, 1.4f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightTop()), + Vector3(400.0f, 200.0f, 0.4f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftBottom()), + Vector3(200.0f, 400.0f, 0.8f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightBottom()), + Vector3(400.0f, 400.0f, -0.2f)); + + Rect expect = Rect::MakeLTRB(142.85715f, 142.85715f, 6553600.f, 6553600.f); + EXPECT_FALSE(src.TransformAndClipBounds(matrix).IsEmpty()); + EXPECT_RECT_NEAR(src.TransformAndClipBounds(matrix), expect); + } + + { + // This matrix should clip two corners. + auto matrix = impeller::Matrix::MakeColumn( + // clang-format off + 2.0f, 0.0f, 0.0f, -.015f, + 0.0f, 2.0f, 0.0f, -.006f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 3.0f + // clang-format on + ); + Rect src = Rect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + // Exactly two of these should have a W<0 + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftTop()), + Vector3(200.0f, 200.0f, 0.9f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightTop()), + Vector3(400.0f, 200.0f, -0.6f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftBottom()), + Vector3(200.0f, 400.0f, 0.3f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightBottom()), + Vector3(400.0f, 400.0f, -1.2f)); + + Rect expect = Rect::MakeLTRB(222.2222f, 222.2222f, 5898373.f, 6553600.f); + EXPECT_FALSE(src.TransformAndClipBounds(matrix).IsEmpty()); + EXPECT_RECT_NEAR(src.TransformAndClipBounds(matrix), expect); + } + + { + // This matrix should clip three corners. + auto matrix = impeller::Matrix::MakeColumn( + // clang-format off + 2.0f, 0.0f, 0.0f, -.02f, + 0.0f, 2.0f, 0.0f, -.006f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 3.0f + // clang-format on + ); + Rect src = Rect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + // Exactly three of these should have a W<0 + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftTop()), + Vector3(200.0f, 200.0f, 0.4f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightTop()), + Vector3(400.0f, 200.0f, -1.6f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftBottom()), + Vector3(200.0f, 400.0f, -0.2f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightBottom()), + Vector3(400.0f, 400.0f, -2.2f)); + + Rect expect = Rect::MakeLTRB(499.99988f, 499.99988f, 5898340.f, 4369400.f); + EXPECT_FALSE(src.TransformAndClipBounds(matrix).IsEmpty()); + EXPECT_RECT_NEAR(src.TransformAndClipBounds(matrix), expect); + } + + { + // This matrix should clip all four corners. + auto matrix = impeller::Matrix::MakeColumn( + // clang-format off + 2.0f, 0.0f, 0.0f, -.025f, + 0.0f, 2.0f, 0.0f, -.006f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 3.0f + // clang-format on + ); + Rect src = Rect::MakeLTRB(100.0f, 100.0f, 200.0f, 200.0f); + // All of these should have a W<0 + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftTop()), + Vector3(200.0f, 200.0f, -0.1f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightTop()), + Vector3(400.0f, 200.0f, -2.6f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetLeftBottom()), + Vector3(200.0f, 400.0f, -0.7f)); + EXPECT_VECTOR3_NEAR(matrix.TransformHomogenous(src.GetRightBottom()), + Vector3(400.0f, 400.0f, -3.2f)); + + EXPECT_TRUE(src.TransformAndClipBounds(matrix).IsEmpty()); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/round_rect.cc b/flutter/engine/src/flutter/impeller/geometry/round_rect.cc new file mode 100644 index 0000000000000000000000000000000000000000..23d1dd6b763c870f482f534228e9e4b3486cb021 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_rect.cc @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/round_rect.h" + +namespace impeller { + +RoundRect RoundRect::MakeRectRadii(const Rect& in_bounds, + const RoundingRadii& in_radii) { + if (!in_bounds.IsFinite()) { + return {}; + } + Rect bounds = in_bounds.GetPositive(); + // RoundingRadii::Scaled might return an empty radii if bounds or in_radii is + // empty, which is expected. Pass along the bounds even if the radii is empty + // as it would still have a valid location and/or 1-dimensional size which + // might appear when stroked + return RoundRect(bounds, in_radii.Scaled(bounds)); +} + +// Determine if p is inside the elliptical corner curve defined by the +// indicated corner point and the indicated radii. +// p - is the test point in absolute coordinates +// corner - is the location of the associated corner in absolute coordinates +// direction - is the sign of (corner - center), or the sign of coordinates +// as they move in the direction of the corner from inside the +// rect ((-1,-1) for the upper left corner for instance) +// radii - the non-negative X and Y size of the corner's radii. +static bool CornerContains(const Point& p, + const Point& corner, + const Point& direction, + const Size& radii) { + FML_DCHECK(radii.width >= 0.0f && radii.height >= 0.0f); + if (radii.IsEmpty()) { + // This corner is not curved, therefore the containment is the same as + // the previously checked bounds containment. + return true; + } + + // The positive X,Y distance between the corner and the point. + Point corner_relative = (corner - p) * direction; + + // The distance from the "center" of the corner's elliptical curve. + // If both numbers are positive then we need to do an elliptical distance + // check to determine if it is inside the curve. + // If either number is negative, then the point is outside this quadrant + // and is governed by inclusion in the bounds and inclusion within other + // corners of this round rect. In that case, we return true here to allow + // further evaluation within other quadrants. + Point quadrant_relative = radii - corner_relative; + if (quadrant_relative.x <= 0.0f || quadrant_relative.y <= 0.0f) { + // Not within the curved quadrant of this corner, therefore "inside" + // relative to this one corner. + return true; + } + + // Dividing the quadrant_relative point by the radii gives a corresponding + // location within a unit circle which can be more easily tested for + // containment. We can use x^2 + y^2 and compare it against the radius + // squared (1.0) to avoid the sqrt. + Point quadrant_unit_circle_point = quadrant_relative / radii; + return quadrant_unit_circle_point.GetLengthSquared() <= 1.0; +} + +// The sign of the direction that points move as they approach the indicated +// corner from within the rectangle. +static constexpr Point kUpperLeftDirection(-1.0f, -1.0f); +static constexpr Point kUpperRightDirection(1.0f, -1.0f); +static constexpr Point kLowerLeftDirection(-1.0f, 1.0f); +static constexpr Point kLowerRightDirection(1.0f, 1.0f); + +[[nodiscard]] bool RoundRect::Contains(const Point& p) const { + if (!bounds_.Contains(p)) { + return false; + } + if (!CornerContains(p, bounds_.GetLeftTop(), kUpperLeftDirection, + radii_.top_left) || + !CornerContains(p, bounds_.GetRightTop(), kUpperRightDirection, + radii_.top_right) || + !CornerContains(p, bounds_.GetLeftBottom(), kLowerLeftDirection, + radii_.bottom_left) || + !CornerContains(p, bounds_.GetRightBottom(), kLowerRightDirection, + radii_.bottom_right)) { + return false; + } + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/round_rect.h b/flutter/engine/src/flutter/impeller/geometry/round_rect.h new file mode 100644 index 0000000000000000000000000000000000000000..d20c6cb0a9c39945d1f95d58fe7b95d3084bb54f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_rect.h @@ -0,0 +1,156 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_ROUND_RECT_H_ +#define FLUTTER_IMPELLER_GEOMETRY_ROUND_RECT_H_ + +#include "flutter/impeller/geometry/point.h" +#include "flutter/impeller/geometry/rect.h" +#include "flutter/impeller/geometry/rounding_radii.h" +#include "flutter/impeller/geometry/size.h" + +namespace impeller { + +struct RoundRect { + RoundRect() = default; + + constexpr static RoundRect MakeRect(const Rect& rect) { + return MakeRectRadii(rect, RoundingRadii()); + } + + constexpr static RoundRect MakeOval(const Rect& rect) { + return MakeRectRadii(rect, RoundingRadii::MakeRadii(rect.GetSize() * 0.5f)); + } + + constexpr static RoundRect MakeRectRadius(const Rect& rect, Scalar radius) { + return MakeRectRadii(rect, RoundingRadii::MakeRadius(radius)); + } + + constexpr static RoundRect MakeRectXY(const Rect& rect, + Scalar x_radius, + Scalar y_radius) { + return MakeRectRadii(rect, + RoundingRadii::MakeRadii(Size(x_radius, y_radius))); + } + + constexpr static RoundRect MakeRectXY(const Rect& rect, Size corner_radii) { + return MakeRectRadii(rect, RoundingRadii::MakeRadii(corner_radii)); + } + + constexpr static RoundRect MakeNinePatch(const Rect& rect, + Scalar left, + Scalar top, + Scalar right, + Scalar bottom) { + return MakeRectRadii( + rect, RoundingRadii::MakeNinePatch(left, top, right, bottom)); + } + + static RoundRect MakeRectRadii(const Rect& rect, const RoundingRadii& radii); + + constexpr const Rect& GetBounds() const { return bounds_; } + constexpr const RoundingRadii& GetRadii() const { return radii_; } + + [[nodiscard]] constexpr bool IsFinite() const { + return bounds_.IsFinite() && // + radii_.top_left.IsFinite() && // + radii_.top_right.IsFinite() && // + radii_.bottom_left.IsFinite() && // + radii_.bottom_right.IsFinite(); + } + + [[nodiscard]] constexpr bool IsEmpty() const { return bounds_.IsEmpty(); } + + [[nodiscard]] constexpr bool IsRect() const { + return !bounds_.IsEmpty() && radii_.AreAllCornersEmpty(); + } + + [[nodiscard]] constexpr bool IsOval() const { + return !bounds_.IsEmpty() && radii_.AreAllCornersSame() && + ScalarNearlyEqual(radii_.top_left.width, + bounds_.GetWidth() * 0.5f) && + ScalarNearlyEqual(radii_.top_left.height, + bounds_.GetHeight() * 0.5f); + } + + /// @brief Returns true iff the provided point |p| is inside the + /// half-open interior of this rectangle. + /// + /// For purposes of containment, a rectangle contains points + /// along the top and left edges but not points along the + /// right and bottom edges so that a point is only ever + /// considered inside one of two abutting rectangles. + [[nodiscard]] bool Contains(const Point& p) const; + + /// @brief Returns a new round rectangle translated by the given offset. + [[nodiscard]] constexpr RoundRect Shift(Scalar dx, Scalar dy) const { + // Just in case, use the factory rather than the internal constructor + // as shifting the rectangle may increase/decrease its bit precision + // so we should re-validate the radii to the newly located rectangle. + return MakeRectRadii(bounds_.Shift(dx, dy), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundRect Expand(Scalar left, + Scalar top, + Scalar right, + Scalar bottom) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(left, top, right, bottom), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundRect Expand(Scalar horizontal, + Scalar vertical) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(horizontal, vertical), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundRect Expand(Scalar amount) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(amount), radii_); + } + + [[nodiscard]] constexpr bool operator==(const RoundRect& rr) const { + return bounds_ == rr.bounds_ && radii_ == rr.radii_; + } + + [[nodiscard]] constexpr bool operator!=(const RoundRect& r) const { + return !(*this == r); + } + + private: + constexpr RoundRect(const Rect& bounds, const RoundingRadii& radii) + : bounds_(bounds), radii_(radii) {} + + Rect bounds_; + RoundingRadii radii_; +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::RoundRect& rr) { + out << "(" // + << "rect: " << rr.GetBounds() << ", " // + << "radii: " << rr.GetRadii() // + << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_ROUND_RECT_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/round_rect_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/round_rect_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b9e3d1212723c989c1ae71fc24a60ef5ee10fb8d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_rect_unittests.cc @@ -0,0 +1,696 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/round_rect.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +TEST(RoundRectTest, EmptyDeclaration) { + RoundRect round_rect; + + EXPECT_TRUE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_TRUE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect()); + EXPECT_EQ(round_rect.GetBounds().GetLeft(), 0.0f); + EXPECT_EQ(round_rect.GetBounds().GetTop(), 0.0f); + EXPECT_EQ(round_rect.GetBounds().GetRight(), 0.0f); + EXPECT_EQ(round_rect.GetBounds().GetBottom(), 0.0f); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); + EXPECT_EQ(round_rect.GetRadii().top_left.width, 0.0f); + EXPECT_EQ(round_rect.GetRadii().top_left.height, 0.0f); + EXPECT_EQ(round_rect.GetRadii().top_right.width, 0.0f); + EXPECT_EQ(round_rect.GetRadii().top_right.height, 0.0f); + EXPECT_EQ(round_rect.GetRadii().bottom_left.width, 0.0f); + EXPECT_EQ(round_rect.GetRadii().bottom_left.height, 0.0f); + EXPECT_EQ(round_rect.GetRadii().bottom_right.width, 0.0f); + EXPECT_EQ(round_rect.GetRadii().bottom_right.height, 0.0f); +} + +TEST(RoundRectTest, DefaultConstructor) { + RoundRect round_rect = RoundRect(); + + EXPECT_TRUE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_TRUE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect()); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); +} + +TEST(RoundRectTest, EmptyRectConstruction) { + RoundRect round_rect = + RoundRect::MakeRect(Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + + EXPECT_TRUE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_TRUE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); +} + +TEST(RoundRectTest, RectConstructor) { + RoundRect round_rect = + RoundRect::MakeRect(Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_TRUE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); +} + +TEST(RoundRectTest, InvertedRectConstruction) { + RoundRect round_rect = + RoundRect::MakeRect(Rect::MakeLTRB(20.0f, 20.0f, 10.0f, 10.0f)); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_TRUE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); +} + +TEST(RoundRectTest, EmptyOvalConstruction) { + RoundRect round_rect = RoundRect::MakeRectXY( + Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f), 10.0f, 10.0f); + + EXPECT_TRUE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_TRUE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size()); + EXPECT_EQ(round_rect.GetRadii().top_right, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size()); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size()); +} + +TEST(RoundRectTest, OvalConstructor) { + RoundRect round_rect = + RoundRect::MakeOval(Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_TRUE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(5.0f, 5.0f)); +} + +TEST(RoundRectTest, InvertedOvalConstruction) { + RoundRect round_rect = RoundRect::MakeRectXY( + Rect::MakeLTRB(20.0f, 20.0f, 10.0f, 10.0f), 10.0f, 10.0f); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_TRUE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(5.0f, 5.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(5.0f, 5.0f)); +} + +TEST(RoundRectTest, RectRadiusConstructor) { + RoundRect round_rect = RoundRect::MakeRectRadius( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), 2.0f); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(2.0f, 2.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(2.0f, 2.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(2.0f, 2.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(2.0f, 2.0f)); +} + +TEST(RoundRectTest, RectXYConstructor) { + RoundRect round_rect = RoundRect::MakeRectXY( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), 2.0f, 3.0f); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(2.0f, 3.0f)); +} + +TEST(RoundRectTest, RectSizeConstructor) { + RoundRect round_rect = RoundRect::MakeRectXY( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), Size(2.0f, 3.0f)); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(2.0f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(2.0f, 3.0f)); +} + +TEST(RoundRectTest, RectRadiiConstructor) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), + { + .top_left = Size(1.0, 1.5), + .top_right = Size(2.0, 2.5f), + .bottom_left = Size(3.0, 3.5f), + .bottom_right = Size(4.0, 4.5f), + }); + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(1.0f, 1.5f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(2.0f, 2.5f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(3.0f, 3.5f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(4.0f, 4.5f)); +} + +TEST(RoundRectTest, RectRadiiOverflowWidthConstructor) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 6.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + // Largest sum of paired radii widths is the bottom edge which sums to 12 + // Rect is only 6 wide so all radii are scaled by half + // Rect is 30 tall so no scaling should happen due to radii heights + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 16.0f, 40.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(3.5f, 4.0f)); +} + +TEST(RoundRectTest, RectRadiiOverflowHeightConstructor) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 6.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + // Largest sum of paired radii heights is the right edge which sums to 12 + // Rect is only 6 tall so all radii are scaled by half + // Rect is 30 wide so no scaling should happen due to radii widths + + EXPECT_FALSE(round_rect.IsEmpty()); + EXPECT_FALSE(round_rect.IsRect()); + EXPECT_FALSE(round_rect.IsOval()); + EXPECT_TRUE(round_rect.IsFinite()); + EXPECT_FALSE(round_rect.GetBounds().IsEmpty()); + EXPECT_EQ(round_rect.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 40.0f, 16.0f)); + EXPECT_EQ(round_rect.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(round_rect.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(round_rect.GetRadii().bottom_right, Size(3.5f, 4.0f)); +} + +TEST(RoundRectTest, Shift) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect shifted = round_rect.Shift(5.0, 6.0); + + EXPECT_FALSE(shifted.IsEmpty()); + EXPECT_FALSE(shifted.IsRect()); + EXPECT_FALSE(shifted.IsOval()); + EXPECT_TRUE(shifted.IsFinite()); + EXPECT_FALSE(shifted.GetBounds().IsEmpty()); + EXPECT_EQ(shifted.GetBounds(), Rect::MakeLTRB(15.0f, 16.0f, 45.0f, 46.0f)); + EXPECT_EQ(shifted.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(shifted.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(shifted.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(shifted.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(shifted, + RoundRect::MakeRectRadii(Rect::MakeXYWH(15.0f, 16.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ExpandScalar) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(5.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 5.0f, 45.0f, 45.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(5.0f, 5.0f, 40.0f, 40.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ExpandTwoScalars) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(5.0, 6.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 4.0f, 45.0f, 46.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(5.0f, 4.0f, 40.0f, 42.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ExpandFourScalars) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(5.0, 6.0, 7.0, 8.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 4.0f, 47.0f, 48.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(5.0f, 4.0f, 42.0f, 44.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ContractScalar) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(-2.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(12.0f, 12.0f, 38.0f, 38.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(12.0f, 12.0f, 26.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ContractTwoScalars) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(-1.0, -2.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(11.0f, 12.0f, 39.0f, 38.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(11.0f, 12.0f, 28.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ContractFourScalars) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(-1.0, -1.5, -2.0, -2.5); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(11.0f, 11.5f, 38.0f, 37.5f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(11.0f, 11.5f, 27.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundRectTest, ContractAndRequireRadiiAdjustment) { + RoundRect round_rect = + RoundRect::MakeRectRadii(Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundRect expanded = round_rect.Expand(-12.0); + // Largest sum of paired radii sizes are the bottom and right edges + // both of which sum to 12 + // Rect was 30x30 reduced by 12 on all sides leaving only 6x6, so all + // radii are scaled by half to avoid overflowing the contracted rect + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(22.0f, 22.0f, 28.0f, 28.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(3.5f, 4.0f)); + + // In this test, the MakeRectRadii constructor will make the same + // adjustment to the radii that the Expand method applied. + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(22.0f, 22.0f, 6.0f, 6.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); + + // In this test, the arguments to the constructor supply the correctly + // adjusted radii (though there is no real way to tell other than + // the result is the same). + EXPECT_EQ(expanded, + RoundRect::MakeRectRadii(Rect::MakeXYWH(22.0f, 22.0f, 6.0f, 6.0f), + { + .top_left = Size(0.5f, 1.0f), + .top_right = Size(1.5f, 2.0f), + .bottom_left = Size(2.5f, 3.0f), + .bottom_right = Size(3.5f, 4.0f), + })); +} + +TEST(RoundRectTest, NoCornerRoundRectContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + // RRect of bounds with no corners contains corners just barely + auto no_corners = RoundRect::MakeRectXY(bounds, 0.0f, 0.0f); + + EXPECT_TRUE(no_corners.Contains({-50, -50})); + // Rectangles have half-in, half-out containment so we need + // to be careful about testing containment of right/bottom corners. + EXPECT_TRUE(no_corners.Contains({-50, 49.99})); + EXPECT_TRUE(no_corners.Contains({49.99, -50})); + EXPECT_TRUE(no_corners.Contains({49.99, 49.99})); + EXPECT_FALSE(no_corners.Contains({-50.01, -50})); + EXPECT_FALSE(no_corners.Contains({-50, -50.01})); + EXPECT_FALSE(no_corners.Contains({-50.01, 50})); + EXPECT_FALSE(no_corners.Contains({-50, 50.01})); + EXPECT_FALSE(no_corners.Contains({50.01, -50})); + EXPECT_FALSE(no_corners.Contains({50, -50.01})); + EXPECT_FALSE(no_corners.Contains({50.01, 50})); + EXPECT_FALSE(no_corners.Contains({50, 50.01})); +} + +TEST(RoundRectTest, TinyCornerRoundRectContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + // RRect of bounds with even the tiniest corners does not contain corners + auto tiny_corners = RoundRect::MakeRectXY(bounds, 0.01f, 0.01f); + + EXPECT_FALSE(tiny_corners.Contains({-50, -50})); + EXPECT_FALSE(tiny_corners.Contains({-50, 50})); + EXPECT_FALSE(tiny_corners.Contains({50, -50})); + EXPECT_FALSE(tiny_corners.Contains({50, 50})); +} + +TEST(RoundRectTest, UniformCircularRoundRectContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto expanded_2_r_2 = RoundRect::MakeRectXY(bounds.Expand(2.0), 2.0f, 2.0f); + + // Expanded by 2.0 and then with a corner of 2.0 obviously still + // contains the corners + EXPECT_TRUE(expanded_2_r_2.Contains({-50, -50})); + EXPECT_TRUE(expanded_2_r_2.Contains({-50, 50})); + EXPECT_TRUE(expanded_2_r_2.Contains({50, -50})); + EXPECT_TRUE(expanded_2_r_2.Contains({50, 50})); + + // Now we try to box in the corner containment to exactly where the + // rounded corner of the expanded round rect with radii of 2.0 lies. + // The 45-degree diagonal point of a circle of radius 2.0 lies at: + // + // (2 * sqrt(2) / 2, 2 * sqrt(2) / 2) + // (sqrt(2), sqrt(2)) + // + // So we test +/- (50 + sqrt(2) +/- epsilon) + const auto coord_out = 50 + kSqrt2 + kEhCloseEnough; + const auto coord_in = 50 + kSqrt2 - kEhCloseEnough; + // Upper left corner + EXPECT_TRUE(expanded_2_r_2.Contains({-coord_in, -coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({-coord_out, -coord_out})); + // Upper right corner + EXPECT_TRUE(expanded_2_r_2.Contains({coord_in, -coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({coord_out, -coord_out})); + // Lower left corner + EXPECT_TRUE(expanded_2_r_2.Contains({-coord_in, coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({-coord_out, coord_out})); + // Lower right corner + EXPECT_TRUE(expanded_2_r_2.Contains({coord_in, coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({coord_out, coord_out})); +} + +TEST(RoundRectTest, UniformEllipticalRoundRectContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto expanded_2_r_2 = RoundRect::MakeRectXY(bounds.Expand(2.0), 2.0f, 3.0f); + + // Expanded by 2.0 and then with a corner of 2x3 should still + // contain the corners + EXPECT_TRUE(expanded_2_r_2.Contains({-50, -50})); + EXPECT_TRUE(expanded_2_r_2.Contains({-50, 50})); + EXPECT_TRUE(expanded_2_r_2.Contains({50, -50})); + EXPECT_TRUE(expanded_2_r_2.Contains({50, 50})); + + // Now we try to box in the corner containment to exactly where the + // rounded corner of the expanded round rect with radii of 2x3 lies. + // The "45-degree diagonal point" of an ellipse of radii 2x3 lies at: + // + // (2 * sqrt(2) / 2, 3 * sqrt(2) / 2) + // (sqrt(2), 3 * sqrt(2) / 2) + // + // And the center(s) of these corners are at: + // (+/-(50 + 2 - 2), +/-(50 + 2 - 3)) + // = (+/-50, +/-49) + const auto x_coord_out = 50 + kSqrt2 + kEhCloseEnough; + const auto x_coord_in = 50 + kSqrt2 - kEhCloseEnough; + const auto y_coord_out = 49 + 3 * kSqrt2 / 2 + kEhCloseEnough; + const auto y_coord_in = 49 + 3 * kSqrt2 / 2 - kEhCloseEnough; + // Upper left corner + EXPECT_TRUE(expanded_2_r_2.Contains({-x_coord_in, -y_coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({-x_coord_out, -y_coord_out})); + // Upper right corner + EXPECT_TRUE(expanded_2_r_2.Contains({x_coord_in, -y_coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({x_coord_out, -y_coord_out})); + // Lower left corner + EXPECT_TRUE(expanded_2_r_2.Contains({-x_coord_in, y_coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({-x_coord_out, y_coord_out})); + // Lower right corner + EXPECT_TRUE(expanded_2_r_2.Contains({x_coord_in, y_coord_in})); + EXPECT_FALSE(expanded_2_r_2.Contains({x_coord_out, y_coord_out})); +} + +TEST(RoundRectTest, DifferingCornersRoundRectContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto round_rect = + RoundRect::MakeRectRadii(bounds, { + .top_left = Size(2.0, 3.0), + .top_right = Size(4.0, 5.0), + .bottom_left = Size(6.0, 7.0), + .bottom_right = Size(8.0, 9.0), + }); + + // For a corner with radii {A, B}, the "45 degree point" on the + // corner curve will be at an offset of: + // + // (A * sqrt(2) / 2, B * sqrt(2) / 2) + // + // And the center(s) of these corners are at: + // + // (+/-(50 - A), +/-(50 - B)) + auto coord = [](Scalar radius) { + return 50 - radius + radius * kSqrt2 / 2.0f - kEhCloseEnough; + }; + auto coord_in = [&coord](Scalar radius) { + return coord(radius) - kEhCloseEnough; + }; + auto coord_out = [&coord](Scalar radius) { + // For some reason 1 kEhCloseEnough is not enough to put us outside + // in some of the cases, so we use 2x the epsilon. + return coord(radius) + 2 * kEhCloseEnough; + }; + // Upper left corner (radii = {2.0, 3.0}) + EXPECT_TRUE(round_rect.Contains({-coord_in(2.0), -coord_in(3.0)})); + EXPECT_FALSE(round_rect.Contains({-coord_out(2.0), -coord_out(3.0)})); + // Upper right corner (radii = {4.0, 5.0}) + EXPECT_TRUE(round_rect.Contains({coord_in(4.0), -coord_in(5.0)})); + EXPECT_FALSE(round_rect.Contains({coord_out(4.0), -coord_out(5.0)})); + // Lower left corner (radii = {6.0, 7.0}) + EXPECT_TRUE(round_rect.Contains({-coord_in(6.0), coord_in(7.0)})); + EXPECT_FALSE(round_rect.Contains({-coord_out(6.0), coord_out(7.0)})); + // Lower right corner (radii = {8.0, 9.0}) + EXPECT_TRUE(round_rect.Contains({coord_in(8.0), coord_in(9.0)})); + EXPECT_FALSE(round_rect.Contains({coord_out(8.0), coord_out(9.0)})); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/round_superellipse.cc b/flutter/engine/src/flutter/impeller/geometry/round_superellipse.cc new file mode 100644 index 0000000000000000000000000000000000000000..b47533c84b4598932b758b4a424ee69ea27ddbfd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_superellipse.cc @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/round_superellipse.h" + +#include "flutter/impeller/geometry/round_rect.h" +#include "flutter/impeller/geometry/round_superellipse_param.h" + +namespace impeller { + +RoundSuperellipse RoundSuperellipse::MakeRectRadii( + const Rect& in_bounds, + const RoundingRadii& in_radii) { + if (!in_bounds.IsFinite()) { + return {}; + } + Rect bounds = in_bounds.GetPositive(); + // RoundingRadii::Scaled might return an empty radii if bounds or in_radii is + // empty, which is expected. Pass along the bounds even if the radii is empty + // as it would still have a valid location and/or 1-dimensional size which + // might appear when stroked + return RoundSuperellipse(bounds, in_radii.Scaled(bounds)); +} + +[[nodiscard]] bool RoundSuperellipse::Contains(const Point& p) const { + if (!bounds_.Contains(p)) { + return false; + } + auto param = RoundSuperellipseParam::MakeBoundsRadii(bounds_, radii_); + return param.Contains(p); +} + +RoundRect RoundSuperellipse::ToApproximateRoundRect() const { + // Experiments have shown that using the same corner radii for the RRect + // provides an approximation that is close to optimal, as achieving a perfect + // match is not feasible. + return RoundRect::MakeRectRadii(GetBounds(), GetRadii()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/round_superellipse.h b/flutter/engine/src/flutter/impeller/geometry/round_superellipse.h new file mode 100644 index 0000000000000000000000000000000000000000..12fe74a413014e4e67db1ebbbd4661200cc31866 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_superellipse.h @@ -0,0 +1,160 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_H_ +#define FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_H_ + +#include "flutter/impeller/geometry/point.h" +#include "flutter/impeller/geometry/rect.h" +#include "flutter/impeller/geometry/rounding_radii.h" +#include "flutter/impeller/geometry/size.h" + +namespace impeller { + +struct RoundRect; + +struct RoundSuperellipse { + RoundSuperellipse() = default; + + constexpr static RoundSuperellipse MakeRect(const Rect& rect) { + return MakeRectRadii(rect, RoundingRadii()); + } + + constexpr static RoundSuperellipse MakeOval(const Rect& rect) { + return MakeRectRadii(rect, RoundingRadii::MakeRadii(rect.GetSize() * 0.5f)); + } + + constexpr static RoundSuperellipse MakeRectRadius(const Rect& rect, + Scalar radius) { + return MakeRectRadii(rect, RoundingRadii::MakeRadius(radius)); + } + + constexpr static RoundSuperellipse MakeRectXY(const Rect& rect, + Scalar x_radius, + Scalar y_radius) { + return MakeRectRadii(rect, + RoundingRadii::MakeRadii(Size(x_radius, y_radius))); + } + + constexpr static RoundSuperellipse MakeRectXY(const Rect& rect, + Size corner_radii) { + return MakeRectRadii(rect, RoundingRadii::MakeRadii(corner_radii)); + } + + static RoundSuperellipse MakeRectRadii(const Rect& rect, + const RoundingRadii& radii); + + constexpr const Rect& GetBounds() const { return bounds_; } + constexpr const RoundingRadii& GetRadii() const { return radii_; } + + [[nodiscard]] constexpr bool IsFinite() const { + return bounds_.IsFinite() && // + radii_.top_left.IsFinite() && // + radii_.top_right.IsFinite() && // + radii_.bottom_left.IsFinite() && // + radii_.bottom_right.IsFinite(); + } + + [[nodiscard]] constexpr bool IsEmpty() const { return bounds_.IsEmpty(); } + + [[nodiscard]] constexpr bool IsRect() const { + return !bounds_.IsEmpty() && radii_.AreAllCornersEmpty(); + } + + [[nodiscard]] constexpr bool IsOval() const { + return !bounds_.IsEmpty() && radii_.AreAllCornersSame() && + ScalarNearlyEqual(radii_.top_left.width, + bounds_.GetWidth() * 0.5f) && + ScalarNearlyEqual(radii_.top_left.height, + bounds_.GetHeight() * 0.5f); + } + + /// @brief Returns true iff the provided point |p| is inside the + /// half-open interior of this rectangle. + /// + /// For purposes of containment, a rectangle contains points + /// along the top and left edges but not points along the + /// right and bottom edges so that a point is only ever + /// considered inside one of two abutting rectangles. + [[nodiscard]] bool Contains(const Point& p) const; + + /// @brief Returns a new round rectangle translated by the given offset. + [[nodiscard]] constexpr RoundSuperellipse Shift(Scalar dx, Scalar dy) const { + // Just in case, use the factory rather than the internal constructor + // as shifting the rectangle may increase/decrease its bit precision + // so we should re-validate the radii to the newly located rectangle. + return MakeRectRadii(bounds_.Shift(dx, dy), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundSuperellipse Expand(Scalar left, + Scalar top, + Scalar right, + Scalar bottom) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(left, top, right, bottom), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundSuperellipse Expand(Scalar horizontal, + Scalar vertical) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(horizontal, vertical), radii_); + } + + /// @brief Returns a round rectangle with expanded edges. Negative expansion + /// results in shrinking. + [[nodiscard]] constexpr RoundSuperellipse Expand(Scalar amount) const { + // Use the factory rather than the internal constructor as the changing + // size of the rectangle requires that we re-validate the radii to the + // newly sized rectangle. + return MakeRectRadii(bounds_.Expand(amount), radii_); + } + + [[nodiscard]] constexpr bool operator==(const RoundSuperellipse& rr) const { + return bounds_ == rr.bounds_ && radii_ == rr.radii_; + } + + [[nodiscard]] constexpr bool operator!=(const RoundSuperellipse& r) const { + return !(*this == r); + } + + // Approximates a rounded superellipse with a round rectangle to the + // best practical accuracy. + // + // This is used for Skia backends, which does not support rounded + // superellipses directly, so rendering rounded superellipses + // falls back to RRect. + [[nodiscard]] RoundRect ToApproximateRoundRect() const; + + private: + constexpr RoundSuperellipse(const Rect& bounds, const RoundingRadii& radii) + : bounds_(bounds), radii_(radii) {} + + Rect bounds_; + RoundingRadii radii_; +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::RoundSuperellipse& rr) { + out << "(" // + << "rect: " << rr.GetBounds() << ", " // + << "radii: " << rr.GetRadii(); + out << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.cc b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.cc new file mode 100644 index 0000000000000000000000000000000000000000..7dd600453d6643c5246e2c57fd66438771853948 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.cc @@ -0,0 +1,532 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/round_superellipse_param.h" + +namespace impeller { + +namespace { + +// Return the value that splits the range from `left` to `right` into two +// portions whose ratio equals to `ratio_left` : `ratio_right`. +Scalar Split(Scalar left, Scalar right, Scalar ratio_left, Scalar ratio_right) { + if (ratio_left == 0 && ratio_right == 0) { + return (left + right) / 2; + } + return (left * ratio_right + right * ratio_left) / (ratio_left + ratio_right); +} + +// Return the same Point, but each NaN coordinate is replaced by 1. +inline Point ReplanceNaNWithOne(Point in) { + return Point{std::isnan(in.x) ? 1 : in.x, std::isnan(in.y) ? 1 : in.y}; +} + +// Swap the x and y coordinate of a point. +// +// Effectively mirrors the point by the y=x line. +inline Point Flip(Point a) { + return Point{a.y, a.x}; +} + +// A look up table with precomputed variables. +// +// The columns represent the following variabls respectively: +// +// * n +// * k_xJ, which is defined as 1 / (1 - xJ / a) +// +// For definition of the variables, see ComputeOctant. +constexpr Scalar kPrecomputedVariables[][2] = { + /*ratio=2.00*/ {2.00000000, 1.13276676}, + /*ratio=2.10*/ {2.18349805, 1.20311921}, + /*ratio=2.20*/ {2.33888662, 1.28698796}, + /*ratio=2.30*/ {2.48660575, 1.36351941}, + /*ratio=2.40*/ {2.62226596, 1.44717976}, + /*ratio=2.50*/ {2.75148990, 1.53385819}, + /*ratio=3.00*/ {3.36298265, 1.98288283}, + /*ratio=3.50*/ {4.08649929, 2.23811846}, + /*ratio=4.00*/ {4.85481134, 2.47563463}, + /*ratio=4.50*/ {5.62945551, 2.72948597}, + /*ratio=5.00*/ {6.43023796, 2.98020421}}; + +constexpr Scalar kMinRatio = 2.00; + +// The curve is split into 3 parts: +// * The first part uses a denser look up table. +// * The second part uses a sparser look up table. +// * The third part uses a straight line. +constexpr Scalar kFirstStepInverse = 10; // = 1 / 0.10 +constexpr Scalar kFirstMaxRatio = 2.50; +constexpr Scalar kFirstNumRecords = 6; + +constexpr Scalar kSecondStepInverse = 2; // = 1 / 0.50 +constexpr Scalar kSecondMaxRatio = 5.00; + +constexpr Scalar kThirdNSlope = 1.559599389; +constexpr Scalar kThirdKxjSlope = 0.522807185; + +constexpr size_t kNumRecords = + sizeof(kPrecomputedVariables) / sizeof(kPrecomputedVariables[0]); + +// Compute the `n` and `xJ / a` for the given ratio. +std::array ComputeNAndXj(Scalar ratio) { + if (ratio > kSecondMaxRatio) { + Scalar n = kThirdNSlope * (ratio - kSecondMaxRatio) + + kPrecomputedVariables[kNumRecords - 1][0]; + Scalar k_xJ = kThirdKxjSlope * (ratio - kSecondMaxRatio) + + kPrecomputedVariables[kNumRecords - 1][1]; + return {n, 1 - 1 / k_xJ}; + } + ratio = std::clamp(ratio, kMinRatio, kSecondMaxRatio); + Scalar steps; + if (ratio < kFirstMaxRatio) { + steps = (ratio - kMinRatio) * kFirstStepInverse; + } else { + steps = + (ratio - kFirstMaxRatio) * kSecondStepInverse + kFirstNumRecords - 1; + } + + size_t left = std::clamp(static_cast(std::floor(steps)), 0, + kNumRecords - 2); + Scalar frac = steps - left; + + Scalar n = (1 - frac) * kPrecomputedVariables[left][0] + + frac * kPrecomputedVariables[left + 1][0]; + Scalar k_xJ = (1 - frac) * kPrecomputedVariables[left][1] + + frac * kPrecomputedVariables[left + 1][1]; + return {n, 1 - 1 / k_xJ}; +} + +// Find the center of the circle that passes the given two points and have the +// given radius. +Point FindCircleCenter(Point a, Point b, Scalar r) { + /* Denote the middle point of A and B as M. The key is to find the center of + * the circle. + * A --__ + * / ⟍ `、 + * / M ⟍\ + * / ⟋ B + * / ⟋ ↗ + * / ⟋ + * / ⟋ r + * C ᜱ ↙ + */ + + Point a_to_b = b - a; + Point m = (a + b) / 2; + Point c_to_m = Point(-a_to_b.y, a_to_b.x); + Scalar distance_am = a_to_b.GetLength() / 2; + Scalar distance_cm = sqrt(r * r - distance_am * distance_am); + return m - distance_cm * c_to_m.Normalize(); +} + +// Compute parameters for a square-like rounded superellipse with a symmetrical +// radius. +RoundSuperellipseParam::Octant ComputeOctant(Point center, + Scalar a, + Scalar radius) { + /* The following figure shows the first quadrant of a square-like rounded + * superellipse. + * + * superelipse + * A ↓ circular arc + * ---------...._J ↙ + * | / `⟍ M (where x=y) + * | / ⟋ ⟍ + * | / ⟋ \ + * | / ⟋ | + * | ᜱD | + * | ⟋ | + * | ⟋ | + * |⟋ | + * +--------------------| A' + * O + * ←-------- a ---------→ + */ + + if (radius <= 0) { + return RoundSuperellipseParam::Octant{ + .offset = center, + + .se_a = a, + .se_n = 0, + }; + } + + Scalar ratio = a * 2 / radius; + Scalar g = RoundSuperellipseParam::kGapFactor * radius; + + auto precomputed_vars = ComputeNAndXj(ratio); + Scalar n = precomputed_vars[0]; + Scalar xJ = precomputed_vars[1] * a; + Scalar yJ = pow(1 - pow(precomputed_vars[1], n), 1 / n) * a; + Scalar max_theta = asinf(pow(precomputed_vars[1], n / 2)); + + Scalar tan_phiJ = pow(xJ / yJ, n - 1); + Scalar d = (xJ - tan_phiJ * yJ) / (1 - tan_phiJ); + Scalar R = (a - d - g) * sqrt(2); + + Point pointM{a - g, a - g}; + Point pointJ = Point{xJ, yJ}; + Point circle_center = + radius == 0 ? pointM : FindCircleCenter(pointJ, pointM, R); + Radians circle_max_angle = + radius == 0 ? Radians(0) + : (pointM - circle_center).AngleTo(pointJ - circle_center); + + return RoundSuperellipseParam::Octant{ + .offset = center, + + .se_a = a, + .se_n = n, + .se_max_theta = max_theta, + + .circle_start = pointJ, + .circle_center = circle_center, + .circle_max_angle = circle_max_angle, + }; +} + +// Compute parameters for a quadrant of a rounded superellipse with asymmetrical +// radii. +// +// The `corner` is the coordinate of the corner point in the same coordinate +// space as `center`, which specifies both the half size of the bounding box and +// which quadrant the curve should be. +RoundSuperellipseParam::Quadrant ComputeQuadrant(Point center, + Point corner, + Size in_radii) { + Point corner_vector = corner - center; + Size radii = in_radii.Abs(); + + // The prefix "norm" is short for "normalized". + // + // Be extra careful to avoid NaNs in cases that some coordinates of `in_radii` + // or `corner_vector` are zero. + Scalar norm_radius = radii.MinDimension(); + Size forward_scale = norm_radius == 0 ? Size{1, 1} : radii / norm_radius; + Point norm_half_size = corner_vector.Abs() / forward_scale; + Point signed_scale = ReplanceNaNWithOne(corner_vector / norm_half_size); + + // Each quadrant curve is composed of two octant curves, each of which belongs + // to a square-like rounded rectangle. For the two octants to connect at the + // circular arc, the centers these two square-like rounded rectangle must be + // offset from the quadrant center by a same distance in different directions. + // The distance is denoted as `c`. + Scalar c = norm_half_size.x - norm_half_size.y; + + return RoundSuperellipseParam::Quadrant{ + .offset = center, + .signed_scale = signed_scale, + .top = ComputeOctant(Point{0, -c}, norm_half_size.x, norm_radius), + .right = ComputeOctant(Point{c, 0}, norm_half_size.y, norm_radius), + }; +} + +// Checks whether the given point is contained in the first octant of the given +// square-like rounded superellipse. +// +// The first octant refers to the region that spans from 0 to pi/4 starting from +// positive Y axis clockwise. +// +// If the point is not within this octant at all, then this function always +// returns true. Otherwise this function returns whether the point is contained +// within the rounded superellipse. +// +// The `param.offset` is ignored. The input point should have been transformed +// to the coordinate space where the rounded superellipse is centered at the +// origin. +bool OctantContains(const RoundSuperellipseParam::Octant& param, + const Point& p) { + // Check whether the point is within the octant. + if (p.x < 0 || p.y < 0 || p.y < p.x) { + return true; + } + // Check if the point is within the superellipsoid segment. + if (p.x <= param.circle_start.x) { + Point p_se = p / param.se_a; + return powf(p_se.x, param.se_n) + powf(p_se.y, param.se_n) <= 1; + } + Scalar circle_radius = + param.circle_start.GetDistanceSquared(param.circle_center); + Point p_circle = p - param.circle_center; + return p_circle.GetDistanceSquared(Point()) < circle_radius; +} + +// Determine if p is inside the corner curve defined by the indicated corner +// param. +// +// The coordinates of p should be within the same coordinate space with +// `param.offset`. +// +// If `check_quadrant` is true, then this function first checks if the point is +// within the quadrant of given corner. If not, this function returns true, +// otherwise this method continues to check whether the point is contained in +// the rounded superellipse. +// +// If `check_quadrant` is false, then the first step above is skipped, and the +// function checks whether the absolute (relative to the center) coordinate of p +// is contained in the rounded superellipse. +bool CornerContains(const RoundSuperellipseParam::Quadrant& param, + const Point& p, + bool check_quadrant = true) { + Point norm_point = (p - param.offset) / param.signed_scale; + if (check_quadrant) { + if (norm_point.x < 0 || norm_point.y < 0) { + return true; + } + } else { + norm_point = norm_point.Abs(); + } + if (param.top.se_n < 2 || param.right.se_n < 2) { + // A rectangular corner. The top and left sides contain the borders + // while the bottom and right sides don't (see `Rect.contains`). + Scalar x_delta = param.right.offset.x + param.right.se_a - norm_point.x; + Scalar y_delta = param.top.offset.y + param.top.se_a - norm_point.y; + bool x_within = x_delta > 0 || (x_delta == 0 && param.signed_scale.x < 0); + bool y_within = y_delta > 0 || (y_delta == 0 && param.signed_scale.y < 0); + return x_within && y_within; + } + return OctantContains(param.top, norm_point - param.top.offset) && + OctantContains(param.right, Flip(norm_point - param.right.offset)); +} + +class RoundSuperellipseBuilder { + public: + explicit RoundSuperellipseBuilder(PathBuilder& builder) : builder_(builder) {} + + // Draws an arc representing 1/4 of a rounded superellipse. + // + // If `reverse` is false, the resulting arc spans from 0 to pi/2, moving + // clockwise starting from the positive Y-axis. Otherwise it moves from pi/2 + // to 0. + void AddQuadrant(const RoundSuperellipseParam::Quadrant& param, + bool reverse, + Point scale_sign = Point(1, 1)) { + auto transform = Matrix::MakeTranslateScale(param.signed_scale * scale_sign, + param.offset); + if (param.top.se_n < 2 || param.right.se_n < 2) { + builder_.LineTo(transform * (param.top.offset + + Point(param.top.se_a, param.top.se_a))); + if (!reverse) { + builder_.LineTo(transform * + (param.top.offset + Point(param.top.se_a, 0))); + } else { + builder_.LineTo(transform * + (param.top.offset + Point(0, param.top.se_a))); + } + return; + } + if (!reverse) { + AddOctant(param.top, /*reverse=*/false, /*flip=*/false, transform); + AddOctant(param.right, /*reverse=*/true, /*flip=*/true, transform); + } else { + AddOctant(param.right, /*reverse=*/false, /*flip=*/true, transform); + AddOctant(param.top, /*reverse=*/true, /*flip=*/false, transform); + } + } + + private: + std::array SuperellipseArcPoints( + const RoundSuperellipseParam::Octant& param) { + Point start = {0, param.se_a}; + const Point& end = param.circle_start; + constexpr Point start_tangent = {1, 0}; + Point circle_start_vector = param.circle_start - param.circle_center; + Point end_tangent = + Point{-circle_start_vector.y, circle_start_vector.x}.Normalize(); + + std::array factors = SuperellipseBezierFactors(param.se_n); + + return std::array{ + start, start + start_tangent * factors[0] * param.se_a, + end + end_tangent * factors[1] * param.se_a, end}; + }; + + std::array CircularArcPoints( + const RoundSuperellipseParam::Octant& param) { + Point start_vector = param.circle_start - param.circle_center; + Point end_vector = + start_vector.Rotate(Radians(-param.circle_max_angle.radians)); + Point circle_end = param.circle_center + end_vector; + Point start_tangent = Point{start_vector.y, -start_vector.x}.Normalize(); + Point end_tangent = Point{-end_vector.y, end_vector.x}.Normalize(); + Scalar bezier_factor = std::tan(param.circle_max_angle.radians / 4) * 4 / 3; + Scalar radius = start_vector.GetLength(); + + return std::array{ + param.circle_start, + param.circle_start + start_tangent * bezier_factor * radius, + circle_end + end_tangent * bezier_factor * radius, circle_end}; + }; + + // Draws an arc representing 1/8 of a rounded superellipse. + // + // If `reverse` is false, the resulting arc spans from 0 to pi/4, moving + // clockwise starting from the positive Y-axis. Otherwise it moves from pi/4 + // to 0. + // + // If `flip` is true, all points have their X and Y coordinates swapped, + // effectively mirrowing each point by the y=x line. + // + // All points are transformed by `external_transform` after the optional + // flipping before being used as control points for the cubic curves. + void AddOctant(const RoundSuperellipseParam::Octant& param, + bool reverse, + bool flip, + const Matrix& external_transform) { + Matrix transform = + external_transform * Matrix::MakeTranslation(param.offset); + if (flip) { + transform = transform * kFlip; + } + + auto circle_points = CircularArcPoints(param); + auto se_points = SuperellipseArcPoints(param); + + if (!reverse) { + builder_.CubicCurveTo(transform * se_points[1], transform * se_points[2], + transform * se_points[3]); + builder_.CubicCurveTo(transform * circle_points[1], + transform * circle_points[2], + transform * circle_points[3]); + } else { + builder_.CubicCurveTo(transform * circle_points[2], + transform * circle_points[1], + transform * circle_points[0]); + builder_.CubicCurveTo(transform * se_points[2], transform * se_points[1], + transform * se_points[0]); + } + }; + + // Get the Bezier factor for the superellipse arc in a rounded superellipse. + // + // The result will be assigned to output, where [0] will be the factor for the + // starting tangent and [1] for the ending tangent. + // + // These values are computed by brute-force searching for the minimal distance + // on a rounded superellipse and are not for general purpose superellipses. + std::array SuperellipseBezierFactors(Scalar n) { + constexpr Scalar kPrecomputedVariables[][2] = { + /*n=2.0*/ {0.01339448, 0.05994973}, + /*n=3.0*/ {0.13664115, 0.13592082}, + /*n=4.0*/ {0.24545546, 0.14099516}, + /*n=5.0*/ {0.32353151, 0.12808021}, + /*n=6.0*/ {0.39093068, 0.11726264}, + /*n=7.0*/ {0.44847800, 0.10808278}, + /*n=8.0*/ {0.49817452, 0.10026175}, + /*n=9.0*/ {0.54105583, 0.09344429}, + /*n=10.0*/ {0.57812578, 0.08748984}, + /*n=11.0*/ {0.61050961, 0.08224722}, + /*n=12.0*/ {0.63903989, 0.07759639}, + /*n=13.0*/ {0.66416338, 0.07346530}, + /*n=14.0*/ {0.68675338, 0.06974996}, + /*n=15.0*/ {0.70678034, 0.06529512}}; + constexpr size_t kNumRecords = + sizeof(kPrecomputedVariables) / sizeof(kPrecomputedVariables[0]); + constexpr Scalar kStep = 1.00f; + constexpr Scalar kMinN = 2.00f; + constexpr Scalar kMaxN = kMinN + (kNumRecords - 1) * kStep; + + if (n >= kMaxN) { + // Heuristic formula derived from fitting. + return {1.07f - expf(1.307649835) * powf(n, -0.8568516731), + -0.01f + expf(-0.9287690322) * powf(n, -0.6120901398)}; + } + + Scalar steps = std::clamp((n - kMinN) / kStep, 0, kNumRecords - 1); + size_t left = std::clamp(static_cast(std::floor(steps)), 0, + kNumRecords - 2); + Scalar frac = steps - left; + + return std::array{(1 - frac) * kPrecomputedVariables[left][0] + + frac * kPrecomputedVariables[left + 1][0], + (1 - frac) * kPrecomputedVariables[left][1] + + frac * kPrecomputedVariables[left + 1][1]}; + } + + PathBuilder& builder_; + + // A matrix that swaps the coordinates of a point. + // clang-format off + static constexpr Matrix kFlip = Matrix( + 0.0f, 1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + // clang-format on +}; + +} // namespace + +RoundSuperellipseParam RoundSuperellipseParam::MakeBoundsRadii( + const Rect& bounds, + const RoundingRadii& radii) { + if (radii.AreAllCornersSame() && !radii.top_left.IsEmpty()) { + // Having four empty corners indicate a rectangle, which needs special + // treatment on border containment and therefore is not `all_corners_same`. + return RoundSuperellipseParam{ + .top_right = ComputeQuadrant(bounds.GetCenter(), bounds.GetRightTop(), + radii.top_right), + .all_corners_same = true, + }; + } + Scalar top_split = Split(bounds.GetLeft(), bounds.GetRight(), + radii.top_left.width, radii.top_right.width); + Scalar right_split = Split(bounds.GetTop(), bounds.GetBottom(), + radii.top_right.height, radii.bottom_right.height); + Scalar bottom_split = + Split(bounds.GetLeft(), bounds.GetRight(), radii.bottom_left.width, + radii.bottom_right.width); + Scalar left_split = Split(bounds.GetTop(), bounds.GetBottom(), + radii.top_left.height, radii.bottom_left.height); + + return RoundSuperellipseParam{ + .top_right = ComputeQuadrant(Point{top_split, right_split}, + bounds.GetRightTop(), radii.top_right), + .bottom_right = + ComputeQuadrant(Point{bottom_split, right_split}, + bounds.GetRightBottom(), radii.bottom_right), + .bottom_left = ComputeQuadrant(Point{bottom_split, left_split}, + bounds.GetLeftBottom(), radii.bottom_left), + .top_left = ComputeQuadrant(Point{top_split, left_split}, + bounds.GetLeftTop(), radii.top_left), + .all_corners_same = false, + }; +} + +void RoundSuperellipseParam::AddToPath(PathBuilder& path_builder) const { + RoundSuperellipseBuilder builder(path_builder); + + Point start = top_right.offset + + top_right.signed_scale * + (top_right.top.offset + Point(0, top_right.top.se_a)); + path_builder.MoveTo(start); + + if (all_corners_same) { + builder.AddQuadrant(top_right, /*reverse=*/false, Point(1, 1)); + builder.AddQuadrant(top_right, /*reverse=*/true, Point(1, -1)); + builder.AddQuadrant(top_right, /*reverse=*/false, Point(-1, -1)); + builder.AddQuadrant(top_right, /*reverse=*/true, Point(-1, 1)); + } else { + builder.AddQuadrant(top_right, /*reverse=*/false); + builder.AddQuadrant(bottom_right, /*reverse=*/true); + builder.AddQuadrant(bottom_left, /*reverse=*/false); + builder.AddQuadrant(top_left, /*reverse=*/true); + } + + path_builder.LineTo(start); + path_builder.Close(); +} + +bool RoundSuperellipseParam::Contains(const Point& point) const { + if (all_corners_same) { + return CornerContains(top_right, point, /*check_quadrant=*/false); + } + return CornerContains(top_right, point) && + CornerContains(bottom_right, point) && + CornerContains(bottom_left, point) && CornerContains(top_left, point); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.h b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e4b3b7fa784345e4df3feb6eb521db8e4f49b9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_param.h @@ -0,0 +1,128 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_PARAM_H_ +#define FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_PARAM_H_ + +#include "flutter/impeller/geometry/path_builder.h" +#include "flutter/impeller/geometry/point.h" +#include "flutter/impeller/geometry/rect.h" +#include "flutter/impeller/geometry/rounding_radii.h" +#include "flutter/impeller/geometry/size.h" + +namespace impeller { + +// A utility struct that expands input parameters for a rounded superellipse to +// drawing variables. +struct RoundSuperellipseParam { + // Parameters for drawing a square-like rounded superellipse. + // + // This structure is used to define an octant of an arbitrary rounded + // superellipse. + // + // A `se_n` of 0 means that the radius is 0, and this octant is a square + // of size `se_a` at `offset` and all other fields are ignored. + struct Octant { + // The offset of the square-like rounded superellipse's center from the + // origin. + // + // All other coordinates in this structure are relative to this point. + Point offset; + + // The semi-axis length of the superellipse. + Scalar se_a; + // The degree of the superellipse. + // + // If this value is 0, then this octant is a square of size `se_a`. + Scalar se_n; + // The range of the parameter "theta" used to define the superellipse curve. + // + // The "theta" is not the angle of the curve but the implicit parameter + // used in the curve's parametric equation. + Scalar se_max_theta; + + // The coordinate of the top left end of the circular arc, relative to the + // `offset` point. + Point circle_start; + // The center of the circular arc, relative to the `offset` point. + Point circle_center; + // The angular span of the circular arc, measured in radians. + Radians circle_max_angle; + }; + + // Parameters for drawing a rounded superellipse with equal radius size for + // all corners. + // + // This structure is used to define a quadrant of an arbitrary rounded + // superellipse. + struct Quadrant { + // The offset of the rounded superellipse's center from the origin. + // + // All other coordinates in this structure are relative to this point. + Point offset; + + // The scaling factor used to transform a normalized rounded superellipse + // back to its original, unnormalized shape. + // + // Normalization refers to adjusting the original curve, which may have + // asymmetrical corner sizes, into a symmetrical one by reducing the longer + // radius to match the shorter one. For instance, to draw a rounded + // superellipse with size (200, 300) and radii (20, 10), the function first + // draws a normalized RSE with size (100, 300) and radii (10, 10), then + // scales it by (2x, 1x) to restore the original proportions. + // + // Normalization also flips the curve to the first quadrant (positive x and + // y) if it originally resides in another quadrant. This affects the signs + // of `signed_scale`. + Point signed_scale; + + // The parameters for the two octants that make up this quadrant after + // normalization. + Octant top; + Octant right; + }; + + // The parameters for the four quadrants that make up the full contour. + // + // If `all_corners_same` is true, then only `top_right` is popularized. + Quadrant top_right; + Quadrant bottom_right; + Quadrant bottom_left; + Quadrant top_left; + + // If true, all corners are the same and only `top_right` is popularized. + bool all_corners_same; + + // Create a param for a rounded superellipse with the specific bounds and + // radii. + [[nodiscard]] static RoundSuperellipseParam MakeBoundsRadii( + const Rect& bounds, + const RoundingRadii& radii); + + // Returns whether this rounded superellipse contains the point. + // + // This method does not perform any prescreening such as comparing the point + // with the bounds, which is recommended for callers. + bool Contains(const Point& point) const; + + // Add a path of this rounded superellipse to the provided path builder. + void AddToPath(PathBuilder& path) const; + + // A factor used to calculate the "gap", defined as the distance from the + // midpoint of the curved corners to the nearest sides of the bounding box. + // + // When the corner radius is symmetrical on both dimensions, the midpoint of + // the corner is where the circular arc intersects its quadrant bisector. When + // the corner radius is asymmetrical, since the corner can be considered + // "elongated" from a symmetrical corner, the midpoint is transformed in the + // same way. + // + // Experiments indicate that the gap is linear with respect to the corner + // radius on that dimension. + static constexpr Scalar kGapFactor = 0.29289321881f; // 1-cos(pi/4) +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_ROUND_SUPERELLIPSE_PARAM_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/round_superellipse_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..86324be1f480f5e2a35d1ab6d9fe399f066336bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/round_superellipse_unittests.cc @@ -0,0 +1,696 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/round_superellipse.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" + +#define CHECK_POINT_WITH_OFFSET(rr, p, outward_offset) \ + EXPECT_TRUE(rr.Contains(p)); \ + EXPECT_FALSE(rr.Contains(p + outward_offset)); + +namespace impeller { +namespace testing { + +TEST(RoundSuperellipseTest, EmptyDeclaration) { + RoundSuperellipse rse; + + EXPECT_TRUE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_TRUE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect()); + EXPECT_EQ(rse.GetBounds().GetLeft(), 0.0f); + EXPECT_EQ(rse.GetBounds().GetTop(), 0.0f); + EXPECT_EQ(rse.GetBounds().GetRight(), 0.0f); + EXPECT_EQ(rse.GetBounds().GetBottom(), 0.0f); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); + EXPECT_EQ(rse.GetRadii().top_left.width, 0.0f); + EXPECT_EQ(rse.GetRadii().top_left.height, 0.0f); + EXPECT_EQ(rse.GetRadii().top_right.width, 0.0f); + EXPECT_EQ(rse.GetRadii().top_right.height, 0.0f); + EXPECT_EQ(rse.GetRadii().bottom_left.width, 0.0f); + EXPECT_EQ(rse.GetRadii().bottom_left.height, 0.0f); + EXPECT_EQ(rse.GetRadii().bottom_right.width, 0.0f); + EXPECT_EQ(rse.GetRadii().bottom_right.height, 0.0f); +} + +TEST(RoundSuperellipseTest, DefaultConstructor) { + RoundSuperellipse rse = RoundSuperellipse(); + + EXPECT_TRUE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_TRUE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect()); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); +} + +TEST(RoundSuperellipseTest, EmptyRectConstruction) { + RoundSuperellipse rse = + RoundSuperellipse::MakeRect(Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + + EXPECT_TRUE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_TRUE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); +} + +TEST(RoundSuperellipseTest, RectConstructor) { + RoundSuperellipse rse = + RoundSuperellipse::MakeRect(Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_TRUE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); +} + +TEST(RoundSuperellipseTest, InvertedRectConstruction) { + RoundSuperellipse rse = + RoundSuperellipse::MakeRect(Rect::MakeLTRB(20.0f, 20.0f, 10.0f, 10.0f)); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_TRUE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); +} + +TEST(RoundSuperellipseTest, EmptyOvalConstruction) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectXY( + Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f), 10.0f, 10.0f); + + EXPECT_TRUE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_TRUE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(20.0f, 20.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size()); + EXPECT_EQ(rse.GetRadii().top_right, Size()); + EXPECT_EQ(rse.GetRadii().bottom_left, Size()); + EXPECT_EQ(rse.GetRadii().bottom_right, Size()); +} + +TEST(RoundSuperellipseTest, OvalConstructor) { + RoundSuperellipse rse = + RoundSuperellipse::MakeOval(Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_TRUE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(5.0f, 5.0f)); +} + +TEST(RoundSuperellipseTest, InvertedOvalConstruction) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectXY( + Rect::MakeLTRB(20.0f, 20.0f, 10.0f, 10.0f), 10.0f, 10.0f); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_TRUE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(5.0f, 5.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(5.0f, 5.0f)); +} + +TEST(RoundSuperellipseTest, RectRadiusConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadius( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), 2.0f); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(2.0f, 2.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(2.0f, 2.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(2.0f, 2.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(2.0f, 2.0f)); +} + +TEST(RoundSuperellipseTest, RectXYConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectXY( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), 2.0f, 3.0f); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(2.0f, 3.0f)); +} + +TEST(RoundSuperellipseTest, RectSizeConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectXY( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), Size(2.0f, 3.0f)); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(2.0f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(2.0f, 3.0f)); +} + +TEST(RoundSuperellipseTest, RectRadiiConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f), + { + .top_left = Size(1.0, 1.5), + .top_right = Size(2.0, 2.5f), + .bottom_left = Size(3.0, 3.5f), + .bottom_right = Size(4.0, 4.5f), + }); + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 20.0f, 20.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(1.0f, 1.5f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(2.0f, 2.5f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(3.0f, 3.5f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(4.0f, 4.5f)); +} + +TEST(RoundSuperellipseTest, RectRadiiOverflowWidthConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 6.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + // Largest sum of paired radii widths is the bottom edge which sums to 12 + // Rect is only 6 wide so all radii are scaled by half + // Rect is 30 tall so no scaling should happen due to radii heights + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 16.0f, 40.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(3.5f, 4.0f)); +} + +TEST(RoundSuperellipseTest, RectRadiiOverflowHeightConstructor) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 6.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + // Largest sum of paired radii heights is the right edge which sums to 12 + // Rect is only 6 tall so all radii are scaled by half + // Rect is 30 wide so no scaling should happen due to radii widths + + EXPECT_FALSE(rse.IsEmpty()); + EXPECT_FALSE(rse.IsRect()); + EXPECT_FALSE(rse.IsOval()); + EXPECT_TRUE(rse.IsFinite()); + EXPECT_FALSE(rse.GetBounds().IsEmpty()); + EXPECT_EQ(rse.GetBounds(), Rect::MakeLTRB(10.0f, 10.0f, 40.0f, 16.0f)); + EXPECT_EQ(rse.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(rse.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(rse.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(rse.GetRadii().bottom_right, Size(3.5f, 4.0f)); +} + +TEST(RoundSuperellipseTest, Shift) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse shifted = rse.Shift(5.0, 6.0); + + EXPECT_FALSE(shifted.IsEmpty()); + EXPECT_FALSE(shifted.IsRect()); + EXPECT_FALSE(shifted.IsOval()); + EXPECT_TRUE(shifted.IsFinite()); + EXPECT_FALSE(shifted.GetBounds().IsEmpty()); + EXPECT_EQ(shifted.GetBounds(), Rect::MakeLTRB(15.0f, 16.0f, 45.0f, 46.0f)); + EXPECT_EQ(shifted.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(shifted.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(shifted.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(shifted.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(shifted, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(15.0f, 16.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ExpandScalar) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(5.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 5.0f, 45.0f, 45.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(5.0f, 5.0f, 40.0f, 40.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ExpandTwoScalars) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(5.0, 6.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 4.0f, 45.0f, 46.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(5.0f, 4.0f, 40.0f, 42.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ExpandFourScalars) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(5.0, 6.0, 7.0, 8.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(5.0f, 4.0f, 47.0f, 48.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(5.0f, 4.0f, 42.0f, 44.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ContractScalar) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(-2.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(12.0f, 12.0f, 38.0f, 38.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(12.0f, 12.0f, 26.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ContractTwoScalars) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(-1.0, -2.0); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(11.0f, 12.0f, 39.0f, 38.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(11.0f, 12.0f, 28.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ContractFourScalars) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(-1.0, -1.5, -2.0, -2.5); + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(11.0f, 11.5f, 38.0f, 37.5f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(1.0f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(3.0f, 4.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(7.0f, 8.0f)); + + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(11.0f, 11.5f, 27.0f, 26.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); +} + +TEST(RoundSuperellipseTest, ContractAndRequireRadiiAdjustment) { + RoundSuperellipse rse = RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(10.0f, 10.0f, 30.0f, 30.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + }); + RoundSuperellipse expanded = rse.Expand(-12.0); + // Largest sum of paired radii sizes are the bottom and right edges + // both of which sum to 12 + // Rect was 30x30 reduced by 12 on all sides leaving only 6x6, so all + // radii are scaled by half to avoid overflowing the contracted rect + + EXPECT_FALSE(expanded.IsEmpty()); + EXPECT_FALSE(expanded.IsRect()); + EXPECT_FALSE(expanded.IsOval()); + EXPECT_TRUE(expanded.IsFinite()); + EXPECT_FALSE(expanded.GetBounds().IsEmpty()); + EXPECT_EQ(expanded.GetBounds(), Rect::MakeLTRB(22.0f, 22.0f, 28.0f, 28.0f)); + EXPECT_EQ(expanded.GetRadii().top_left, Size(0.5f, 1.0f)); + EXPECT_EQ(expanded.GetRadii().top_right, Size(1.5f, 2.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_left, Size(2.5f, 3.0f)); + EXPECT_EQ(expanded.GetRadii().bottom_right, Size(3.5f, 4.0f)); + + // In this test, the MakeRectRadii constructor will make the same + // adjustment to the radii that the Expand method applied. + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(22.0f, 22.0f, 6.0f, 6.0f), + { + .top_left = Size(1.0f, 2.0f), + .top_right = Size(3.0f, 4.0f), + .bottom_left = Size(5.0f, 6.0f), + .bottom_right = Size(7.0f, 8.0f), + })); + + // In this test, the arguments to the constructor supply the correctly + // adjusted radii (though there is no real way to tell other than + // the result is the same). + EXPECT_EQ(expanded, RoundSuperellipse::MakeRectRadii( + Rect::MakeXYWH(22.0f, 22.0f, 6.0f, 6.0f), + { + .top_left = Size(0.5f, 1.0f), + .top_right = Size(1.5f, 2.0f), + .bottom_left = Size(2.5f, 3.0f), + .bottom_right = Size(3.5f, 4.0f), + })); +} + +TEST(RoundSuperellipseTest, NoCornerRoundSuperellipseContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + // Rounded superellipses of bounds with no corners contains corners just + // barely. + auto no_corners = RoundSuperellipse::MakeRectRadii( + bounds, RoundingRadii::MakeRadii({0.0f, 0.0f})); + + EXPECT_TRUE(no_corners.Contains({-50, -50})); + // Rectangles have half-in, half-out containment so we need + // to be careful about testing containment of right/bottom corners. + EXPECT_TRUE(no_corners.Contains({-50, 49.99})); + EXPECT_TRUE(no_corners.Contains({49.99, -50})); + EXPECT_TRUE(no_corners.Contains({49.99, 49.99})); + EXPECT_FALSE(no_corners.Contains({-50.01, -50})); + EXPECT_FALSE(no_corners.Contains({-50, -50.01})); + EXPECT_FALSE(no_corners.Contains({-50.01, 50})); + EXPECT_FALSE(no_corners.Contains({-50, 50.01})); + EXPECT_FALSE(no_corners.Contains({50.01, -50})); + EXPECT_FALSE(no_corners.Contains({50, -50.01})); + EXPECT_FALSE(no_corners.Contains({50.01, 50})); + EXPECT_FALSE(no_corners.Contains({50, 50.01})); +} + +TEST(RoundSuperellipseTest, TinyCornerContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + // Rounded superellipses of bounds with even the tiniest corners does not + // contain corners. + auto tiny_corners = RoundSuperellipse::MakeRectRadii( + bounds, RoundingRadii::MakeRadii({0.01f, 0.01f})); + + EXPECT_FALSE(tiny_corners.Contains({-50, -50})); + EXPECT_FALSE(tiny_corners.Contains({-50, 50})); + EXPECT_FALSE(tiny_corners.Contains({50, -50})); + EXPECT_FALSE(tiny_corners.Contains({50, 50})); +} + +TEST(RoundSuperellipseTest, UniformSquareContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto rr = RoundSuperellipse::MakeRectRadii( + bounds, RoundingRadii::MakeRadii({5.0f, 5.0f})); + +#define CHECK_POINT_AND_MIRRORS(p) \ + CHECK_POINT_WITH_OFFSET(rr, (p), Point(0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(1, -1), Point(0.02, -0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(-1, 1), Point(-0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(-1, -1), Point(-0.02, -0.02)); + + CHECK_POINT_AND_MIRRORS(Point(0, 49.995)); // Top + CHECK_POINT_AND_MIRRORS(Point(44.245, 49.95)); // Top curve start + CHECK_POINT_AND_MIRRORS(Point(45.72, 49.87)); // Top joint + CHECK_POINT_AND_MIRRORS(Point(48.53, 48.53)); // Circular arc mid + CHECK_POINT_AND_MIRRORS(Point(49.87, 45.72)); // Right joint + CHECK_POINT_AND_MIRRORS(Point(49.95, 44.245)); // Right curve start + CHECK_POINT_AND_MIRRORS(Point(49.995, 0)); // Right +#undef CHECK_POINT_AND_MIRRORS +} + +TEST(RoundSuperellipseTest, UniformEllipticalContains) { + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto rr = RoundSuperellipse::MakeRectRadii( + bounds, RoundingRadii::MakeRadii({5.0f, 10.0f})); + +#define CHECK_POINT_AND_MIRRORS(p) \ + CHECK_POINT_WITH_OFFSET(rr, (p), Point(0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(1, -1), Point(0.02, -0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(-1, 1), Point(-0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(-1, -1), Point(-0.02, -0.02)); + + CHECK_POINT_AND_MIRRORS(Point(0, 49.995)); // Top + CHECK_POINT_AND_MIRRORS(Point(44.245, 49.911)); // Top curve start + CHECK_POINT_AND_MIRRORS(Point(45.72, 49.75)); // Top joint + CHECK_POINT_AND_MIRRORS(Point(48.51, 47.07)); // Circular arc mid + CHECK_POINT_AND_MIRRORS(Point(49.87, 41.44)); // Right joint + CHECK_POINT_AND_MIRRORS(Point(49.95, 38.49)); // Right curve start + CHECK_POINT_AND_MIRRORS(Point(49.995, 0)); // Right +#undef CHECK_POINT_AND_MIRRORS +} + +TEST(RoundSuperellipseTest, UniformRectangularContains) { + // The bounds is not centered at the origin and has unequal height and width. + Rect bounds = Rect::MakeLTRB(0.0f, 0.0f, 50.0f, 100.0f); + auto rr = RoundSuperellipse::MakeRectRadii( + bounds, RoundingRadii::MakeRadii({23.0f, 30.0f})); + + Point center = bounds.GetCenter(); +#define CHECK_POINT_AND_MIRRORS(p) \ + CHECK_POINT_WITH_OFFSET(rr, (p - center) * Point(1, 1) + center, \ + Point(0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p - center) * Point(1, -1) + center, \ + Point(0.02, -0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p - center) * Point(-1, 1) + center, \ + Point(-0.02, 0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p - center) * Point(-1, -1) + center, \ + Point(-0.02, -0.02)); + + CHECK_POINT_AND_MIRRORS(Point(24.99, 99.99)); // Bottom mid edge + CHECK_POINT_AND_MIRRORS(Point(29.99, 99.64)); + CHECK_POINT_AND_MIRRORS(Point(34.99, 98.06)); + CHECK_POINT_AND_MIRRORS(Point(39.99, 94.73)); + CHECK_POINT_AND_MIRRORS(Point(44.13, 89.99)); + CHECK_POINT_AND_MIRRORS(Point(48.46, 79.99)); + CHECK_POINT_AND_MIRRORS(Point(49.70, 69.99)); + CHECK_POINT_AND_MIRRORS(Point(49.97, 59.99)); + CHECK_POINT_AND_MIRRORS(Point(49.99, 49.99)); // Right mid edge + +#undef CHECK_POINT_AND_MIRRORS +} + +TEST(RoundSuperellipseTest, SlimDiagnalContains) { + // This shape has large radii on one diagnal and tiny radii on the other, + // resulting in a almond-like shape placed diagnally (NW to SE). + Rect bounds = Rect::MakeLTRB(-50.0f, -50.0f, 50.0f, 50.0f); + auto rr = RoundSuperellipse::MakeRectRadii( + bounds, { + .top_left = Size(1.0, 1.0), + .top_right = Size(99.0, 99.0), + .bottom_left = Size(99.0, 99.0), + .bottom_right = Size(1.0, 1.0), + }); + + EXPECT_TRUE(rr.Contains(Point{0, 0})); + EXPECT_FALSE(rr.Contains(Point{-49.999, -49.999})); + EXPECT_FALSE(rr.Contains(Point{-49.999, 49.999})); + EXPECT_FALSE(rr.Contains(Point{49.999, 49.999})); + EXPECT_FALSE(rr.Contains(Point{49.999, -49.999})); + + // The pointy ends at the NE and SW corners + CHECK_POINT_WITH_OFFSET(rr, Point(-49.70, -49.70), Point(-0.02, -0.02)); + CHECK_POINT_WITH_OFFSET(rr, Point(49.70, 49.70), Point(0.02, 0.02)); + +// Checks two points symmetrical to the origin. +#define CHECK_DIAGNAL_POINTS(p) \ + CHECK_POINT_WITH_OFFSET(rr, (p), Point(0.02, -0.02)); \ + CHECK_POINT_WITH_OFFSET(rr, (p) * Point(-1, -1), Point(-0.02, 0.02)); + + // A few other points along the edge + CHECK_DIAGNAL_POINTS(Point(-40.0, -49.59)); + CHECK_DIAGNAL_POINTS(Point(-20.0, -45.64)); + CHECK_DIAGNAL_POINTS(Point(0.0, -37.01)); + CHECK_DIAGNAL_POINTS(Point(20.0, -21.96)); + CHECK_DIAGNAL_POINTS(Point(21.05, -20.92)); + CHECK_DIAGNAL_POINTS(Point(40.0, 5.68)); +#undef CHECK_POINT_AND_MIRRORS +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rounding_radii.cc b/flutter/engine/src/flutter/impeller/geometry/rounding_radii.cc new file mode 100644 index 0000000000000000000000000000000000000000..a74d7b64cf4023d3a88f44cb1961f16f4e8fd110 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rounding_radii.cc @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/rounding_radii.h" + +namespace impeller { + +static inline void NormalizeEmptyToZero(Size& radii) { + if (radii.IsEmpty()) { + radii = Size(); + } +} + +static inline void AdjustScale(Scalar& radius1, + Scalar& radius2, + Scalar dimension, + Scalar& scale) { + FML_DCHECK(radius1 >= 0.0f && radius2 >= 0.0f); + FML_DCHECK(dimension > 0.0f); + if (radius1 + radius2 > dimension) { + scale = std::min(scale, dimension / (radius1 + radius2)); + } +} + +RoundingRadii RoundingRadii::Scaled(const Rect& in_bounds) const { + Rect bounds = in_bounds.GetPositive(); + if (bounds.IsEmpty() || // + AreAllCornersEmpty() || !IsFinite()) { + // Normalize empty radii. + return RoundingRadii(); + } + + // Copy the incoming radii so that we can work on normalizing them to the + // particular rectangle they are paired with without disturbing the caller. + RoundingRadii radii = *this; + + // If any corner is flat or has a negative value, normalize it to zeros + // We do this first so that the unnecessary non-flat part of that radius + // does not contribute to the global scaling below. + NormalizeEmptyToZero(radii.top_left); + NormalizeEmptyToZero(radii.top_right); + NormalizeEmptyToZero(radii.bottom_left); + NormalizeEmptyToZero(radii.bottom_right); + + // Now determine a global scale to apply to all of the radii to ensure + // that none of the adjacent pairs of radius values sum to larger than + // the corresponding dimension of the rectangle. + Size size = bounds.GetSize(); + Scalar scale = 1.0f; + // clang-format off + AdjustScale(radii.top_left.width, radii.top_right.width, size.width, + scale); + AdjustScale(radii.bottom_left.width, radii.bottom_right.width, size.width, + scale); + AdjustScale(radii.top_left.height, radii.bottom_left.height, size.height, + scale); + AdjustScale(radii.top_right.height, radii.bottom_right.height, size.height, + scale); + // clang-format on + if (scale < 1.0f) { + radii = radii * scale; + } + + return radii; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rounding_radii.h b/flutter/engine/src/flutter/impeller/geometry/rounding_radii.h new file mode 100644 index 0000000000000000000000000000000000000000..97de2a7b65852306ddaf09b260a106c45d29998f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rounding_radii.h @@ -0,0 +1,110 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_ROUNDING_RADII_H_ +#define FLUTTER_IMPELLER_GEOMETRY_ROUNDING_RADII_H_ + +#include "flutter/impeller/geometry/point.h" +#include "flutter/impeller/geometry/rect.h" +#include "flutter/impeller/geometry/size.h" + +namespace impeller { + +struct RoundingRadii { + Size top_left; + Size top_right; + Size bottom_left; + Size bottom_right; + + constexpr static RoundingRadii MakeRadius(Scalar radius) { + return {Size(radius), Size(radius), Size(radius), Size(radius)}; + } + + constexpr static RoundingRadii MakeRadii(Size radii) { + return {radii, radii, radii, radii}; + } + + constexpr static RoundingRadii MakeNinePatch(Scalar left, + Scalar top, + Scalar right, + Scalar bottom) { + return { + .top_left = Size{left, top}, + .top_right = Size{right, top}, + .bottom_left = Size(left, bottom), + .bottom_right = Size(right, bottom), + }; + } + + constexpr bool IsFinite() const { + return top_left.IsFinite() && // + top_right.IsFinite() && // + bottom_left.IsFinite() && // + bottom_right.IsFinite(); + } + + constexpr bool AreAllCornersEmpty() const { + return top_left.IsEmpty() && // + top_right.IsEmpty() && // + bottom_left.IsEmpty() && // + bottom_right.IsEmpty(); + } + + constexpr bool AreAllCornersSame(Scalar tolerance = kEhCloseEnough) const { + return ScalarNearlyEqual(top_left.width, top_right.width, tolerance) && + ScalarNearlyEqual(top_left.width, bottom_right.width, tolerance) && + ScalarNearlyEqual(top_left.width, bottom_left.width, tolerance) && + ScalarNearlyEqual(top_left.height, top_right.height, tolerance) && + ScalarNearlyEqual(top_left.height, bottom_right.height, tolerance) && + ScalarNearlyEqual(top_left.height, bottom_left.height, tolerance); + } + + /// @brief Returns a scaled copy of this object, ensuring that the sum of the + /// corner radii on each side does not exceed the width or height of + /// the given bounds. + /// + /// See the [Skia scaling + /// implementation](https://github.com/google/skia/blob/main/src/core/SkRRect.cpp) + /// for more details. + RoundingRadii Scaled(const Rect& bounds) const; + + constexpr inline RoundingRadii operator*(Scalar scale) { + return { + .top_left = top_left * scale, + .top_right = top_right * scale, + .bottom_left = bottom_left * scale, + .bottom_right = bottom_right * scale, + }; + } + + [[nodiscard]] constexpr bool operator==(const RoundingRadii& rr) const { + return top_left == rr.top_left && // + top_right == rr.top_right && // + bottom_left == rr.bottom_left && // + bottom_right == rr.bottom_right; + } + + [[nodiscard]] constexpr bool operator!=(const RoundingRadii& rr) const { + return !(*this == rr); + } +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::RoundingRadii& rr) { + out << "(" // + << "ul: " << rr.top_left << ", " // + << "ur: " << rr.top_right << ", " // + << "ll: " << rr.bottom_left << ", " // + << "lr: " << rr.bottom_right // + << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_ROUNDING_RADII_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/rounding_radii_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/rounding_radii_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..89cdd3a092c6c7e34c0ae6a3d4334f70d2f5be27 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rounding_radii_unittests.cc @@ -0,0 +1,321 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/rounding_radii.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +TEST(RoudingRadiiTest, RoundingRadiiEmptyDeclaration) { + RoundingRadii radii; + + EXPECT_TRUE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size()); + EXPECT_EQ(radii.top_right, Size()); + EXPECT_EQ(radii.bottom_left, Size()); + EXPECT_EQ(radii.bottom_right, Size()); + EXPECT_EQ(radii.top_left.width, 0.0f); + EXPECT_EQ(radii.top_left.height, 0.0f); + EXPECT_EQ(radii.top_right.width, 0.0f); + EXPECT_EQ(radii.top_right.height, 0.0f); + EXPECT_EQ(radii.bottom_left.width, 0.0f); + EXPECT_EQ(radii.bottom_left.height, 0.0f); + EXPECT_EQ(radii.bottom_right.width, 0.0f); + EXPECT_EQ(radii.bottom_right.height, 0.0f); +} + +TEST(RoudingRadiiTest, RoundingRadiiDefaultConstructor) { + RoundingRadii radii = RoundingRadii(); + + EXPECT_TRUE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size()); + EXPECT_EQ(radii.top_right, Size()); + EXPECT_EQ(radii.bottom_left, Size()); + EXPECT_EQ(radii.bottom_right, Size()); +} + +TEST(RoudingRadiiTest, RoundingRadiiScalarConstructor) { + RoundingRadii radii = RoundingRadii::MakeRadius(5.0f); + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(5.0f, 5.0f)); + EXPECT_EQ(radii.top_right, Size(5.0f, 5.0f)); + EXPECT_EQ(radii.bottom_left, Size(5.0f, 5.0f)); + EXPECT_EQ(radii.bottom_right, Size(5.0f, 5.0f)); +} + +TEST(RoudingRadiiTest, RoundingRadiiEmptyScalarConstructor) { + RoundingRadii radii = RoundingRadii::MakeRadius(-5.0f); + + EXPECT_TRUE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(-5.0f, -5.0f)); + EXPECT_EQ(radii.top_right, Size(-5.0f, -5.0f)); + EXPECT_EQ(radii.bottom_left, Size(-5.0f, -5.0f)); + EXPECT_EQ(radii.bottom_right, Size(-5.0f, -5.0f)); +} + +TEST(RoudingRadiiTest, RoundingRadiiSizeConstructor) { + RoundingRadii radii = RoundingRadii::MakeRadii(Size(5.0f, 6.0f)); + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(5.0f, 6.0f)); + EXPECT_EQ(radii.top_right, Size(5.0f, 6.0f)); + EXPECT_EQ(radii.bottom_left, Size(5.0f, 6.0f)); + EXPECT_EQ(radii.bottom_right, Size(5.0f, 6.0f)); +} + +TEST(RoudingRadiiTest, RoundingRadiiEmptySizeConstructor) { + { + RoundingRadii radii = RoundingRadii::MakeRadii(Size(-5.0f, 6.0f)); + + EXPECT_TRUE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(-5.0f, 6.0f)); + EXPECT_EQ(radii.top_right, Size(-5.0f, 6.0f)); + EXPECT_EQ(radii.bottom_left, Size(-5.0f, 6.0f)); + EXPECT_EQ(radii.bottom_right, Size(-5.0f, 6.0f)); + } + + { + RoundingRadii radii = RoundingRadii::MakeRadii(Size(5.0f, -6.0f)); + + EXPECT_TRUE(radii.AreAllCornersEmpty()); + EXPECT_TRUE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(5.0f, -6.0f)); + EXPECT_EQ(radii.top_right, Size(5.0f, -6.0f)); + EXPECT_EQ(radii.bottom_left, Size(5.0f, -6.0f)); + EXPECT_EQ(radii.bottom_right, Size(5.0f, -6.0f)); + } +} + +TEST(RoudingRadiiTest, RoundingRadiiNamedSizesConstructor) { + RoundingRadii radii = { + .top_left = Size(5.0f, 5.5f), + .top_right = Size(6.0f, 6.5f), + .bottom_left = Size(7.0f, 7.5f), + .bottom_right = Size(8.0f, 8.5f), + }; + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_FALSE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(5.0f, 5.5f)); + EXPECT_EQ(radii.top_right, Size(6.0f, 6.5f)); + EXPECT_EQ(radii.bottom_left, Size(7.0f, 7.5f)); + EXPECT_EQ(radii.bottom_right, Size(8.0f, 8.5f)); +} + +TEST(RoudingRadiiTest, RoundingRadiiPartialNamedSizesConstructor) { + { + RoundingRadii radii = { + .top_left = Size(5.0f, 5.5f), + }; + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_FALSE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size(5.0f, 5.5f)); + EXPECT_EQ(radii.top_right, Size()); + EXPECT_EQ(radii.bottom_left, Size()); + EXPECT_EQ(radii.bottom_right, Size()); + } + + { + RoundingRadii radii = { + .top_right = Size(6.0f, 6.5f), + }; + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_FALSE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size()); + EXPECT_EQ(radii.top_right, Size(6.0f, 6.5f)); + EXPECT_EQ(radii.bottom_left, Size()); + EXPECT_EQ(radii.bottom_right, Size()); + } + + { + RoundingRadii radii = { + .bottom_left = Size(7.0f, 7.5f), + }; + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_FALSE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size()); + EXPECT_EQ(radii.top_right, Size()); + EXPECT_EQ(radii.bottom_left, Size(7.0f, 7.5f)); + EXPECT_EQ(radii.bottom_right, Size()); + } + + { + RoundingRadii radii = { + .bottom_right = Size(8.0f, 8.5f), + }; + + EXPECT_FALSE(radii.AreAllCornersEmpty()); + EXPECT_FALSE(radii.AreAllCornersSame()); + EXPECT_TRUE(radii.IsFinite()); + EXPECT_EQ(radii.top_left, Size()); + EXPECT_EQ(radii.top_right, Size()); + EXPECT_EQ(radii.bottom_left, Size()); + EXPECT_EQ(radii.bottom_right, Size(8.0f, 8.5f)); + } +} + +TEST(RoudingRadiiTest, RoundingRadiiMultiply) { + RoundingRadii radii = { + .top_left = Size(5.0f, 5.5f), + .top_right = Size(6.0f, 6.5f), + .bottom_left = Size(7.0f, 7.5f), + .bottom_right = Size(8.0f, 8.5f), + }; + RoundingRadii doubled = radii * 2.0f; + + EXPECT_FALSE(doubled.AreAllCornersEmpty()); + EXPECT_FALSE(doubled.AreAllCornersSame()); + EXPECT_TRUE(doubled.IsFinite()); + EXPECT_EQ(doubled.top_left, Size(10.0f, 11.0f)); + EXPECT_EQ(doubled.top_right, Size(12.0f, 13.0f)); + EXPECT_EQ(doubled.bottom_left, Size(14.0f, 15.0f)); + EXPECT_EQ(doubled.bottom_right, Size(16.0f, 17.0f)); +} + +TEST(RoudingRadiiTest, RoundingRadiiEquals) { + RoundingRadii radii = { + .top_left = Size(5.0f, 5.5f), + .top_right = Size(6.0f, 6.5f), + .bottom_left = Size(7.0f, 7.5f), + .bottom_right = Size(8.0f, 8.5f), + }; + RoundingRadii other = { + .top_left = Size(5.0f, 5.5f), + .top_right = Size(6.0f, 6.5f), + .bottom_left = Size(7.0f, 7.5f), + .bottom_right = Size(8.0f, 8.5f), + }; + + EXPECT_EQ(radii, other); +} + +TEST(RoudingRadiiTest, RoundingRadiiNotEquals) { + const RoundingRadii radii = { + .top_left = Size(5.0f, 5.5f), + .top_right = Size(6.0f, 6.5f), + .bottom_left = Size(7.0f, 7.5f), + .bottom_right = Size(8.0f, 8.5f), + }; + + { + RoundingRadii different = radii; + different.top_left.width = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.top_left.height = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.top_right.width = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.top_right.height = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.bottom_left.width = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.bottom_left.height = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.bottom_right.width = 100.0f; + EXPECT_NE(different, radii); + } + { + RoundingRadii different = radii; + different.bottom_right.height = 100.0f; + EXPECT_NE(different, radii); + } +} + +TEST(RoudingRadiiTest, RoundingRadiiCornersSameTolerance) { + RoundingRadii radii{ + .top_left = {10, 20}, + .top_right = {10.01, 20.01}, + .bottom_left = {9.99, 19.99}, + .bottom_right = {9.99, 20.01}, + }; + + EXPECT_TRUE(radii.AreAllCornersSame(.02)); + + { + RoundingRadii different = radii; + different.top_left.width = 10.03; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.top_left.height = 20.03; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.top_right.width = 10.03; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.top_right.height = 20.03; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.bottom_left.width = 9.97; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.bottom_left.height = 19.97; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.bottom_right.width = 9.97; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } + { + RoundingRadii different = radii; + different.bottom_right.height = 20.03; + EXPECT_FALSE(different.AreAllCornersSame(.02)); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rstransform.cc b/flutter/engine/src/flutter/impeller/geometry/rstransform.cc new file mode 100644 index 0000000000000000000000000000000000000000..05a509e992d4011f798f2fe74b359c2eec609a77 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rstransform.cc @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/geometry/rstransform.h" + +#include "flutter/impeller/geometry/matrix.h" + +namespace impeller { + +bool RSTransform::IsAxisAligned() const { + return scaled_cos == 0.0f || scaled_sin == 0.0f; +} + +Matrix RSTransform::GetMatrix() const { + // clang-format off + return Matrix::MakeRow(scaled_cos, -scaled_sin, 0.0f, translate_x, + scaled_sin, scaled_cos, 0.0f, translate_y, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + // clang-format on +} + +void RSTransform::GetQuad(Scalar width, Scalar height, Quad& quad) const { + Point origin = {translate_x, translate_y}; + Point dx = width * Point{scaled_cos, scaled_sin}; + Point dy = height * Point{-scaled_sin, scaled_cos}; + quad = { + // Ordered in the same Z pattern as Rect::GetPoints() + origin, + origin + dx, + origin + dy, + origin + dx + dy, + }; +} + +Quad RSTransform::GetQuad(Scalar width, Scalar height) const { + Quad quad; + GetQuad(width, height, quad); + return quad; +} + +Quad RSTransform::GetQuad(Size size) const { + Quad quad; + GetQuad(size.width, size.height, quad); + return quad; +} + +std::optional RSTransform::GetBounds(Scalar width, Scalar height) const { + return Rect::MakePointBounds(GetQuad(width, height)); +} + +std::optional RSTransform::GetBounds(Size size) const { + return Rect::MakePointBounds(GetQuad(size)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/rstransform.h b/flutter/engine/src/flutter/impeller/geometry/rstransform.h new file mode 100644 index 0000000000000000000000000000000000000000..28b4cd09b452511b9ce3ad930d6d3ba55bfd5a1f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rstransform.h @@ -0,0 +1,89 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_RSTRANSFORM_H_ +#define FLUTTER_IMPELLER_GEOMETRY_RSTRANSFORM_H_ + +#include "flutter/impeller/geometry/point.h" +#include "flutter/impeller/geometry/rect.h" +#include "flutter/impeller/geometry/scalar.h" +#include "flutter/impeller/geometry/size.h" + +namespace impeller { + +/// A utility struct that stores a simple transform composed of a translation, +/// a rotation, and a uniform scale. +/// +/// This transform is used by drawAtlas to transform the sprites. +/// This structure mirrors the Flutter RSTransform class. +struct RSTransform { + constexpr RSTransform() + : scaled_cos(1.0f), + scaled_sin(0.0f), + translate_x(0.0f), + translate_y(0.0f) {} + + constexpr RSTransform(Scalar scaled_cos, + Scalar scaled_sin, + Scalar translate_x, + Scalar translate_y) + : scaled_cos(scaled_cos), + scaled_sin(scaled_sin), + translate_x(translate_x), + translate_y(translate_y) {} + + /// Constructs an RSTransform from the indicated origin, uniform scale, + /// and radians rotation. + static constexpr RSTransform Make(Point origin, + Scalar scale, + Radians radians) { + auto scaled_cos_sin = Matrix::CosSin(radians) * scale; + return {scaled_cos_sin.x, scaled_cos_sin.y, origin.x, origin.y}; + } + + Scalar scaled_cos; + Scalar scaled_sin; + Scalar translate_x; + Scalar translate_y; + + /// Returns true iff the resulting transformed quad will be aligned with + /// the axes, even if rotated by a quadrant rotation. + bool IsAxisAligned() const; + + Matrix GetMatrix() const; + + /// Returns the 4 corner points of the transformed quad for a sub-image + /// of the indicated size in the same order as Rect::GetPoints. + /// + /// The order is UpperLeft, UpperRight, LowerLeft, LowerRight + void GetQuad(Scalar width, Scalar height, Quad& quad) const; + Quad GetQuad(Scalar width, Scalar height) const; + Quad GetQuad(Size size) const; + + /// Returns the bounds of the 4 corner points of the transformed quad + /// for a sub-image of the indicated size. + std::optional GetBounds(Scalar width, Scalar height) const; + std::optional GetBounds(Size size) const; +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::RSTransform& rst) { + // clang-format off + out << "(" + << "scos: " << rst.scaled_cos << ", " + << "ssin: " << rst.scaled_sin << ", " + << "origin: (" << rst.translate_x << ", " + << rst.translate_y << ")" + << ")"; + // clang-format on + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_RSTRANSFORM_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/rstransform_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/rstransform_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e9e046409d06b50e874300d31774ad0729a31a20 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/rstransform_unittests.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/rstransform.h" + +#include "flutter/impeller/geometry/geometry_asserts.h" + +namespace impeller { +namespace testing { + +TEST(RSTransformTest, Construction) { + RSTransform transform = RSTransform::Make({10.0f, 12.0f}, 2.0f, Degrees(90)); + + EXPECT_EQ(transform.scaled_cos, 0.0f); + EXPECT_EQ(transform.scaled_sin, 2.0f); + EXPECT_EQ(transform.translate_x, 10.0f); + EXPECT_EQ(transform.translate_y, 12.0f); + + EXPECT_EQ(transform.GetBounds(20.0f, 30.0f), + // relative corners are at + // 0, 0 + // 0, 40 + // -60, 0 + // -60, 40 + // then add 10, 12 to all values + Rect::MakeLTRB(10 + -2 * 30, 12 + 0, 10 + 0, 12 + 40)); +} + +TEST(RSTransformTest, CompareToMatrix) { + for (int tx = 0; tx <= 100; tx += 10) { + for (int ty = 0; ty <= 100; ty += 10) { + Point origin(tx, ty); + for (int scale = 1; scale <= 20; scale += 5) { + // Overshoot a full circle by 30 degrees + for (int degrees = 0; degrees <= 390; degrees += 45) { + auto matrix = Matrix::MakeTranslation(origin) * + Matrix::MakeRotationZ(Degrees(degrees)) * + Matrix::MakeScale(Vector2(scale, scale)); + auto rst = RSTransform::Make(origin, scale, Degrees(degrees)); + EXPECT_MATRIX_NEAR(rst.GetMatrix(), matrix); + for (int w = 10; w <= 100; w += 10) { + for (int h = 10; h <= 100; h += 10) { + Quad q = rst.GetQuad(w, h); + auto points = Rect::MakeWH(w, h).GetTransformedPoints(matrix); + for (int i = 0; i < 4; i++) { + EXPECT_NEAR(q[i].x, points[i].x, kEhCloseEnough); + EXPECT_NEAR(q[i].y, points[i].y, kEhCloseEnough); + } + } + } + } + } + } + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/saturated_math.h b/flutter/engine/src/flutter/impeller/geometry/saturated_math.h new file mode 100644 index 0000000000000000000000000000000000000000..bd92cbf42474c7e69df64959813402a9cdb6c157 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/saturated_math.h @@ -0,0 +1,148 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SATURATED_MATH_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SATURATED_MATH_H_ + +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +namespace saturated { + +// NOLINTBEGIN(readability-identifier-naming) +template +inline constexpr bool is_signed_integral_v = + std::is_integral_v && std::is_signed_v; +// NOLINTEND(readability-identifier-naming) + +#define ONLY_ON_SIGNED_INT_RET(Type, Ret) \ + template \ + constexpr inline std::enable_if_t, Ret> +#define ONLY_ON_SIGNED_INT(Type) ONLY_ON_SIGNED_INT_RET(Type, Type) + +#define ONLY_ON_FLOAT_RET(Type, Ret) \ + template \ + constexpr inline std::enable_if_t, Ret> +#define ONLY_ON_FLOAT(Type) ONLY_ON_FLOAT_RET(Type, Type) + +#define ONLY_ON_FLOAT_TO_SIGNED_INT_RET(FPType, SIType, Ret) \ + template \ + constexpr inline std::enable_if_t< \ + std::is_floating_point_v && is_signed_integral_v, Ret> +#define ONLY_ON_FLOAT_TO_SIGNED_INT(FPType, SIType) \ + ONLY_ON_FLOAT_TO_SIGNED_INT_RET(FPType, SIType, SIType) + +#define ONLY_ON_DIFFERING_FLOAT_RET(FPType1, FPType2, Ret) \ + template \ + constexpr inline std::enable_if_t && \ + std::is_floating_point_v && \ + !std::is_same_v, \ + Ret> +#define ONLY_ON_DIFFERING_FLOAT(FPType1, FPType2) \ + ONLY_ON_DIFFERING_FLOAT_RET(FPType1, FPType2, FPType2) + +#define ONLY_ON_SAME_TYPES_RET(Type1, Type2, Ret) \ + template \ + constexpr inline std::enable_if_t, Ret> +#define ONLY_ON_SAME_TYPES(Type1, Type2) \ + ONLY_ON_SAME_TYPES_RET(Type1, Type2, Type2) + +ONLY_ON_SIGNED_INT(SI) Add(SI location, SI distance) { + if (location >= 0) { + if (distance > std::numeric_limits::max() - location) { + return std::numeric_limits::max(); + } + } else if (distance < std::numeric_limits::min() - location) { + return std::numeric_limits::min(); + } + return location + distance; +} + +ONLY_ON_FLOAT(FP) Add(FP location, FP distance) { + return location + distance; +} + +ONLY_ON_SIGNED_INT(SI) Sub(SI upper, SI lower) { + if (upper >= 0) { + if (lower < 0 && upper > std::numeric_limits::max() + lower) { + return std::numeric_limits::max(); + } + } else if (lower > 0 && upper < std::numeric_limits::min() + lower) { + return std::numeric_limits::min(); + } + return upper - lower; +} + +ONLY_ON_FLOAT(FP) Sub(FP upper, FP lower) { + return upper - lower; +} + +ONLY_ON_SIGNED_INT_RET(SI, Scalar) AverageScalar(SI a, SI b) { + // scalbn has an implementation for ints that converts to double + // while adjusting the exponent. + return static_cast(std::scalbn(a, -1) + std::scalbn(b, -1)); +} + +ONLY_ON_FLOAT(FP) AverageScalar(FP a, FP b) { + // GetCenter might want this to return 0 for a Maximum Rect, but it + // will currently produce NaN instead. For the Maximum Rect itself + // a 0 would make sense as the center, but for a computed rect that + // incidentally ended up with infinities, NaN may be a better choice. + // return static_cast(std::scalbn(a, -1) + std::scalbn(b, -1)); + + // This equation would save an extra scalbn operation but at the cost + // of having very large (or very neagive) a's and b's overflow to + // +/- infinity. Scaling first allows finite numbers to be more likely + // to have a finite average. + // return std::scalbn(a + b, -1); + + return static_cast(std::scalbn(a, -1) + std::scalbn(b, -1)); +} + +ONLY_ON_SAME_TYPES(T, U) Cast(T v) { + return v; +} + +ONLY_ON_FLOAT_TO_SIGNED_INT(FP, SI) Cast(FP v) { + if (v <= static_cast(std::numeric_limits::min())) { + return std::numeric_limits::min(); + } else if (v >= static_cast(std::numeric_limits::max())) { + return std::numeric_limits::max(); + } + return static_cast(v); +} + +ONLY_ON_DIFFERING_FLOAT(FP1, FP2) Cast(FP1 v) { + if (std::isfinite(v)) { + // Avoid truncation to inf/-inf. + return std::clamp(static_cast(v), // + std::numeric_limits::lowest(), + std::numeric_limits::max()); + } else { + return static_cast(v); + } +} + +#undef ONLY_ON_SAME_TYPES +#undef ONLY_ON_SAME_TYPES_RET +#undef ONLY_ON_DIFFERING_FLOAT +#undef ONLY_ON_DIFFERING_FLOAT_RET +#undef ONLY_ON_FLOAT_TO_SIGNED_INT +#undef ONLY_ON_FLOAT_TO_SIGNED_INT_RET +#undef ONLY_ON_FLOAT +#undef ONLY_ON_FLOAT_RET +#undef ONLY_ON_SIGNED_INT +#undef ONLY_ON_SIGNED_INT_RET + +} // namespace saturated + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_SATURATED_MATH_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/saturated_math_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/saturated_math_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e845e5a4b42e542b57d1fe86791411749bb2a7a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/saturated_math_unittests.cc @@ -0,0 +1,1133 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "impeller/geometry/saturated_math.h" + +namespace impeller { +namespace testing { + +TEST(SaturatedMath, ExplicitAddOfSignedInts) { + { + EXPECT_EQ(saturated::Add(0x79, 5), int8_t(0x7E)); + EXPECT_EQ(saturated::Add(0x7A, 5), int8_t(0x7F)); + EXPECT_EQ(saturated::Add(0x7B, 5), int8_t(0x7F)); + } + { + EXPECT_EQ(saturated::Add(0x86, -5), int8_t(0x81)); + EXPECT_EQ(saturated::Add(0x85, -5), int8_t(0x80)); + EXPECT_EQ(saturated::Add(0x84, -5), int8_t(0x80)); + } + { + EXPECT_EQ(saturated::Add(0x7FF9, 5), int16_t(0x7FFE)); + EXPECT_EQ(saturated::Add(0x7FFA, 5), int16_t(0x7FFF)); + EXPECT_EQ(saturated::Add(0x7FFB, 5), int16_t(0x7FFF)); + } + { + EXPECT_EQ(saturated::Add(0x8006, -5), int16_t(0x8001)); + EXPECT_EQ(saturated::Add(0x8005, -5), int16_t(0x8000)); + EXPECT_EQ(saturated::Add(0x8004, -5), int16_t(0x8000)); + } + { + EXPECT_EQ(saturated::Add(0x7FFFFFF9, 5), int32_t(0x7FFFFFFE)); + EXPECT_EQ(saturated::Add(0x7FFFFFFA, 5), int32_t(0x7FFFFFFF)); + EXPECT_EQ(saturated::Add(0x7FFFFFFB, 5), int32_t(0x7FFFFFFF)); + } + { + EXPECT_EQ(saturated::Add(0x80000006, -5), int32_t(0x80000001)); + EXPECT_EQ(saturated::Add(0x80000005, -5), int32_t(0x80000000)); + EXPECT_EQ(saturated::Add(0x80000004, -5), int32_t(0x80000000)); + } + { + EXPECT_EQ(saturated::Add(0x7FFFFFFFFFFFFFF9, 5), + int64_t(0x7FFFFFFFFFFFFFFE)); + EXPECT_EQ(saturated::Add(0x7FFFFFFFFFFFFFFA, 5), + int64_t(0x7FFFFFFFFFFFFFFF)); + EXPECT_EQ(saturated::Add(0x7FFFFFFFFFFFFFFB, 5), + int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + EXPECT_EQ(saturated::Add(0x8000000000000006, -5), + int64_t(0x8000000000000001)); + EXPECT_EQ(saturated::Add(0x8000000000000005, -5), + int64_t(0x8000000000000000)); + EXPECT_EQ(saturated::Add(0x8000000000000004, -5), + int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, ImplicitAddOfSignedInts) { + { + int8_t a = 0x79; + int8_t b = 5; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x7E)); + a = 0x7A; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x7F)); + a = 0x7B; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x7F)); + } + { + int8_t a = 0x86; + int8_t b = -5; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x81)); + a = 0x85; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x80)); + a = 0x84; + EXPECT_EQ(saturated::Add(a, b), int8_t(0x80)); + } + { + int16_t a = 0x7FF9; + int16_t b = 5; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x7FFE)); + a = 0x7FFA; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x7FFF)); + a = 0x7FFB; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x7FFF)); + } + { + int16_t a = 0x8006; + int16_t b = -5; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x8001)); + a = 0x8005; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x8000)); + a = 0x8004; + EXPECT_EQ(saturated::Add(a, b), int16_t(0x8000)); + } + { + int32_t a = 0x7FFFFFF9; + int32_t b = 5; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x7FFFFFFE)); + a = 0x7FFFFFFA; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x7FFFFFFF)); + a = 0x7FFFFFFB; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x7FFFFFFF)); + } + { + int32_t a = 0x80000006; + int32_t b = -5; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x80000001)); + a = 0x80000005; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x80000000)); + a = 0x80000004; + EXPECT_EQ(saturated::Add(a, b), int32_t(0x80000000)); + } + { + int64_t a = 0x7FFFFFFFFFFFFFF9; + int64_t b = 5; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x7FFFFFFFFFFFFFFE)); + a = 0x7FFFFFFFFFFFFFFA; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x7FFFFFFFFFFFFFFF)); + a = 0x7FFFFFFFFFFFFFFB; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + int64_t a = 0x8000000000000006; + int64_t b = -5; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x8000000000000001)); + a = 0x8000000000000005; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x8000000000000000)); + a = 0x8000000000000004; + EXPECT_EQ(saturated::Add(a, b), int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, ExplicitAddOfFloatingPoint) { + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } +} + +TEST(SaturatedMath, ImplicitAddOfFloatingPoint) { + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::Add(big, big), max); + EXPECT_EQ(saturated::Add(max, big), inf); + EXPECT_EQ(saturated::Add(big, max), inf); + EXPECT_EQ(saturated::Add(max, max), inf); + EXPECT_EQ(saturated::Add(max, inf), inf); + EXPECT_EQ(saturated::Add(inf, max), inf); + EXPECT_EQ(saturated::Add(inf, inf), inf); + + EXPECT_EQ(saturated::Add(-big, -big), -max); + EXPECT_EQ(saturated::Add(-max, -big), -inf); + EXPECT_EQ(saturated::Add(-big, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -max), -inf); + EXPECT_EQ(saturated::Add(-max, -inf), -inf); + EXPECT_EQ(saturated::Add(-inf, -max), -inf); + EXPECT_EQ(saturated::Add(-inf, -inf), -inf); + + EXPECT_EQ(saturated::Add(big, -big), 0.0f); + EXPECT_EQ(saturated::Add(max, -big), big); + EXPECT_EQ(saturated::Add(big, -max), -big); + EXPECT_EQ(saturated::Add(max, -max), 0.0f); + EXPECT_EQ(saturated::Add(max, -inf), -inf); + EXPECT_EQ(saturated::Add(inf, -max), inf); + EXPECT_TRUE(std::isnan(saturated::Add(inf, -inf))); + + EXPECT_EQ(saturated::Add(-big, big), 0.0f); + EXPECT_EQ(saturated::Add(-max, big), -big); + EXPECT_EQ(saturated::Add(-big, max), big); + EXPECT_EQ(saturated::Add(-max, max), 0.0f); + EXPECT_EQ(saturated::Add(-max, inf), inf); + EXPECT_EQ(saturated::Add(-inf, max), -inf); + EXPECT_TRUE(std::isnan(saturated::Add(-inf, inf))); + } +} + +TEST(SaturatedMath, ExplicitSubOfSignedInts) { + { + EXPECT_EQ(saturated::Sub(0x79, -5), int8_t(0x7E)); + EXPECT_EQ(saturated::Sub(0x7A, -5), int8_t(0x7F)); + EXPECT_EQ(saturated::Sub(0x7B, -5), int8_t(0x7F)); + } + { + EXPECT_EQ(saturated::Sub(0x86, 5), int8_t(0x81)); + EXPECT_EQ(saturated::Sub(0x85, 5), int8_t(0x80)); + EXPECT_EQ(saturated::Sub(0x84, 5), int8_t(0x80)); + } + { + EXPECT_EQ(saturated::Sub(0x7FF9, -5), int16_t(0x7FFE)); + EXPECT_EQ(saturated::Sub(0x7FFA, -5), int16_t(0x7FFF)); + EXPECT_EQ(saturated::Sub(0x7FFB, -5), int16_t(0x7FFF)); + } + { + EXPECT_EQ(saturated::Sub(0x8006, 5), int16_t(0x8001)); + EXPECT_EQ(saturated::Sub(0x8005, 5), int16_t(0x8000)); + EXPECT_EQ(saturated::Sub(0x8004, 5), int16_t(0x8000)); + } + { + EXPECT_EQ(saturated::Sub(0x7FFFFFF9, -5), int32_t(0x7FFFFFFE)); + EXPECT_EQ(saturated::Sub(0x7FFFFFFA, -5), int32_t(0x7FFFFFFF)); + EXPECT_EQ(saturated::Sub(0x7FFFFFFB, -5), int32_t(0x7FFFFFFF)); + } + { + EXPECT_EQ(saturated::Sub(0x80000006, 5), int32_t(0x80000001)); + EXPECT_EQ(saturated::Sub(0x80000005, 5), int32_t(0x80000000)); + EXPECT_EQ(saturated::Sub(0x80000004, 5), int32_t(0x80000000)); + } + { + EXPECT_EQ(saturated::Sub(0x7FFFFFFFFFFFFFF9, -5), + int64_t(0x7FFFFFFFFFFFFFFE)); + EXPECT_EQ(saturated::Sub(0x7FFFFFFFFFFFFFFA, -5), + int64_t(0x7FFFFFFFFFFFFFFF)); + EXPECT_EQ(saturated::Sub(0x7FFFFFFFFFFFFFFB, -5), + int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + EXPECT_EQ(saturated::Sub(0x8000000000000006, 5), + int64_t(0x8000000000000001)); + EXPECT_EQ(saturated::Sub(0x8000000000000005, 5), + int64_t(0x8000000000000000)); + EXPECT_EQ(saturated::Sub(0x8000000000000004, 5), + int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, ImplicitSubOfSignedInts) { + { + int8_t a = 0x79; + int8_t b = -5; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x7E)); + a = 0x7A; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x7F)); + a = 0x7B; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x7F)); + } + { + int8_t a = 0x86; + int8_t b = 5; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x81)); + a = 0x85; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x80)); + a = 0x84; + EXPECT_EQ(saturated::Sub(a, b), int8_t(0x80)); + } + { + int16_t a = 0x7FF9; + int16_t b = -5; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x7FFE)); + a = 0x7FFA; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x7FFF)); + a = 0x7FFB; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x7FFF)); + } + { + int16_t a = 0x8006; + int16_t b = 5; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x8001)); + a = 0x8005; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x8000)); + a = 0x8004; + EXPECT_EQ(saturated::Sub(a, b), int16_t(0x8000)); + } + { + int32_t a = 0x7FFFFFF9; + int32_t b = -5; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x7FFFFFFE)); + a = 0x7FFFFFFA; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x7FFFFFFF)); + a = 0x7FFFFFFB; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x7FFFFFFF)); + } + { + int32_t a = 0x80000006; + int32_t b = 5; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x80000001)); + a = 0x80000005; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x80000000)); + a = 0x80000004; + EXPECT_EQ(saturated::Sub(a, b), int32_t(0x80000000)); + } + { + int64_t a = 0x7FFFFFFFFFFFFFF9; + int64_t b = -5; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x7FFFFFFFFFFFFFFE)); + a = 0x7FFFFFFFFFFFFFFA; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x7FFFFFFFFFFFFFFF)); + a = 0x7FFFFFFFFFFFFFFB; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + int64_t a = 0x8000000000000006; + int64_t b = 5; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x8000000000000001)); + a = 0x8000000000000005; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x8000000000000000)); + a = 0x8000000000000004; + EXPECT_EQ(saturated::Sub(a, b), int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, ExplicitSubOfFloatingPoint) { + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } +} + +TEST(SaturatedMath, ImplicitSubOfFloatingPoint) { + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::Sub(big, big), 0.0f); + EXPECT_EQ(saturated::Sub(max, big), big); + EXPECT_EQ(saturated::Sub(big, max), -big); + EXPECT_EQ(saturated::Sub(max, max), 0.0f); + EXPECT_EQ(saturated::Sub(max, inf), -inf); + EXPECT_EQ(saturated::Sub(inf, max), inf); + EXPECT_TRUE(std::isnan(saturated::Sub(inf, inf))); + + EXPECT_EQ(saturated::Sub(-big, -big), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -big), -big); + EXPECT_EQ(saturated::Sub(-big, -max), big); + EXPECT_EQ(saturated::Sub(-max, -max), 0.0f); + EXPECT_EQ(saturated::Sub(-max, -inf), inf); + EXPECT_EQ(saturated::Sub(-inf, -max), -inf); + EXPECT_TRUE(std::isnan(saturated::Sub(-inf, -inf))); + + EXPECT_EQ(saturated::Sub(big, -big), max); + EXPECT_EQ(saturated::Sub(max, -big), inf); + EXPECT_EQ(saturated::Sub(big, -max), inf); + EXPECT_EQ(saturated::Sub(max, -max), inf); + EXPECT_EQ(saturated::Sub(max, -inf), inf); + EXPECT_EQ(saturated::Sub(inf, -max), inf); + EXPECT_EQ(saturated::Sub(inf, -inf), inf); + + EXPECT_EQ(saturated::Sub(-big, big), -max); + EXPECT_EQ(saturated::Sub(-max, big), -inf); + EXPECT_EQ(saturated::Sub(-big, max), -inf); + EXPECT_EQ(saturated::Sub(-max, max), -inf); + EXPECT_EQ(saturated::Sub(-max, inf), -inf); + EXPECT_EQ(saturated::Sub(-inf, max), -inf); + EXPECT_EQ(saturated::Sub(-inf, inf), -inf); + } +} + +TEST(SaturatedMath, ExplicitAverageScalarOfSignedInts) { + // For each type try: + // + // - near the limits, averaging to 0 + // - at the limits, averaging to 0 or 0.5 depending on precision + // - both large enough for the sum to overflow + // - both negative enough for the sum to underflow + { + EXPECT_EQ(saturated::AverageScalar(0x81, 0x7F), -0.0f); + EXPECT_EQ(saturated::AverageScalar(0x80, 0x7F), -0.5f); + EXPECT_EQ(saturated::AverageScalar(0x70, 0x75), 114.5f); + EXPECT_EQ(saturated::AverageScalar(0x85, 0x8A), -120.5f); + } + { + EXPECT_EQ(saturated::AverageScalar(0x8001, 0x7FFF), -0.0f); + EXPECT_EQ(saturated::AverageScalar(0x8000, 0x7FFF), -0.5f); + EXPECT_EQ(saturated::AverageScalar(0x7000, 0x7005), 28674.5f); + EXPECT_EQ(saturated::AverageScalar(0x8005, 0x800A), -32760.5f); + } + { + EXPECT_EQ(saturated::AverageScalar(0x80000001, 0x7FFFFFFF), -0.0f); + EXPECT_EQ(saturated::AverageScalar(0x80000000, 0x7FFFFFFF), -0.5f); + EXPECT_EQ(saturated::AverageScalar(0x70000000, 0x70000005), + 1879048195.5f); + EXPECT_EQ(saturated::AverageScalar(0x80000005, 0x8000000A), + -2147483655.5f); + } + { + EXPECT_EQ(saturated::AverageScalar(0x8000000000000001, + 0x7FFFFFFFFFFFFFFF), + 0.0f); + // 64-bit integers overflow the ability of a Scalar (float) to + // represent discrete integers and so the two numbers we are + // averaging here will look like the same number with different + // signs and the answer will be "0" + EXPECT_EQ(saturated::AverageScalar(0x8000000000000000, + 0x7FFFFFFFFFFFFFFF), + 0.0f); + EXPECT_NEAR(saturated::AverageScalar(0x7000000000000000, + 0x7000000000000005), + 8.07045053e+18, 1e18); + EXPECT_NEAR(saturated::AverageScalar(0x8000000000000005, + 0x800000000000000A), + -9.223372e+18, 1e18); + } +} + +TEST(SaturatedMath, ImplicitAverageScalarOfSignedInts) { + // For each type try: + // + // - near the limits, averaging to 0 + // - at the limits, averaging to 0 or 0.5 depending on precision + // - both large enough for the sum to overflow + // - both negative enough for the sum to underflow + { + int8_t a = 0x81; + int8_t b = 0x7f; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.0f); + a = 0x80; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.5f); + a = 0x70; + b = 0x75; + EXPECT_EQ(saturated::AverageScalar(a, b), 114.5f); + a = 0x85; + b = 0x8A; + EXPECT_EQ(saturated::AverageScalar(a, b), -120.5f); + } + { + int16_t a = 0x8001; + int16_t b = 0x7FFF; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.0f); + a = 0x8000; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.5f); + a = 0x7000; + b = 0x7005; + EXPECT_EQ(saturated::AverageScalar(a, b), 28674.5f); + a = 0x8005; + b = 0x800A; + EXPECT_EQ(saturated::AverageScalar(a, b), -32760.5f); + } + { + int32_t a = 0x80000001; + int32_t b = 0x7FFFFFFF; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.0f); + a = 0x80000000; + EXPECT_EQ(saturated::AverageScalar(a, b), -0.5f); + a = 0x70000000; + b = 0x70000005; + EXPECT_EQ(saturated::AverageScalar(a, b), 1879048195.5f); + a = 0x80000005; + b = 0x8000000A; + EXPECT_EQ(saturated::AverageScalar(a, b), -2147483655.5f); + } + { + int64_t a = 0x8000000000000001; + int64_t b = 0x7FFFFFFFFFFFFFFF; + EXPECT_EQ(saturated::AverageScalar(a, b), 0.0f); + // 64-bit integers overflow the ability of a Scalar (float) to + // represent discrete integers and so the two numbers we are + // averaging here will look like the same number with different + // signs and the answer will be "0" + a = 0x8000000000000000; + EXPECT_EQ(saturated::AverageScalar(a, b), 0.0f); + a = 0x7000000000000000; + b = 0x7000000000000005; + EXPECT_NEAR(saturated::AverageScalar(a, b), 8.0704505e+18, 1e18); + a = 0x8000000000000005; + b = 0x800000000000000A; + EXPECT_NEAR(saturated::AverageScalar(a, b), -9.223372e+18, 1e18); + } +} + +TEST(SaturatedMath, ExplicitAverageScalarOfFloatingPoint) { + const Scalar s_inf = std::numeric_limits::infinity(); + const Scalar s_max = std::numeric_limits::max(); + const Scalar s_big = s_max * 0.5f; + + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::AverageScalar(big, big), s_big); + EXPECT_EQ(saturated::AverageScalar(max, max), s_max); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_max); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -inf))); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5; + + // Most of the averages below using the double constants will + // overflow the Scalar return value and result in infinity, + // so we also test with some Scalar constants (promoted to double) + // to verify that they don't overflow in the double template + EXPECT_EQ(saturated::AverageScalar(s_big, s_big), s_big); + EXPECT_EQ(saturated::AverageScalar(s_max, s_max), s_max); + EXPECT_EQ(saturated::AverageScalar(-s_big, -s_big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-s_max, -s_max), -s_max); + + // And now testing continues with the double constants which + // mostly overflow + EXPECT_EQ(saturated::AverageScalar(big, big), s_inf); + EXPECT_EQ(saturated::AverageScalar(max, max), s_inf); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_inf); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_inf); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -inf))); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::AverageScalar(big, big), s_big); + EXPECT_EQ(saturated::AverageScalar(max, max), s_max); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_max); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, s_inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -s_inf))); + } +} + +TEST(SaturatedMath, ImplicitAverageScalarOfFloatingPoint) { + // All return values are Scalar regardless of the operand types + // so these constants are used as the expected answers. + const Scalar s_inf = std::numeric_limits::infinity(); + const Scalar s_max = std::numeric_limits::max(); + const Scalar s_big = s_max * 0.5f; + + { + const float inf = std::numeric_limits::infinity(); + const float max = std::numeric_limits::max(); + const float big = max * 0.5f; + + EXPECT_EQ(saturated::AverageScalar(big, big), s_big); + EXPECT_EQ(saturated::AverageScalar(max, max), s_max); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_max); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -inf))); + } + { + const double inf = std::numeric_limits::infinity(); + const double max = std::numeric_limits::max(); + const double big = max * 0.5; + + // The s_constants converted to double. We should get finite results + // from finding the averages of these values, but we'll get a lot of + // overflow to infinity when testing the large double constants. + const double d_s_max = s_max; + const double d_s_big = s_big; + EXPECT_EQ(saturated::AverageScalar(d_s_big, d_s_big), s_big); + EXPECT_EQ(saturated::AverageScalar(d_s_max, d_s_max), s_max); + EXPECT_EQ(saturated::AverageScalar(-d_s_big, -d_s_big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-d_s_max, -d_s_max), -s_max); + + // And now testing continues with the double constants which + // mostly overflow + EXPECT_EQ(saturated::AverageScalar(big, big), s_inf); + EXPECT_EQ(saturated::AverageScalar(max, max), s_inf); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_inf); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_inf); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -inf))); + } + { + const Scalar inf = std::numeric_limits::infinity(); + const Scalar max = std::numeric_limits::max(); + const Scalar big = max * 0.5f; + + EXPECT_EQ(saturated::AverageScalar(big, big), s_big); + EXPECT_EQ(saturated::AverageScalar(max, max), s_max); + EXPECT_EQ(saturated::AverageScalar(big, -big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(max, -max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, big), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-max, max), 0.0f); + EXPECT_EQ(saturated::AverageScalar(-big, -big), -s_big); + EXPECT_EQ(saturated::AverageScalar(-max, -max), -s_max); + + EXPECT_EQ(saturated::AverageScalar(inf, inf), s_inf); + EXPECT_EQ(saturated::AverageScalar(-inf, -inf), -s_inf); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(-inf, s_inf))); + EXPECT_TRUE(std::isnan(saturated::AverageScalar(inf, -s_inf))); + } +} + +TEST(SaturatedMath, CastingFiniteDoubleToFloatStaysFinite) { + const double d_max = std::numeric_limits::max(); + const float f_max = std::numeric_limits::max(); + + { + const float result = saturated::Cast(d_max); + EXPECT_EQ(result, f_max); + } + + { + const float result = saturated::Cast(-d_max); + EXPECT_EQ(result, -f_max); + } +} + +TEST(SaturatedMath, CastingInfiniteDoubleToFloatStaysInfinite) { + const double d_inf = std::numeric_limits::infinity(); + const float f_max = std::numeric_limits::infinity(); + + { + const float result = saturated::Cast(d_inf); + EXPECT_EQ(result, f_max); + } + + { + const float result = saturated::Cast(-d_inf); + EXPECT_EQ(result, -f_max); + } +} + +TEST(SaturatedMath, CastingNaNDoubleToFloatStaysNaN) { + const double d_nan = std::numeric_limits::quiet_NaN(); + + { + const float result = saturated::Cast(d_nan); + EXPECT_TRUE(std::isnan(result)); + } + + { + const float result = saturated::Cast(-d_nan); + EXPECT_TRUE(std::isnan(result)); + } +} + +TEST(SaturatedMath, CastingLargeScalarToSignedIntProducesLimit) { + // larger than even any [u]int64_t; + const Scalar large = 1e20f; + + { + const auto result = saturated::Cast(large); + EXPECT_EQ(result, int8_t(0x7F)); + } + { + const auto result = saturated::Cast(-large); + EXPECT_EQ(result, int8_t(0x80)); + } + + { + const auto result = saturated::Cast(large); + EXPECT_EQ(result, int16_t(0x7FFF)); + } + { + const auto result = saturated::Cast(-large); + EXPECT_EQ(result, int16_t(0x8000)); + } + + { + const auto result = saturated::Cast(large); + EXPECT_EQ(result, int32_t(0x7FFFFFFF)); + } + { + const auto result = saturated::Cast(-large); + EXPECT_EQ(result, int32_t(0x80000000)); + } + + { + const auto result = saturated::Cast(large); + EXPECT_EQ(result, int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + const auto result = saturated::Cast(-large); + EXPECT_EQ(result, int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, CastingInfiniteScalarToSignedIntProducesLimit) { + // larger than even any [u]int64_t; + const Scalar inf = std::numeric_limits::infinity(); + + { + const auto result = saturated::Cast(inf); + EXPECT_EQ(result, int8_t(0x7F)); + } + { + const auto result = saturated::Cast(-inf); + EXPECT_EQ(result, int8_t(0x80)); + } + + { + const auto result = saturated::Cast(inf); + EXPECT_EQ(result, int16_t(0x7FFF)); + } + { + const auto result = saturated::Cast(-inf); + EXPECT_EQ(result, int16_t(0x8000)); + } + + { + const auto result = saturated::Cast(inf); + EXPECT_EQ(result, int32_t(0x7FFFFFFF)); + } + { + const auto result = saturated::Cast(-inf); + EXPECT_EQ(result, int32_t(0x80000000)); + } + + { + const auto result = saturated::Cast(inf); + EXPECT_EQ(result, int64_t(0x7FFFFFFFFFFFFFFF)); + } + { + const auto result = saturated::Cast(-inf); + EXPECT_EQ(result, int64_t(0x8000000000000000)); + } +} + +TEST(SaturatedMath, CastingNaNScalarToSignedIntProducesZero) { + // larger than even any [u]int64_t; + const Scalar nan = std::numeric_limits::quiet_NaN(); + + { + const auto result = saturated::Cast(nan); + EXPECT_EQ(result, int8_t(0)); + } + + { + const auto result = saturated::Cast(nan); + EXPECT_EQ(result, int16_t(0)); + } + + { + const auto result = saturated::Cast(nan); + EXPECT_EQ(result, int32_t(0)); + } + + { + const auto result = saturated::Cast(nan); + EXPECT_EQ(result, int64_t(0)); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/scalar.h b/flutter/engine/src/flutter/impeller/geometry/scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..dadc52850cb5f6faf66d926c57ecc3f286eb4723 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/scalar.h @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SCALAR_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SCALAR_H_ + +#include +#include +#include + +#include "impeller/geometry/constants.h" + +namespace impeller { + +// NOLINTBEGIN(google-explicit-constructor) + +using Scalar = float; + +template >> +constexpr T Absolute(const T& val) { + return val >= T{} ? val : -val; +} + +template <> +constexpr Scalar Absolute(const float& val) { + return fabsf(val); +} + +constexpr inline bool ScalarNearlyZero(Scalar x, + Scalar tolerance = kEhCloseEnough) { + return Absolute(x) <= tolerance; +} + +constexpr inline bool ScalarNearlyEqual(Scalar x, + Scalar y, + Scalar tolerance = kEhCloseEnough) { + return ScalarNearlyZero(x - y, tolerance); +} + +struct Degrees; + +struct Radians { + Scalar radians = 0.0; + + constexpr Radians() = default; + + explicit constexpr Radians(Scalar p_radians) : radians(p_radians) {} +}; + +struct Degrees { + Scalar degrees = 0.0; + + constexpr Degrees() = default; + + explicit constexpr Degrees(Scalar p_degrees) : degrees(p_degrees) {} + + constexpr operator Radians() const { + return Radians{degrees * kPi / 180.0f}; + }; +}; + +// NOLINTEND(google-explicit-constructor) + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_SCALAR_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/separated_vector.cc b/flutter/engine/src/flutter/impeller/geometry/separated_vector.cc new file mode 100644 index 0000000000000000000000000000000000000000..dbf0da62ced36d318d7545609700b6f0dc2ec181 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/separated_vector.cc @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "separated_vector.h" + +namespace impeller { + +SeparatedVector2::SeparatedVector2() = default; + +SeparatedVector2::SeparatedVector2(Vector2 direction, Scalar magnitude) + : direction(direction), magnitude(magnitude){}; + +SeparatedVector2::SeparatedVector2(Vector2 vector) + : direction(vector.Normalize()), magnitude(vector.GetLength()){}; + +Vector2 SeparatedVector2::GetVector() const { + return direction * magnitude; +} + +Scalar SeparatedVector2::GetAlignment(const SeparatedVector2& other) const { + return direction.Dot(other.direction); +} + +Radians SeparatedVector2::AngleTo(const SeparatedVector2& other) const { + return direction.AngleTo(other.direction); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/separated_vector.h b/flutter/engine/src/flutter/impeller/geometry/separated_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..304029d2d6aa0984f23dfa2e860c53181ac31117 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/separated_vector.h @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SEPARATED_VECTOR_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SEPARATED_VECTOR_H_ + +#include "impeller/geometry/point.h" + +#include "impeller/geometry/scalar.h" + +namespace impeller { + +/// @brief A Vector2, broken down as a separate magnitude and direction. +/// Assumes that the direction given is normalized. +/// +/// This is a simple convenience struct for handling polyline offset +/// values when generating stroke geometry. For performance reasons, +/// it's sometimes adventageous to track the direction and magnitude +/// for offsets separately. +struct SeparatedVector2 { + /// The normalized direction of the vector. + Vector2 direction; + + /// The magnitude of the vector. + Scalar magnitude = 0.0; + + SeparatedVector2(); + SeparatedVector2(Vector2 direction, Scalar magnitude); + explicit SeparatedVector2(Vector2 vector); + + /// Returns the vector representation of the vector. + Vector2 GetVector() const; + + /// Returns the scalar alignment of the two vectors. + /// In other words, the dot product of the two normalized vectors. + /// + /// Range: [-1, 1] + /// A value of 1 indicates the directions are parallel and pointing in the + /// same direction. A value of -1 indicates the vectors are parallel and + /// pointing in opposite directions. A value of 0 indicates the vectors are + /// perpendicular. + Scalar GetAlignment(const SeparatedVector2& other) const; + + /// Returns the scalar angle between the two rays. + Radians AngleTo(const SeparatedVector2& other) const; +}; + +#endif // FLUTTER_IMPELLER_GEOMETRY_SEPARATED_VECTOR_H_ + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/shear.cc b/flutter/engine/src/flutter/impeller/geometry/shear.cc new file mode 100644 index 0000000000000000000000000000000000000000..34986a9d787ce7a60cfc8c58e75f2ee3951685c3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/shear.cc @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "shear.h" +#include + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/shear.h b/flutter/engine/src/flutter/impeller/geometry/shear.h new file mode 100644 index 0000000000000000000000000000000000000000..c94e26e5f0cb53991805970bc48c965cc253de67 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/shear.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_ + +#include + +namespace impeller { + +struct Shear { + union { + struct { + double xy = 0.0; + double xz = 0.0; + double yz = 0.0; + }; + double e[3]; + }; + + Shear() {} + + Shear(double xy, double xz, double yz) : xy(xy), xz(xz), yz(yz) {} + + bool operator==(const Shear& o) const { + return xy == o.xy && xz == o.xz && yz == o.yz; + } + + bool operator!=(const Shear& o) const { return !(*this == o); } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_SHEAR_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/sigma.cc b/flutter/engine/src/flutter/impeller/geometry/sigma.cc new file mode 100644 index 0000000000000000000000000000000000000000..a73bcd7cea8bd7b8380ea83a603c7c1733c2597a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/sigma.cc @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/sigma.h" + +#include + +namespace impeller { + +Sigma::operator Radius() const { + return Radius{sigma > 0.5f ? (sigma - 0.5f) * kKernelRadiusPerSigma : 0.0f}; +} + +Radius::operator Sigma() const { + return Sigma{radius > 0 ? radius / kKernelRadiusPerSigma + 0.5f : 0.0f}; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/sigma.h b/flutter/engine/src/flutter/impeller/geometry/sigma.h new file mode 100644 index 0000000000000000000000000000000000000000..93c43ee135a3404ba47cf1e43e90e6b35bc111f9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/sigma.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SIGMA_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SIGMA_H_ + +#include "impeller/geometry/scalar.h" + +namespace impeller { + +/// For filters that use a Gaussian distribution, this is the `Radius` size to +/// use per `Sigma` (standard deviation). +/// +/// This cutoff (sqrt(3)) is taken from Flutter and Skia (where the +/// multiplicative inverse of this constant is used (1 / sqrt(3)): +/// https://api.flutter.dev/flutter/dart-ui/Shadow/convertRadiusToSigma.html +/// +/// In practice, this value is somewhat arbitrary, and can be changed to a +/// higher number to integrate more of the Gaussian function and render higher +/// quality blurs (with exponentially diminishing returns for the same sigma +/// input). Making this value any lower results in a noticable loss of +/// quality in the blur. +constexpr static float kKernelRadiusPerSigma = 1.73205080757f; + +struct Radius; + +/// @brief In filters that use Gaussian distributions, "sigma" is a size of +/// one standard deviation in terms of the local space pixel grid of +/// the filter input. In other words, this determines how wide the +/// distribution stretches. +struct Sigma { + Scalar sigma = 0.0; + + constexpr Sigma() = default; + + explicit constexpr Sigma(Scalar p_sigma) : sigma(p_sigma) {} + + operator Radius() const; // NOLINT(google-explicit-constructor) +}; + +/// @brief For convolution filters, the "radius" is the size of the +/// convolution kernel to use on the local space pixel grid of the +/// filter input. +/// For Gaussian blur kernels, this unit has a linear +/// relationship with `Sigma`. See `kKernelRadiusPerSigma` for +/// details on how this relationship works. +struct Radius { + Scalar radius = 0.0; + + constexpr Radius() = default; + + explicit constexpr Radius(Scalar p_radius) : radius(p_radius) {} + + operator Sigma() const; // NOLINT(google-explicit-constructor) +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_SIGMA_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/size.cc b/flutter/engine/src/flutter/impeller/geometry/size.cc new file mode 100644 index 0000000000000000000000000000000000000000..77460b7ce431f364381521c1db0161dd74e9e2ae --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/size.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "size.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/size.h b/flutter/engine/src/flutter/impeller/geometry/size.h new file mode 100644 index 0000000000000000000000000000000000000000..de2ade7524e7c434cbb35dff39238402c1b8feba --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/size.h @@ -0,0 +1,179 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_SIZE_H_ +#define FLUTTER_IMPELLER_GEOMETRY_SIZE_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/geometry/scalar.h" + +namespace impeller { + +#define ONLY_ON_FLOAT_M(Modifiers, Return) \ + template \ + Modifiers std::enable_if_t, Return> +#define ONLY_ON_FLOAT(Return) DL_ONLY_ON_FLOAT_M(, Return) + +template +struct TSize { + using Type = T; + + Type width = {}; + Type height = {}; + + constexpr TSize() {} + + constexpr TSize(Type width, Type height) : width(width), height(height) {} + + constexpr explicit TSize(Type dimension) + : width(dimension), height(dimension) {} + + template + explicit constexpr TSize(const TSize& other) + : TSize(static_cast(other.width), static_cast(other.height)) { + } + + static constexpr TSize MakeWH(Type width, Type height) { + return TSize{width, height}; + } + + static constexpr TSize Infinite() { + return TSize{std::numeric_limits::max(), + std::numeric_limits::max()}; + } + + constexpr TSize operator*(Scalar scale) const { + return {width * scale, height * scale}; + } + + template >> + inline TSize operator*=(U scale) { + width *= static_cast(scale); + height *= static_cast(scale); + return *this; + } + + constexpr TSize operator/(Scalar scale) const { + return {static_cast(width) / scale, + static_cast(height) / scale}; + } + + constexpr TSize operator/(const TSize& s) const { + return {width / s.width, height / s.height}; + } + + constexpr bool operator==(const TSize& s) const { + return s.width == width && s.height == height; + } + + constexpr bool operator!=(const TSize& s) const { + return s.width != width || s.height != height; + } + + constexpr TSize operator+(const TSize& s) const { + return {width + s.width, height + s.height}; + } + + constexpr TSize operator-(const TSize& s) const { + return {width - s.width, height - s.height}; + } + + constexpr TSize operator-() const { return {-width, -height}; } + + constexpr TSize Min(const TSize& o) const { + return { + std::min(width, o.width), + std::min(height, o.height), + }; + } + + constexpr TSize Max(const TSize& o) const { + return { + std::max(width, o.width), + std::max(height, o.height), + }; + } + + constexpr Type MinDimension() const { return std::min(width, height); } + + constexpr Type MaxDimension() const { return std::max(width, height); } + + constexpr TSize Abs() const { return {std::fabs(width), std::fabs(height)}; } + + constexpr TSize Floor() const { + return {std::floor(width), std::floor(height)}; + } + + constexpr TSize Ceil() const { return {std::ceil(width), std::ceil(height)}; } + + constexpr TSize Round() const { + return {std::round(width), std::round(height)}; + } + + constexpr Type Area() const { return width * height; } + + /// Returns true if either of the width or height are 0, negative, or NaN. + constexpr bool IsEmpty() const { return !(width > 0 && height > 0); } + + ONLY_ON_FLOAT_M(constexpr, bool) + IsFinite() const { return std::isfinite(width) && std::isfinite(height); } + + constexpr bool IsSquare() const { return width == height; } + + template + static constexpr TSize Ceil(const TSize& other) { + return TSize{static_cast(std::ceil(other.width)), + static_cast(std::ceil(other.height))}; + } + + /// Return the mip count of the texture. + constexpr size_t MipCount() const { + constexpr size_t minimum_mip = 1u; + if (IsEmpty() || width <= 0 || height <= 0) { + return minimum_mip; + } + size_t result = std::min(log2(width), log2(height)); + return std::max(result, minimum_mip); + } +}; + +// RHS algebraic operations with arithmetic types. + +template >> +constexpr TSize operator*(U s, const TSize& p) { + return p * s; +} + +template >> +constexpr TSize operator/(U s, const TSize& p) { + return {static_cast(s) / p.width, static_cast(s) / p.height}; +} + +using Size = TSize; +using ISize32 = TSize; +using ISize64 = TSize; +using ISize = ISize64; + +static_assert(sizeof(Size) == 2 * sizeof(Scalar)); + +} // namespace impeller + +namespace std { + +template +inline std::ostream& operator<<(std::ostream& out, + const impeller::TSize& s) { + out << "(" << s.width << ", " << s.height << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_SIZE_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/size_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/size_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c1a65eebc00e82fd3438227798083102b8cfacf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/size_unittests.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/size.h" + +namespace impeller { +namespace testing { + +TEST(SizeTest, SizeIsEmpty) { + auto nan = std::numeric_limits::quiet_NaN(); + + // Non-empty + EXPECT_FALSE(Size(10.5, 7.2).IsEmpty()); + + // Empty both width and height both 0 or negative, in all combinations + EXPECT_TRUE(Size(0.0, 0.0).IsEmpty()); + EXPECT_TRUE(Size(-1.0, -1.0).IsEmpty()); + EXPECT_TRUE(Size(-1.0, 0.0).IsEmpty()); + EXPECT_TRUE(Size(0.0, -1.0).IsEmpty()); + + // Empty for 0 or negative width or height (but not both at the same time) + EXPECT_TRUE(Size(10.5, 0.0).IsEmpty()); + EXPECT_TRUE(Size(10.5, -1.0).IsEmpty()); + EXPECT_TRUE(Size(0.0, 7.2).IsEmpty()); + EXPECT_TRUE(Size(-1.0, 7.2).IsEmpty()); + + // Empty for NaN in width or height or both + EXPECT_TRUE(Size(10.5, nan).IsEmpty()); + EXPECT_TRUE(Size(nan, 7.2).IsEmpty()); + EXPECT_TRUE(Size(nan, nan).IsEmpty()); +} + +TEST(SizeTest, ISizeIsEmpty) { + // Non-empty + EXPECT_FALSE(ISize(10, 7).IsEmpty()); + + // Empty both width and height both 0 or negative, in all combinations + EXPECT_TRUE(ISize(0, 0).IsEmpty()); + EXPECT_TRUE(ISize(-1, -1).IsEmpty()); + EXPECT_TRUE(ISize(-1, 0).IsEmpty()); + EXPECT_TRUE(ISize(0, -1).IsEmpty()); + + // Empty for 0 or negative width or height (but not both at the same time) + EXPECT_TRUE(ISize(10, 0).IsEmpty()); + EXPECT_TRUE(ISize(10, -1).IsEmpty()); + EXPECT_TRUE(ISize(0, 7).IsEmpty()); + EXPECT_TRUE(ISize(-1, 7).IsEmpty()); +} + +TEST(SizeTest, IsSquare) { + EXPECT_TRUE(Size(20, 20).IsSquare()); + EXPECT_FALSE(Size(20, 19).IsSquare()); + EXPECT_FALSE(Size(19, 20).IsSquare()); + + EXPECT_TRUE(ISize(20, 20).IsSquare()); + EXPECT_FALSE(ISize(20, 19).IsSquare()); + EXPECT_FALSE(ISize(19, 20).IsSquare()); +} + +TEST(SizeTest, MaxDimension) { + EXPECT_EQ(Size(20, 20).MaxDimension(), 20); + EXPECT_EQ(Size(20, 19).MaxDimension(), 20); + EXPECT_EQ(Size(19, 20).MaxDimension(), 20); + EXPECT_EQ(Size(20, 21).MaxDimension(), 21); + EXPECT_EQ(Size(21, 20).MaxDimension(), 21); + + EXPECT_EQ(ISize(20, 20).MaxDimension(), 20); + EXPECT_EQ(ISize(20, 19).MaxDimension(), 20); + EXPECT_EQ(ISize(19, 20).MaxDimension(), 20); + EXPECT_EQ(ISize(20, 21).MaxDimension(), 21); + EXPECT_EQ(ISize(21, 20).MaxDimension(), 21); +} + +TEST(SizeTest, NegationOperator) { + EXPECT_EQ(-Size(10, 20), Size(-10, -20)); + EXPECT_EQ(-Size(-10, 20), Size(10, -20)); + EXPECT_EQ(-Size(10, -20), Size(-10, 20)); + EXPECT_EQ(-Size(-10, -20), Size(10, 20)); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/trig.cc b/flutter/engine/src/flutter/impeller/geometry/trig.cc new file mode 100644 index 0000000000000000000000000000000000000000..c613a7b5c96201dbe29a2b841975709cc2947626 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/trig.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "trig.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/trig.h b/flutter/engine/src/flutter/impeller/geometry/trig.h new file mode 100644 index 0000000000000000000000000000000000000000..da43375744f7795e3eda92c00147ec9223b5e336 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/trig.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_TRIG_H_ +#define FLUTTER_IMPELLER_GEOMETRY_TRIG_H_ + +#include +#include + +#include "flutter/impeller/geometry/point.h" + +namespace impeller { + +/// @brief A structure to store the sine and cosine of an angle. +struct Trig { + /// Construct a Trig object from a given angle in radians. + explicit Trig(Radians r) + : cos(std::cos(r.radians)), sin(std::sin(r.radians)) {} + + /// Construct a Trig object from the given cosine and sine values. + Trig(double cos, double sin) : cos(cos), sin(sin) {} + + double cos; + double sin; + + /// @brief Returns the corresponding point on a circle of a given |radius|. + Vector2 operator*(double radius) const { + return Vector2(static_cast(cos * radius), + static_cast(sin * radius)); + } + + /// @brief Returns the corresponding point on an ellipse with the given size. + Vector2 operator*(const Size& ellipse_radii) const { + return Vector2(static_cast(cos * ellipse_radii.width), + static_cast(sin * ellipse_radii.height)); + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_TRIG_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/trig_unittests.cc b/flutter/engine/src/flutter/impeller/geometry/trig_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff15c974b5e0bfa70aa2fa32992433a0a4a2d2de --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/trig_unittests.cc @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "fml/logging.h" +#include "gtest/gtest.h" + +#include "flutter/impeller/geometry/trig.h" + +namespace impeller { +namespace testing { + +TEST(TrigTest, TrigAngles) { + { + Trig trig(Degrees(0.0)); + EXPECT_EQ(trig.cos, 1.0); + EXPECT_EQ(trig.sin, 0.0); + } + + { + Trig trig(Radians(0.0)); + EXPECT_EQ(trig.cos, 1.0); + EXPECT_EQ(trig.sin, 0.0); + } + + { + Trig trig(Degrees(30.0)); + EXPECT_NEAR(trig.cos, sqrt(0.75), kEhCloseEnough); + EXPECT_NEAR(trig.sin, 0.5, kEhCloseEnough); + } + + { + Trig trig(Radians(kPi / 6.0)); + EXPECT_NEAR(trig.cos, sqrt(0.75), kEhCloseEnough); + EXPECT_NEAR(trig.sin, 0.5, kEhCloseEnough); + } + + { + Trig trig(Degrees(60.0)); + EXPECT_NEAR(trig.cos, 0.5, kEhCloseEnough); + EXPECT_NEAR(trig.sin, sqrt(0.75), kEhCloseEnough); + } + + { + Trig trig(Radians(kPi / 3.0)); + EXPECT_NEAR(trig.cos, 0.5, kEhCloseEnough); + EXPECT_NEAR(trig.sin, sqrt(0.75), kEhCloseEnough); + } + + { + Trig trig(Degrees(90.0)); + EXPECT_NEAR(trig.cos, 0.0, kEhCloseEnough); + EXPECT_NEAR(trig.sin, 1.0, kEhCloseEnough); + } + + { + Trig trig(Radians(kPi / 2.0)); + EXPECT_NEAR(trig.cos, 0.0, kEhCloseEnough); + EXPECT_NEAR(trig.sin, 1.0, kEhCloseEnough); + } +} + +TEST(TrigTest, MultiplyByScalarRadius) { + for (int i = 0; i <= 360; i++) { + for (int i = 1; i <= 10; i++) { + Scalar radius = i * 5.0f; + EXPECT_EQ(Trig(Degrees(i)) * radius, + Point(radius * std::cos(i * kPi / 180), + radius * std::sin(i * kPi / 180))) + << "at " << i << " degrees and radius " << radius; + } + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/type_traits.cc b/flutter/engine/src/flutter/impeller/geometry/type_traits.cc new file mode 100644 index 0000000000000000000000000000000000000000..84aea9a9330b086e693f0119a093810b2fc3aa02 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/type_traits.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "type_traits.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/type_traits.h b/flutter/engine/src/flutter/impeller/geometry/type_traits.h new file mode 100644 index 0000000000000000000000000000000000000000..7fc0ac436040d8064e241cc8268adb6ccee7b7ee --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/type_traits.h @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_TYPE_TRAITS_H_ +#define FLUTTER_IMPELLER_GEOMETRY_TYPE_TRAITS_H_ + +#include + +namespace impeller { + +template && + std::is_integral_v>> +struct MixedOp_ : public std::true_type {}; + +template +using MixedOp = typename MixedOp_::type; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_TYPE_TRAITS_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/vector.cc b/flutter/engine/src/flutter/impeller/geometry/vector.cc new file mode 100644 index 0000000000000000000000000000000000000000..fecc8476d3f3f34d02cee9b0a2d727b17f9da5db --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/vector.cc @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "vector.h" +#include + +namespace impeller { + +std::string Vector3::ToString() const { + std::stringstream stream; + stream << "{" << x << ", " << y << ", " << z << "}"; + return stream.str(); +} + +std::string Vector4::ToString() const { + std::stringstream stream; + stream << "{" << x << ", " << y << ", " << z << ", " << w << "}"; + return stream.str(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/vector.h b/flutter/engine/src/flutter/impeller/geometry/vector.h new file mode 100644 index 0000000000000000000000000000000000000000..0f1c4dc10681e2e887cd308833579c6ca472ba48 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/vector.h @@ -0,0 +1,344 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_VECTOR_H_ +#define FLUTTER_IMPELLER_GEOMETRY_VECTOR_H_ + +#include +#include + +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +// NOLINTBEGIN(google-explicit-constructor) + +struct Vector3 { + union { + struct { + Scalar x = 0.0f; + Scalar y = 0.0f; + Scalar z = 0.0f; + }; + Scalar e[3]; + }; + + constexpr Vector3(){}; + + constexpr Vector3(const Color& c) : x(c.red), y(c.green), z(c.blue) {} + + constexpr Vector3(const Point& p) : x(p.x), y(p.y) {} + + constexpr Vector3(const Size& s) : x(s.width), y(s.height) {} + + constexpr Vector3(Scalar x, Scalar y) : x(x), y(y) {} + + constexpr Vector3(Scalar x, Scalar y, Scalar z) : x(x), y(y), z(z) {} + + /** + * The length (or magnitude of the vector). + * + * @return the calculated length. + */ + constexpr Scalar GetLength() const { return sqrt(x * x + y * y + z * z); } + + constexpr Vector3 Normalize() const { + const auto len = GetLength(); + return {x / len, y / len, z / len}; + } + + constexpr Scalar Dot(const Vector3& other) const { + return ((x * other.x) + (y * other.y) + (z * other.z)); + } + + constexpr Vector3 Abs() const { + return {std::fabs(x), std::fabs(y), std::fabs(z)}; + } + + constexpr Vector3 Cross(const Vector3& other) const { + return { + (y * other.z) - (z * other.y), // + (z * other.x) - (x * other.z), // + (x * other.y) - (y * other.x) // + }; + } + + constexpr Vector3 Min(const Vector3& p) const { + return {std::min(x, p.x), std::min(y, p.y), std::min(z, p.z)}; + } + + constexpr Vector3 Max(const Vector3& p) const { + return {std::max(x, p.x), std::max(y, p.y), std::max(z, p.z)}; + } + + constexpr Vector3 Floor() const { + return {std::floor(x), std::floor(y), std::floor(z)}; + } + + constexpr Vector3 Ceil() const { + return {std::ceil(x), std::ceil(y), std::ceil(z)}; + } + + constexpr Vector3 Round() const { + return {std::round(x), std::round(y), std::round(z)}; + } + + constexpr bool operator==(const Vector3& v) const { + return v.x == x && v.y == y && v.z == z; + } + + constexpr bool operator!=(const Vector3& v) const { + return v.x != x || v.y != y || v.z != z; + } + + constexpr Vector3 operator+=(const Vector3& p) { + x += p.x; + y += p.y; + z += p.z; + return *this; + } + + constexpr Vector3 operator-=(const Vector3& p) { + x -= p.x; + y -= p.y; + z -= p.z; + return *this; + } + + constexpr Vector3 operator*=(const Vector3& p) { + x *= p.x; + y *= p.y; + z *= p.z; + return *this; + } + + template >> + constexpr Vector3 operator*=(U scale) { + x *= scale; + y *= scale; + z *= scale; + return *this; + } + + constexpr Vector3 operator/=(const Vector3& p) { + x /= p.x; + y /= p.y; + z /= p.z; + return *this; + } + + template >> + constexpr Vector3 operator/=(U scale) { + x /= scale; + y /= scale; + z /= scale; + return *this; + } + + constexpr Vector3 operator-() const { return Vector3(-x, -y, -z); } + + constexpr Vector3 operator+(const Vector3& v) const { + return Vector3(x + v.x, y + v.y, z + v.z); + } + + constexpr Vector3 operator-(const Vector3& v) const { + return Vector3(x - v.x, y - v.y, z - v.z); + } + + constexpr Vector3 operator+(Scalar s) const { + return Vector3(x + s, y + s, z + s); + } + + constexpr Vector3 operator-(Scalar s) const { + return Vector3(x - s, y - s, z - s); + } + + constexpr Vector3 operator*(const Vector3& v) const { + return Vector3(x * v.x, y * v.y, z * v.z); + } + + template >> + constexpr Vector3 operator*(U scale) const { + return Vector3(x * scale, y * scale, z * scale); + } + + constexpr Vector3 operator/(const Vector3& v) const { + return Vector3(x / v.x, y / v.y, z / v.z); + } + + template >> + constexpr Vector3 operator/(U scale) const { + return Vector3(x / scale, y / scale, z / scale); + } + + constexpr Vector3 Lerp(const Vector3& v, Scalar t) const { + return *this + (v - *this) * t; + } + + /** + * Make a linear combination of two vectors and return the result. + * + * @param a the first vector. + * @param aScale the scale to use for the first vector. + * @param b the second vector. + * @param bScale the scale to use for the second vector. + * + * @return the combined vector. + */ + static constexpr Vector3 Combine(const Vector3& a, + Scalar aScale, + const Vector3& b, + Scalar bScale) { + return { + aScale * a.x + bScale * b.x, // + aScale * a.y + bScale * b.y, // + aScale * a.z + bScale * b.z, // + }; + } + + std::string ToString() const; +}; + +// RHS algebraic operations with arithmetic types. + +template >> +constexpr Vector3 operator*(U s, const Vector3& p) { + return p * s; +} + +template >> +constexpr Vector3 operator+(U s, const Vector3& p) { + return p + s; +} + +template >> +constexpr Vector3 operator-(U s, const Vector3& p) { + return -p + s; +} + +template >> +constexpr Vector3 operator/(U s, const Vector3& p) { + return { + static_cast(s) / p.x, + static_cast(s) / p.y, + static_cast(s) / p.z, + }; +} + +struct Vector4 { + union { + struct { + Scalar x = 0.0f; + Scalar y = 0.0f; + Scalar z = 0.0f; + Scalar w = 1.0f; + }; + Scalar e[4]; + }; + + constexpr Vector4() {} + + constexpr Vector4(const Color& c) + : x(c.red), y(c.green), z(c.blue), w(c.alpha) {} + + constexpr Vector4(Scalar x, Scalar y, Scalar z, Scalar w) + : x(x), y(y), z(z), w(w) {} + + constexpr Vector4(const Vector3& v) : x(v.x), y(v.y), z(v.z) {} + + constexpr Vector4(const Point& p) : x(p.x), y(p.y) {} + + constexpr Vector4(std::array values) + : x(values[0]), y(values[1]), z(values[2]), w(values[3]) {} + + constexpr bool IsFinite() const { + return std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && + std::isfinite(w); + } + + Vector4 Normalize() const { + const Scalar inverse = 1.0f / sqrt(x * x + y * y + z * z + w * w); + return Vector4(x * inverse, y * inverse, z * inverse, w * inverse); + } + + constexpr bool operator==(const Vector4& v) const { + return (x == v.x) && (y == v.y) && (z == v.z) && (w == v.w); + } + + constexpr bool operator!=(const Vector4& v) const { + return (x != v.x) || (y != v.y) || (z != v.z) || (w != v.w); + } + + constexpr Vector4 operator+(const Vector4& v) const { + return Vector4(x + v.x, y + v.y, z + v.z, w + v.w); + } + + constexpr Vector4 operator-(const Vector4& v) const { + return Vector4(x - v.x, y - v.y, z - v.z, w - v.w); + } + + constexpr Vector4 operator*(Scalar f) const { + return Vector4(x * f, y * f, z * f, w * f); + } + + constexpr Vector4 operator*(const Vector4& v) const { + return Vector4(x * v.x, y * v.y, z * v.z, w * v.w); + } + + constexpr Vector4 Min(const Vector4& p) const { + return {std::min(x, p.x), std::min(y, p.y), std::min(z, p.z), + std::min(w, p.w)}; + } + + constexpr Vector4 Max(const Vector4& p) const { + return {std::max(x, p.x), std::max(y, p.y), std::max(z, p.z), + std::max(w, p.w)}; + } + + constexpr Vector4 Floor() const { + return {std::floor(x), std::floor(y), std::floor(z), std::floor(w)}; + } + + constexpr Vector4 Ceil() const { + return {std::ceil(x), std::ceil(y), std::ceil(z), std::ceil(w)}; + } + + constexpr Vector4 Round() const { + return {std::round(x), std::round(y), std::round(z), std::round(w)}; + } + + constexpr Vector4 Lerp(const Vector4& v, Scalar t) const { + return *this + (v - *this) * t; + } + + constexpr Vector2 xy() const { return Vector2(x, y); } + + std::string ToString() const; +}; + +static_assert(sizeof(Vector3) == 3 * sizeof(Scalar)); +static_assert(sizeof(Vector4) == 4 * sizeof(Scalar)); + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, const impeller::Vector3& p) { + out << "(" << p.x << ", " << p.y << ", " << p.z << ")"; + return out; +} + +inline std::ostream& operator<<(std::ostream& out, const impeller::Vector4& p) { + out << "(" << p.x << ", " << p.y << ", " << p.z << ", " << p.w << ")"; + return out; +} + +// NOLINTEND(google-explicit-constructor) + +} // namespace std + +#endif // FLUTTER_IMPELLER_GEOMETRY_VECTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/geometry/wangs_formula.cc b/flutter/engine/src/flutter/impeller/geometry/wangs_formula.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5b775c22a81c328b17597ab892f5a0934408b0e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/wangs_formula.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/geometry/wangs_formula.h" + +namespace impeller { + +namespace { + +// Don't allow linearized segments to be off by more than 1/4th of a pixel from +// the true curve. This value should be scaled by the max basis of the +// X and Y directions. +constexpr static Scalar kPrecision = 4; + +constexpr Scalar length(Point n) { + Point nn = n * n; + return std::sqrt(nn.x + nn.y); +} + +} // namespace + +Scalar ComputeCubicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2, + Point p3) { + Scalar k = scale_factor * .75f * kPrecision; + Point a = (p0 - p1 * 2 + p2).Abs(); + Point b = (p1 - p2 * 2 + p3).Abs(); + return std::sqrt(k * length(a.Max(b))); +} + +Scalar ComputeQuadradicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2) { + Scalar k = scale_factor * .25f * kPrecision; + return std::sqrt(k * length(p0 - p1 * 2 + p2)); +} + +// Returns Wang's formula specialized for a conic curve. +// +// This is not actually due to Wang, but is an analogue from: +// (Theorem 3, corollary 1): +// J. Zheng, T. Sederberg. "Estimating Tessellation Parameter Intervals for +// Rational Curves and Surfaces." ACM Transactions on Graphics 19(1). 2000. +Scalar ComputeConicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2, + Scalar w) { + // Compute center of bounding box in projected space + const Point C = 0.5f * (p0.Min(p1).Min(p2) + p0.Max(p1).Max(p2)); + + // Translate by -C. This improves translation-invariance of the formula, + // see Sec. 3.3 of cited paper + p0 -= C; + p1 -= C; + p2 -= C; + + // Compute max length + const Scalar max_len = + std::sqrt(std::max(p0.Dot(p0), std::max(p1.Dot(p1), p2.Dot(p2)))); + + // Compute forward differences + const Point dp = -2 * w * p1 + p0 + p2; + const Scalar dw = std::abs(-2 * w + 2); + + // Compute numerator and denominator for parametric step size of + // linearization. Here, the epsilon referenced from the cited paper + // is 1/precision. + Scalar k = scale_factor * kPrecision; + const Scalar rp_minus_1 = std::max(0.0f, max_len * k - 1); + const Scalar numer = std::sqrt(dp.Dot(dp)) * k + rp_minus_1 * dw; + const Scalar denom = 4 * std::min(w, 1.0f); + + // Number of segments = sqrt(numer / denom). + // This assumes parametric interval of curve being linearized is + // [t0,t1] = [0, 1]. + // If not, the number of segments is (tmax - tmin) / sqrt(denom / numer). + return std::sqrt(numer / denom); +} + +Scalar ComputeQuadradicSubdivisions(Scalar scale_factor, + const QuadraticPathComponent& quad) { + return ComputeQuadradicSubdivisions(scale_factor, quad.p1, quad.cp, quad.p2); +} + +Scalar ComputeCubicSubdivisions(float scale_factor, + const CubicPathComponent& cub) { + return ComputeCubicSubdivisions(scale_factor, cub.p1, cub.cp1, cub.cp2, + cub.p2); +} + +Scalar ComputeConicSubdivisions(float scale_factor, + const ConicPathComponent& conic) { + return ComputeConicSubdivisions(scale_factor, conic.p1, conic.cp, conic.p2, + conic.weight.x); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/geometry/wangs_formula.h b/flutter/engine/src/flutter/impeller/geometry/wangs_formula.h new file mode 100644 index 0000000000000000000000000000000000000000..907512e6806a2fed62b087a0b8470248b1be0def --- /dev/null +++ b/flutter/engine/src/flutter/impeller/geometry/wangs_formula.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GEOMETRY_WANGS_FORMULA_H_ +#define FLUTTER_IMPELLER_GEOMETRY_WANGS_FORMULA_H_ + +#include "impeller/geometry/path_component.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/scalar.h" + +// Skia GPU Ports + +// Wang's formula gives the minimum number of evenly spaced (in the parametric +// sense) line segments that a bezier curve must be chopped into in order to +// guarantee all lines stay within a distance of "1/precision" pixels from the +// true curve. Its definition for a bezier curve of degree "n" is as follows: +// +// maxLength = max([length(p[i+2] - 2p[i+1] + p[i]) for (0 <= i <= n-2)]) +// numParametricSegments = sqrt(maxLength * precision * n*(n - 1)/8) +// +// (Goldman, Ron. (2003). 5.6.3 Wang's Formula. "Pyramid Algorithms: A Dynamic +// Programming Approach to Curves and Surfaces for Geometric Modeling". Morgan +// Kaufmann Publishers.) +namespace impeller { + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the cubic must be chopped into in order to guarantee all lines +/// stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeCubicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2, + Point p3); + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the quadratic must be chopped into in order to guarantee all +/// lines stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeQuadradicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2); + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the conic must be chopped into in order to guarantee all +/// lines stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeConicSubdivisions(Scalar scale_factor, + Point p0, + Point p1, + Point p2, + Scalar w); + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the quadratic must be chopped into in order to guarantee all +/// lines stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeQuadradicSubdivisions(Scalar scale_factor, + const QuadraticPathComponent& quad); + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the cubic must be chopped into in order to guarantee all lines +/// stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeCubicSubdivisions(float scale_factor, + const CubicPathComponent& cub); + +/// Returns the minimum number of evenly spaced (in the parametric sense) line +/// segments that the conic must be chopped into in order to guarantee all lines +/// stay within a distance of "1/intolerance" pixels from the true curve. +/// +/// The scale_factor should be the max basis XY of the current transform. +Scalar ComputeConicSubdivisions(float scale_factor, + const ConicPathComponent& conic); +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GEOMETRY_WANGS_FORMULA_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/BUILD.gn b/flutter/engine/src/flutter/impeller/golden_tests/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a3156120b2a3723f54bbbead0522ef0cc8e37263 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/BUILD.gn @@ -0,0 +1,103 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("golden_playground_test") { + testonly = true + + sources = [ "golden_playground_test.h" ] + + deps = [ + ":digest", + ":screenshot", + "//flutter/display_list", + "//flutter/fml", + "//flutter/impeller/display_list:display_list", + "//flutter/impeller/playground", + "//flutter/impeller/typographer/backends/skia:typographer_skia_backend", + "//flutter/testing:testing_lib", + ] + + if (is_mac) { + sources += [ "golden_playground_test_mac.cc" ] + deps += [ + ":metal_screenshot", + "//flutter/third_party/abseil-cpp/absl/base:no_destructor", + ] + } else { + sources += [ "golden_playground_test_stub.cc" ] + } +} + +impeller_component("digest") { + testonly = true + + sources = [ + "golden_digest.cc", + "golden_digest.h", + "working_directory.cc", + "working_directory.h", + ] + + deps = [ "//flutter/fml" ] +} + +impeller_component("screenshot") { + testonly = true + sources = [ "screenshot.h" ] +} + +if (is_mac) { + impeller_component("metal_screenshot") { + testonly = true + + sources = [ + "metal_screenshot.h", + "metal_screenshot.mm", + "metal_screenshotter.h", + "metal_screenshotter.mm", + "screenshotter.h", + "vulkan_screenshotter.h", + "vulkan_screenshotter.mm", + ] + + deps = [ + ":screenshot", + "//flutter/display_list", + "//flutter/fml", + "//flutter/impeller/display_list", + "//flutter/impeller/playground", + "//flutter/impeller/renderer/backend/metal:metal", + "//flutter/impeller/renderer/backend/vulkan", + ] + } + + impeller_component("impeller_golden_tests") { + target_type = "executable" + + testonly = true + + sources = [ + "golden_tests.cc", + "main.cc", + ] + + deps = [ + ":digest", + ":metal_screenshot", + "//flutter/display_list", + "//flutter/impeller/display_list", + "//flutter/impeller/display_list:aiks_unittests_golden", + "//flutter/impeller/display_list:display_list_unittests_golden", + "//flutter/impeller/fixtures", + "//flutter/impeller/renderer:renderer_unittests_golden", + "//flutter/third_party/angle:libEGL", + "//flutter/third_party/angle:libGLESv2", + "//flutter/third_party/googletest:gtest", + "//flutter/third_party/swiftshader", + ] + } +} diff --git a/flutter/engine/src/flutter/impeller/golden_tests/README.md b/flutter/engine/src/flutter/impeller/golden_tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e590ee0938c25a14d8e5c1d4e48f452c21a5f13 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/README.md @@ -0,0 +1,35 @@ +# Impeller Golden Tests + +This is the executable that will generate the golden image results that can then +be sent to Skia Gold vial the +[golden_tests_harvester]("../../tools/golden_tests_harvester"). + +Running these tests should happen from +[//flutter/testing/run_tests.py](../../testing/run_tests.py). That will do all +the steps to generate the golden images and transmit them to Skia Gold. If you +run the tests locally it will not actually upload anything. That only happens if +the script is executed from LUCI. + +Example invocation: + +```sh +./run_tests.py --variant="host_debug_unopt_arm64" --type="impeller-golden" +``` + +Currently these tests are only supported on macOS and only test the Metal +backend to Impeller. + +## Adding tests + +To add a golden image test, the `impeller_golden_tests` target must be modified +to generate the correct image and modification to its generated `digest.json`. +If a test case is added to [golden_tests.cc](./golden_tests.cc), for example +"GoldenTests.FooBar", that will turn into the golden test +"impeller_GoldenTests_Foobar" automatically if the `SaveScreenshot()` function +is used. + +The examples in `golden_tests.cc` use GLFW for rendering the tests, but +technically anything could be used. Using the `SaveScreenshot()` function will +automatically update the `GoldenDigest::Instance()` which will make sure that it +is included in the generated `digest.json`. If that function isn't used the +`GoldenDigest` should be updated manually. diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.cc b/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d68220b10022c8f55295872537426e0ab478877e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.cc @@ -0,0 +1,96 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/golden_tests/golden_digest.h" + +#include +#include + +static const double kMaxDiffPixelsPercent = 0.01; +static const int32_t kMaxColorDelta = 8; + +namespace impeller { +namespace testing { + +GoldenDigest* GoldenDigest::instance_ = nullptr; + +GoldenDigest* GoldenDigest::Instance() { + if (!instance_) { + instance_ = new GoldenDigest(); + } + return instance_; +} + +GoldenDigest::GoldenDigest() {} + +void GoldenDigest::AddDimension(const std::string& name, + const std::string& value) { + std::stringstream ss; + ss << "\"" << value << "\""; + dimensions_[name] = ss.str(); +} + +void GoldenDigest::AddImage(const std::string& test_name, + const std::string& filename, + int32_t width, + int32_t height) { + entries_.push_back({test_name, filename, width, height, kMaxDiffPixelsPercent, + kMaxColorDelta}); +} + +bool GoldenDigest::Write(WorkingDirectory* working_directory) { + std::ofstream fout; + fout.open(working_directory->GetFilenamePath("digest.json")); + if (!fout.good()) { + return false; + } + + fout << "{" << std::endl; + fout << " \"dimensions\": {" << std::endl; + bool is_first = true; + for (const auto& dimension : dimensions_) { + if (!is_first) { + fout << "," << std::endl; + } + is_first = false; + fout << " \"" << dimension.first << "\": " << dimension.second; + } + fout << std::endl << " }," << std::endl; + fout << " \"entries\":" << std::endl; + + fout << " [" << std::endl; + is_first = true; + for (const auto& entry : entries_) { + if (!is_first) { + fout << "," << std::endl; + } + is_first = false; + + fout << " { " << "\"testName\" : \"" << entry.test_name << "\", " + << "\"filename\" : \"" << entry.filename << "\", " + << "\"width\" : " << entry.width << ", " + << "\"height\" : " << entry.height << ", "; + + if (entry.max_diff_pixels_percent == + static_cast(entry.max_diff_pixels_percent)) { + fout << "\"maxDiffPixelsPercent\" : " << entry.max_diff_pixels_percent + << ".0, "; + } else { + fout << "\"maxDiffPixelsPercent\" : " << entry.max_diff_pixels_percent + << ", "; + } + + fout << "\"maxColorDelta\":" << entry.max_color_delta << " "; + fout << "}"; + } + fout << std::endl << " ]" << std::endl; + + fout << "}" << std::endl; + + fout.close(); + return true; +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.h b/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.h new file mode 100644 index 0000000000000000000000000000000000000000..3fa989a5f0cedcf882f43656792ecaf2d09b53ef --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_digest.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_ + +#include +#include +#include + +#include "flutter/impeller/golden_tests/working_directory.h" + +namespace impeller { +namespace testing { + +/// Manages a global variable for tracking instances of golden images. +class GoldenDigest { + public: + static GoldenDigest* Instance(); + + void AddDimension(const std::string& name, const std::string& value); + + void AddImage(const std::string& test_name, + const std::string& filename, + int32_t width, + int32_t height); + + /// Writes a "digest.json" file to `working_directory`. + /// + /// Returns `true` on success. + bool Write(WorkingDirectory* working_directory); + + private: + GoldenDigest(const GoldenDigest&) = delete; + + GoldenDigest& operator=(const GoldenDigest&) = delete; + GoldenDigest(); + struct Entry { + std::string test_name; + std::string filename; + int32_t width; + int32_t height; + double max_diff_pixels_percent; + int32_t max_color_delta; + }; + + static GoldenDigest* instance_; + std::vector entries_; + std::map dimensions_; +}; +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_DIGEST_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test.h b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test.h new file mode 100644 index 0000000000000000000000000000000000000000..cb0d1772ed978340641f228afaacf59a71fb7495 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test.h @@ -0,0 +1,114 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_PLAYGROUND_TEST_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_PLAYGROUND_TEST_H_ + +#include + +#include "flutter/display_list/display_list.h" +#include "flutter/display_list/image/dl_image.h" +#include "flutter/impeller/display_list/aiks_context.h" +#include "flutter/impeller/golden_tests/screenshot.h" +#include "flutter/impeller/playground/playground.h" +#include "flutter/impeller/renderer/render_target.h" +#include "flutter/testing/testing.h" +#include "impeller/typographer/typographer_context.h" +#include "third_party/imgui/imgui.h" + +#if FML_OS_MACOSX +#include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" +#endif + +namespace impeller { + +class GoldenPlaygroundTest + : public ::testing::TestWithParam { + public: + using AiksPlaygroundCallback = + std::function(AiksContext& renderer)>; + + using AiksDlPlaygroundCallback = std::function()>; + + GoldenPlaygroundTest(); + + ~GoldenPlaygroundTest() override; + + void SetUp(); + + void TearDown(); + + PlaygroundBackend GetBackend() const; + + void SetTypographerContext( + std::shared_ptr typographer_context); + + bool OpenPlaygroundHere(Picture picture); + + bool OpenPlaygroundHere(AiksPlaygroundCallback callback); + + bool OpenPlaygroundHere(const AiksDlPlaygroundCallback& callback); + + bool OpenPlaygroundHere(const sk_sp& list); + + std::unique_ptr MakeScreenshot( + const sk_sp& list); + + static bool SaveScreenshot(std::unique_ptr screenshot, + const std::string& postfix = ""); + + static bool ImGuiBegin(const char* name, + bool* p_open, + ImGuiWindowFlags flags); + + std::shared_ptr CreateTextureForFixture( + const char* fixture_name, + bool enable_mipmapping = false) const; + + sk_sp CreateDlImageForFixture( + const char* fixture_name, + bool enable_mipmapping = false) const; + + RuntimeStage::Map OpenAssetAsRuntimeStage(const char* asset_name) const; + + std::shared_ptr GetContext() const; + + std::shared_ptr MakeContext() const; + + Point GetContentScale() const; + + Scalar GetSecondsElapsed() const; + + ISize GetWindowSize() const; + + [[nodiscard]] fml::Status SetCapabilities( + const std::shared_ptr& capabilities); + + /// Returns true if `OpenPlaygroundHere` will actually render anything. + bool WillRenderSomething() const { return true; } + + protected: + void SetWindowSize(ISize size); + + private: +#if FML_OS_MACOSX + // This must be placed first so that the autorelease pool is not destroyed + // until the GoldenPlaygroundTestImpl has been destructed. + fml::ScopedNSAutoreleasePool autorelease_pool_; +#endif + + std::shared_ptr typographer_context_; + + struct GoldenPlaygroundTestImpl; + // This is only a shared_ptr so it can work with a forward declared type. + std::shared_ptr pimpl_; + + GoldenPlaygroundTest(const GoldenPlaygroundTest&) = delete; + + GoldenPlaygroundTest& operator=(const GoldenPlaygroundTest&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_PLAYGROUND_TEST_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_mac.cc b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_mac.cc new file mode 100644 index 0000000000000000000000000000000000000000..fd8445dbe2811446e425961627a1570bad51ec30 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_mac.cc @@ -0,0 +1,336 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#include "display_list/display_list.h" +#include "flutter/impeller/golden_tests/golden_playground_test.h" + +#include "flutter/impeller/golden_tests/golden_digest.h" +#include "flutter/impeller/golden_tests/metal_screenshotter.h" +#include "flutter/impeller/golden_tests/vulkan_screenshotter.h" +#include "flutter/third_party/abseil-cpp/absl/base/no_destructor.h" +#include "fml/closure.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/display_list/dl_image_impeller.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" +#include "impeller/typographer/typographer_context.h" + +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +namespace impeller { + +namespace { +std::unique_ptr MakeVulkanPlayground(bool enable_validations) { + FML_CHECK(::glfwInit() == GLFW_TRUE); + PlaygroundSwitches playground_switches; + playground_switches.enable_vulkan_validation = enable_validations; + return PlaygroundImpl::Create(PlaygroundBackend::kVulkan, + playground_switches); +} + +// Returns a static instance to a playground that can be used across tests. +const std::unique_ptr& GetSharedVulkanPlayground( + bool enable_validations) { + if (enable_validations) { + static absl::NoDestructor> + vulkan_validation_playground( + MakeVulkanPlayground(/*enable_validations=*/true)); + // TODO(142237): This can be removed when the thread local storage is + // removed. + static fml::ScopedCleanupClosure context_cleanup( + [&] { (*vulkan_validation_playground)->GetContext()->Shutdown(); }); + return *vulkan_validation_playground; + } else { + static absl::NoDestructor> + vulkan_playground(MakeVulkanPlayground(/*enable_validations=*/false)); + // TODO(142237): This can be removed when the thread local storage is + // removed. + static fml::ScopedCleanupClosure context_cleanup( + [&] { (*vulkan_playground)->GetContext()->Shutdown(); }); + return *vulkan_playground; + } +} + +} // namespace + +#define IMP_AIKSTEST(name) \ + "impeller_Play_AiksTest_" #name "_Metal", \ + "impeller_Play_AiksTest_" #name "_OpenGLES", \ + "impeller_Play_AiksTest_" #name "_Vulkan" + +// If you add a new playground test to the aiks unittests and you do not want it +// to also be a golden test, then add the test name here. +static const std::vector kSkipTests = { + // TextRotated is flakey and we can't seem to get it to stabilize on Skia + // Gold. + IMP_AIKSTEST(TextRotated), + // Runtime stage based tests get confused with a Metal context. + "impeller_Play_AiksTest_CanRenderClippedRuntimeEffects_Vulkan", +}; + +namespace { +std::string GetTestName() { + std::string suite_name = + ::testing::UnitTest::GetInstance()->current_test_suite()->name(); + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + std::stringstream ss; + ss << "impeller_" << suite_name << "_" << test_name; + std::string result = ss.str(); + // Make sure there are no slashes in the test name. + std::replace(result.begin(), result.end(), '/', '_'); + return result; +} + +std::string GetGoldenFilename(const std::string& postfix) { + return GetTestName() + postfix + ".png"; +} +} // namespace + +bool GoldenPlaygroundTest::SaveScreenshot( + std::unique_ptr screenshot, + const std::string& postfix) { + if (!screenshot || !screenshot->GetBytes()) { + FML_LOG(ERROR) << "Failed to collect screenshot for test " << GetTestName(); + return false; + } + std::string test_name = GetTestName(); + std::string filename = GetGoldenFilename(postfix); + testing::GoldenDigest::Instance()->AddImage( + test_name, filename, screenshot->GetWidth(), screenshot->GetHeight()); + if (!screenshot->WriteToPNG( + testing::WorkingDirectory::Instance()->GetFilenamePath(filename))) { + FML_LOG(ERROR) << "Failed to write screenshot to " << filename; + return false; + } + return true; +} + +struct GoldenPlaygroundTest::GoldenPlaygroundTestImpl { + std::unique_ptr test_vulkan_playground; + std::unique_ptr test_opengl_playground; + std::unique_ptr screenshotter; + ISize window_size = ISize{1024, 768}; +}; + +GoldenPlaygroundTest::GoldenPlaygroundTest() + : typographer_context_(TypographerContextSkia::Make()), + pimpl_(new GoldenPlaygroundTest::GoldenPlaygroundTestImpl()) {} + +GoldenPlaygroundTest::~GoldenPlaygroundTest() = default; + +void GoldenPlaygroundTest::SetTypographerContext( + std::shared_ptr typographer_context) { + typographer_context_ = std::move(typographer_context); +}; + +void GoldenPlaygroundTest::TearDown() { + ASSERT_FALSE(dlopen("/usr/local/lib/libMoltenVK.dylib", RTLD_NOLOAD)); + + auto context = GetContext(); + if (context) { + context->DisposeThreadLocalCachedResources(); + } +} + +namespace { +bool DoesSupportWideGamutTests() { +#ifdef __arm64__ + return true; +#else + return false; +#endif +} +} // namespace + +void GoldenPlaygroundTest::SetUp() { + std::filesystem::path testing_assets_path = + flutter::testing::GetTestingAssetsPath(); + std::filesystem::path target_path = testing_assets_path.parent_path() + .parent_path() + .parent_path() + .parent_path(); + std::filesystem::path icd_path = target_path / "vk_swiftshader_icd.json"; + setenv("VK_ICD_FILENAMES", icd_path.c_str(), 1); + + std::string test_name = GetTestName(); + PlaygroundSwitches switches; + switches.enable_wide_gamut = + test_name.find("WideGamut_") != std::string::npos; + switches.flags.antialiased_lines = + test_name.find("ExperimentAntialiasLines_") != std::string::npos; + switch (GetParam()) { + case PlaygroundBackend::kMetal: + if (!DoesSupportWideGamutTests()) { + GTEST_SKIP() + << "This metal device doesn't support wide gamut golden tests."; + } + pimpl_->screenshotter = + std::make_unique(switches); + break; + case PlaygroundBackend::kVulkan: { + if (switches.enable_wide_gamut) { + GTEST_SKIP() << "Vulkan doesn't support wide gamut golden tests."; + } + if (switches.flags.antialiased_lines) { + GTEST_SKIP() + << "Vulkan doesn't support antialiased lines golden tests."; + } + const std::unique_ptr& playground = + GetSharedVulkanPlayground(/*enable_validations=*/true); + pimpl_->screenshotter = + std::make_unique(playground); + break; + } + case PlaygroundBackend::kOpenGLES: { + if (switches.enable_wide_gamut) { + GTEST_SKIP() << "OpenGLES doesn't support wide gamut golden tests."; + } + if (switches.flags.antialiased_lines) { + GTEST_SKIP() + << "OpenGLES doesn't support antialiased lines golden tests."; + } + FML_CHECK(::glfwInit() == GLFW_TRUE); + PlaygroundSwitches playground_switches; + playground_switches.use_angle = true; + pimpl_->test_opengl_playground = PlaygroundImpl::Create( + PlaygroundBackend::kOpenGLES, playground_switches); + pimpl_->screenshotter = std::make_unique( + pimpl_->test_opengl_playground); + break; + } + } + + if (std::find(kSkipTests.begin(), kSkipTests.end(), test_name) != + kSkipTests.end()) { + GTEST_SKIP() + << "GoldenPlaygroundTest doesn't support interactive playground tests " + "yet."; + } + + testing::GoldenDigest::Instance()->AddDimension( + "gpu_string", GetContext()->DescribeGpuModel()); +} + +PlaygroundBackend GoldenPlaygroundTest::GetBackend() const { + return GetParam(); +} + +bool GoldenPlaygroundTest::OpenPlaygroundHere( + const AiksDlPlaygroundCallback& callback) { + AiksContext renderer(GetContext(), typographer_context_); + + std::unique_ptr screenshot; + for (int i = 0; i < 2; ++i) { + auto display_list = callback(); + auto texture = + DisplayListToTexture(display_list, pimpl_->window_size, renderer); + screenshot = pimpl_->screenshotter->MakeScreenshot(renderer, texture); + } + return SaveScreenshot(std::move(screenshot)); +} + +bool GoldenPlaygroundTest::OpenPlaygroundHere( + const sk_sp& list) { + return OpenPlaygroundHere([&list]() { return list; }); +} + +bool GoldenPlaygroundTest::ImGuiBegin(const char* name, + bool* p_open, + ImGuiWindowFlags flags) { + return false; +} + +std::shared_ptr GoldenPlaygroundTest::CreateTextureForFixture( + const char* fixture_name, + bool enable_mipmapping) const { + std::shared_ptr mapping = + flutter::testing::OpenFixtureAsMapping(fixture_name); + auto result = Playground::CreateTextureForMapping(GetContext(), mapping, + enable_mipmapping); + if (result) { + result->SetLabel(fixture_name); + } + return result; +} + +sk_sp GoldenPlaygroundTest::CreateDlImageForFixture( + const char* fixture_name, + bool enable_mipmapping) const { + std::shared_ptr texture = + CreateTextureForFixture(fixture_name, enable_mipmapping); + return DlImageImpeller::Make(texture); +} + +RuntimeStage::Map GoldenPlaygroundTest::OpenAssetAsRuntimeStage( + const char* asset_name) const { + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping(asset_name); + if (!fixture || fixture->GetSize() == 0) { + return {}; + } + return RuntimeStage::DecodeRuntimeStages(fixture); +} + +std::shared_ptr GoldenPlaygroundTest::GetContext() const { + if (!pimpl_->screenshotter) { + return nullptr; + } + return pimpl_->screenshotter->GetPlayground().GetContext(); +} + +std::shared_ptr GoldenPlaygroundTest::MakeContext() const { + if (GetParam() == PlaygroundBackend::kMetal) { + /// On Metal we create a context for each test. + return GetContext(); + } else if (GetParam() == PlaygroundBackend::kVulkan) { + bool enable_vulkan_validations = true; + FML_CHECK(!pimpl_->test_vulkan_playground) + << "We don't support creating multiple contexts for one test"; + pimpl_->test_vulkan_playground = + MakeVulkanPlayground(enable_vulkan_validations); + pimpl_->screenshotter = std::make_unique( + pimpl_->test_vulkan_playground); + return pimpl_->test_vulkan_playground->GetContext(); + } else { + /// On OpenGL we create a context for each test. + return GetContext(); + } +} + +Point GoldenPlaygroundTest::GetContentScale() const { + return pimpl_->screenshotter->GetPlayground().GetContentScale(); +} + +Scalar GoldenPlaygroundTest::GetSecondsElapsed() const { + return 0.0f; +} + +ISize GoldenPlaygroundTest::GetWindowSize() const { + return pimpl_->window_size; +} + +void GoldenPlaygroundTest::GoldenPlaygroundTest::SetWindowSize(ISize size) { + pimpl_->window_size = size; +} + +fml::Status GoldenPlaygroundTest::SetCapabilities( + const std::shared_ptr& capabilities) { + return pimpl_->screenshotter->GetPlayground().SetCapabilities(capabilities); +} + +std::unique_ptr GoldenPlaygroundTest::MakeScreenshot( + const sk_sp& list) { + AiksContext renderer(GetContext(), typographer_context_); + + return pimpl_->screenshotter->MakeScreenshot( + renderer, DisplayListToTexture(list, pimpl_->window_size, renderer)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_stub.cc b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_stub.cc new file mode 100644 index 0000000000000000000000000000000000000000..fbe32a7fa471d75891081d6b7894338c26c5b320 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_playground_test_stub.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/golden_tests/golden_playground_test.h" + +namespace impeller { + +GoldenPlaygroundTest::GoldenPlaygroundTest() = default; + +GoldenPlaygroundTest::~GoldenPlaygroundTest() = default; + +void GoldenPlaygroundTest::SetTypographerContext( + std::shared_ptr typographer_context) { + typographer_context_ = std::move(typographer_context); +}; + +void GoldenPlaygroundTest::TearDown() {} + +void GoldenPlaygroundTest::SetUp() { + GTEST_SKIP() << "GoldenPlaygroundTest doesn't support this backend type."; +} + +PlaygroundBackend GoldenPlaygroundTest::GetBackend() const { + return GetParam(); +} + +bool GoldenPlaygroundTest::OpenPlaygroundHere( + const AiksDlPlaygroundCallback& callback) { + return false; +} + +bool GoldenPlaygroundTest::OpenPlaygroundHere( + const sk_sp& list) { + return false; +} + +std::shared_ptr GoldenPlaygroundTest::CreateTextureForFixture( + const char* fixture_name, + bool enable_mipmapping) const { + return nullptr; +} + +sk_sp GoldenPlaygroundTest::CreateDlImageForFixture( + const char* fixture_name, + bool enable_mipmapping) const { + return nullptr; +} + +RuntimeStage::Map GoldenPlaygroundTest::OpenAssetAsRuntimeStage( + const char* asset_name) const { + return {}; +} + +std::shared_ptr GoldenPlaygroundTest::GetContext() const { + return nullptr; +} + +Point GoldenPlaygroundTest::GetContentScale() const { + return Point(); +} + +Scalar GoldenPlaygroundTest::GetSecondsElapsed() const { + return Scalar(); +} + +ISize GoldenPlaygroundTest::GetWindowSize() const { + return ISize(); +} + +void GoldenPlaygroundTest::SetWindowSize(ISize size) {} + +fml::Status GoldenPlaygroundTest::SetCapabilities( + const std::shared_ptr& capabilities) { + return fml::Status( + fml::StatusCode::kUnimplemented, + "GoldenPlaygroundTest-Stub doesn't support SetCapabilities."); +} + +std::unique_ptr GoldenPlaygroundTest::MakeScreenshot( + const sk_sp& list) { + return nullptr; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/golden_tests.cc b/flutter/engine/src/flutter/impeller/golden_tests/golden_tests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d3456110c6fd24adc1855cbaeed9261359e2dc75 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/golden_tests.cc @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "display_list/dl_color.h" +#include "display_list/dl_tile_mode.h" +#include "gtest/gtest.h" + +#include + +#include "display_list/dl_builder.h" +#include "display_list/dl_paint.h" +#include "display_list/effects/dl_color_source.h" +#include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/display_list/dl_dispatcher.h" // nogncheck +#include "impeller/golden_tests/golden_digest.h" +#include "impeller/golden_tests/metal_screenshot.h" +#include "impeller/golden_tests/metal_screenshotter.h" +#include "impeller/golden_tests/working_directory.h" + +namespace impeller { +namespace testing { + +namespace { +std::string GetTestName() { + std::string suite_name = + ::testing::UnitTest::GetInstance()->current_test_suite()->name(); + std::string test_name = + ::testing::UnitTest::GetInstance()->current_test_info()->name(); + std::stringstream ss; + ss << "impeller_" << suite_name << "_" << test_name; + return ss.str(); +} + +std::string GetGoldenFilename() { + return GetTestName() + ".png"; +} + +bool SaveScreenshot(std::unique_ptr screenshot) { + if (!screenshot || !screenshot->GetBytes()) { + return false; + } + std::string test_name = GetTestName(); + std::string filename = GetGoldenFilename(); + GoldenDigest::Instance()->AddImage( + test_name, filename, screenshot->GetWidth(), screenshot->GetHeight()); + return screenshot->WriteToPNG( + WorkingDirectory::Instance()->GetFilenamePath(filename)); +} + +PlaygroundSwitches GetPlaygroundSwitches() { + PlaygroundSwitches switches; + switches.enable_wide_gamut = false; + return switches; +} +} // namespace + +class GoldenTests : public ::testing::Test { + public: + GoldenTests() + : screenshotter_(new MetalScreenshotter(GetPlaygroundSwitches())) {} + + MetalScreenshotter& Screenshotter() { return *screenshotter_; } + + void SetUp() override { + testing::GoldenDigest::Instance()->AddDimension( + "gpu_string", + Screenshotter().GetPlayground().GetContext()->DescribeGpuModel()); + } + + private: + // This must be placed before any other members that may use the + // autorelease pool. + fml::ScopedNSAutoreleasePool autorelease_pool_; + + std::unique_ptr screenshotter_; +}; + +TEST_F(GoldenTests, ConicalGradient) { + flutter::DisplayListBuilder builder; + flutter::DlPaint paint; + paint.setDrawStyle(flutter::DlDrawStyle::kFill); + + flutter::DlColor colors[2] = {flutter::DlColor::RGBA(1, 0, 0, 1), + flutter::DlColor::RGBA(0, 0, 1, 1)}; + Scalar stops[2] = {0, 1}; + + paint.setColorSource(flutter::DlColorSource::MakeConical( + /*start_center=*/{125, 125}, // + /*start_radius=*/125, {180, 180}, // + /*end_radius=*/0, // + /*stop_count=*/2, // + /*colors=*/colors, // + /*stops=*/stops, // + /*tile_mode=*/flutter::DlTileMode::kClamp // + )); + + builder.DrawRect(DlRect::MakeXYWH(10, 10, 250, 250), paint); + + auto aiks_context = + AiksContext(Screenshotter().GetPlayground().GetContext(), nullptr); + auto screenshot = Screenshotter().MakeScreenshot( + aiks_context, + DisplayListToTexture(builder.Build(), {240, 240}, aiks_context)); + ASSERT_TRUE(SaveScreenshot(std::move(screenshot))); +} +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/main.cc b/flutter/engine/src/flutter/impeller/golden_tests/main.cc new file mode 100644 index 0000000000000000000000000000000000000000..4791f3818a9f03bcfd010a0f6e9e2c204a204552 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/main.cc @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/fml/backtrace.h" +#include "flutter/fml/build_config.h" +#include "flutter/fml/command_line.h" +#include "flutter/fml/logging.h" +#include "flutter/impeller/base/validation.h" +#include "flutter/impeller/golden_tests/golden_digest.h" +#include "flutter/impeller/golden_tests/working_directory.h" +#include "gtest/gtest.h" + +namespace { +void print_usage() { + std::cout << "usage: impeller_golden_tests --working_dir=" + << std::endl + << std::endl; + std::cout << "flags:" << std::endl; + std::cout << " working_dir: Where the golden images will be generated and " + "uploaded to Skia Gold from." + << std::endl; +} +} // namespace + +namespace impeller { +TEST(ValidationTest, IsFatal) { + EXPECT_TRUE(ImpellerValidationErrorsAreFatal()); +} +} // namespace impeller + +int main(int argc, char** argv) { + impeller::ImpellerValidationErrorsSetFatal(true); + fml::InstallCrashHandler(); + testing::InitGoogleTest(&argc, argv); + fml::CommandLine cmd = fml::CommandLineFromPlatformOrArgcArgv(argc, argv); + + std::optional working_dir; + for (const auto& option : cmd.options()) { + if (option.name == "working_dir") { + wordexp_t wordexp_result; + int code = wordexp(option.value.c_str(), &wordexp_result, 0); + FML_CHECK(code == 0); + FML_CHECK(wordexp_result.we_wordc != 0); + working_dir = wordexp_result.we_wordv[0]; + wordfree(&wordexp_result); + } + } + if (!working_dir) { + std::cout << "required argument \"working_dir\" is missing." << std::endl + << std::endl; + print_usage(); + return 1; + } + + impeller::testing::WorkingDirectory::Instance()->SetPath(working_dir.value()); + std::cout << "working directory: " + << impeller::testing::WorkingDirectory::Instance()->GetPath() + << std::endl; + + int return_code = RUN_ALL_TESTS(); + if (0 == return_code) { + impeller::testing::GoldenDigest::Instance()->Write( + impeller::testing::WorkingDirectory::Instance()); + } + return return_code; +} diff --git a/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.h b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.h new file mode 100644 index 0000000000000000000000000000000000000000..739c7691d238e7aef2ad470c3106284248956144 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_ + +#include "flutter/impeller/golden_tests/screenshot.h" + +#include +#include +#include + +#include "flutter/fml/platform/darwin/cf_utils.h" + +namespace fml { + +/// fml::CFRef retain and release implementations for CGImageRef. +template <> +struct CFRefTraits { + static constexpr CGImageRef kNullValue = nullptr; + static void Retain(CGImageRef instance) { CGImageRetain(instance); } + static void Release(CGImageRef instance) { CGImageRelease(instance); } +}; + +} // namespace fml + +namespace impeller { +namespace testing { + +/// A screenshot that was produced from `MetalScreenshotter`. +class MetalScreenshot : public Screenshot { + public: + explicit MetalScreenshot(CGImageRef cgImage); + + ~MetalScreenshot(); + + const uint8_t* GetBytes() const override; + + size_t GetHeight() const override; + + size_t GetWidth() const override; + + size_t GetBytesPerRow() const override; + + bool WriteToPNG(const std::string& path) const override; + + private: + MetalScreenshot(const MetalScreenshot&) = delete; + + MetalScreenshot& operator=(const MetalScreenshot&) = delete; + fml::CFRef cg_image_; + fml::CFRef pixel_data_; +}; +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOT_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm new file mode 100644 index 0000000000000000000000000000000000000000..7062372e74eaf3b40bb02c261043fe5b0101e0e2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshot.mm @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/golden_tests/metal_screenshot.h" + +namespace impeller { +namespace testing { + +MetalScreenshot::MetalScreenshot(CGImageRef cgImage) : cg_image_(cgImage) { + CGDataProviderRef data_provider = CGImageGetDataProvider(cgImage); + pixel_data_.Reset(CGDataProviderCopyData(data_provider)); +} + +MetalScreenshot::~MetalScreenshot() = default; + +const uint8_t* MetalScreenshot::GetBytes() const { + return CFDataGetBytePtr(pixel_data_); +} + +size_t MetalScreenshot::GetHeight() const { + return CGImageGetHeight(cg_image_); +} + +size_t MetalScreenshot::GetWidth() const { + return CGImageGetWidth(cg_image_); +} + +size_t MetalScreenshot::GetBytesPerRow() const { + return CGImageGetBytesPerRow(cg_image_); +} + +bool MetalScreenshot::WriteToPNG(const std::string& path) const { + bool result = false; + NSURL* output_url = + [NSURL fileURLWithPath:[NSString stringWithUTF8String:path.c_str()]]; + fml::CFRef destination(CGImageDestinationCreateWithURL( + (__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr)); + if (destination) { + CGImageDestinationAddImage(destination, cg_image_, + (__bridge CFDictionaryRef) @{}); + + if (CGImageDestinationFinalize(destination)) { + result = true; + } + } + return result; +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.h b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.h new file mode 100644 index 0000000000000000000000000000000000000000..30cf3d43eb43aac8952c4f2dfc15137332fd0418 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_ + +#include "flutter/impeller/golden_tests/metal_screenshot.h" +#include "flutter/impeller/golden_tests/screenshotter.h" +#include "flutter/impeller/playground/playground_impl.h" +#include "impeller/display_list/aiks_context.h" + +namespace impeller { +namespace testing { + +/// Converts `Picture`s and `DisplayList`s to `MetalScreenshot`s with the +/// playground backend. +class MetalScreenshotter : public Screenshotter { + public: + explicit MetalScreenshotter(const PlaygroundSwitches& switches); + + std::unique_ptr MakeScreenshot( + AiksContext& aiks_context, + const std::shared_ptr texture) override; + + PlaygroundImpl& GetPlayground() override { return *playground_; } + + private: + std::unique_ptr playground_; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_METAL_SCREENSHOTTER_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.mm b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.mm new file mode 100644 index 0000000000000000000000000000000000000000..051347dfb5746f15604cd5fc66e637bc0e19a1c3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/metal_screenshotter.mm @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/golden_tests/metal_screenshotter.h" + +#include +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +namespace impeller { +namespace testing { + +MetalScreenshotter::MetalScreenshotter(const PlaygroundSwitches& switches) { + FML_CHECK(::glfwInit() == GLFW_TRUE); + playground_ = PlaygroundImpl::Create(PlaygroundBackend::kMetal, switches); +} + +std::unique_ptr MetalScreenshotter::MakeScreenshot( + AiksContext& aiks_context, + const std::shared_ptr texture) { + @autoreleasepool { + id metal_texture = + std::static_pointer_cast(texture)->GetMTLTexture(); + + CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB(); + CIImage* ciImage = [[CIImage alloc] + initWithMTLTexture:metal_texture + options:@{kCIImageColorSpace : (__bridge id)color_space}]; + CGColorSpaceRelease(color_space); + FML_CHECK(ciImage); + + std::shared_ptr context = playground_->GetContext(); + std::shared_ptr context_mtl = + std::static_pointer_cast(context); + CIContext* cicontext = + [CIContext contextWithMTLDevice:context_mtl->GetMTLDevice()]; + FML_CHECK(context); + + CIImage* flipped = [ciImage + imageByApplyingOrientation:kCGImagePropertyOrientationDownMirrored]; + + CGImageRef cgImage = [cicontext createCGImage:flipped + fromRect:[ciImage extent]]; + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return std::unique_ptr(new MetalScreenshot(cgImage)); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/screenshot.h b/flutter/engine/src/flutter/impeller/golden_tests/screenshot.h new file mode 100644 index 0000000000000000000000000000000000000000..4772609b2fb156318a4eda831098fbb0f33dfb71 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/screenshot.h @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_ + +#include +#include +#include +#include + +namespace impeller { +namespace testing { + +class Screenshot { + public: + virtual ~Screenshot() = default; + + /// Access raw data of the screenshot. + virtual const uint8_t* GetBytes() const = 0; + + /// Returns the height of the image in pixels. + virtual size_t GetHeight() const = 0; + + /// Returns the width of the image in pixels. + virtual size_t GetWidth() const = 0; + + /// Returns number of bytes required to represent one row of the raw image. + virtual size_t GetBytesPerRow() const = 0; + + /// Synchronously write the screenshot to disk as a PNG at `path`. Returns + /// `true` if it succeeded. + virtual bool WriteToPNG(const std::string& path) const = 0; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOT_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/screenshotter.h b/flutter/engine/src/flutter/impeller/golden_tests/screenshotter.h new file mode 100644 index 0000000000000000000000000000000000000000..7d6520c890334fa7a862f8104113d9e7332d0608 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/screenshotter.h @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOTTER_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOTTER_H_ + +#include "flutter/impeller/golden_tests/screenshot.h" +#include "flutter/impeller/playground/playground_impl.h" +#include "impeller/display_list/aiks_context.h" + +namespace impeller { +namespace testing { + +/// Converts `Picture`s and `DisplayList`s to `MetalScreenshot`s with the +/// playground backend. +class Screenshotter { + public: + virtual ~Screenshotter() = default; + + virtual std::unique_ptr MakeScreenshot( + AiksContext& aiks_context, + const std::shared_ptr texture) = 0; + + virtual PlaygroundImpl& GetPlayground() = 0; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_SCREENSHOTTER_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.h b/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.h new file mode 100644 index 0000000000000000000000000000000000000000..8099661f626553c269b57a1878f3d5e4099f691a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.h @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_VULKAN_SCREENSHOTTER_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_VULKAN_SCREENSHOTTER_H_ + +#include "flutter/impeller/golden_tests/metal_screenshot.h" +#include "flutter/impeller/golden_tests/screenshotter.h" +#include "flutter/impeller/playground/playground_impl.h" + +namespace impeller { +namespace testing { + +/// Converts `Picture`s and `DisplayList`s to `MetalScreenshot`s with the +/// playground backend. +class VulkanScreenshotter : public Screenshotter { + public: + explicit VulkanScreenshotter( + const std::unique_ptr& playground); + + std::unique_ptr MakeScreenshot( + AiksContext& aiks_context, + const std::shared_ptr texture) override; + + PlaygroundImpl& GetPlayground() override { return *playground_; } + + private: + const std::unique_ptr& playground_; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_VULKAN_SCREENSHOTTER_H_ diff --git a/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.mm b/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.mm new file mode 100644 index 0000000000000000000000000000000000000000..0315fdfd7b941228afd165bac7c188b17b2c45cd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/vulkan_screenshotter.mm @@ -0,0 +1,96 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/golden_tests/vulkan_screenshotter.h" + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/impeller/golden_tests/metal_screenshot.h" +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +namespace impeller { +namespace testing { + +namespace { + +using CGContextPtr = std::unique_ptr::type, + decltype(&CGContextRelease)>; +using CGImagePtr = std::unique_ptr::type, + decltype(&CGImageRelease)>; +using CGColorSpacePtr = + std::unique_ptr::type, + decltype(&CGColorSpaceRelease)>; + +std::unique_ptr ReadTexture( + const std::shared_ptr& surface_context, + const std::shared_ptr& texture) { + DeviceBufferDescriptor buffer_desc; + buffer_desc.storage_mode = StorageMode::kHostVisible; + buffer_desc.size = + texture->GetTextureDescriptor().GetByteSizeOfBaseMipLevel(); + buffer_desc.readback = true; + std::shared_ptr device_buffer = + surface_context->GetResourceAllocator()->CreateBuffer(buffer_desc); + FML_CHECK(device_buffer); + + auto command_buffer = surface_context->CreateCommandBuffer(); + auto blit_pass = command_buffer->CreateBlitPass(); + bool success = blit_pass->AddCopy(texture, device_buffer); + FML_CHECK(success); + + success = blit_pass->EncodeCommands(); + FML_CHECK(success); + + fml::AutoResetWaitableEvent latch; + success = + surface_context->GetCommandQueue() + ->Submit({command_buffer}, + [&latch](CommandBuffer::Status status) { + FML_CHECK(status == CommandBuffer::Status::kCompleted); + latch.Signal(); + }) + .ok(); + FML_CHECK(success); + latch.Wait(); + device_buffer->Invalidate(); + + // TODO(gaaclarke): Replace CoreImage requirement with something + // crossplatform. + + CGColorSpacePtr color_space(CGColorSpaceCreateDeviceRGB(), + &CGColorSpaceRelease); + CGBitmapInfo bitmap_info = + texture->GetTextureDescriptor().format == PixelFormat::kB8G8R8A8UNormInt + ? kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little + : kCGImageAlphaPremultipliedLast; + CGContextPtr context( + CGBitmapContextCreate( + device_buffer->OnGetContents(), texture->GetSize().width, + texture->GetSize().height, + /*bitsPerComponent=*/8, + /*bytesPerRow=*/texture->GetTextureDescriptor().GetBytesPerRow(), + color_space.get(), bitmap_info), + &CGContextRelease); + FML_CHECK(context); + CGImagePtr image(CGBitmapContextCreateImage(context.get()), &CGImageRelease); + FML_CHECK(image); + + return std::make_unique(image.release()); +} +} // namespace + +VulkanScreenshotter::VulkanScreenshotter( + const std::unique_ptr& playground) + : playground_(playground) { + FML_CHECK(playground_); +} + +std::unique_ptr VulkanScreenshotter::MakeScreenshot( + AiksContext& aiks_context, + const std::shared_ptr texture) { + return ReadTexture(aiks_context.GetContext(), texture); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/working_directory.cc b/flutter/engine/src/flutter/impeller/golden_tests/working_directory.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac9e608cf98ade828feffab6962bf795a611582c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/working_directory.cc @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/golden_tests/working_directory.h" + +#include "flutter/fml/paths.h" + +namespace impeller { +namespace testing { + +WorkingDirectory* WorkingDirectory::instance_ = nullptr; + +WorkingDirectory::WorkingDirectory() {} + +WorkingDirectory* WorkingDirectory::Instance() { + if (!instance_) { + instance_ = new WorkingDirectory(); + } + return instance_; +} + +std::string WorkingDirectory::GetFilenamePath( + const std::string& filename) const { + return fml::paths::JoinPaths({path_, filename}); +} + +void WorkingDirectory::SetPath(const std::string& path) { + FML_CHECK(did_set_ == false); + path_ = path; + did_set_ = true; +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/golden_tests/working_directory.h b/flutter/engine/src/flutter/impeller/golden_tests/working_directory.h new file mode 100644 index 0000000000000000000000000000000000000000..94d4ca872ffa6e017f631a1b99dcd1d3b4ba2938 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/golden_tests/working_directory.h @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_ +#define FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_ + +#include + +namespace impeller { +namespace testing { + +/// Keeps track of the global variable for the specified working +/// directory. +class WorkingDirectory { + public: + static WorkingDirectory* Instance(); + + std::string GetFilenamePath(const std::string& filename) const; + + void SetPath(const std::string& path); + + const std::string& GetPath() const { return path_; } + + private: + WorkingDirectory(const WorkingDirectory&) = delete; + + WorkingDirectory& operator=(const WorkingDirectory&) = delete; + WorkingDirectory(); + static WorkingDirectory* instance_; + std::string path_; + bool did_set_ = false; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_GOLDEN_TESTS_WORKING_DIRECTORY_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/BUILD.gn b/flutter/engine/src/flutter/impeller/playground/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5b611bb99a143e48915c392556ac55f7f2dd6093 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/BUILD.gn @@ -0,0 +1,91 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/testing/testing.gni") + +impeller_component("playground") { + testonly = true + + sources = [ + "playground.cc", + "playground.h", + "playground_impl.cc", + "playground_impl.h", + "switches.cc", + "switches.h", + "widgets.cc", + "widgets.h", + + # Swiftshader is Vulkan backend specific but the utilities are not. + "backend/vulkan/swiftshader_utilities.cc", + "backend/vulkan/swiftshader_utilities.h", + ] + + deps = [ "../renderer/backend" ] + + if (impeller_enable_metal) { + sources += [ + "backend/metal/playground_impl_mtl.h", + "backend/metal/playground_impl_mtl.mm", + ] + } + + if (impeller_enable_opengles) { + sources += [ + "backend/gles/playground_impl_gles.cc", + "backend/gles/playground_impl_gles.h", + ] + } + + if (impeller_enable_vulkan) { + sources += [ + "backend/vulkan/playground_impl_vk.cc", + "backend/vulkan/playground_impl_vk.h", + ] + } + + public_deps = [ + "../fixtures:modern_shader_fixtures", + "../fixtures:shader_fixtures", + "../renderer", + "image:image_skia_backend", + "imgui:imgui_impeller_backend", + "//flutter/fml", + "//flutter/testing:testing_lib", + "//flutter/third_party/glfw", + "//flutter/third_party/imgui:imgui_glfw", + ] + + if (impeller_supports_rendering) { + public_deps += [ + "../entity:entity_shaders", + "../entity:framebuffer_blend_entity_shaders", + "../entity:modern_entity_shaders", + ] + } + + if (is_mac) { + frameworks = [ + "AppKit.framework", + "QuartzCore.framework", + ] + } +} + +impeller_component("playground_test") { + testonly = true + + sources = [ + "compute_playground_test.cc", + "compute_playground_test.h", + "playground_test.cc", + "playground_test.h", + ] + + public_deps = [ + ":playground", + "//flutter/testing:testing_lib", + ] +} diff --git a/flutter/engine/src/flutter/impeller/playground/README.md b/flutter/engine/src/flutter/impeller/playground/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d1964b51fbea1393eeee0b6e2fe2781208fe846e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/README.md @@ -0,0 +1,9 @@ +# The Impeller Playground + +An extension of the testing fixtures set, provides utilities for interactive +experimentation with the Impeller rendering subsystem. One the test author is +satisfied with the behavior of component as verified in the playground, pixel +test assertions can be added to before committing the new test case. Meant to +provide a gentle-er on-ramp to testing Impeller components. The WSI in the +playground allows for points at which third-party profiling and instrumentation +tools can be used to examine isolated test cases. diff --git a/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.cc b/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..092a07cfd79dfa94d91acbfb70f145f540006211 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.cc @@ -0,0 +1,203 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/backend/gles/playground_impl_gles.h" + +#define IMPELLER_PLAYGROUND_SUPPORTS_ANGLE FML_OS_MACOSX + +#if IMPELLER_PLAYGROUND_SUPPORTS_ANGLE +#include +#endif + +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +#include "flutter/fml/build_config.h" +#include "impeller/entity/gles/entity_shaders_gles.h" +#include "impeller/entity/gles/framebuffer_blend_shaders_gles.h" +#include "impeller/entity/gles/modern_shaders_gles.h" +#include "impeller/fixtures/gles/fixtures_shaders_gles.h" +#include "impeller/fixtures/gles/modern_fixtures_shaders_gles.h" +#include "impeller/playground/imgui/gles/imgui_shaders_gles.h" +#include "impeller/renderer/backend/gles/context_gles.h" +#include "impeller/renderer/backend/gles/surface_gles.h" + +namespace impeller { + +class PlaygroundImplGLES::ReactorWorker final : public ReactorGLES::Worker { + public: + ReactorWorker() = default; + + // |ReactorGLES::Worker| + bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const override { + ReaderLock lock(mutex_); + auto found = reactions_allowed_.find(std::this_thread::get_id()); + if (found == reactions_allowed_.end()) { + return false; + } + return found->second; + } + + void SetReactionsAllowedOnCurrentThread(bool allowed) { + WriterLock lock(mutex_); + reactions_allowed_[std::this_thread::get_id()] = allowed; + } + + private: + mutable RWMutex mutex_; + std::map reactions_allowed_ IPLR_GUARDED_BY(mutex_); + + ReactorWorker(const ReactorWorker&) = delete; + + ReactorWorker& operator=(const ReactorWorker&) = delete; +}; + +void PlaygroundImplGLES::DestroyWindowHandle(WindowHandle handle) { + if (!handle) { + return; + } + ::glfwDestroyWindow(reinterpret_cast(handle)); +} + +PlaygroundImplGLES::PlaygroundImplGLES(PlaygroundSwitches switches) + : PlaygroundImpl(switches), + handle_(nullptr, &DestroyWindowHandle), + worker_(std::shared_ptr(new ReactorWorker())), + use_angle_(switches.use_angle) { + if (use_angle_) { +#if IMPELLER_PLAYGROUND_SUPPORTS_ANGLE + angle_glesv2_ = dlopen("libGLESv2.dylib", RTLD_LAZY); +#endif + FML_CHECK(angle_glesv2_ != nullptr); + } + + ::glfwDefaultWindowHints(); + +#if FML_OS_MACOSX + FML_CHECK(use_angle_) << "Must use Angle on macOS for OpenGL ES."; + ::glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); +#endif // FML_OS_MACOSX + ::glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); + ::glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); + ::glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); + ::glfwWindowHint(GLFW_RED_BITS, 8); + ::glfwWindowHint(GLFW_GREEN_BITS, 8); + ::glfwWindowHint(GLFW_BLUE_BITS, 8); + ::glfwWindowHint(GLFW_ALPHA_BITS, 8); + ::glfwWindowHint(GLFW_DEPTH_BITS, 32); // 32 bit depth buffer + ::glfwWindowHint(GLFW_STENCIL_BITS, 8); // 8 bit stencil buffer + ::glfwWindowHint(GLFW_SAMPLES, 4); // 4xMSAA + + ::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + + auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr); + + ::glfwMakeContextCurrent(window); + worker_->SetReactionsAllowedOnCurrentThread(true); + + handle_.reset(window); +} + +PlaygroundImplGLES::~PlaygroundImplGLES() = default; + +static std::vector> +ShaderLibraryMappingsForPlayground() { + return { + std::make_shared( + impeller_entity_shaders_gles_data, + impeller_entity_shaders_gles_length), + std::make_shared( + impeller_modern_shaders_gles_data, + impeller_modern_shaders_gles_length), + std::make_shared( + impeller_framebuffer_blend_shaders_gles_data, + impeller_framebuffer_blend_shaders_gles_length), + std::make_shared( + impeller_fixtures_shaders_gles_data, + impeller_fixtures_shaders_gles_length), + std::make_shared( + impeller_modern_fixtures_shaders_gles_data, + impeller_modern_fixtures_shaders_gles_length), + std::make_shared( + impeller_imgui_shaders_gles_data, impeller_imgui_shaders_gles_length), + }; +} + +// |PlaygroundImpl| +std::shared_ptr PlaygroundImplGLES::GetContext() const { + auto gl = std::make_unique(CreateGLProcAddressResolver()); + if (!gl->IsValid()) { + FML_LOG(ERROR) << "Proc table when creating a playground was invalid."; + return nullptr; + } + + auto context = + ContextGLES::Create(switches_.flags, std::move(gl), + ShaderLibraryMappingsForPlayground(), true); + if (!context) { + FML_LOG(ERROR) << "Could not create context."; + return nullptr; + } + + auto worker_id = context->AddReactorWorker(worker_); + if (!worker_id.has_value()) { + FML_LOG(ERROR) << "Could not add reactor worker."; + return nullptr; + } + return context; +} + +// |PlaygroundImpl| +Playground::GLProcAddressResolver +PlaygroundImplGLES::CreateGLProcAddressResolver() const { + return use_angle_ ? [](const char* name) -> void* { + void* symbol = nullptr; +#if IMPELLER_PLAYGROUND_SUPPORTS_ANGLE + void* angle_glesv2 = dlopen("libGLESv2.dylib", RTLD_LAZY); + symbol = dlsym(angle_glesv2, name); +#endif + FML_CHECK(symbol); + return symbol; + } + : [](const char* name) -> void* { + return reinterpret_cast(::glfwGetProcAddress(name)); + }; +} + +// |PlaygroundImpl| +PlaygroundImpl::WindowHandle PlaygroundImplGLES::GetWindowHandle() const { + return handle_.get(); +} + +// |PlaygroundImpl| +std::unique_ptr PlaygroundImplGLES::AcquireSurfaceFrame( + std::shared_ptr context) { + auto window = reinterpret_cast(GetWindowHandle()); + int width = 0; + int height = 0; + ::glfwGetFramebufferSize(window, &width, &height); + if (width <= 0 || height <= 0) { + return nullptr; + } + SurfaceGLES::SwapCallback swap_callback = [window]() -> bool { + ::glfwSwapBuffers(window); + return true; + }; + return SurfaceGLES::WrapFBO(context, // + swap_callback, // + 0u, // + PixelFormat::kR8G8B8A8UNormInt, // + ISize::MakeWH(width, height) // + ); +} + +fml::Status PlaygroundImplGLES::SetCapabilities( + const std::shared_ptr& capabilities) { + return fml::Status( + fml::StatusCode::kUnimplemented, + "PlaygroundImplGLES doesn't support setting the capabilities."); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.h b/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..c1973e929414f490abe434de1906fd6e64647fca --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/gles/playground_impl_gles.h @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_ + +#include "impeller/playground/playground_impl.h" + +namespace impeller { + +class PlaygroundImplGLES final : public PlaygroundImpl { + public: + explicit PlaygroundImplGLES(PlaygroundSwitches switches); + + ~PlaygroundImplGLES(); + + fml::Status SetCapabilities( + const std::shared_ptr& capabilities) override; + + private: + class ReactorWorker; + + static void DestroyWindowHandle(WindowHandle handle); + using UniqueHandle = std::unique_ptr; + UniqueHandle handle_; + std::shared_ptr worker_; + const bool use_angle_; + void* angle_glesv2_; + + // |PlaygroundImpl| + std::shared_ptr GetContext() const override; + + // |PlaygroundImpl| + WindowHandle GetWindowHandle() const override; + + // |PlaygroundImpl| + std::unique_ptr AcquireSurfaceFrame( + std::shared_ptr context) override; + + // |PlaygroundImpl| + Playground::GLProcAddressResolver CreateGLProcAddressResolver() + const override; + + PlaygroundImplGLES(const PlaygroundImplGLES&) = delete; + + PlaygroundImplGLES& operator=(const PlaygroundImplGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_GLES_PLAYGROUND_IMPL_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.h b/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..2028a82529ba45d524d923ef4b032decc514831d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_METAL_PLAYGROUND_IMPL_MTL_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_METAL_PLAYGROUND_IMPL_MTL_H_ + +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "impeller/playground/playground_impl.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" + +namespace impeller { + +// Forward declared to avoid objc in a C++ header. +class ContextMTL; + +class PlaygroundImplMTL final : public PlaygroundImpl { + public: + explicit PlaygroundImplMTL(PlaygroundSwitches switches); + + ~PlaygroundImplMTL(); + + fml::Status SetCapabilities( + const std::shared_ptr& capabilities) override; + + private: + struct Data; + + static void DestroyWindowHandle(WindowHandle handle); + using UniqueHandle = std::unique_ptr; + UniqueHandle handle_; + + // To ensure that ObjC stuff doesn't leak into C++ TUs. + std::unique_ptr data_; + std::shared_ptr context_; + std::shared_ptr concurrent_loop_; + std::shared_ptr swapchain_transients_; + std::shared_ptr is_gpu_disabled_sync_switch_; + + // |PlaygroundImpl| + std::shared_ptr GetContext() const override; + + // |PlaygroundImpl| + WindowHandle GetWindowHandle() const override; + + // |PlaygroundImpl| + std::unique_ptr AcquireSurfaceFrame( + std::shared_ptr context) override; + + // |PlaygroundImpl| + void SetGPUDisabled(bool disabled) const override; + + PlaygroundImplMTL(const PlaygroundImplMTL&) = delete; + + PlaygroundImplMTL& operator=(const PlaygroundImplMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_METAL_PLAYGROUND_IMPL_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.mm b/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..a276c11aeaa69db641b962324650e79fb2854f08 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/metal/playground_impl_mtl.mm @@ -0,0 +1,145 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/backend/metal/playground_impl_mtl.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" + +#define GLFW_INCLUDE_NONE +#import "third_party/glfw/include/GLFW/glfw3.h" + +#define GLFW_EXPOSE_NATIVE_COCOA +#import "third_party/glfw/include/GLFW/glfw3native.h" + +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/entity/mtl/entity_shaders.h" +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" +#include "impeller/entity/mtl/modern_shaders.h" +#include "impeller/fixtures/mtl/fixtures_shaders.h" +#include "impeller/fixtures/mtl/modern_fixtures_shaders.h" +#include "impeller/playground/imgui/mtl/imgui_shaders.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/surface_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/mtl/compute_shaders.h" + +namespace impeller { + +struct PlaygroundImplMTL::Data { + CAMetalLayer* metal_layer = nil; +}; + +static std::vector> +ShaderLibraryMappingsForPlayground() { + return {std::make_shared( + impeller_entity_shaders_data, impeller_entity_shaders_length), + std::make_shared( + impeller_modern_shaders_data, impeller_modern_shaders_length), + std::make_shared( + impeller_framebuffer_blend_shaders_data, + impeller_framebuffer_blend_shaders_length), + std::make_shared( + impeller_fixtures_shaders_data, impeller_fixtures_shaders_length), + std::make_shared( + impeller_modern_fixtures_shaders_data, + impeller_modern_fixtures_shaders_length), + std::make_shared(impeller_imgui_shaders_data, + impeller_imgui_shaders_length), + std::make_shared( + impeller_compute_shaders_data, impeller_compute_shaders_length) + + }; +} + +void PlaygroundImplMTL::DestroyWindowHandle(WindowHandle handle) { + if (!handle) { + return; + } + ::glfwDestroyWindow(reinterpret_cast(handle)); +} + +PlaygroundImplMTL::PlaygroundImplMTL(PlaygroundSwitches switches) + : PlaygroundImpl(switches), + handle_(nullptr, &DestroyWindowHandle), + data_(std::make_unique()), + concurrent_loop_(fml::ConcurrentMessageLoop::Create()), + is_gpu_disabled_sync_switch_(new fml::SyncSwitch(false)) { + ::glfwDefaultWindowHints(); + ::glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + ::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr); + if (!window) { + return; + } + + auto context = ContextMTL::Create( + switches.flags, ShaderLibraryMappingsForPlayground(), + is_gpu_disabled_sync_switch_, "Playground Library", + switches.enable_wide_gamut + ? std::optional(PixelFormat::kB10G10R10A10XR) + : std::nullopt); + if (!context) { + return; + } + NSWindow* cocoa_window = ::glfwGetCocoaWindow(window); + if (cocoa_window == nil) { + return; + } + data_->metal_layer = [CAMetalLayer layer]; + data_->metal_layer.device = ContextMTL::Cast(*context).GetMTLDevice(); + data_->metal_layer.pixelFormat = + ToMTLPixelFormat(context->GetCapabilities()->GetDefaultColorFormat()); + data_->metal_layer.framebufferOnly = NO; + cocoa_window.contentView.layer = data_->metal_layer; + cocoa_window.contentView.wantsLayer = YES; + + handle_.reset(window); + context_ = std::move(context); + swapchain_transients_ = std::make_shared( + context_->GetResourceAllocator()); +} + +PlaygroundImplMTL::~PlaygroundImplMTL() = default; + +std::shared_ptr PlaygroundImplMTL::GetContext() const { + return context_; +} + +// |PlaygroundImpl| +PlaygroundImpl::WindowHandle PlaygroundImplMTL::GetWindowHandle() const { + return handle_.get(); +} + +// |PlaygroundImpl| +std::unique_ptr PlaygroundImplMTL::AcquireSurfaceFrame( + std::shared_ptr context) { + if (!data_->metal_layer) { + return nullptr; + } + + const auto layer_size = data_->metal_layer.bounds.size; + const auto scale = GetContentScale(); + data_->metal_layer.drawableSize = + CGSizeMake(layer_size.width * scale.x, layer_size.height * scale.y); + + auto drawable = + SurfaceMTL::GetMetalDrawableAndValidate(context, data_->metal_layer); + return SurfaceMTL::MakeFromMetalLayerDrawable(context, drawable, + swapchain_transients_); +} + +fml::Status PlaygroundImplMTL::SetCapabilities( + const std::shared_ptr& capabilities) { + context_->SetCapabilities(capabilities); + return fml::Status(); +} + +void PlaygroundImplMTL::SetGPUDisabled(bool disabled) const { + is_gpu_disabled_sync_switch_->SetSwitch(disabled); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ea803d954041228e3020290e8fdd5d54d9f50f5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.cc @@ -0,0 +1,249 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/backend/vulkan/playground_impl_vk.h" + +#include "flutter/fml/paths.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +#define GLFW_INCLUDE_VULKAN +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/mapping.h" +#include "impeller/entity/vk/entity_shaders_vk.h" +#include "impeller/entity/vk/framebuffer_blend_shaders_vk.h" +#include "impeller/entity/vk/modern_shaders_vk.h" +#include "impeller/fixtures/vk/fixtures_shaders_vk.h" +#include "impeller/fixtures/vk/modern_fixtures_shaders_vk.h" +#include "impeller/playground/imgui/vk/imgui_shaders_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/surface_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/vk/compute_shaders_vk.h" + +namespace impeller { + +static std::vector> +ShaderLibraryMappingsForPlayground() { + return { + std::make_shared(impeller_entity_shaders_vk_data, + impeller_entity_shaders_vk_length), + std::make_shared(impeller_modern_shaders_vk_data, + impeller_modern_shaders_vk_length), + std::make_shared( + impeller_framebuffer_blend_shaders_vk_data, + impeller_framebuffer_blend_shaders_vk_length), + std::make_shared( + impeller_fixtures_shaders_vk_data, + impeller_fixtures_shaders_vk_length), + std::make_shared( + impeller_modern_fixtures_shaders_vk_data, + impeller_modern_fixtures_shaders_vk_length), + std::make_shared(impeller_imgui_shaders_vk_data, + impeller_imgui_shaders_vk_length), + std::make_shared( + impeller_compute_shaders_vk_data, impeller_compute_shaders_vk_length), + }; +} + +// A global Vulkan instance that is reused across all Vulkan playgrounds. +// This instance is kept for the entire process lifetime. It is not cleaned +// up during shutdown to avoid conflicts with destruction of other globals +// in dependencies like the Vulkan validation layers. +VkInstance PlaygroundImplVK::global_instance_ = VK_NULL_HANDLE; + +void PlaygroundImplVK::DestroyWindowHandle(WindowHandle handle) { + if (!handle) { + return; + } + ::glfwDestroyWindow(reinterpret_cast(handle)); +} + +PlaygroundImplVK::PlaygroundImplVK(PlaygroundSwitches switches) + : PlaygroundImpl(switches), handle_(nullptr, &DestroyWindowHandle) { + FML_CHECK(IsVulkanDriverPresent()); + + InitGlobalVulkanInstance(); + + ::glfwDefaultWindowHints(); + ::glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + ::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + + auto window = ::glfwCreateWindow(1, 1, "Test", nullptr, nullptr); + if (!window) { + VALIDATION_LOG << "Unable to create glfw window"; + return; + } + + int width = 0; + int height = 0; + ::glfwGetWindowSize(window, &width, &height); + size_ = ISize{width, height}; + + handle_.reset(window); + + ContextVK::Settings context_settings; + context_settings.proc_address_callback = + reinterpret_cast( + &::glfwGetInstanceProcAddress); + context_settings.shader_libraries_data = ShaderLibraryMappingsForPlayground(); + context_settings.cache_directory = fml::paths::GetCachesDirectory(); + context_settings.enable_validation = switches_.enable_vulkan_validation; + context_settings.fatal_missing_validations = + switches_.enable_vulkan_validation; + context_settings.flags = switches_.flags; + + auto context_vk = ContextVK::Create(std::move(context_settings)); + if (!context_vk || !context_vk->IsValid()) { + VALIDATION_LOG << "Could not create Vulkan context in the playground."; + return; + } + + VkSurfaceKHR vk_surface; + auto res = vk::Result{::glfwCreateWindowSurface( + context_vk->GetInstance(), // instance + window, // window + nullptr, // allocator + &vk_surface // surface + )}; + if (res != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create surface for GLFW window: " + << vk::to_string(res); + return; + } + + vk::UniqueSurfaceKHR surface{vk_surface, context_vk->GetInstance()}; + auto context = context_vk->CreateSurfaceContext(); + if (!context->SetWindowSurface(std::move(surface), size_)) { + VALIDATION_LOG << "Could not set up surface for context."; + return; + } + + context_ = std::move(context); +} + +PlaygroundImplVK::~PlaygroundImplVK() = default; + +// |PlaygroundImpl| +std::shared_ptr PlaygroundImplVK::GetContext() const { + return context_; +} + +// |PlaygroundImpl| +PlaygroundImpl::WindowHandle PlaygroundImplVK::GetWindowHandle() const { + return handle_.get(); +} + +// |PlaygroundImpl| +std::unique_ptr PlaygroundImplVK::AcquireSurfaceFrame( + std::shared_ptr context) { + SurfaceContextVK* surface_context_vk = + reinterpret_cast(context_.get()); + + int width = 0; + int height = 0; + ::glfwGetFramebufferSize(reinterpret_cast(handle_.get()), &width, + &height); + size_ = ISize{width, height}; + surface_context_vk->UpdateSurfaceSize(ISize{width, height}); + + return surface_context_vk->AcquireNextSurface(); +} + +// Create a global instance of Vulkan in order to prevent unloading of the +// Vulkan library. +// A test suite may repeatedly create and destroy PlaygroundImplVK instances, +// and if the PlaygroundImplVK's Vulkan instance is the only one in the +// process then the Vulkan library will be unloaded when the instance is +// destroyed. Repeated loading and unloading of SwiftShader was leaking +// resources, so this will work around that leak. +// (see https://github.com/flutter/flutter/issues/138028) +void PlaygroundImplVK::InitGlobalVulkanInstance() { + if (global_instance_) { + return; + } + + VULKAN_HPP_DEFAULT_DISPATCHER.init(::glfwGetInstanceProcAddress); + + vk::ApplicationInfo application_info; + application_info.setApplicationVersion(VK_API_VERSION_1_0); + application_info.setApiVersion(VK_API_VERSION_1_1); + application_info.setEngineVersion(VK_API_VERSION_1_0); + application_info.setPEngineName("PlaygroundImplVK"); + application_info.setPApplicationName("PlaygroundImplVK"); + + auto caps = std::shared_ptr( + new CapabilitiesVK(/*enable_validations=*/true)); + FML_DCHECK(caps->IsValid()); + + std::optional> enabled_layers = + caps->GetEnabledLayers(); + std::optional> enabled_extensions = + caps->GetEnabledInstanceExtensions(); + FML_DCHECK(enabled_layers.has_value() && enabled_extensions.has_value()); + + std::vector enabled_layers_c; + std::vector enabled_extensions_c; + + if (enabled_layers.has_value()) { + for (const auto& layer : enabled_layers.value()) { + enabled_layers_c.push_back(layer.c_str()); + } + } + + if (enabled_extensions.has_value()) { + for (const auto& ext : enabled_extensions.value()) { + enabled_extensions_c.push_back(ext.c_str()); + } + } + + vk::InstanceCreateFlags instance_flags = {}; + instance_flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR; + vk::InstanceCreateInfo instance_info; + instance_info.setPEnabledLayerNames(enabled_layers_c); + instance_info.setPEnabledExtensionNames(enabled_extensions_c); + instance_info.setPApplicationInfo(&application_info); + instance_info.setFlags(instance_flags); + auto instance_result = vk::createInstanceUnique(instance_info); + FML_CHECK(instance_result.result == vk::Result::eSuccess) + << "Unable to initialize global Vulkan instance"; + global_instance_ = instance_result.value.release(); +} + +fml::Status PlaygroundImplVK::SetCapabilities( + const std::shared_ptr& capabilities) { + return fml::Status( + fml::StatusCode::kUnimplemented, + "PlaygroundImplVK doesn't support setting the capabilities."); +} + +bool PlaygroundImplVK::IsVulkanDriverPresent() { + if (::glfwVulkanSupported()) { + return true; + } +#ifdef TARGET_OS_MAC + FML_LOG(ERROR) << "Attempting to initialize a Vulkan playground on macOS " + "where Vulkan cannot be found. It can be installed via " + "MoltenVK and make sure to install it globally so " + "dlopen can find it."; +#else // TARGET_OS_MAC + FML_LOG(ERROR) << "Attempting to initialize a Vulkan playground on a system " + "that does not support Vulkan."; +#endif // TARGET_OS_MAC + return false; +} + +// |PlaygroundImpl| +Playground::VKProcAddressResolver +PlaygroundImplVK::CreateVKProcAddressResolver() const { + return [](void* instance, const char* proc_name) -> void* { + return reinterpret_cast(::glfwGetInstanceProcAddress( + reinterpret_cast(instance), proc_name)); + }; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..0f4012469a0535156ccc5b97214c42ba50003767 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/playground_impl_vk.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_ + +#include "impeller/playground/playground_impl.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class PlaygroundImplVK final : public PlaygroundImpl { + public: + static bool IsVulkanDriverPresent(); + + explicit PlaygroundImplVK(PlaygroundSwitches switches); + + ~PlaygroundImplVK(); + + fml::Status SetCapabilities( + const std::shared_ptr& capabilities) override; + + private: + std::shared_ptr context_; + + // Windows management. + static void DestroyWindowHandle(WindowHandle handle); + using UniqueHandle = std::unique_ptr; + UniqueHandle handle_; + ISize size_ = {1, 1}; + + // A global Vulkan instance which ensures that the Vulkan library will remain + // loaded throughout the lifetime of the process. + static VkInstance global_instance_; + + // |PlaygroundImpl| + std::shared_ptr GetContext() const override; + + // |PlaygroundImpl| + WindowHandle GetWindowHandle() const override; + + // |PlaygroundImpl| + std::unique_ptr AcquireSurfaceFrame( + std::shared_ptr context) override; + + // |PlaygroundImpl| + Playground::VKProcAddressResolver CreateVKProcAddressResolver() + const override; + + PlaygroundImplVK(const PlaygroundImplVK&) = delete; + + PlaygroundImplVK& operator=(const PlaygroundImplVK&) = delete; + + static void InitGlobalVulkanInstance(); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_PLAYGROUND_IMPL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.cc b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.cc new file mode 100644 index 0000000000000000000000000000000000000000..96e5ad6f0c5e8a0980f00911be11ab9bd3676fdc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.cc @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/playground/backend/vulkan/swiftshader_utilities.h" + +#include + +#include "flutter/fml/build_config.h" +#include "flutter/fml/file.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/paths.h" + +#if FML_OS_WIN +#include +#endif // FML_OS_WIN + +namespace impeller { + +static void FindSwiftShaderICDAtKnownPaths() { + static constexpr const char* kSwiftShaderICDJSON = "vk_swiftshader_icd.json"; + static constexpr const char* kVulkanICDFileNamesEnvVariableKey = + "VK_ICD_FILENAMES"; + const auto executable_directory_path = + fml::paths::GetExecutableDirectoryPath(); + FML_CHECK(executable_directory_path.first); + const auto executable_directory = + fml::OpenDirectory(executable_directory_path.second.c_str(), false, + fml::FilePermission::kRead); + FML_CHECK(executable_directory.is_valid()); + if (fml::FileExists(executable_directory, kSwiftShaderICDJSON)) { + const auto icd_path = fml::paths::JoinPaths( + {executable_directory_path.second, kSwiftShaderICDJSON}); +#if FML_OS_WIN + const auto success = + ::SetEnvironmentVariableA(kVulkanICDFileNamesEnvVariableKey, // + icd_path.c_str() // + ) != 0; +#else // FML_OS_WIN + const auto success = ::setenv(kVulkanICDFileNamesEnvVariableKey, // + icd_path.c_str(), // + 1 // overwrite + ) == 0; +#endif // FML_OS_WIN + FML_CHECK(success) + << "Could not set the environment variable to use SwiftShader."; + } else { + FML_CHECK(false) + << "Was asked to use SwiftShader but could not find the installable " + "client driver (ICD) for the locally built SwiftShader."; + } +} + +void SetupSwiftshaderOnce(bool use_swiftshader) { + static bool swiftshader_preference = false; + static std::once_flag sOnceInitializer; + std::call_once(sOnceInitializer, [use_swiftshader]() { + if (use_swiftshader) { + FindSwiftShaderICDAtKnownPaths(); + swiftshader_preference = use_swiftshader; + } + }); + FML_CHECK(swiftshader_preference == use_swiftshader) + << "The option to use SwiftShader in a process can only be set once and " + "may not be changed later."; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.h b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.h new file mode 100644 index 0000000000000000000000000000000000000000..5331ed69550dd1fb74191a8233dbaeaa62dc05b8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/backend/vulkan/swiftshader_utilities.h @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_ + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Find and setup the installable client driver for a locally built +/// SwiftShader at known paths. The option to use SwiftShader can +/// only be used once in the process. While calling this method +/// multiple times is fine, specifying a different use_swiftshader +/// value will trip an assertion. +/// +/// @warning This call must be made before any Vulkan contexts are created in +/// the process. +/// +/// @param[in] use_swiftshader If SwiftShader should be used. +/// +void SetupSwiftshaderOnce(bool use_swiftshader); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_BACKEND_VULKAN_SWIFTSHADER_UTILITIES_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/compute_playground_test.cc b/flutter/engine/src/flutter/impeller/playground/compute_playground_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1848e01bc33150e2164f0839d2349e0a3baceaf7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/compute_playground_test.cc @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/time/time_point.h" + +#include "flutter/testing/test_args.h" +#include "impeller/playground/compute_playground_test.h" + +namespace impeller { + +ComputePlaygroundTest::ComputePlaygroundTest() + : Playground(PlaygroundSwitches{flutter::testing::GetArgsForProcess()}) {} + +ComputePlaygroundTest::~ComputePlaygroundTest() = default; + +void ComputePlaygroundTest::SetUp() { + if (!Playground::SupportsBackend(GetParam())) { + GTEST_SKIP() << "Playground doesn't support this backend type."; + return; + } + + if (!Playground::ShouldOpenNewPlaygrounds()) { + GTEST_SKIP() << "Skipping due to user action."; + return; + } + + SetupContext(GetParam(), switches_); + SetupWindow(); + + start_time_ = fml::TimePoint::Now().ToEpochDelta(); +} + +void ComputePlaygroundTest::TearDown() { + TeardownWindow(); +} + +// |Playground| +std::unique_ptr ComputePlaygroundTest::OpenAssetAsMapping( + std::string asset_name) const { + return flutter::testing::OpenFixtureAsMapping(asset_name); +} + +static std::string FormatWindowTitle(const std::string& test_name) { + std::stringstream stream; + stream << "Impeller Playground for '" << test_name << "' (Press ESC to quit)"; + return stream.str(); +} + +// |Playground| +std::string ComputePlaygroundTest::GetWindowTitle() const { + return FormatWindowTitle(flutter::testing::GetCurrentTestName()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/compute_playground_test.h b/flutter/engine/src/flutter/impeller/playground/compute_playground_test.h new file mode 100644 index 0000000000000000000000000000000000000000..bed292b2690d845c0407daf33a57164cb3ddeecf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/compute_playground_test.h @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_ + +#include + +#include "flutter/fml/time/time_delta.h" +#include "flutter/testing/testing.h" +#include "impeller/core/device_buffer.h" +#include "impeller/playground/playground.h" + +namespace impeller { + +class ComputePlaygroundTest + : public Playground, + public ::testing::TestWithParam { + public: + ComputePlaygroundTest(); + + virtual ~ComputePlaygroundTest(); + + void SetUp() override; + + void TearDown() override; + + // |Playground| + std::unique_ptr OpenAssetAsMapping( + std::string asset_name) const override; + + // |Playground| + std::string GetWindowTitle() const override; + + template + std::shared_ptr CreateHostVisibleDeviceBuffer( + const std::shared_ptr& context, + const std::string& label) { + DeviceBufferDescriptor desc; + desc.storage_mode = StorageMode::kHostVisible; + desc.size = sizeof(T); + auto buffer = context->GetResourceAllocator()->CreateBuffer(desc); + buffer->SetLabel(label); + return buffer; + } + + private: + fml::TimeDelta start_time_; + + ComputePlaygroundTest(const ComputePlaygroundTest&) = delete; + + ComputePlaygroundTest& operator=(const ComputePlaygroundTest&) = delete; +}; + +#define INSTANTIATE_COMPUTE_SUITE(playground) \ + INSTANTIATE_TEST_SUITE_P( \ + Compute, playground, \ + ::testing::Values(PlaygroundBackend::kMetal, \ + PlaygroundBackend::kVulkan), \ + [](const ::testing::TestParamInfo& \ + info) { return PlaygroundBackendToString(info.param); }); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_COMPUTE_PLAYGROUND_TEST_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/image/BUILD.gn b/flutter/engine/src/flutter/impeller/playground/image/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ed44158f9b2fd3864e26487468d68e6ea07cc0b8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("image") { + testonly = true + public = [ + "compressed_image.h", + "decompressed_image.h", + ] + + sources = [ + "compressed_image.cc", + "decompressed_image.cc", + ] + + public_deps = [ + "../../base", + "../../geometry", + ] + + deps = [ "//flutter/fml" ] +} + +impeller_component("image_skia_backend") { + testonly = true + public = [ "backends/skia/compressed_image_skia.h" ] + + sources = [ "backends/skia/compressed_image_skia.cc" ] + + public_deps = [ + ":image", + "../../base", + "../../geometry", + ] + + deps = [ + "//flutter/fml", + "//flutter/skia", + ] +} diff --git a/flutter/engine/src/flutter/impeller/playground/image/README.md b/flutter/engine/src/flutter/impeller/playground/image/README.md new file mode 100644 index 0000000000000000000000000000000000000000..97840b564b674d1ca67fc959405b4584142c1bf4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/README.md @@ -0,0 +1,4 @@ +# The Impeller Image Library + +Set of utilities for working with texture information. The library is indepenent +of the rendering subsystem. diff --git a/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.cc b/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..e44510cdfded97d8c335ed9bf0db0847876225d9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.cc @@ -0,0 +1,86 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/image/backends/skia/compressed_image_skia.h" + +#include + +#include "impeller/base/validation.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/skia/include/core/SkImage.h" +#include "third_party/skia/include/core/SkPixmap.h" +#include "third_party/skia/include/core/SkRefCnt.h" + +namespace impeller { + +std::shared_ptr CompressedImageSkia::Create( + std::shared_ptr allocation) { + // There is only one backend today. + if (!allocation) { + return nullptr; + } + return std::make_shared(std::move(allocation)); +} + +CompressedImageSkia::CompressedImageSkia( + std::shared_ptr allocation) + : CompressedImage(std::move(allocation)) {} + +CompressedImageSkia::~CompressedImageSkia() = default; + +// |CompressedImage| +DecompressedImage CompressedImageSkia::Decode() const { + if (!IsValid()) { + return {}; + } + if (source_->GetSize() == 0u) { + return {}; + } + + auto src = new std::shared_ptr(source_); + auto sk_data = SkData::MakeWithProc( + source_->GetMapping(), source_->GetSize(), + [](const void* ptr, void* context) { + delete reinterpret_cast(context); + }, + src); + + auto image = SkImages::DeferredFromEncodedData(sk_data); + if (!image) { + return {}; + } + + const auto dims = image->imageInfo().dimensions(); + auto info = SkImageInfo::Make(dims.width(), dims.height(), + kRGBA_8888_SkColorType, kPremul_SkAlphaType); + + auto bitmap = std::make_shared(); + if (!bitmap->tryAllocPixels(info)) { + VALIDATION_LOG << "Could not allocate arena for decompressing image."; + return {}; + } + + if (!image->readPixels(nullptr, bitmap->pixmap(), 0, 0)) { + VALIDATION_LOG << "Could not decompress image into arena."; + return {}; + } + + auto mapping = std::make_shared( + reinterpret_cast(bitmap->pixmap().addr()), // data + bitmap->pixmap().rowBytes() * bitmap->pixmap().height(), // size + [bitmap](const uint8_t* data, size_t size) mutable { + bitmap.reset(); + } // proc + ); + + return { + {bitmap->pixmap().dimensions().fWidth, + bitmap->pixmap().dimensions().fHeight}, // size + DecompressedImage::Format::kRGBA, // format + mapping // allocation + }; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.h b/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..c8360fd46668f2e494921c82ef9e3de256e5070a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/backends/skia/compressed_image_skia.h @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_ + +#include "impeller/playground/image/compressed_image.h" + +namespace impeller { + +class CompressedImageSkia final : public CompressedImage { + public: + static std::shared_ptr Create( + std::shared_ptr allocation); + + explicit CompressedImageSkia(std::shared_ptr allocation); + + ~CompressedImageSkia() override; + + // |CompressedImage| + DecompressedImage Decode() const override; + + private: + CompressedImageSkia(const CompressedImageSkia&) = delete; + + CompressedImageSkia& operator=(const CompressedImageSkia&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_BACKENDS_SKIA_COMPRESSED_IMAGE_SKIA_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/image/compressed_image.cc b/flutter/engine/src/flutter/impeller/playground/image/compressed_image.cc new file mode 100644 index 0000000000000000000000000000000000000000..5d1ad4e0fd7ae888dcf18925cacb206420b294ff --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/compressed_image.cc @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/image/compressed_image.h" + +namespace impeller { + +CompressedImage::CompressedImage(std::shared_ptr allocation) + : source_(std::move(allocation)) {} + +CompressedImage::~CompressedImage() = default; + +bool CompressedImage::IsValid() const { + return static_cast(source_); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/image/compressed_image.h b/flutter/engine/src/flutter/impeller/playground/image/compressed_image.h new file mode 100644 index 0000000000000000000000000000000000000000..f5962e202b15b41e3eddbe9766eab60ae745d49c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/compressed_image.h @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/playground/image/decompressed_image.h" + +namespace impeller { + +class ImageSource; + +class CompressedImage { + public: + virtual ~CompressedImage(); + + [[nodiscard]] virtual DecompressedImage Decode() const = 0; + + bool IsValid() const; + + protected: + const std::shared_ptr source_; + + explicit CompressedImage(std::shared_ptr allocation); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.cc b/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e7f8fd6214a045e801139abdf532e96ed0868e0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.cc @@ -0,0 +1,123 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/image/decompressed_image.h" + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/allocation.h" + +namespace impeller { + +DecompressedImage::DecompressedImage() = default; + +DecompressedImage::DecompressedImage( + ISize size, + Format format, + std::shared_ptr allocation) + : size_(size), format_(format), allocation_(std::move(allocation)) { + if (!allocation_ || size.IsEmpty() || format_ == Format::kInvalid) { + return; + } + is_valid_ = true; +} + +DecompressedImage::~DecompressedImage() = default; + +bool DecompressedImage::IsValid() const { + return is_valid_; +} + +const ISize& DecompressedImage::GetSize() const { + return size_; +} + +DecompressedImage::Format DecompressedImage::GetFormat() const { + return format_; +} + +const std::shared_ptr& DecompressedImage::GetAllocation() + const { + return allocation_; +} + +static size_t GetBytesPerPixel(DecompressedImage::Format format) { + switch (format) { + case DecompressedImage::Format::kInvalid: + return 0u; + case DecompressedImage::Format::kGrey: + return 1u; + case DecompressedImage::Format::kGreyAlpha: + return 1u; + case DecompressedImage::Format::kRGB: + return 3u; + case DecompressedImage::Format::kRGBA: + return 4; + } + return 0u; +} + +DecompressedImage DecompressedImage::ConvertToRGBA() const { + if (!is_valid_) { + return {}; + } + + if (format_ == Format::kRGBA) { + return DecompressedImage{size_, format_, allocation_}; + } + + const auto bpp = GetBytesPerPixel(format_); + const auto source_byte_size = size_.Area() * bpp; + if (allocation_->GetSize() < source_byte_size) { + return {}; + } + + auto rgba_allocation = std::make_shared(); + if (!rgba_allocation->Truncate(Bytes{size_.Area() * 4u}, false)) { + return {}; + } + + const uint8_t* source = allocation_->GetMapping(); + uint8_t* dest = rgba_allocation->GetBuffer(); + + for (size_t i = 0, j = 0; i < source_byte_size; i += bpp, j += 4u) { + switch (format_) { + case DecompressedImage::Format::kGrey: + dest[j + 0] = source[i]; + dest[j + 1] = source[i]; + dest[j + 2] = source[i]; + dest[j + 3] = std::numeric_limits::max(); + break; + case DecompressedImage::Format::kGreyAlpha: + dest[j + 0] = std::numeric_limits::max(); + dest[j + 1] = std::numeric_limits::max(); + dest[j + 2] = std::numeric_limits::max(); + dest[j + 3] = source[i]; + break; + case DecompressedImage::Format::kRGB: + dest[j + 0] = source[i + 0]; + dest[j + 1] = source[i + 1]; + dest[j + 2] = source[i + 2]; + dest[j + 3] = std::numeric_limits::max(); + break; + case DecompressedImage::Format::kInvalid: + case DecompressedImage::Format::kRGBA: + // Should never happen. The necessary checks have already been + // performed. + FML_CHECK(false); + break; + } + } + + return DecompressedImage{ + size_, Format::kRGBA, + std::make_shared( + rgba_allocation->GetBuffer(), // + rgba_allocation->GetLength().GetByteSize(), // + [rgba_allocation](auto, auto) {}) // + }; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.h b/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.h new file mode 100644 index 0000000000000000000000000000000000000000..9df680fc47cd65bad7523071c7a40c5d8511f4c7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/image/decompressed_image.h @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +class DecompressedImage { + public: + enum class Format { + kInvalid, + kGrey, + kGreyAlpha, + kRGB, + kRGBA, + }; + + DecompressedImage(); + + DecompressedImage(ISize size, + Format format, + std::shared_ptr allocation); + + ~DecompressedImage(); + + const ISize& GetSize() const; + + bool IsValid() const; + + Format GetFormat() const; + + const std::shared_ptr& GetAllocation() const; + + DecompressedImage ConvertToRGBA() const; + + private: + ISize size_; + Format format_ = Format::kInvalid; + std::shared_ptr allocation_; + bool is_valid_ = false; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_DECOMPRESSED_IMAGE_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/imgui/BUILD.gn b/flutter/engine/src/flutter/impeller/playground/imgui/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..19bb195876f4d1b0ae784163d5bd25c646e2cccc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/imgui/BUILD.gn @@ -0,0 +1,31 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_shaders("imgui_shaders") { + name = "imgui" + + # Not analyzing because they are not performance critical, and mipmap uses + # textureLod, which uses an extension that malioc does not support. + analyze = false + shaders = [ + "imgui_raster.vert", + "imgui_raster.frag", + ] +} + +impeller_component("imgui_impeller_backend") { + public_deps = [ + ":imgui_shaders", + "//flutter/third_party/imgui", + ] + + deps = [ "//flutter/impeller/renderer" ] + + sources = [ + "imgui_impl_impeller.cc", + "imgui_impl_impeller.h", + ] +} diff --git a/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.cc b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..61c08db35f0a12ce1ebbd48fb7aa3007b1624841 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.cc @@ -0,0 +1,285 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "imgui_impl_impeller.h" + +#include +#include +#include +#include + +#include "fml/mapping.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/platform.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/vector.h" +#include "impeller/playground/imgui/imgui_raster.frag.h" +#include "impeller/playground/imgui/imgui_raster.vert.h" +#include "third_party/imgui/imgui.h" + +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/core/range.h" +#include "impeller/core/sampler.h" +#include "impeller/core/texture.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/pipeline_builder.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/render_pass.h" + +struct ImGui_ImplImpeller_Data { + explicit ImGui_ImplImpeller_Data( + impeller::raw_ptr p_sampler) + : sampler(p_sampler) {} + + std::shared_ptr context; + std::shared_ptr font_texture; + std::shared_ptr> pipeline; + impeller::raw_ptr sampler; +}; + +static ImGui_ImplImpeller_Data* ImGui_ImplImpeller_GetBackendData() { + return ImGui::GetCurrentContext() + ? static_cast( + ImGui::GetIO().BackendRendererUserData) + : nullptr; +} + +bool ImGui_ImplImpeller_Init( + const std::shared_ptr& context) { + ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendRendererUserData == nullptr && + "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + auto* bd = + new ImGui_ImplImpeller_Data(context->GetSamplerLibrary()->GetSampler({})); + io.BackendRendererUserData = reinterpret_cast(bd); + io.BackendRendererName = "imgui_impl_impeller"; + io.BackendFlags |= + ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the + // ImDrawCmd::VtxOffset field, + // allowing for large meshes. + + bd->context = context; + + // Generate/upload the font atlas. + { + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + + impeller::TextureDescriptor texture_descriptor; + texture_descriptor.storage_mode = impeller::StorageMode::kDevicePrivate; + texture_descriptor.format = impeller::PixelFormat::kR8G8B8A8UNormInt; + texture_descriptor.size = {width, height}; + texture_descriptor.mip_count = 1u; + + bd->font_texture = + context->GetResourceAllocator()->CreateTexture(texture_descriptor); + IM_ASSERT(bd->font_texture != nullptr && + "Could not allocate ImGui font texture."); + bd->font_texture->SetLabel("ImGui Font Texture"); + + auto command_buffer = context->CreateCommandBuffer(); + auto blit_pass = command_buffer->CreateBlitPass(); + auto mapping = std::make_shared( + reinterpret_cast(pixels), + texture_descriptor.GetByteSizeOfBaseMipLevel()); + auto device_buffer = + context->GetResourceAllocator()->CreateBufferWithCopy(*mapping); + + blit_pass->AddCopy(impeller::DeviceBuffer::AsBufferView(device_buffer), + bd->font_texture); + blit_pass->EncodeCommands(); + + [[maybe_unused]] bool uploaded = + context->GetCommandQueue()->Submit({command_buffer}).ok(); + IM_ASSERT(uploaded && + "Could not upload ImGui font texture to device memory."); + } + + // Build the raster pipeline. + { + auto desc = impeller::PipelineBuilder:: + MakeDefaultPipelineDescriptor(*context); + IM_ASSERT(desc.has_value() && "Could not create Impeller pipeline"); + if (desc.has_value()) { // Needed to silence clang-tidy check + // bugprone-unchecked-optional-access. + desc->ClearStencilAttachments(); + desc->ClearDepthAttachment(); + } + + bd->pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + IM_ASSERT(bd->pipeline != nullptr && "Could not create ImGui pipeline."); + IM_ASSERT(bd->pipeline != nullptr && "Could not create ImGui sampler."); + } + + return true; +} + +void ImGui_ImplImpeller_Shutdown() { + auto* bd = ImGui_ImplImpeller_GetBackendData(); + IM_ASSERT(bd != nullptr && + "No renderer backend to shutdown, or already shutdown?"); + delete bd; +} + +void ImGui_ImplImpeller_RenderDrawData(ImDrawData* draw_data, + impeller::RenderPass& render_pass, + impeller::HostBuffer& host_buffer) { + if (draw_data->CmdListsCount == 0) { + return; // Nothing to render. + } + + using VS = impeller::ImguiRasterVertexShader; + using FS = impeller::ImguiRasterFragmentShader; + + auto* bd = ImGui_ImplImpeller_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplImpeller_Init()?"); + + size_t total_vtx_bytes = draw_data->TotalVtxCount * sizeof(VS::PerVertexData); + size_t total_idx_bytes = draw_data->TotalIdxCount * sizeof(ImDrawIdx); + if (!total_vtx_bytes || !total_idx_bytes) { + return; // Nothing to render. + } + + // Allocate buffer for vertices + indices. + impeller::DeviceBufferDescriptor buffer_desc; + buffer_desc.size = total_vtx_bytes + total_idx_bytes; + buffer_desc.storage_mode = impeller::StorageMode::kHostVisible; + + auto buffer = bd->context->GetResourceAllocator()->CreateBuffer(buffer_desc); + buffer->SetLabel(impeller::SPrintF("ImGui vertex+index buffer")); + + auto display_rect = impeller::Rect::MakeXYWH( + draw_data->DisplayPos.x, draw_data->DisplayPos.y, + draw_data->DisplaySize.x, draw_data->DisplaySize.y); + + auto viewport = impeller::Viewport{ + .rect = display_rect.Scale(draw_data->FramebufferScale.x, + draw_data->FramebufferScale.y)}; + + // Allocate vertex shader uniform buffer. + VS::UniformBuffer uniforms; + uniforms.mvp = impeller::Matrix::MakeOrthographic(display_rect.GetSize()) + .Translate(-display_rect.GetOrigin()); + auto vtx_uniforms = host_buffer.EmplaceUniform(uniforms); + + size_t vertex_buffer_offset = 0; + size_t index_buffer_offset = total_vtx_bytes; + + for (int draw_list_i = 0; draw_list_i < draw_data->CmdListsCount; + draw_list_i++) { + const ImDrawList* cmd_list = draw_data->CmdLists[draw_list_i]; + + // Convert ImGui's per-vertex data (`ImDrawVert`) into the per-vertex data + // required by the shader (`VS::PerVectexData`). The only difference is that + // `ImDrawVert` uses an `int` for the color and the impeller shader uses 4 + // floats. + + // TODO(102778): Remove the need for this by adding support for attribute + // mapping of uint32s host-side to vec4s shader-side in + // impellerc. + std::vector vtx_data; + vtx_data.reserve(cmd_list->VtxBuffer.size()); + for (const auto& v : cmd_list->VtxBuffer) { + ImVec4 color = ImGui::ColorConvertU32ToFloat4(v.col); + vtx_data.push_back({{v.pos.x, v.pos.y}, // + {v.uv.x, v.uv.y}, // + {color.x, color.y, color.z, color.w}}); + } + + auto draw_list_vtx_bytes = + static_cast(vtx_data.size() * sizeof(VS::PerVertexData)); + auto draw_list_idx_bytes = + static_cast(cmd_list->IdxBuffer.size_in_bytes()); + if (!buffer->CopyHostBuffer(reinterpret_cast(vtx_data.data()), + impeller::Range{0, draw_list_vtx_bytes}, + vertex_buffer_offset)) { + IM_ASSERT(false && "Could not copy vertices to buffer."); + } + if (!buffer->CopyHostBuffer( + reinterpret_cast(cmd_list->IdxBuffer.Data), + impeller::Range{0, draw_list_idx_bytes}, index_buffer_offset)) { + IM_ASSERT(false && "Could not copy indices to buffer."); + } + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + + if (pcmd->UserCallback) { + pcmd->UserCallback(cmd_list, pcmd); + } else { + // Make the clip rect relative to the viewport. + auto clip_rect = impeller::Rect::MakeLTRB( + (pcmd->ClipRect.x - draw_data->DisplayPos.x) * + draw_data->FramebufferScale.x, + (pcmd->ClipRect.y - draw_data->DisplayPos.y) * + draw_data->FramebufferScale.y, + (pcmd->ClipRect.z - draw_data->DisplayPos.x) * + draw_data->FramebufferScale.x, + (pcmd->ClipRect.w - draw_data->DisplayPos.y) * + draw_data->FramebufferScale.y); + { + // Clamp the clip to the viewport bounds. + auto visible_clip = clip_rect.Intersection(viewport.rect); + if (!visible_clip.has_value()) { + continue; // Nothing to render. + } + clip_rect = visible_clip.value(); + } + { + // Clamp the clip to ensure it never goes outside of the render + // target. + auto visible_clip = clip_rect.Intersection( + impeller::Rect::MakeSize(render_pass.GetRenderTargetSize())); + if (!visible_clip.has_value()) { + continue; // Nothing to render. + } + clip_rect = visible_clip.value(); + } + + render_pass.SetCommandLabel(impeller::SPrintF( + "ImGui draw list %d (command %d)", draw_list_i, cmd_i)); + render_pass.SetViewport(viewport); + render_pass.SetScissor(impeller::IRect::RoundOut(clip_rect)); + render_pass.SetPipeline(bd->pipeline); + VS::BindUniformBuffer(render_pass, vtx_uniforms); + FS::BindTex(render_pass, bd->font_texture, bd->sampler); + + size_t vb_start = + vertex_buffer_offset + pcmd->VtxOffset * sizeof(ImDrawVert); + + impeller::VertexBuffer vertex_buffer; + vertex_buffer.vertex_buffer = impeller::BufferView( + buffer, impeller::Range(vb_start, draw_list_vtx_bytes - vb_start)); + vertex_buffer.index_buffer = impeller::BufferView( + buffer, impeller::Range(index_buffer_offset + + pcmd->IdxOffset * sizeof(ImDrawIdx), + pcmd->ElemCount * sizeof(ImDrawIdx))); + vertex_buffer.vertex_count = pcmd->ElemCount; + vertex_buffer.index_type = impeller::IndexType::k16bit; + render_pass.SetVertexBuffer(std::move(vertex_buffer)); + render_pass.SetBaseVertex(pcmd->VtxOffset); + + render_pass.Draw().ok(); + } + } + + vertex_buffer_offset += draw_list_vtx_bytes; + index_buffer_offset += draw_list_idx_bytes; + } + host_buffer.Reset(); +} diff --git a/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.h b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..163dac8f9a01c9a0326cdb86aeaa41b76527a246 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_impl_impeller.h @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_ + +#include + +#include "impeller/core/host_buffer.h" +#include "third_party/imgui/imgui.h" + +namespace impeller { + +class Context; +class RenderPass; + +} // namespace impeller + +IMGUI_IMPL_API bool ImGui_ImplImpeller_Init( + const std::shared_ptr& context); + +IMGUI_IMPL_API void ImGui_ImplImpeller_Shutdown(); + +IMGUI_IMPL_API void ImGui_ImplImpeller_RenderDrawData( + ImDrawData* draw_data, + impeller::RenderPass& renderpass, + impeller::HostBuffer& host_buffer); + +#endif // FLUTTER_IMPELLER_PLAYGROUND_IMGUI_IMGUI_IMPL_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.frag b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.frag new file mode 100644 index 0000000000000000000000000000000000000000..f159e20d69845e760207f21c8e3c8dff0efc4cbe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.frag @@ -0,0 +1,14 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +in vec2 frag_texture_coordinates; +in vec4 frag_vertex_color; + +out vec4 frag_color; + +uniform sampler2D tex; + +void main() { + frag_color = frag_vertex_color * texture(tex, frag_texture_coordinates.st); +} diff --git a/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.vert b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.vert new file mode 100644 index 0000000000000000000000000000000000000000..8a103dc6bfeb50901e5c2af9890333769124b34c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/imgui/imgui_raster.vert @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +uniform UniformBuffer { + mat4 mvp; +} +uniform_buffer; + +in vec2 vertex_position; +in vec2 texture_coordinates; +in vec4 vertex_color; + +out vec2 frag_texture_coordinates; +out vec4 frag_vertex_color; + +void main() { + gl_Position = uniform_buffer.mvp * vec4(vertex_position.xy, 0.0, 1.0); + frag_texture_coordinates = texture_coordinates; + frag_vertex_color = vertex_color; +} diff --git a/flutter/engine/src/flutter/impeller/playground/playground.cc b/flutter/engine/src/flutter/impeller/playground/playground.cc new file mode 100644 index 0000000000000000000000000000000000000000..164500ca49fdbaff8fa04cddae0b81443f6f42d4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground.cc @@ -0,0 +1,533 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include + +#include "fml/closure.h" +#include "fml/time/time_point.h" +#include "impeller/core/host_buffer.h" +#include "impeller/playground/image/backends/skia/compressed_image_skia.h" +#include "impeller/playground/image/decompressed_image.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_target.h" +#include "impeller/runtime_stage/runtime_stage.h" + +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +#include "flutter/fml/paths.h" +#include "impeller/base/validation.h" +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/playground/backend/vulkan/swiftshader_utilities.h" +#include "impeller/playground/image/compressed_image.h" +#include "impeller/playground/imgui/imgui_impl_impeller.h" +#include "impeller/playground/playground.h" +#include "impeller/playground/playground_impl.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/render_pass.h" +#include "third_party/imgui/backends/imgui_impl_glfw.h" +#include "third_party/imgui/imgui.h" + +#if FML_OS_MACOSX +#include "fml/platform/darwin/scoped_nsautorelease_pool.h" +#endif // FML_OS_MACOSX + +#if IMPELLER_ENABLE_VULKAN +#include "impeller/playground/backend/vulkan/playground_impl_vk.h" +#endif // IMPELLER_ENABLE_VULKAN + +namespace impeller { + +std::string PlaygroundBackendToString(PlaygroundBackend backend) { + switch (backend) { + case PlaygroundBackend::kMetal: + return "Metal"; + case PlaygroundBackend::kOpenGLES: + return "OpenGLES"; + case PlaygroundBackend::kVulkan: + return "Vulkan"; + } + FML_UNREACHABLE(); +} + +static void InitializeGLFWOnce() { + // This guard is a hack to work around a problem where glfwCreateWindow + // hangs when opening a second window after GLFW has been reinitialized (for + // example, when flipping through multiple playground tests). + // + // Explanation: + // * glfwCreateWindow calls [NSApp run], which begins running the event + // loop on the current thread. + // * GLFW then immediately stops the loop when + // applicationDidFinishLaunching is fired. + // * applicationDidFinishLaunching is only ever fired once during the + // application's lifetime, so subsequent calls to [NSApp run] will always + // hang with this setup. + // * glfwInit resets the flag that guards against [NSApp run] being + // called a second time, which causes the subsequent `glfwCreateWindow` + // to hang indefinitely in the event loop, because + // applicationDidFinishLaunching is never fired. + static std::once_flag sOnceInitializer; + std::call_once(sOnceInitializer, []() { + ::glfwSetErrorCallback([](int code, const char* description) { + FML_LOG(ERROR) << "GLFW Error '" << description << "' (" << code << ")."; + }); + FML_CHECK(::glfwInit() == GLFW_TRUE); + }); +} + +Playground::Playground(PlaygroundSwitches switches) : switches_(switches) { + InitializeGLFWOnce(); + SetupSwiftshaderOnce(switches_.use_swiftshader); +} + +Playground::~Playground() = default; + +std::shared_ptr Playground::GetContext() const { + return context_; +} + +std::shared_ptr Playground::MakeContext() const { + // Playgrounds are already making a context for each test, so we can just + // return the `context_`. + return context_; +} + +bool Playground::SupportsBackend(PlaygroundBackend backend) { + switch (backend) { + case PlaygroundBackend::kMetal: +#if IMPELLER_ENABLE_METAL + return true; +#else // IMPELLER_ENABLE_METAL + return false; +#endif // IMPELLER_ENABLE_METAL + case PlaygroundBackend::kOpenGLES: +#if IMPELLER_ENABLE_OPENGLES + return true; +#else // IMPELLER_ENABLE_OPENGLES + return false; +#endif // IMPELLER_ENABLE_OPENGLES + case PlaygroundBackend::kVulkan: +#if IMPELLER_ENABLE_VULKAN + return PlaygroundImplVK::IsVulkanDriverPresent(); +#else // IMPELLER_ENABLE_VULKAN + return false; +#endif // IMPELLER_ENABLE_VULKAN + } + FML_UNREACHABLE(); +} + +void Playground::SetupContext(PlaygroundBackend backend, + const PlaygroundSwitches& switches) { + FML_CHECK(SupportsBackend(backend)); + + impl_ = PlaygroundImpl::Create(backend, switches); + if (!impl_) { + FML_LOG(WARNING) << "PlaygroundImpl::Create failed."; + return; + } + + context_ = impl_->GetContext(); +} + +void Playground::SetupWindow() { + if (!context_) { + FML_LOG(WARNING) << "Asked to set up a window with no context (call " + "SetupContext first)."; + return; + } + start_time_ = fml::TimePoint::Now().ToEpochDelta(); +} + +bool Playground::IsPlaygroundEnabled() const { + return switches_.enable_playground; +} + +void Playground::TeardownWindow() { + if (host_buffer_) { + host_buffer_.reset(); + } + if (context_) { + context_->Shutdown(); + } + context_.reset(); + impl_.reset(); +} + +static std::atomic_bool gShouldOpenNewPlaygrounds = true; + +bool Playground::ShouldOpenNewPlaygrounds() { + return gShouldOpenNewPlaygrounds; +} + +static void PlaygroundKeyCallback(GLFWwindow* window, + int key, + int scancode, + int action, + int mods) { + if ((key == GLFW_KEY_ESCAPE) && action == GLFW_RELEASE) { + if (mods & (GLFW_MOD_CONTROL | GLFW_MOD_SUPER | GLFW_MOD_SHIFT)) { + gShouldOpenNewPlaygrounds = false; + } + ::glfwSetWindowShouldClose(window, GLFW_TRUE); + } +} + +Point Playground::GetCursorPosition() const { + return cursor_position_; +} + +ISize Playground::GetWindowSize() const { + return window_size_; +} + +Point Playground::GetContentScale() const { + return impl_->GetContentScale(); +} + +Scalar Playground::GetSecondsElapsed() const { + return (fml::TimePoint::Now().ToEpochDelta() - start_time_).ToSecondsF(); +} + +void Playground::SetCursorPosition(Point pos) { + cursor_position_ = pos; +} + +bool Playground::OpenPlaygroundHere( + const Playground::RenderCallback& render_callback) { + if (!switches_.enable_playground) { + return true; + } + + if (!render_callback) { + return true; + } + + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + fml::ScopedCleanupClosure destroy_imgui_context( + []() { ImGui::DestroyContext(); }); + ImGui::StyleColorsDark(); + + auto& io = ImGui::GetIO(); + io.IniFilename = nullptr; + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + io.ConfigWindowsResizeFromEdges = true; + + auto window = reinterpret_cast(impl_->GetWindowHandle()); + if (!window) { + return false; + } + ::glfwSetWindowTitle(window, GetWindowTitle().c_str()); + ::glfwSetWindowUserPointer(window, this); + ::glfwSetWindowSizeCallback( + window, [](GLFWwindow* window, int width, int height) -> void { + auto playground = + reinterpret_cast(::glfwGetWindowUserPointer(window)); + if (!playground) { + return; + } + playground->SetWindowSize(ISize{width, height}.Max({})); + }); + ::glfwSetKeyCallback(window, &PlaygroundKeyCallback); + ::glfwSetCursorPosCallback(window, [](GLFWwindow* window, double x, + double y) { + reinterpret_cast(::glfwGetWindowUserPointer(window)) + ->SetCursorPosition({static_cast(x), static_cast(y)}); + }); + + ImGui_ImplGlfw_InitForOther(window, true); + fml::ScopedCleanupClosure shutdown_imgui([]() { ImGui_ImplGlfw_Shutdown(); }); + + ImGui_ImplImpeller_Init(context_); + fml::ScopedCleanupClosure shutdown_imgui_impeller( + []() { ImGui_ImplImpeller_Shutdown(); }); + + ImGui::SetNextWindowPos({10, 10}); + + ::glfwSetWindowSize(window, GetWindowSize().width, GetWindowSize().height); + ::glfwSetWindowPos(window, 200, 100); + ::glfwShowWindow(window); + + while (true) { +#if FML_OS_MACOSX + fml::ScopedNSAutoreleasePool pool; +#endif + ::glfwPollEvents(); + + if (::glfwWindowShouldClose(window)) { + return true; + } + + ImGui_ImplGlfw_NewFrame(); + + auto surface = impl_->AcquireSurfaceFrame(context_); + RenderTarget render_target = surface->GetRenderTarget(); + + ImGui::NewFrame(); + ImGui::DockSpaceOverViewport(ImGui::GetMainViewport(), + ImGuiDockNodeFlags_PassthruCentralNode); + bool result = render_callback(render_target); + ImGui::Render(); + + // Render ImGui overlay. + { + auto buffer = context_->CreateCommandBuffer(); + if (!buffer) { + VALIDATION_LOG << "Could not create command buffer."; + return false; + } + buffer->SetLabel("ImGui Command Buffer"); + + auto color0 = render_target.GetColorAttachment(0); + color0.load_action = LoadAction::kLoad; + if (color0.resolve_texture) { + color0.texture = color0.resolve_texture; + color0.resolve_texture = nullptr; + color0.store_action = StoreAction::kStore; + } + render_target.SetColorAttachment(color0, 0); + render_target.SetStencilAttachment(std::nullopt); + render_target.SetDepthAttachment(std::nullopt); + + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + VALIDATION_LOG << "Could not create render pass."; + return false; + } + pass->SetLabel("ImGui Render Pass"); + if (!host_buffer_) { + host_buffer_ = HostBuffer::Create(context_->GetResourceAllocator(), + context_->GetIdleWaiter()); + } + + ImGui_ImplImpeller_RenderDrawData(ImGui::GetDrawData(), *pass, + *host_buffer_); + + pass->EncodeCommands(); + + if (!context_->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + } + + if (!result || !surface->Present()) { + return false; + } + + if (!ShouldKeepRendering()) { + break; + } + } + + ::glfwHideWindow(window); + + return true; +} + +bool Playground::OpenPlaygroundHere(SinglePassCallback pass_callback) { + return OpenPlaygroundHere( + [context = GetContext(), &pass_callback](RenderTarget& render_target) { + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + return false; + } + pass->SetLabel("Playground Render Pass"); + + if (!pass_callback(*pass)) { + return false; + } + + pass->EncodeCommands(); + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + return true; + }); +} + +std::shared_ptr Playground::LoadFixtureImageCompressed( + std::shared_ptr mapping) { + auto compressed_image = CompressedImageSkia::Create(std::move(mapping)); + if (!compressed_image) { + VALIDATION_LOG << "Could not create compressed image."; + return nullptr; + } + + return compressed_image; +} + +std::optional Playground::DecodeImageRGBA( + const std::shared_ptr& compressed) { + if (compressed == nullptr) { + return std::nullopt; + } + // The decoded image is immediately converted into RGBA as that format is + // known to be supported everywhere. For image sources that don't need 32 + // bit pixel strides, this is overkill. Since this is a test fixture we + // aren't necessarily trying to eke out memory savings here and instead + // favor simplicity. + auto image = compressed->Decode().ConvertToRGBA(); + if (!image.IsValid()) { + VALIDATION_LOG << "Could not decode image."; + return std::nullopt; + } + + return image; +} + +static std::shared_ptr CreateTextureForDecompressedImage( + const std::shared_ptr& context, + DecompressedImage& decompressed_image, + bool enable_mipmapping) { + TextureDescriptor texture_descriptor; + texture_descriptor.storage_mode = StorageMode::kDevicePrivate; + texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt; + texture_descriptor.size = decompressed_image.GetSize(); + texture_descriptor.mip_count = + enable_mipmapping ? decompressed_image.GetSize().MipCount() : 1u; + + auto texture = + context->GetResourceAllocator()->CreateTexture(texture_descriptor); + if (!texture) { + VALIDATION_LOG << "Could not allocate texture for fixture."; + return nullptr; + } + + auto command_buffer = context->CreateCommandBuffer(); + if (!command_buffer) { + FML_DLOG(ERROR) << "Could not create command buffer for mipmap generation."; + return nullptr; + } + command_buffer->SetLabel("Mipmap Command Buffer"); + + auto blit_pass = command_buffer->CreateBlitPass(); + auto buffer_view = DeviceBuffer::AsBufferView( + context->GetResourceAllocator()->CreateBufferWithCopy( + *decompressed_image.GetAllocation())); + blit_pass->AddCopy(buffer_view, texture); + if (enable_mipmapping) { + blit_pass->SetLabel("Mipmap Blit Pass"); + blit_pass->GenerateMipmap(texture); + } + blit_pass->EncodeCommands(); + if (!context->GetCommandQueue()->Submit({command_buffer}).ok()) { + FML_DLOG(ERROR) << "Failed to submit blit pass command buffer."; + return nullptr; + } + return texture; +} + +std::shared_ptr Playground::CreateTextureForMapping( + const std::shared_ptr& context, + std::shared_ptr mapping, + bool enable_mipmapping) { + auto image = Playground::DecodeImageRGBA( + Playground::LoadFixtureImageCompressed(std::move(mapping))); + if (!image.has_value()) { + return nullptr; + } + return CreateTextureForDecompressedImage(context, image.value(), + enable_mipmapping); +} + +std::shared_ptr Playground::CreateTextureForFixture( + const char* fixture_name, + bool enable_mipmapping) const { + auto texture = CreateTextureForMapping( + context_, OpenAssetAsMapping(fixture_name), enable_mipmapping); + if (texture == nullptr) { + return nullptr; + } + texture->SetLabel(fixture_name); + return texture; +} + +std::shared_ptr Playground::CreateTextureCubeForFixture( + std::array fixture_names) const { + std::array images; + for (size_t i = 0; i < fixture_names.size(); i++) { + auto image = DecodeImageRGBA( + LoadFixtureImageCompressed(OpenAssetAsMapping(fixture_names[i]))); + if (!image.has_value()) { + return nullptr; + } + images[i] = image.value(); + } + + TextureDescriptor texture_descriptor; + texture_descriptor.storage_mode = StorageMode::kDevicePrivate; + texture_descriptor.type = TextureType::kTextureCube; + texture_descriptor.format = PixelFormat::kR8G8B8A8UNormInt; + texture_descriptor.size = images[0].GetSize(); + texture_descriptor.mip_count = 1u; + + auto texture = + context_->GetResourceAllocator()->CreateTexture(texture_descriptor); + if (!texture) { + VALIDATION_LOG << "Could not allocate texture cube."; + return nullptr; + } + texture->SetLabel("Texture cube"); + + auto cmd_buffer = context_->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + for (size_t i = 0; i < fixture_names.size(); i++) { + auto device_buffer = context_->GetResourceAllocator()->CreateBufferWithCopy( + *images[i].GetAllocation()); + blit_pass->AddCopy(DeviceBuffer::AsBufferView(device_buffer), texture, {}, + "", /*mip_level=*/0, /*slice=*/i); + } + + if (!blit_pass->EncodeCommands() || + !context_->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()) { + VALIDATION_LOG << "Could not upload texture to device memory."; + return nullptr; + } + + return texture; +} + +void Playground::SetWindowSize(ISize size) { + window_size_ = size; +} + +bool Playground::ShouldKeepRendering() const { + return true; +} + +fml::Status Playground::SetCapabilities( + const std::shared_ptr& capabilities) { + return impl_->SetCapabilities(capabilities); +} + +bool Playground::WillRenderSomething() const { + return switches_.enable_playground; +} + +Playground::GLProcAddressResolver Playground::CreateGLProcAddressResolver() + const { + return impl_->CreateGLProcAddressResolver(); +} + +Playground::VKProcAddressResolver Playground::CreateVKProcAddressResolver() + const { + return impl_->CreateVKProcAddressResolver(); +} + +void Playground::SetGPUDisabled(bool value) const { + impl_->SetGPUDisabled(value); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/playground.h b/flutter/engine/src/flutter/impeller/playground/playground.h new file mode 100644 index 0000000000000000000000000000000000000000..6878a5975156cf4a5177ae3f78b8fb2287ba7581 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground.h @@ -0,0 +1,154 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_ + +#include +#include + +#include "flutter/fml/status.h" +#include "flutter/fml/time/time_delta.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/texture.h" +#include "impeller/geometry/point.h" +#include "impeller/playground/image/compressed_image.h" +#include "impeller/playground/image/decompressed_image.h" +#include "impeller/playground/switches.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace impeller { + +class PlaygroundImpl; + +enum class PlaygroundBackend { + kMetal, + kOpenGLES, + kVulkan, +}; + +constexpr inline RuntimeStageBackend PlaygroundBackendToRuntimeStageBackend( + PlaygroundBackend backend) { + switch (backend) { + case PlaygroundBackend::kMetal: + return RuntimeStageBackend::kMetal; + case PlaygroundBackend::kOpenGLES: + return RuntimeStageBackend::kOpenGLES; + case PlaygroundBackend::kVulkan: + return RuntimeStageBackend::kVulkan; + } + FML_UNREACHABLE(); +} + +std::string PlaygroundBackendToString(PlaygroundBackend backend); + +class Playground { + public: + using SinglePassCallback = std::function; + + explicit Playground(PlaygroundSwitches switches); + + virtual ~Playground(); + + static bool ShouldOpenNewPlaygrounds(); + + void SetupContext(PlaygroundBackend backend, + const PlaygroundSwitches& switches); + + void SetupWindow(); + + void TeardownWindow(); + + bool IsPlaygroundEnabled() const; + + Point GetCursorPosition() const; + + ISize GetWindowSize() const; + + Point GetContentScale() const; + + /// @brief Get the amount of time elapsed from the start of the playground's + /// execution. + Scalar GetSecondsElapsed() const; + + std::shared_ptr GetContext() const; + + std::shared_ptr MakeContext() const; + + using RenderCallback = std::function; + + bool OpenPlaygroundHere(const RenderCallback& render_callback); + + bool OpenPlaygroundHere(SinglePassCallback pass_callback); + + static std::shared_ptr LoadFixtureImageCompressed( + std::shared_ptr mapping); + + static std::optional DecodeImageRGBA( + const std::shared_ptr& compressed); + + static std::shared_ptr CreateTextureForMapping( + const std::shared_ptr& context, + std::shared_ptr mapping, + bool enable_mipmapping = false); + + std::shared_ptr CreateTextureForFixture( + const char* fixture_name, + bool enable_mipmapping = false) const; + + std::shared_ptr CreateTextureCubeForFixture( + std::array fixture_names) const; + + static bool SupportsBackend(PlaygroundBackend backend); + + virtual std::unique_ptr OpenAssetAsMapping( + std::string asset_name) const = 0; + + virtual std::string GetWindowTitle() const = 0; + + [[nodiscard]] fml::Status SetCapabilities( + const std::shared_ptr& capabilities); + + /// Returns true if `OpenPlaygroundHere` will actually render anything. + bool WillRenderSomething() const; + + using GLProcAddressResolver = std::function; + GLProcAddressResolver CreateGLProcAddressResolver() const; + + using VKProcAddressResolver = + std::function; + VKProcAddressResolver CreateVKProcAddressResolver() const; + + /// @brief Mark the GPU as unavilable. + /// + /// Only supported on the Metal backend. + void SetGPUDisabled(bool disabled) const; + + protected: + const PlaygroundSwitches switches_; + + virtual bool ShouldKeepRendering() const; + + void SetWindowSize(ISize size); + + private: + fml::TimeDelta start_time_; + std::unique_ptr impl_; + std::shared_ptr context_; + Point cursor_position_; + ISize window_size_ = ISize{1024, 768}; + std::shared_ptr host_buffer_; + + void SetCursorPosition(Point pos); + + Playground(const Playground&) = delete; + + Playground& operator=(const Playground&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/playground_impl.cc b/flutter/engine/src/flutter/impeller/playground/playground_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..df086c9100400504d18829df5524f09d16deadf3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground_impl.cc @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/playground_impl.h" +#include "flutter/testing/testing.h" + +#define GLFW_INCLUDE_NONE +#include "third_party/glfw/include/GLFW/glfw3.h" + +#if IMPELLER_ENABLE_METAL +#include "impeller/playground/backend/metal/playground_impl_mtl.h" +#endif // IMPELLER_ENABLE_METAL + +#if IMPELLER_ENABLE_OPENGLES +#include "impeller/playground/backend/gles/playground_impl_gles.h" +#endif // IMPELLER_ENABLE_OPENGLES + +#if IMPELLER_ENABLE_VULKAN +#include "impeller/playground/backend/vulkan/playground_impl_vk.h" +#endif // IMPELLER_ENABLE_VULKAN + +namespace impeller { + +std::unique_ptr PlaygroundImpl::Create( + PlaygroundBackend backend, + PlaygroundSwitches switches) { + switch (backend) { +#if IMPELLER_ENABLE_METAL + case PlaygroundBackend::kMetal: + return std::make_unique(switches); +#endif // IMPELLER_ENABLE_METAL +#if IMPELLER_ENABLE_OPENGLES + case PlaygroundBackend::kOpenGLES: + return std::make_unique(switches); +#endif // IMPELLER_ENABLE_OPENGLES +#if IMPELLER_ENABLE_VULKAN + case PlaygroundBackend::kVulkan: + if (!PlaygroundImplVK::IsVulkanDriverPresent()) { + FML_CHECK(false) << "Attempted to create playground with backend that " + "isn't available or was disabled on this platform: " + << PlaygroundBackendToString(backend); + } + switches.enable_vulkan_validation = true; + return std::make_unique(switches); +#endif // IMPELLER_ENABLE_VULKAN + default: + FML_CHECK(false) << "Attempted to create playground with backend that " + "isn't available or was disabled on this platform: " + << PlaygroundBackendToString(backend); + } + FML_UNREACHABLE(); +} + +PlaygroundImpl::PlaygroundImpl(PlaygroundSwitches switches) + : switches_(switches) {} + +PlaygroundImpl::~PlaygroundImpl() = default; + +Vector2 PlaygroundImpl::GetContentScale() const { + auto window = reinterpret_cast(GetWindowHandle()); + + Vector2 scale(1, 1); + ::glfwGetWindowContentScale(window, &scale.x, &scale.y); + + return scale; +} + +Playground::GLProcAddressResolver PlaygroundImpl::CreateGLProcAddressResolver() + const { + return nullptr; +} + +Playground::VKProcAddressResolver PlaygroundImpl::CreateVKProcAddressResolver() + const { + return nullptr; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/playground_impl.h b/flutter/engine/src/flutter/impeller/playground/playground_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..ed2593fc98ffb56dfbcc2140bcefe13e4bc71642 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground_impl.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_IMPL_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_IMPL_H_ + +#include +#include + +#include "impeller/playground/playground.h" +#include "impeller/playground/switches.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +class PlaygroundImpl { + public: + static std::unique_ptr Create(PlaygroundBackend backend, + PlaygroundSwitches switches); + + virtual ~PlaygroundImpl(); + + using WindowHandle = void*; + + virtual WindowHandle GetWindowHandle() const = 0; + + virtual std::shared_ptr GetContext() const = 0; + + virtual std::unique_ptr AcquireSurfaceFrame( + std::shared_ptr context) = 0; + + Vector2 GetContentScale() const; + + virtual fml::Status SetCapabilities( + const std::shared_ptr& capabilities) = 0; + + virtual Playground::GLProcAddressResolver CreateGLProcAddressResolver() const; + + virtual Playground::VKProcAddressResolver CreateVKProcAddressResolver() const; + + virtual void SetGPUDisabled(bool disabled) const {} + + protected: + const PlaygroundSwitches switches_; + + explicit PlaygroundImpl(PlaygroundSwitches switches); + + private: + PlaygroundImpl(const PlaygroundImpl&) = delete; + + PlaygroundImpl& operator=(const PlaygroundImpl&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_IMPL_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/playground_test.cc b/flutter/engine/src/flutter/impeller/playground/playground_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e6f9f491d61189e435e7ba4507d022af25a61f75 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground_test.cc @@ -0,0 +1,135 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/time/time_point.h" + +#include "impeller/base/timing.h" +#include "impeller/base/validation.h" +#include "impeller/playground/playground_test.h" + +namespace impeller { + +PlaygroundTest::PlaygroundTest() + : Playground(PlaygroundSwitches{flutter::testing::GetArgsForProcess()}) { + ImpellerValidationErrorsSetCallback( + [](const char* message, const char* file, int line) -> bool { + // GTEST_MESSAGE_AT_ can only be used in a function that returns void. + // Hence the goofy lambda. The failure message and location will still + // be correct however. + // + // https://google.github.io/googletest/advanced.html#assertion-placement + [message, file, line]() -> void { + GTEST_MESSAGE_AT_(file, line, "Impeller Validation Error", + ::testing::TestPartResult::kFatalFailure) + << message; + }(); + return true; + }); +} + +PlaygroundTest::~PlaygroundTest() { + ImpellerValidationErrorsSetCallback(nullptr); +} + +namespace { +bool DoesSupportWideGamutTests() { +#ifdef __arm64__ + return true; +#else + return false; +#endif +} +} // namespace + +void PlaygroundTest::SetUp() { + if (!Playground::SupportsBackend(GetParam())) { + GTEST_SKIP() << "Playground doesn't support this backend type."; + return; + } + + if (!Playground::ShouldOpenNewPlaygrounds()) { + GTEST_SKIP() << "Skipping due to user action."; + return; + } + + // Test names that end with "WideGamut" will render with wide gamut support. + std::string test_name = flutter::testing::GetCurrentTestName(); + PlaygroundSwitches switches = switches_; + switches.enable_wide_gamut = + test_name.find("WideGamut/") != std::string::npos; + + if (switches.enable_wide_gamut && (GetParam() != PlaygroundBackend::kMetal || + !DoesSupportWideGamutTests())) { + GTEST_SKIP() << "This backend doesn't yet support wide gamut."; + return; + } + + switches.flags.antialiased_lines = + test_name.find("ExperimentAntialiasLines/") != std::string::npos; + + SetupContext(GetParam(), switches); + SetupWindow(); +} + +PlaygroundBackend PlaygroundTest::GetBackend() const { + return GetParam(); +} + +void PlaygroundTest::TearDown() { + TeardownWindow(); +} + +// |Playground| +std::unique_ptr PlaygroundTest::OpenAssetAsMapping( + std::string asset_name) const { + return flutter::testing::OpenFixtureAsMapping(asset_name); +} + +RuntimeStage::Map PlaygroundTest::OpenAssetAsRuntimeStage( + const char* asset_name) const { + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping(asset_name); + if (!fixture || fixture->GetSize() == 0) { + return {}; + } + return RuntimeStage::DecodeRuntimeStages(fixture); +} + +// |Playground| +std::string PlaygroundTest::GetWindowTitle() const { + std::stringstream stream; + stream << "Impeller Playground for '" + << flutter::testing::GetCurrentTestName() << "' "; + switch (GetBackend()) { + case PlaygroundBackend::kMetal: + break; + case PlaygroundBackend::kOpenGLES: + if (switches_.use_angle) { + stream << " (Angle) "; + } + break; + case PlaygroundBackend::kVulkan: + if (switches_.use_swiftshader) { + stream << " (SwiftShader) "; + } + break; + } + stream << " (Press ESC to quit)"; + return stream.str(); +} + +// |Playground| +bool PlaygroundTest::ShouldKeepRendering() const { + if (!switches_.timeout.has_value()) { + return true; + } + + if (SecondsF{GetSecondsElapsed()} > switches_.timeout.value()) { + return false; + } + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/playground_test.h b/flutter/engine/src/flutter/impeller/playground/playground_test.h new file mode 100644 index 0000000000000000000000000000000000000000..26b8d611a4a2991baa991fffc5e95b6b3209346a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/playground_test.h @@ -0,0 +1,97 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_TEST_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_TEST_H_ + +#include + +#include "flutter/testing/test_args.h" +#include "flutter/testing/testing.h" +#include "impeller/playground/playground.h" +#include "impeller/playground/switches.h" + +#if FML_OS_MACOSX +#include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" +#endif + +namespace impeller { + +class PlaygroundTest : public Playground, + public ::testing::TestWithParam { + public: + PlaygroundTest(); + + virtual ~PlaygroundTest(); + + void SetUp() override; + + void TearDown() override; + + PlaygroundBackend GetBackend() const; + + // |Playground| + std::unique_ptr OpenAssetAsMapping( + std::string asset_name) const override; + + RuntimeStage::Map OpenAssetAsRuntimeStage(const char* asset_name) const; + + // |Playground| + std::string GetWindowTitle() const override; + + private: + // |Playground| + bool ShouldKeepRendering() const override; + +#if FML_OS_MACOSX + fml::ScopedNSAutoreleasePool autorelease_pool_; +#endif + + PlaygroundTest(const PlaygroundTest&) = delete; + + PlaygroundTest& operator=(const PlaygroundTest&) = delete; +}; + +#define INSTANTIATE_PLAYGROUND_SUITE(playground) \ + [[maybe_unused]] const char* kYouInstantiated##playground##MultipleTimes = \ + ""; \ + INSTANTIATE_TEST_SUITE_P( \ + Play, playground, \ + ::testing::Values(PlaygroundBackend::kMetal, \ + PlaygroundBackend::kOpenGLES, \ + PlaygroundBackend::kVulkan), \ + [](const ::testing::TestParamInfo& info) { \ + return PlaygroundBackendToString(info.param); \ + }); + +#define INSTANTIATE_METAL_PLAYGROUND_SUITE(playground) \ + [[maybe_unused]] const char* kYouInstantiated##playground##MultipleTimes = \ + ""; \ + INSTANTIATE_TEST_SUITE_P( \ + Play, playground, ::testing::Values(PlaygroundBackend::kMetal), \ + [](const ::testing::TestParamInfo& info) { \ + return PlaygroundBackendToString(info.param); \ + }); + +#define INSTANTIATE_VULKAN_PLAYGROUND_SUITE(playground) \ + [[maybe_unused]] const char* kYouInstantiated##playground##MultipleTimes = \ + ""; \ + INSTANTIATE_TEST_SUITE_P( \ + Play, playground, ::testing::Values(PlaygroundBackend::kVulkan), \ + [](const ::testing::TestParamInfo& info) { \ + return PlaygroundBackendToString(info.param); \ + }); + +#define INSTANTIATE_OPENGLES_PLAYGROUND_SUITE(playground) \ + [[maybe_unused]] const char* kYouInstantiated##playground##MultipleTimes = \ + ""; \ + INSTANTIATE_TEST_SUITE_P( \ + Play, playground, ::testing::Values(PlaygroundBackend::kOpenGLES), \ + [](const ::testing::TestParamInfo& info) { \ + return PlaygroundBackendToString(info.param); \ + }); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_PLAYGROUND_TEST_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/switches.cc b/flutter/engine/src/flutter/impeller/playground/switches.cc new file mode 100644 index 0000000000000000000000000000000000000000..89971fc25a06dcfaa7be2e05ff6540cfdbcc5764 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/switches.cc @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/switches.h" + +#include + +#include "flutter/fml/build_config.h" + +namespace impeller { + +PlaygroundSwitches::PlaygroundSwitches() = default; + +PlaygroundSwitches::PlaygroundSwitches(const fml::CommandLine& args) { + enable_playground = args.HasOption("enable_playground"); + std::string timeout_str; + if (args.GetOptionValue("playground_timeout_ms", &timeout_str)) { + timeout = std::chrono::milliseconds(atoi(timeout_str.c_str())); + // Specifying a playground timeout implies you want to enable playgrounds. + enable_playground = true; + } + enable_vulkan_validation = args.HasOption("enable_vulkan_validation"); + use_swiftshader = args.HasOption("use_swiftshader"); + use_angle = args.HasOption("use_angle"); +#if FML_OS_MACOSX + // OpenGL on macOS is busted and deprecated. Use Angle there by default. + use_angle = true; +#endif // FML_OS_MACOSX +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/switches.h b/flutter/engine/src/flutter/impeller/playground/switches.h new file mode 100644 index 0000000000000000000000000000000000000000..29f26847261d2d34b30138fb25f0c42b942cae0e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/switches.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_ + +#include +#include + +#include "flutter/fml/command_line.h" +#include "impeller/base/flags.h" + +namespace impeller { + +struct PlaygroundSwitches { + bool enable_playground = false; + // If specified, the playgrounds will render for at least the duration + // specified in the timeout. If the timeout is zero, exactly one frame will be + // rendered in the playground. + std::optional timeout; + bool enable_vulkan_validation = false; + //---------------------------------------------------------------------------- + /// Seek a SwiftShader library in known locations and use it when running + /// Vulkan. It is a fatal error to provide this option and not have the test + /// find a SwiftShader implementation. + /// + bool use_swiftshader = false; + /// Attempt to use Angle on the system instead of the available OpenGL ES + /// implementation. This is on-by-default on macOS due to the broken-ness in + /// the deprecated OpenGL implementation. On other platforms, it this opt-in + /// via the flag with the system OpenGL ES implementation used by fault. + /// + bool use_angle = false; + + bool enable_wide_gamut = false; + + Flags flags; + + PlaygroundSwitches(); + + explicit PlaygroundSwitches(const fml::CommandLine& args); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_PLAYGROUND_SWITCHES_H_ diff --git a/flutter/engine/src/flutter/impeller/playground/widgets.cc b/flutter/engine/src/flutter/impeller/playground/widgets.cc new file mode 100644 index 0000000000000000000000000000000000000000..62122996c6b9e6904925a529ccd5b955b8579f54 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/widgets.cc @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/widgets.h" + +namespace impeller { + +Point DrawPlaygroundPoint(PlaygroundPoint& point) { + if (ImGui::GetCurrentContext()) { + impeller::Point mouse_pos(ImGui::GetMousePos().x, ImGui::GetMousePos().y); + if (!point.prev_mouse_pos.has_value()) { + point.prev_mouse_pos = mouse_pos; + } + + if (ImGui::IsKeyPressed(ImGuiKey_R)) { + point.position = point.reset_position; + point.dragging = false; + } + + bool hovering = + point.position.GetDistance(mouse_pos) < point.radius && + point.position.GetDistance(point.prev_mouse_pos.value()) < point.radius; + if (!ImGui::IsMouseDown(0)) { + point.dragging = false; + } else if (hovering && ImGui::IsMouseClicked(0)) { + point.dragging = true; + } + if (point.dragging) { + point.position += mouse_pos - point.prev_mouse_pos.value(); + } + ImGui::GetBackgroundDrawList()->AddCircleFilled( + {point.position.x, point.position.y}, point.radius, + ImColor(point.color.red, point.color.green, point.color.blue, + (hovering || point.dragging) ? 0.6f : 0.3f)); + if (hovering || point.dragging) { + ImGui::GetBackgroundDrawList()->AddText( + {point.position.x - point.radius, + point.position.y + point.radius + 10}, + ImColor(point.color.red, point.color.green, point.color.blue, 1.0f), + impeller::SPrintF("x:%0.3f y:%0.3f", point.position.x, + point.position.y) + .c_str()); + } + point.prev_mouse_pos = mouse_pos; + } + return point.position; +} + +std::tuple DrawPlaygroundLine(PlaygroundPoint& point_a, + PlaygroundPoint& point_b) { + Point position_a = DrawPlaygroundPoint(point_a); + Point position_b = DrawPlaygroundPoint(point_b); + + if (ImGui::GetCurrentContext()) { + auto dir = (position_b - position_a).Normalize() * point_a.radius; + auto line_a = position_a + dir; + auto line_b = position_b - dir; + ImGui::GetBackgroundDrawList()->AddLine( + {line_a.x, line_a.y}, {line_b.x, line_b.y}, + ImColor(point_b.color.red, point_b.color.green, point_b.color.blue, + 0.3f)); + } + return std::make_tuple(position_a, position_b); +} +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/playground/widgets.h b/flutter/engine/src/flutter/impeller/playground/widgets.h new file mode 100644 index 0000000000000000000000000000000000000000..7da9b4b4865cba984d1d2acc4ee80bc83bec3a2c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/playground/widgets.h @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_PLAYGROUND_WIDGETS_H_ +#define FLUTTER_IMPELLER_PLAYGROUND_WIDGETS_H_ + +#include +#include + +#include "impeller/base/strings.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/point.h" +#include "third_party/imgui/imgui.h" + +namespace impeller { +struct PlaygroundPoint { + PlaygroundPoint(Point default_position, Scalar p_radius, Color p_color) + : position(default_position), + reset_position(default_position), + radius(p_radius), + color(p_color) {} + Point position; + Point reset_position; + bool dragging = false; + std::optional prev_mouse_pos; + Scalar radius; + Color color; + PlaygroundPoint(const PlaygroundPoint&) = delete; + PlaygroundPoint(PlaygroundPoint&&) = delete; + PlaygroundPoint& operator=(const PlaygroundPoint&) = delete; +}; + +Point DrawPlaygroundPoint(PlaygroundPoint& point); + +std::tuple DrawPlaygroundLine(PlaygroundPoint& point_a, + PlaygroundPoint& point_b); +} // namespace impeller +#endif // FLUTTER_IMPELLER_PLAYGROUND_WIDGETS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/BUILD.gn b/flutter/engine/src/flutter/impeller/renderer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5fdc59a92b8ab0d1d78f187c67a5b4e435820c50 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/BUILD.gn @@ -0,0 +1,166 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +if (impeller_enable_compute) { + impeller_shaders("compute_shaders") { + name = "compute" + enable_opengles = false + + if (impeller_enable_vulkan) { + vulkan_language_version = 130 + } + + if (is_ios) { + metal_version = "2.4" + } else if (is_mac) { + metal_version = "2.1" + } + + shaders = [ + "prefix_sum_test.comp", + "threadgroup_sizing_test.comp", + ] + } +} + +impeller_component("renderer") { + sources = [ + "blit_command.cc", + "blit_command.h", + "blit_pass.cc", + "blit_pass.h", + "capabilities.cc", + "capabilities.h", + "command.cc", + "command.h", + "command_buffer.cc", + "command_buffer.h", + "command_queue.cc", + "command_queue.h", + "compute_pass.cc", + "compute_pass.h", + "compute_pipeline_builder.cc", + "compute_pipeline_builder.h", + "compute_pipeline_descriptor.cc", + "compute_pipeline_descriptor.h", + "context.cc", + "context.h", + "pipeline.cc", + "pipeline.h", + "pipeline_builder.cc", + "pipeline_builder.h", + "pipeline_descriptor.cc", + "pipeline_descriptor.h", + "pipeline_library.cc", + "pipeline_library.h", + "pool.h", + "render_pass.cc", + "render_pass.h", + "render_target.cc", + "render_target.h", + "sampler_library.cc", + "sampler_library.h", + "shader_function.cc", + "shader_function.h", + "shader_key.cc", + "shader_key.h", + "shader_library.cc", + "shader_library.h", + "snapshot.cc", + "snapshot.h", + "surface.cc", + "surface.h", + "texture_util.cc", + "texture_util.h", + "vertex_buffer_builder.cc", + "vertex_buffer_builder.h", + "vertex_descriptor.cc", + "vertex_descriptor.h", + ] + + public_deps = [ + "../base", + "../core", + "../geometry", + "../runtime_stage", + "../tessellator", + ] + + if (impeller_enable_compute) { + public_deps += [ ":compute_shaders" ] + } + + deps = [ "//flutter/fml" ] +} + +template("renderer_unittests_component") { + target_name = invoker.target_name + predefined_sources = [ + "blit_pass_unittests.cc", + "capabilities_unittests.cc", + "device_buffer_unittests.cc", + "pipeline_descriptor_unittests.cc", + "pool_unittests.cc", + "renderer_unittests.cc", + ] + impeller_component(target_name) { + testonly = true + if (defined(invoker.defines)) { + defines = invoker.defines + } else { + defines = [] + } + sources = predefined_sources + if (defined(invoker.deps)) { + deps = invoker.deps + } else { + deps = [] + } + deps += [ + ":renderer", + "../fixtures", + "../playground:playground_test", + "../tessellator:tessellator_libtess", + "//flutter/impeller/display_list:display_list", + "//flutter/testing:testing_lib", + ] + if (defined(invoker.public_configs)) { + public_configs = invoker.public_configs + } + } +} + +renderer_unittests_component("renderer_unittests") { + deps = [ "//flutter/impeller/display_list:aiks_unittests" ] +} + +renderer_unittests_component("renderer_unittests_golden") { + deps = [ "//flutter/impeller/display_list:aiks_unittests_golden" ] + defines = [ + "IMPELLER_GOLDEN_TESTS", + "IMPELLER_ENABLE_VALIDATION=1", + ] +} + +impeller_component("renderer_dart_unittests") { + testonly = true + + sources = [ "renderer_dart_unittests.cc" ] + + public_configs = [ "//flutter:export_dynamic_symbols" ] + + deps = [ + ":renderer", + "../fixtures:flutter_gpu_fixtures", + "../fixtures:flutter_gpu_shaders", + "../playground:playground_test", + "//flutter/lib/gpu", + "//flutter/lib/snapshot", + "//flutter/runtime:runtime", + "//flutter/testing:fixture_test", + "//flutter/testing:testing", + ] +} diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/BUILD.gn b/flutter/engine/src/flutter/impeller/renderer/backend/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2f6b15b0d9a55affe34c1baf82111f34dad2dbd7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/BUILD.gn @@ -0,0 +1,24 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../../tools/impeller.gni") + +group("backend") { + public_deps = [] + + if (impeller_enable_metal) { + assert(is_mac || is_ios) + public_deps += [ "metal" ] + } + + if (impeller_enable_opengles) { + assert(is_mac || is_linux || is_win || is_android) + public_deps += [ "gles" ] + } + + if (impeller_enable_vulkan) { + assert(is_mac || is_linux || is_win || is_android) + public_deps += [ "vulkan" ] + } +} diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/BUILD.gn b/flutter/engine/src/flutter/impeller/renderer/backend/gles/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a28309f5fa828a034e60525b73942e38ad26bdd4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/BUILD.gn @@ -0,0 +1,112 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/vulkan/config.gni") +import("../../../tools/impeller.gni") + +config("gles_config") { + # Generic GL/GLES/EGL/Vulkan headers. Any will do. We just pick one from Angle + # because they are there. + include_dirs = [ "//flutter/third_party/angle/include" ] +} + +impeller_component("gles_unittests") { + testonly = true + sources = [ + "buffer_bindings_gles_unittests.cc", + "device_buffer_gles_unittests.cc", + "test/capabilities_unittests.cc", + "test/formats_gles_unittests.cc", + "test/gpu_tracer_gles_unittests.cc", + "test/mock_gles.cc", + "test/mock_gles.h", + "test/mock_gles_unittests.cc", + "test/pipeline_library_gles_unittests.cc", + "test/proc_table_gles_unittests.cc", + "test/reactor_unittests.cc", + "test/specialization_constants_unittests.cc", + "test/surface_gles_unittests.cc", + "test/texture_gles_unittests.cc", + "unique_handle_gles_unittests.cc", + ] + deps = [ + ":gles", + "//flutter/impeller/playground:playground_test", + "//flutter/testing:testing_lib", + ] +} + +impeller_component("gles") { + public_configs = [] + + sources = [ + "allocator_gles.cc", + "allocator_gles.h", + "blit_command_gles.cc", + "blit_command_gles.h", + "blit_pass_gles.cc", + "blit_pass_gles.h", + "buffer_bindings_gles.cc", + "buffer_bindings_gles.h", + "capabilities_gles.cc", + "capabilities_gles.h", + "command_buffer_gles.cc", + "command_buffer_gles.h", + "context_gles.cc", + "context_gles.h", + "description_gles.cc", + "description_gles.h", + "device_buffer_gles.cc", + "device_buffer_gles.h", + "formats_gles.cc", + "formats_gles.h", + "gles.h", + "gpu_tracer_gles.cc", + "gpu_tracer_gles.h", + "handle_gles.cc", + "handle_gles.h", + "pipeline_gles.cc", + "pipeline_gles.h", + "pipeline_library_gles.cc", + "pipeline_library_gles.h", + "proc_table_gles.cc", + "proc_table_gles.h", + "reactor_gles.cc", + "reactor_gles.h", + "render_pass_gles.cc", + "render_pass_gles.h", + "sampler_gles.cc", + "sampler_gles.h", + "sampler_library_gles.cc", + "sampler_library_gles.h", + "shader_function_gles.cc", + "shader_function_gles.h", + "shader_library_gles.cc", + "shader_library_gles.h", + "surface_gles.cc", + "surface_gles.h", + "texture_gles.cc", + "texture_gles.h", + "unique_handle_gles.cc", + "unique_handle_gles.h", + ] + + if (!is_android && !is_fuchsia) { + public_configs = [ ":gles_config" ] + sources += [ + "//flutter/third_party/angle/include/GLES2/gl2ext.h", + + # The GLES3 API is a superset of GLES2. Although we target GLES2, we use + # some GLES3 features if the driver supports them. + "//flutter/third_party/angle/include/GLES3/gl3.h", + ] + } + + public_deps = [ + "../../:renderer", + "../../../shader_archive", + "//flutter/fml", + "//flutter/third_party/abseil-cpp/absl/container:flat_hash_map", + ] +} diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..820ec22d691633f42cc2c7bfe9e8dc4ea6b399ce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.cc @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/allocator_gles.h" + +#include + +#include "impeller/base/allocation.h" +#include "impeller/base/config.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" + +namespace impeller { + +AllocatorGLES::AllocatorGLES(std::shared_ptr reactor) + : reactor_(std::move(reactor)), is_valid_(true) {} + +// |Allocator| +AllocatorGLES::~AllocatorGLES() = default; + +// |Allocator| +bool AllocatorGLES::IsValid() const { + return is_valid_; +} + +// |Allocator| +std::shared_ptr AllocatorGLES::OnCreateBuffer( + const DeviceBufferDescriptor& desc) { + auto backing_store = std::make_shared(); + if (!backing_store->Truncate(Bytes{desc.size})) { + return nullptr; + } + return std::make_shared(desc, // + reactor_, // + std::move(backing_store) // + ); +} + +// |Allocator| +std::shared_ptr AllocatorGLES::OnCreateTexture( + const TextureDescriptor& desc) { + return std::make_shared(reactor_, desc); +} + +// |Allocator| +ISize AllocatorGLES::GetMaxTextureSizeSupported() const { + return reactor_->GetProcTable().GetCapabilities()->max_texture_size; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..14728414f467e22093e5e028cd92e28b85212627 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/allocator_gles.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_ + +#include "impeller/core/allocator.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" + +namespace impeller { + +class AllocatorGLES final : public Allocator { + public: + // |Allocator| + ~AllocatorGLES() override; + + private: + friend class ContextGLES; + + std::shared_ptr reactor_; + bool is_valid_ = false; + + explicit AllocatorGLES(std::shared_ptr reactor); + + // |Allocator| + bool IsValid() const; + + // |Allocator| + std::shared_ptr OnCreateBuffer( + const DeviceBufferDescriptor& desc) override; + + // |Allocator| + std::shared_ptr OnCreateTexture( + const TextureDescriptor& desc) override; + + // |Allocator| + ISize GetMaxTextureSizeSupported() const override; + + AllocatorGLES(const AllocatorGLES&) = delete; + + AllocatorGLES& operator=(const AllocatorGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_ALLOCATOR_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..754983837d750876a3bb2e6273d8f350d8a15b16 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.cc @@ -0,0 +1,459 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/blit_command_gles.h" + +#include "flutter/fml/closure.h" +#include "fml/trace_event.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/geometry/point.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" + +namespace impeller { + +namespace { +static void FlipImage(uint8_t* buffer, + size_t width, + size_t height, + size_t stride) { + if (buffer == nullptr || stride == 0) { + return; + } + + const auto byte_width = width * stride; + + for (size_t top = 0; top < height; top++) { + size_t bottom = height - top - 1; + if (top >= bottom) { + break; + } + auto* top_row = buffer + byte_width * top; + auto* bottom_row = buffer + byte_width * bottom; + std::swap_ranges(top_row, top_row + byte_width, bottom_row); + } +} +} // namespace + +BlitEncodeGLES::~BlitEncodeGLES() = default; + +static void DeleteFBO(const ProcTableGLES& gl, GLuint fbo, GLenum type) { + if (fbo != GL_NONE) { + gl.BindFramebuffer(type, GL_NONE); + gl.DeleteFramebuffers(1u, &fbo); + } +}; + +static std::optional ConfigureFBO( + const ProcTableGLES& gl, + const std::shared_ptr& texture, + GLenum fbo_type) { + auto handle = TextureGLES::Cast(texture.get())->GetGLHandle(); + if (!handle.has_value()) { + return std::nullopt; + } + + if (TextureGLES::Cast(*texture).IsWrapped()) { + // The texture is attached to the default FBO, so there's no need to + // create/configure one. + gl.BindFramebuffer(fbo_type, 0); + return 0; + } + + GLuint fbo; + gl.GenFramebuffers(1u, &fbo); + gl.BindFramebuffer(fbo_type, fbo); + + if (!TextureGLES::Cast(*texture).SetAsFramebufferAttachment( + fbo_type, TextureGLES::AttachmentType::kColor0)) { + VALIDATION_LOG << "Could not attach texture to framebuffer."; + DeleteFBO(gl, fbo, fbo_type); + return std::nullopt; + } + + if (gl.CheckFramebufferStatus(fbo_type) != GL_FRAMEBUFFER_COMPLETE) { + VALIDATION_LOG << "Could not create a complete framebuffer."; + DeleteFBO(gl, fbo, fbo_type); + return std::nullopt; + } + + return fbo; +}; + +BlitCopyTextureToTextureCommandGLES::~BlitCopyTextureToTextureCommandGLES() = + default; + +std::string BlitCopyTextureToTextureCommandGLES::GetLabel() const { + return label; +} + +bool BlitCopyTextureToTextureCommandGLES::Encode( + const ReactorGLES& reactor) const { + const auto& gl = reactor.GetProcTable(); + + // glBlitFramebuffer is a GLES3 proc. Since we target GLES2, we need to + // emulate the blit when it's not available in the driver. + if (!gl.BlitFramebuffer.IsAvailable()) { + // TODO(157064): Emulate the blit using a raster draw call here. + VALIDATION_LOG << "Texture blit fallback not implemented yet for GLES2."; + return false; + } + + GLuint read_fbo = GL_NONE; + GLuint draw_fbo = GL_NONE; + fml::ScopedCleanupClosure delete_fbos([&gl, &read_fbo, &draw_fbo]() { + DeleteFBO(gl, read_fbo, GL_READ_FRAMEBUFFER); + DeleteFBO(gl, draw_fbo, GL_DRAW_FRAMEBUFFER); + }); + + { + auto read = ConfigureFBO(gl, source, GL_READ_FRAMEBUFFER); + if (!read.has_value()) { + return false; + } + read_fbo = read.value(); + } + + { + auto draw = ConfigureFBO(gl, destination, GL_DRAW_FRAMEBUFFER); + if (!draw.has_value()) { + return false; + } + draw_fbo = draw.value(); + } + + gl.Disable(GL_SCISSOR_TEST); + gl.Disable(GL_DEPTH_TEST); + gl.Disable(GL_STENCIL_TEST); + + gl.BlitFramebuffer(source_region.GetX(), // srcX0 + source_region.GetY(), // srcY0 + source_region.GetWidth(), // srcX1 + source_region.GetHeight(), // srcY1 + destination_origin.x, // dstX0 + destination_origin.y, // dstY0 + source_region.GetWidth(), // dstX1 + source_region.GetHeight(), // dstY1 + GL_COLOR_BUFFER_BIT, // mask + GL_NEAREST // filter + ); + + return true; +}; + +namespace { +struct TexImage2DData { + GLint internal_format = 0; + GLenum external_format = GL_NONE; + GLenum type = GL_NONE; + BufferView buffer_view; + + explicit TexImage2DData(PixelFormat pixel_format) { + switch (pixel_format) { + case PixelFormat::kA8UNormInt: + internal_format = GL_ALPHA; + external_format = GL_ALPHA; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR8UNormInt: + internal_format = GL_RED; + external_format = GL_RED; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR32G32B32A32Float: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_FLOAT; + break; + case PixelFormat::kR16G16B16A16Float: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_HALF_FLOAT; + break; + case PixelFormat::kS8UInt: + // Pure stencil textures are only available in OpenGL 4.4+, which is + // ~0% of mobile devices. Instead, we use a depth-stencil texture and + // only use the stencil component. + // + // https://registry.khronos.org/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml + case PixelFormat::kD24UnormS8Uint: + internal_format = GL_DEPTH_STENCIL; + external_format = GL_DEPTH_STENCIL; + type = GL_UNSIGNED_INT_24_8; + break; + case PixelFormat::kUnknown: + case PixelFormat::kD32FloatS8UInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10A10XR: + return; + } + is_valid_ = true; + } + + TexImage2DData(PixelFormat pixel_format, BufferView p_buffer_view) + : TexImage2DData(pixel_format) { + buffer_view = std::move(p_buffer_view); + } + + bool IsValid() const { return is_valid_; } + + private: + bool is_valid_ = false; +}; +} // namespace + +BlitCopyBufferToTextureCommandGLES::~BlitCopyBufferToTextureCommandGLES() = + default; + +std::string BlitCopyBufferToTextureCommandGLES::GetLabel() const { + return label; +} + +bool BlitCopyBufferToTextureCommandGLES::Encode( + const ReactorGLES& reactor) const { + TextureGLES& texture_gles = TextureGLES::Cast(*destination); + + if (texture_gles.GetType() != TextureGLES::Type::kTexture) { + VALIDATION_LOG << "Incorrect texture usage flags for setting contents on " + "this texture object."; + return false; + } + + if (texture_gles.IsWrapped()) { + VALIDATION_LOG << "Cannot set the contents of a wrapped texture."; + return false; + } + + const auto& tex_descriptor = texture_gles.GetTextureDescriptor(); + + if (tex_descriptor.size.IsEmpty()) { + return true; + } + + if (!tex_descriptor.IsValid() || + source.GetRange().length != + BytesPerPixelForPixelFormat(tex_descriptor.format) * + destination_region.Area()) { + return false; + } + + destination->SetCoordinateSystem(TextureCoordinateSystem::kUploadFromHost); + + GLenum texture_type; + GLenum texture_target; + switch (tex_descriptor.type) { + case TextureType::kTexture2D: + texture_type = GL_TEXTURE_2D; + texture_target = GL_TEXTURE_2D; + break; + case TextureType::kTexture2DMultisample: + VALIDATION_LOG << "Multisample texture uploading is not supported for " + "the OpenGLES backend."; + return false; + case TextureType::kTextureCube: + texture_type = GL_TEXTURE_CUBE_MAP; + texture_target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice; + break; + case TextureType::kTextureExternalOES: + texture_type = GL_TEXTURE_EXTERNAL_OES; + texture_target = GL_TEXTURE_EXTERNAL_OES; + break; + } + + TexImage2DData data = TexImage2DData(tex_descriptor.format, source); + if (!data.IsValid()) { + VALIDATION_LOG << "Invalid texture format."; + return false; + } + + auto gl_handle = texture_gles.GetGLHandle(); + if (!gl_handle.has_value()) { + VALIDATION_LOG + << "Texture was collected before it could be uploaded to the GPU."; + return false; + } + const auto& gl = reactor.GetProcTable(); + gl.BindTexture(texture_type, gl_handle.value()); + const GLvoid* tex_data = data.buffer_view.GetBuffer()->OnGetContents() + + data.buffer_view.GetRange().offset; + + // GL_INVALID_OPERATION if the texture array has not been + // defined by a previous glTexImage2D operation. + if (!texture_gles.IsSliceInitialized(slice)) { + gl.TexImage2D(texture_target, // target + mip_level, // LOD level + data.internal_format, // internal format + tex_descriptor.size.width, // width + tex_descriptor.size.height, // height + 0u, // border + data.external_format, // external format + data.type, // type + nullptr // data + ); + texture_gles.MarkSliceInitialized(slice); + } + + { + gl.PixelStorei(GL_UNPACK_ALIGNMENT, 1); + gl.TexSubImage2D(texture_target, // target + mip_level, // LOD level + destination_region.GetX(), // xoffset + destination_region.GetY(), // yoffset + destination_region.GetWidth(), // width + destination_region.GetHeight(), // height + data.external_format, // external format + data.type, // type + tex_data // data + + ); + } + return true; +} + +BlitCopyTextureToBufferCommandGLES::~BlitCopyTextureToBufferCommandGLES() = + default; + +std::string BlitCopyTextureToBufferCommandGLES::GetLabel() const { + return label; +} + +bool BlitCopyTextureToBufferCommandGLES::Encode( + const ReactorGLES& reactor) const { + if (source->GetTextureDescriptor().format != PixelFormat::kR8G8B8A8UNormInt) { + VALIDATION_LOG << "Only textures with pixel format RGBA are supported yet."; + return false; + } + + const auto& gl = reactor.GetProcTable(); + TextureCoordinateSystem coord_system = source->GetCoordinateSystem(); + + GLuint read_fbo = GL_NONE; + fml::ScopedCleanupClosure delete_fbos( + [&gl, &read_fbo]() { DeleteFBO(gl, read_fbo, GL_READ_FRAMEBUFFER); }); + + { + auto read = ConfigureFBO(gl, source, GL_READ_FRAMEBUFFER); + if (!read.has_value()) { + return false; + } + read_fbo = read.value(); + } + + DeviceBufferGLES::Cast(*destination) + .UpdateBufferData([&gl, this, coord_system, + rows = source->GetSize().height](uint8_t* data, + + size_t length) { + gl.ReadPixels(source_region.GetX(), source_region.GetY(), + source_region.GetWidth(), source_region.GetHeight(), + GL_RGBA, GL_UNSIGNED_BYTE, data + destination_offset); + switch (coord_system) { + case TextureCoordinateSystem::kUploadFromHost: + break; + case TextureCoordinateSystem::kRenderToTexture: + // The texture is upside down, and must be inverted when copying + // byte data out. + FlipImage(data + destination_offset, source_region.GetWidth(), + source_region.GetHeight(), 4); + } + }); + + return true; +}; + +BlitGenerateMipmapCommandGLES::~BlitGenerateMipmapCommandGLES() = default; + +std::string BlitGenerateMipmapCommandGLES::GetLabel() const { + return label; +} + +bool BlitGenerateMipmapCommandGLES::Encode(const ReactorGLES& reactor) const { + auto texture_gles = TextureGLES::Cast(texture.get()); + if (!texture_gles->GenerateMipmap()) { + return false; + } + + return true; +}; + +////// BlitResizeTextureCommandGLES +////////////////////////////////////////////////////// + +BlitResizeTextureCommandGLES::~BlitResizeTextureCommandGLES() = default; + +std::string BlitResizeTextureCommandGLES::GetLabel() const { + return "Resize Texture"; +} + +bool BlitResizeTextureCommandGLES::Encode(const ReactorGLES& reactor) const { + const auto& gl = reactor.GetProcTable(); + + // glBlitFramebuffer is a GLES3 proc. Since we target GLES2, we need to + // emulate the blit when it's not available in the driver. + if (!gl.BlitFramebuffer.IsAvailable()) { + // TODO(157064): Emulate the blit using a raster draw call here. + VALIDATION_LOG << "Texture blit fallback not implemented yet for GLES2."; + return false; + } + + destination->SetCoordinateSystem(source->GetCoordinateSystem()); + + GLuint read_fbo = GL_NONE; + GLuint draw_fbo = GL_NONE; + fml::ScopedCleanupClosure delete_fbos([&gl, &read_fbo, &draw_fbo]() { + DeleteFBO(gl, read_fbo, GL_READ_FRAMEBUFFER); + DeleteFBO(gl, draw_fbo, GL_DRAW_FRAMEBUFFER); + }); + + { + auto read = ConfigureFBO(gl, source, GL_READ_FRAMEBUFFER); + if (!read.has_value()) { + return false; + } + read_fbo = read.value(); + } + + { + auto draw = ConfigureFBO(gl, destination, GL_DRAW_FRAMEBUFFER); + if (!draw.has_value()) { + return false; + } + draw_fbo = draw.value(); + } + + gl.Disable(GL_SCISSOR_TEST); + gl.Disable(GL_DEPTH_TEST); + gl.Disable(GL_STENCIL_TEST); + + const IRect source_region = IRect::MakeSize(source->GetSize()); + const IRect destination_region = IRect::MakeSize(destination->GetSize()); + + gl.BlitFramebuffer(source_region.GetX(), // srcX0 + source_region.GetY(), // srcY0 + source_region.GetWidth(), // srcX1 + source_region.GetHeight(), // srcY1 + destination_region.GetX(), // dstX0 + destination_region.GetY(), // dstY0 + destination_region.GetWidth(), // dstX1 + destination_region.GetHeight(), // dstY1 + GL_COLOR_BUFFER_BIT, // mask + GL_LINEAR // filter + ); + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..1a3f35f1d2e8295cc8b9b12b4d466ce96819ba1e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_command_gles.h @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/blit_command.h" + +namespace impeller { + +/// Mixin for dispatching GLES commands. +struct BlitEncodeGLES : BackendCast { + virtual ~BlitEncodeGLES(); + + virtual std::string GetLabel() const = 0; + + [[nodiscard]] virtual bool Encode(const ReactorGLES& reactor) const = 0; +}; + +struct BlitCopyBufferToTextureCommandGLES + : public BlitEncodeGLES, + public BlitCopyBufferToTextureCommand { + ~BlitCopyBufferToTextureCommandGLES() override; + + std::string GetLabel() const override; + + [[nodiscard]] bool Encode(const ReactorGLES& reactor) const override; +}; + +struct BlitCopyTextureToTextureCommandGLES + : public BlitEncodeGLES, + public BlitCopyTextureToTextureCommand { + ~BlitCopyTextureToTextureCommandGLES() override; + + std::string GetLabel() const override; + + [[nodiscard]] bool Encode(const ReactorGLES& reactor) const override; +}; + +struct BlitCopyTextureToBufferCommandGLES + : public BlitEncodeGLES, + public BlitCopyTextureToBufferCommand { + ~BlitCopyTextureToBufferCommandGLES() override; + + std::string GetLabel() const override; + + [[nodiscard]] bool Encode(const ReactorGLES& reactor) const override; +}; + +struct BlitGenerateMipmapCommandGLES : public BlitEncodeGLES, + public BlitGenerateMipmapCommand { + ~BlitGenerateMipmapCommandGLES() override; + + std::string GetLabel() const override; + + [[nodiscard]] bool Encode(const ReactorGLES& reactor) const override; +}; + +struct BlitResizeTextureCommandGLES : public BlitEncodeGLES, + public BlitResizeTextureCommand { + ~BlitResizeTextureCommandGLES() override; + + std::string GetLabel() const override; + + [[nodiscard]] bool Encode(const ReactorGLES& reactor) const override; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_COMMAND_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..d26a60dc699688d49f692c3223a78615e70c914f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.cc @@ -0,0 +1,172 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/blit_pass_gles.h" + +#include + +#include "flutter/fml/trace_event.h" +#include "fml/closure.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/gles/blit_command_gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { + +BlitPassGLES::BlitPassGLES(std::shared_ptr reactor) + : reactor_(std::move(reactor)), + is_valid_(reactor_ && reactor_->IsValid()) {} + +// |BlitPass| +BlitPassGLES::~BlitPassGLES() = default; + +// |BlitPass| +bool BlitPassGLES::IsValid() const { + return is_valid_; +} + +// |BlitPass| +void BlitPassGLES::OnSetLabel(std::string_view label) { + label_ = std::string(label); +} + +[[nodiscard]] bool EncodeCommandsInReactor( + const ReactorGLES& reactor, + const std::vector>& commands, + const std::string& label) { + TRACE_EVENT0("impeller", "BlitPassGLES::EncodeCommandsInReactor"); + + if (commands.empty()) { + return true; + } + +#ifdef IMPELLER_DEBUG + const auto& gl = reactor.GetProcTable(); + fml::ScopedCleanupClosure pop_pass_debug_marker( + [&gl]() { gl.PopDebugGroup(); }); + if (!label.empty()) { + gl.PushDebugGroup(label); + } else { + pop_pass_debug_marker.Release(); + } +#endif // IMPELLER_DEBUG + + for (const auto& command : commands) { +#ifdef IMPELLER_DEBUG + fml::ScopedCleanupClosure pop_cmd_debug_marker( + [&gl]() { gl.PopDebugGroup(); }); + auto label = command->GetLabel(); + if (!label.empty()) { + gl.PushDebugGroup(label); + } else { + pop_cmd_debug_marker.Release(); + } +#endif // IMPELLER_DEBUG + + if (!command->Encode(reactor)) { + return false; + } + } + + return true; +} + +// |BlitPass| +bool BlitPassGLES::EncodeCommands() const { + if (!IsValid()) { + return false; + } + if (commands_.empty()) { + return true; + } + + std::shared_ptr shared_this = shared_from_this(); + return reactor_->AddOperation([blit_pass = std::move(shared_this), + label = label_](const auto& reactor) { + auto result = EncodeCommandsInReactor(reactor, blit_pass->commands_, label); + FML_CHECK(result) << "Must be able to encode GL commands without error."; + }); +} + +// |BlitPass| +bool BlitPassGLES::OnCopyTextureToTextureCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) { + auto command = std::make_unique(); + command->label = label; + command->source = std::move(source); + command->destination = std::move(destination); + command->source_region = source_region; + command->destination_origin = destination_origin; + + commands_.push_back(std::move(command)); + return true; +} + +// |BlitPass| +bool BlitPassGLES::OnCopyTextureToBufferCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) { + auto command = std::make_unique(); + command->label = label; + command->source = std::move(source); + command->destination = std::move(destination); + command->source_region = source_region; + command->destination_offset = destination_offset; + + commands_.push_back(std::move(command)); + return true; +} + +// |BlitPass| +bool BlitPassGLES::OnCopyBufferToTextureCommand( + BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) { + auto command = std::make_unique(); + command->label = label; + command->source = std::move(source); + command->destination = std::move(destination); + command->destination_region = destination_region; + command->label = label; + command->mip_level = mip_level; + command->slice = slice; + + commands_.push_back(std::move(command)); + return true; +} + +// |BlitPass| +bool BlitPassGLES::OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) { + auto command = std::make_unique(); + command->label = label; + command->texture = std::move(texture); + + commands_.push_back(std::move(command)); + return true; +} + +// |BlitPass| +bool BlitPassGLES::ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) { + auto command = std::make_unique(); + command->source = source; + command->destination = destination; + + commands_.push_back(std::move(command)); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..6c09bd3eb268c062a906e6b98b6f7e3bbb21ca73 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/blit_pass_gles.h @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_PASS_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_PASS_GLES_H_ + +#include +#include + +#include "flutter/impeller/base/config.h" +#include "flutter/impeller/renderer/backend/gles/reactor_gles.h" +#include "flutter/impeller/renderer/blit_pass.h" +#include "impeller/renderer/backend/gles/blit_command_gles.h" + +namespace impeller { + +class BlitPassGLES final : public BlitPass, + public std::enable_shared_from_this { + public: + // |BlitPass| + ~BlitPassGLES() override; + + private: + friend class CommandBufferGLES; + + std::vector> commands_; + std::shared_ptr reactor_; + std::string label_; + bool is_valid_ = false; + + explicit BlitPassGLES(std::shared_ptr reactor); + + // |BlitPass| + bool IsValid() const override; + + // |BlitPass| + void OnSetLabel(std::string_view label) override; + + // |BlitPass| + bool EncodeCommands() const override; + + // |BlitPass| + bool ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) override; + + // |BlitPass| + bool OnCopyTextureToTextureCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) override; + + // |BlitPass| + bool OnCopyTextureToBufferCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) override; + + // |BlitPass| + bool OnCopyBufferToTextureCommand(BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) override; + + // |BlitPass| + bool OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) override; + + BlitPassGLES(const BlitPassGLES&) = delete; + + BlitPassGLES& operator=(const BlitPassGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BLIT_PASS_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..a73e9823ba0b1999b76574936b4b745119366f9f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.cc @@ -0,0 +1,508 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/buffer_bindings_gles.h" + +#include +#include + +#include "impeller/base/validation.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/formats_gles.h" +#include "impeller/renderer/backend/gles/sampler_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" +#include "impeller/renderer/command.h" + +namespace impeller { + +// This prefix is used in the names of inputs generated by ANGLE's framebuffer +// fetch emulation. +static constexpr std::string_view kAngleInputAttachmentPrefix = + "ANGLEInputAttachment"; + +BufferBindingsGLES::BufferBindingsGLES() = default; + +BufferBindingsGLES::~BufferBindingsGLES() = default; + +bool BufferBindingsGLES::RegisterVertexStageInput( + const ProcTableGLES& gl, + const std::vector& p_inputs, + const std::vector& layouts) { + std::vector> vertex_attrib_arrays( + layouts.size()); + // Every layout corresponds to a vertex binding. + // As we record, separate the attributes into buckets for each layout in + // ascending order. We do this because later on, we'll need to associate each + // of the attributes with bound buffers corresponding to the binding. + for (auto layout_i = 0u; layout_i < layouts.size(); layout_i++) { + const auto& layout = layouts[layout_i]; + for (const auto& input : p_inputs) { + if (input.binding != layout_i) { + continue; + } + VertexAttribPointer attrib; + attrib.index = input.location; + // Component counts must be 1, 2, 3 or 4. Do that validation now. + if (input.vec_size < 1u || input.vec_size > 4u) { + return false; + } + attrib.size = input.vec_size; + auto type = ToVertexAttribType(input.type); + if (!type.has_value()) { + return false; + } + attrib.type = type.value(); + attrib.normalized = GL_FALSE; + attrib.offset = input.offset; + attrib.stride = layout.stride; + vertex_attrib_arrays[layout_i].push_back(attrib); + } + } + vertex_attrib_arrays_ = std::move(vertex_attrib_arrays); + return true; +} + +static std::string NormalizeUniformKey(const std::string& key) { + std::string result; + result.reserve(key.length()); + for (char ch : key) { + if (ch != '_') { + result.push_back(toupper(ch)); + } + } + return result; +} + +static std::string CreateUniformMemberKey(const std::string& struct_name, + const std::string& member, + bool is_array) { + std::string result; + result.reserve(struct_name.length() + member.length() + (is_array ? 4 : 1)); + result += struct_name; + if (!member.empty()) { + result += '.'; + result += member; + } + if (is_array) { + result += "[0]"; + } + return NormalizeUniformKey(result); +} + +static std::string CreateUniformMemberKey( + const std::string& non_struct_member) { + return NormalizeUniformKey(non_struct_member); +} + +bool BufferBindingsGLES::ReadUniformsBindings(const ProcTableGLES& gl, + GLuint program) { + if (!gl.IsProgram(program)) { + return false; + } + program_handle_ = program; + if (gl.GetDescription()->GetGlVersion().IsAtLeast(Version{3, 0, 0})) { + return ReadUniformsBindingsV3(gl, program); + } + return ReadUniformsBindingsV2(gl, program); +} + +bool BufferBindingsGLES::ReadUniformsBindingsV3(const ProcTableGLES& gl, + GLuint program) { + program_handle_ = program; + GLint uniform_blocks = 0; + gl.GetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &uniform_blocks); + for (GLint i = 0; i < uniform_blocks; i++) { + GLint name_length = 0; + gl.GetActiveUniformBlockiv(program, i, GL_UNIFORM_BLOCK_NAME_LENGTH, + &name_length); + + std::vector name; + name.resize(name_length); + GLint length = 0; + gl.GetActiveUniformBlockName(program, i, name_length, &length, name.data()); + + GLuint block_index = gl.GetUniformBlockIndex(program, name.data()); + gl.UniformBlockBinding(program_handle_, block_index, i); + + ubo_locations_[std::string{name.data(), static_cast(length)}] = + std::make_pair(block_index, i); + } + use_ubo_ = true; + return ReadUniformsBindingsV2(gl, program); +} + +bool BufferBindingsGLES::ReadUniformsBindingsV2(const ProcTableGLES& gl, + GLuint program) { + GLint max_name_size = 0; + gl.GetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max_name_size); + + GLint uniform_count = 0; + gl.GetProgramiv(program, GL_ACTIVE_UNIFORMS, &uniform_count); + + // Query the Program for all active uniform locations, and + // record this via normalized key. + for (GLint i = 0; i < uniform_count; i++) { + std::vector name; + name.resize(max_name_size); + GLsizei written_count = 0u; + GLint uniform_var_size = 0u; + GLenum uniform_type = GL_FLOAT; + // Note: Active uniforms are defined as uniforms that may have an impact on + // the output of the shader. Drivers are allowed to (and often do) + // optimize out unused uniforms. + gl.GetActiveUniform(program, // program + i, // index + max_name_size, // buffer_size + &written_count, // length + &uniform_var_size, // size + &uniform_type, // type + name.data() // name + ); + + // Skip unrecognized variables generated by ANGLE. + if (gl.GetCapabilities()->IsANGLE()) { + if (written_count >= + static_cast(kAngleInputAttachmentPrefix.length()) && + std::string_view(name.data(), kAngleInputAttachmentPrefix.length()) == + kAngleInputAttachmentPrefix) { + continue; + } + } + + auto location = gl.GetUniformLocation(program, name.data()); + if (location == -1) { + if (use_ubo_) { + continue; + } + VALIDATION_LOG << "Could not query the location of an active uniform."; + return false; + } + if (written_count <= 0) { + VALIDATION_LOG << "Uniform name could not be read for active uniform."; + return false; + } + uniform_locations_[NormalizeUniformKey(std::string{ + name.data(), static_cast(written_count)})] = location; + } + return true; +} + +bool BufferBindingsGLES::BindVertexAttributes(const ProcTableGLES& gl, + size_t binding, + size_t vertex_offset) { + if (binding >= vertex_attrib_arrays_.size()) { + return false; + } + + if (!gl.GetCapabilities()->IsES()) { + FML_DCHECK(vertex_array_object_ == 0); + gl.GenVertexArrays(1, &vertex_array_object_); + gl.BindVertexArray(vertex_array_object_); + } + + for (const auto& array : vertex_attrib_arrays_[binding]) { + gl.EnableVertexAttribArray(array.index); + gl.VertexAttribPointer(array.index, // index + array.size, // size (must be 1, 2, 3, or 4) + array.type, // type + array.normalized, // normalized + array.stride, // stride + reinterpret_cast(static_cast( + vertex_offset + array.offset)) // pointer + ); + } + + return true; +} + +bool BufferBindingsGLES::BindUniformData( + const ProcTableGLES& gl, + const std::vector& bound_textures, + const std::vector& bound_buffers, + Range texture_range, + Range buffer_range) { + for (auto i = 0u; i < buffer_range.length; i++) { + if (!BindUniformBuffer(gl, bound_buffers[buffer_range.offset + i])) { + return false; + } + } + std::optional next_unit_index = + BindTextures(gl, bound_textures, texture_range, ShaderStage::kVertex); + if (!next_unit_index.has_value()) { + return false; + } + if (!BindTextures(gl, bound_textures, texture_range, ShaderStage::kFragment, + *next_unit_index) + .has_value()) { + return false; + } + + return true; +} + +bool BufferBindingsGLES::UnbindVertexAttributes(const ProcTableGLES& gl) { + for (const auto& array : vertex_attrib_arrays_) { + for (const auto& attribute : array) { + gl.DisableVertexAttribArray(attribute.index); + } + } + if (!gl.GetCapabilities()->IsES()) { + gl.DeleteVertexArrays(1, &vertex_array_object_); + vertex_array_object_ = 0; + } + + return true; +} + +GLint BufferBindingsGLES::ComputeTextureLocation( + const ShaderMetadata* metadata) { + auto location = binding_map_.find(metadata->name); + if (location != binding_map_.end()) { + return location->second[0]; + } + auto& locations = binding_map_[metadata->name] = {}; + auto computed_location = + uniform_locations_.find(CreateUniformMemberKey(metadata->name)); + if (computed_location == uniform_locations_.end()) { + locations.push_back(-1); + } else { + locations.push_back(computed_location->second); + } + return locations[0]; +} + +const std::vector& BufferBindingsGLES::ComputeUniformLocations( + const ShaderMetadata* metadata) { + BindingMap::iterator location = binding_map_.find(metadata->name); + if (location != binding_map_.end()) { + return location->second; + } + + // For each metadata member, look up the binding location and record + // it in the binding map. + std::vector& locations = binding_map_[metadata->name] = {}; + locations.reserve(metadata->members.size()); + for (const ShaderStructMemberMetadata& member : metadata->members) { + if (member.type == ShaderType::kVoid) { + // Void types are used for padding. We are obviously not going to find + // mappings for these. Keep going. + locations.push_back(-1); + continue; + } + + size_t element_count = member.array_elements.value_or(1); + const std::string member_key = + CreateUniformMemberKey(metadata->name, member.name, element_count > 1); + const absl::flat_hash_map::iterator computed_location = + uniform_locations_.find(member_key); + if (computed_location == uniform_locations_.end()) { + // Uniform was not active. + locations.push_back(-1); + continue; + } + locations.push_back(computed_location->second); + } + return locations; +} + +bool BufferBindingsGLES::BindUniformBuffer(const ProcTableGLES& gl, + const BufferResource& buffer) { + const ShaderMetadata* metadata = buffer.GetMetadata(); + const DeviceBuffer* device_buffer = buffer.resource.GetBuffer(); + if (!device_buffer) { + VALIDATION_LOG << "Device buffer not found."; + return false; + } + const DeviceBufferGLES& device_buffer_gles = + DeviceBufferGLES::Cast(*device_buffer); + + if (use_ubo_) { + return BindUniformBufferV3(gl, buffer.resource, metadata, + device_buffer_gles); + } + return BindUniformBufferV2(gl, buffer.resource, metadata, device_buffer_gles); +} + +bool BufferBindingsGLES::BindUniformBufferV3( + const ProcTableGLES& gl, + const BufferView& buffer, + const ShaderMetadata* metadata, + const DeviceBufferGLES& device_buffer_gles) { + absl::flat_hash_map>::iterator it = + ubo_locations_.find(metadata->name); + if (it == ubo_locations_.end()) { + return BindUniformBufferV2(gl, buffer, metadata, device_buffer_gles); + } + const auto& [block_index, binding_point] = it->second; + if (!device_buffer_gles.BindAndUploadDataIfNecessary( + DeviceBufferGLES::BindingType::kUniformBuffer)) { + return false; + } + auto handle = device_buffer_gles.GetHandle(); + if (!handle.has_value()) { + return false; + } + gl.BindBufferRange(GL_UNIFORM_BUFFER, binding_point, handle.value(), + buffer.GetRange().offset, buffer.GetRange().length); + return true; +} + +bool BufferBindingsGLES::BindUniformBufferV2( + const ProcTableGLES& gl, + const BufferView& buffer, + const ShaderMetadata* metadata, + const DeviceBufferGLES& device_buffer_gles) { + const uint8_t* buffer_ptr = + device_buffer_gles.GetBufferData() + buffer.GetRange().offset; + + if (metadata->members.empty()) { + VALIDATION_LOG << "Uniform buffer had no members. This is currently " + "unsupported in the OpenGL ES backend. Use a uniform " + "buffer block."; + return false; + } + + const std::vector& locations = ComputeUniformLocations(metadata); + for (size_t i = 0u; i < metadata->members.size(); i++) { + const ShaderStructMemberMetadata& member = metadata->members[i]; + GLint location = locations[i]; + // Void type or inactive uniform. + if (location == -1 || member.type == ShaderType::kVoid) { + continue; + } + + size_t element_count = member.array_elements.value_or(1); + size_t element_stride = member.byte_length / element_count; + auto* buffer_data = + reinterpret_cast(buffer_ptr + member.offset); + + // When binding uniform arrays, the elements must be contiguous. Copy + // the uniforms to a temp buffer to eliminate any padding needed by the + // other backends if the array elements have padding. + std::vector array_element_buffer; + if (element_count > 1 && element_stride != member.size) { + array_element_buffer.resize(member.size * element_count); + for (size_t element_i = 0; element_i < element_count; element_i++) { + std::memcpy(array_element_buffer.data() + element_i * member.size, + reinterpret_cast(buffer_data) + + element_i * element_stride, + member.size); + } + buffer_data = + reinterpret_cast(array_element_buffer.data()); + } + + if (member.type != ShaderType::kFloat) { + VALIDATION_LOG << "Could not bind uniform buffer data for key: " + << member.name << " : " << static_cast(member.type); + return false; + } + + switch (member.size) { + case sizeof(Matrix): + gl.UniformMatrix4fv(location, // location + element_count, // count + GL_FALSE, // normalize + buffer_data // data + ); + continue; + case sizeof(Vector4): + gl.Uniform4fv(location, // location + element_count, // count + buffer_data // data + ); + continue; + case sizeof(Vector3): + gl.Uniform3fv(location, // location + element_count, // count + buffer_data // data + ); + continue; + case sizeof(Vector2): + gl.Uniform2fv(location, // location + element_count, // count + buffer_data // data + ); + continue; + case sizeof(Scalar): + gl.Uniform1fv(location, // location + element_count, // count + buffer_data // data + ); + continue; + default: + VALIDATION_LOG << "Invalid member size binding: " << member.size; + return false; + } + } + return true; +} + +std::optional BufferBindingsGLES::BindTextures( + const ProcTableGLES& gl, + const std::vector& bound_textures, + Range texture_range, + ShaderStage stage, + size_t unit_start_index) { + size_t active_index = unit_start_index; + for (auto i = 0u; i < texture_range.length; i++) { + const TextureAndSampler& data = bound_textures[texture_range.offset + i]; + if (data.stage != stage) { + continue; + } + const auto& texture_gles = TextureGLES::Cast(*data.texture.resource); + if (data.texture.GetMetadata() == nullptr) { + VALIDATION_LOG << "No metadata found for texture binding."; + return std::nullopt; + } + + auto location = ComputeTextureLocation(data.texture.GetMetadata()); + if (location == -1) { + // The texture binding was optimized out of the shader. Continue. + continue; + } + + //-------------------------------------------------------------------------- + /// Set the active texture unit. + /// + if (active_index >= gl.GetCapabilities()->GetMaxTextureUnits(stage)) { + VALIDATION_LOG << "Texture units specified exceed the capabilities for " + "this shader stage."; + return std::nullopt; + } + gl.ActiveTexture(GL_TEXTURE0 + active_index); + + //-------------------------------------------------------------------------- + /// Bind the texture. + /// + if (!texture_gles.Bind()) { + return std::nullopt; + } + + //-------------------------------------------------------------------------- + /// If there is a sampler for the texture at the same index, configure the + /// bound texture using that sampler. + /// + const auto& sampler_gles = SamplerGLES::Cast(*data.sampler); + if (!sampler_gles.ConfigureBoundTexture(texture_gles, gl)) { + return std::nullopt; + } + + //-------------------------------------------------------------------------- + /// Set the texture uniform location. + /// + gl.Uniform1i(location, active_index); + + //-------------------------------------------------------------------------- + /// Bump up the active index at binding. + /// + active_index++; + } + return active_index; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..d5e5aad531d16c23a4d1c9be3acaa3272c9d3d56 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles.h @@ -0,0 +1,117 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BUFFER_BINDINGS_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BUFFER_BINDINGS_GLES_H_ + +#include + +#include "flutter/third_party/abseil-cpp/absl/container/flat_hash_map.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/command.h" + +namespace impeller { + +namespace testing { +FML_TEST_CLASS(BufferBindingsGLESTest, BindUniformData); +} // namespace testing + +//------------------------------------------------------------------------------ +/// @brief Sets up stage bindings for single draw call in the OpenGLES +/// backend. +/// +class BufferBindingsGLES { + public: + BufferBindingsGLES(); + + ~BufferBindingsGLES(); + + bool RegisterVertexStageInput( + const ProcTableGLES& gl, + const std::vector& inputs, + const std::vector& layouts); + + bool ReadUniformsBindings(const ProcTableGLES& gl, GLuint program); + + bool BindVertexAttributes(const ProcTableGLES& gl, + size_t binding, + size_t vertex_offset); + + bool BindUniformData(const ProcTableGLES& gl, + const std::vector& bound_textures, + const std::vector& bound_buffers, + Range texture_range, + Range buffer_range); + + bool UnbindVertexAttributes(const ProcTableGLES& gl); + + private: + FML_FRIEND_TEST(testing::BufferBindingsGLESTest, BindUniformData); + //---------------------------------------------------------------------------- + /// @brief The arguments to glVertexAttribPointer. + /// + struct VertexAttribPointer { + GLuint index = 0u; + GLint size = 4; + GLenum type = GL_FLOAT; + GLenum normalized = GL_FALSE; + GLsizei stride = 0u; + GLsizei offset = 0u; + }; + std::vector> vertex_attrib_arrays_; + + absl::flat_hash_map uniform_locations_; + absl::flat_hash_map> ubo_locations_; + + using BindingMap = absl::flat_hash_map>; + BindingMap binding_map_ = {}; + GLuint vertex_array_object_ = 0; + GLuint program_handle_ = GL_NONE; + bool use_ubo_ = false; + + const std::vector& ComputeUniformLocations( + const ShaderMetadata* metadata); + + bool ReadUniformsBindingsV2(const ProcTableGLES& gl, GLuint program); + + bool ReadUniformsBindingsV3(const ProcTableGLES& gl, GLuint program); + + GLint ComputeTextureLocation(const ShaderMetadata* metadata); + + bool BindUniformBuffer(const ProcTableGLES& gl, const BufferResource& buffer); + + bool BindUniformBufferV2(const ProcTableGLES& gl, + const BufferView& buffer, + const ShaderMetadata* metadata, + const DeviceBufferGLES& device_buffer_gles); + + bool BindUniformBufferV3(const ProcTableGLES& gl, + const BufferView& buffer, + const ShaderMetadata* metadata, + const DeviceBufferGLES& device_buffer_gles); + + std::optional BindTextures( + const ProcTableGLES& gl, + const std::vector& bound_textures, + Range texture_range, + ShaderStage stage, + size_t unit_start_index = 0); + + BufferBindingsGLES(const BufferBindingsGLES&) = delete; + + BufferBindingsGLES& operator=(const BufferBindingsGLES&) = delete; + + // For testing. + void SetUniformBindings( + absl::flat_hash_map uniform_locations) { + uniform_locations_ = std::move(uniform_locations); + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_BUFFER_BINDINGS_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..45a342bfcbd068374574e1b86ad352e06242fc69 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/buffer_bindings_gles_unittests.cc @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/buffer_bindings_gles.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" +#include "impeller/renderer/command.h" + +namespace impeller { +namespace testing { + +using ::testing::_; + +TEST(BufferBindingsGLESTest, BindUniformData) { + BufferBindingsGLES bindings; + absl::flat_hash_map uniform_bindings; + uniform_bindings["SHADERMETADATA.FOOBAR"] = 1; + bindings.SetUniformBindings(std::move(uniform_bindings)); + auto mock_gles_impl = std::make_unique(); + + EXPECT_CALL(*mock_gles_impl, Uniform1fv(_, _, _)).Times(1); + + std::shared_ptr mock_gl = MockGLES::Init(std::move(mock_gles_impl)); + std::vector bound_buffers; + std::vector bound_textures; + + ShaderMetadata shader_metadata = { + .name = "shader_metadata", + .members = {ShaderStructMemberMetadata{.type = ShaderType::kFloat, + .name = "foobar", + .offset = 0, + .size = sizeof(float), + .byte_length = sizeof(float)}}}; + std::shared_ptr reactor; + std::shared_ptr backing_store = std::make_shared(); + ASSERT_TRUE(backing_store->Truncate(Bytes{sizeof(float)})); + DeviceBufferGLES device_buffer(DeviceBufferDescriptor{.size = sizeof(float)}, + reactor, backing_store); + BufferView buffer_view(&device_buffer, Range(0, sizeof(float))); + bound_buffers.push_back(BufferResource(&shader_metadata, buffer_view)); + + EXPECT_TRUE(bindings.BindUniformData(mock_gl->GetProcTable(), bound_textures, + bound_buffers, Range{0, 0}, + Range{0, 1})); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..0fcb35e6321bc22cc5b30fbe212ce3c163c470a8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.cc @@ -0,0 +1,238 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/capabilities_gles.h" + +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { + +// https://registry.khronos.org/OpenGL/extensions/EXT/EXT_shader_framebuffer_fetch.txt +static const constexpr char* kFramebufferFetchExt = + "GL_EXT_shader_framebuffer_fetch"; + +static const constexpr char* kTextureBorderClampExt = + "GL_EXT_texture_border_clamp"; +static const constexpr char* kNvidiaTextureBorderClampExt = + "GL_NV_texture_border_clamp"; + +// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_multisampled_render_to_texture.txt +static const constexpr char* kMultisampledRenderToTextureExt = + "GL_EXT_multisampled_render_to_texture"; + +// https://registry.khronos.org/OpenGL/extensions/EXT/EXT_multisampled_render_to_texture2.txt +static const constexpr char* kMultisampledRenderToTexture2Ext = + "GL_EXT_multisampled_render_to_texture2"; + +CapabilitiesGLES::CapabilitiesGLES(const ProcTableGLES& gl) { + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &value); + max_combined_texture_image_units = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &value); + max_cube_map_texture_size = value; + } + + auto const desc = gl.GetDescription(); + + if (desc->IsES()) { + GLint value = 0; + gl.GetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &value); + max_fragment_uniform_vectors = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &value); + max_renderbuffer_size = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &value); + max_texture_image_units = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_TEXTURE_SIZE, &value); + max_texture_size = ISize{value, value}; + } + + if (desc->IsES()) { + GLint value = 0; + gl.GetIntegerv(GL_MAX_VARYING_VECTORS, &value); + max_varying_vectors = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_VERTEX_ATTRIBS, &value); + max_vertex_attribs = value; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &value); + max_vertex_texture_image_units = value; + } + + if (desc->IsES()) { + GLint value = 0; + gl.GetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &value); + max_vertex_uniform_vectors = value; + } + + { + GLint values[2] = {}; + gl.GetIntegerv(GL_MAX_VIEWPORT_DIMS, values); + max_viewport_dims = ISize{values[0], values[1]}; + } + + { + GLint value = 0; + gl.GetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &value); + num_compressed_texture_formats = value; + } + + if (desc->IsES()) { + GLint value = 0; + gl.GetIntegerv(GL_NUM_SHADER_BINARY_FORMATS, &value); + num_shader_binary_formats = value; + } + + if (desc->IsES()) { + default_glyph_atlas_format_ = PixelFormat::kA8UNormInt; + } else { + default_glyph_atlas_format_ = PixelFormat::kR8UNormInt; + } + + if (desc->GetGlVersion().major_version >= 3) { + supports_texture_to_texture_blits_ = true; + } + + supports_framebuffer_fetch_ = desc->HasExtension(kFramebufferFetchExt); + + if (desc->HasExtension(kTextureBorderClampExt) || + desc->HasExtension(kNvidiaTextureBorderClampExt)) { + supports_decal_sampler_address_mode_ = true; + } + + if (desc->HasExtension(kMultisampledRenderToTextureExt)) { + supports_implicit_msaa_ = true; + + if (desc->HasExtension(kMultisampledRenderToTexture2Ext)) { + // We hard-code 4x MSAA, so let's make sure it's supported. + GLint value = 0; + gl.GetIntegerv(GL_MAX_SAMPLES_EXT, &value); + supports_offscreen_msaa_ = value >= 4; + } + } else if (desc->GetGlVersion().major_version >= 3 && desc->IsES()) { + GLint value = 0; + gl.GetIntegerv(GL_MAX_SAMPLES, &value); + supports_offscreen_msaa_ = value >= 4; + } + is_es_ = desc->IsES(); + is_angle_ = desc->IsANGLE(); +} + +bool CapabilitiesGLES::IsES() const { + return is_es_; +} + +size_t CapabilitiesGLES::GetMaxTextureUnits(ShaderStage stage) const { + switch (stage) { + case ShaderStage::kVertex: + return max_vertex_texture_image_units; + case ShaderStage::kFragment: + return max_texture_image_units; + case ShaderStage::kUnknown: + case ShaderStage::kCompute: + return 0u; + } + FML_UNREACHABLE(); +} + +bool CapabilitiesGLES::SupportsOffscreenMSAA() const { + return supports_offscreen_msaa_; +} + +bool CapabilitiesGLES::SupportsImplicitResolvingMSAA() const { + return supports_implicit_msaa_; +} + +bool CapabilitiesGLES::SupportsSSBO() const { + return false; +} + +bool CapabilitiesGLES::SupportsTextureToTextureBlits() const { + return supports_texture_to_texture_blits_; +} + +bool CapabilitiesGLES::SupportsFramebufferFetch() const { + return supports_framebuffer_fetch_; +} + +bool CapabilitiesGLES::SupportsCompute() const { + return false; +} + +bool CapabilitiesGLES::SupportsComputeSubgroups() const { + return false; +} + +bool CapabilitiesGLES::SupportsReadFromResolve() const { + return false; +} + +bool CapabilitiesGLES::SupportsDecalSamplerAddressMode() const { + return supports_decal_sampler_address_mode_; +} + +bool CapabilitiesGLES::SupportsDeviceTransientTextures() const { + return false; +} + +bool CapabilitiesGLES::SupportsTriangleFan() const { + return true; +} + +PixelFormat CapabilitiesGLES::GetDefaultColorFormat() const { + return PixelFormat::kR8G8B8A8UNormInt; +} + +PixelFormat CapabilitiesGLES::GetDefaultStencilFormat() const { + return PixelFormat::kS8UInt; +} + +PixelFormat CapabilitiesGLES::GetDefaultDepthStencilFormat() const { + return PixelFormat::kD24UnormS8Uint; +} + +bool CapabilitiesGLES::IsANGLE() const { + return is_angle_; +} + +bool CapabilitiesGLES::SupportsPrimitiveRestart() const { + return false; +} + +bool CapabilitiesGLES::SupportsExtendedRangeFormats() const { + return false; +} + +PixelFormat CapabilitiesGLES::GetDefaultGlyphAtlasFormat() const { + return default_glyph_atlas_format_; +} + +ISize CapabilitiesGLES::GetMaximumRenderPassAttachmentSize() const { + return max_texture_size; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..8783aa469893acaa1a5a901a0c1f99cf9a32e48d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/capabilities_gles.h @@ -0,0 +1,149 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/formats.h" +#include "impeller/core/shader_types.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/capabilities.h" + +namespace impeller { + +class ProcTableGLES; + +//------------------------------------------------------------------------------ +/// @brief The Vulkan layers and extensions wrangler. +/// +class CapabilitiesGLES final + : public Capabilities, + public BackendCast { + public: + explicit CapabilitiesGLES(const ProcTableGLES& gl); + + CapabilitiesGLES(const CapabilitiesGLES&) = delete; + + CapabilitiesGLES(CapabilitiesGLES&&) = delete; + + CapabilitiesGLES& operator=(const CapabilitiesGLES&) = delete; + + CapabilitiesGLES& operator=(CapabilitiesGLES&&) = delete; + + // Must be at least 8. + size_t max_combined_texture_image_units = 8; + + // Must be at least 16. + size_t max_cube_map_texture_size = 16; + + // Must be at least 16. + size_t max_fragment_uniform_vectors = 16; + + // Must be at least 1. + size_t max_renderbuffer_size = 1; + + // Must be at least 8. + size_t max_texture_image_units = 8; + + // Must be at least 64. + ISize max_texture_size = ISize{64, 64}; + + // Must be at least 8. + size_t max_varying_vectors = 8; + + // Must be at least 8. + size_t max_vertex_attribs = 8; + + // May be 0. + size_t max_vertex_texture_image_units = 0; + + // Must be at least 128. + size_t max_vertex_uniform_vectors = 128; + + // Must be at least display size. + ISize max_viewport_dims; + + // May be 0. + size_t num_compressed_texture_formats = 0; + + // May be 0. + size_t num_shader_binary_formats = 0; + + size_t GetMaxTextureUnits(ShaderStage stage) const; + + bool IsANGLE() const; + + /// @brief Whether this is an ES GL variant or (if false) desktop GL. + bool IsES() const; + + // |Capabilities| + bool SupportsOffscreenMSAA() const override; + + // |Capabilities| + bool SupportsImplicitResolvingMSAA() const override; + + // |Capabilities| + bool SupportsSSBO() const override; + + // |Capabilities| + bool SupportsTextureToTextureBlits() const override; + + // |Capabilities| + bool SupportsFramebufferFetch() const override; + + // |Capabilities| + bool SupportsCompute() const override; + + // |Capabilities| + bool SupportsComputeSubgroups() const override; + + // |Capabilities| + bool SupportsReadFromResolve() const override; + + // |Capabilities| + bool SupportsDecalSamplerAddressMode() const override; + + // |Capabilities| + bool SupportsDeviceTransientTextures() const override; + + // |Capabilities| + bool SupportsTriangleFan() const override; + + // |Capabilities| + bool SupportsPrimitiveRestart() const override; + + // |Capabilities| + bool SupportsExtendedRangeFormats() const override; + + // |Capabilities| + PixelFormat GetDefaultColorFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultStencilFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultDepthStencilFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultGlyphAtlasFormat() const override; + + ISize GetMaximumRenderPassAttachmentSize() const override; + + private: + bool supports_texture_to_texture_blits_ = false; + bool supports_framebuffer_fetch_ = false; + bool supports_decal_sampler_address_mode_ = false; + bool supports_offscreen_msaa_ = false; + bool supports_implicit_msaa_ = false; + bool is_angle_ = false; + bool is_es_ = false; + PixelFormat default_glyph_atlas_format_ = PixelFormat::kUnknown; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CAPABILITIES_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..15a42acc618c935c620d36a288b7047d5c54b612 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.cc @@ -0,0 +1,89 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/command_buffer_gles.h" + +#include "impeller/base/config.h" +#include "impeller/renderer/backend/gles/blit_pass_gles.h" +#include "impeller/renderer/backend/gles/render_pass_gles.h" + +namespace impeller { + +CommandBufferGLES::CommandBufferGLES(std::weak_ptr context, + std::shared_ptr reactor) + : CommandBuffer(std::move(context)), + reactor_(std::move(reactor)), + is_valid_(reactor_ && reactor_->IsValid()) {} + +CommandBufferGLES::~CommandBufferGLES() = default; + +// |CommandBuffer| +void CommandBufferGLES::SetLabel(std::string_view label) const { + // Cannot support. +} + +// |CommandBuffer| +bool CommandBufferGLES::IsValid() const { + return is_valid_; +} + +// |CommandBuffer| +bool CommandBufferGLES::OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) { + const auto result = reactor_->React(); + if (callback) { + callback(result ? CommandBuffer::Status::kCompleted + : CommandBuffer::Status::kError); + } + return result; +} + +// |CommandBuffer| +void CommandBufferGLES::OnWaitUntilCompleted() { + reactor_->GetProcTable().Finish(); +} + +// |CommandBuffer| +void CommandBufferGLES::OnWaitUntilScheduled() { + reactor_->GetProcTable().Flush(); +} + +// |CommandBuffer| +std::shared_ptr CommandBufferGLES::OnCreateRenderPass( + RenderTarget target) { + if (!IsValid()) { + return nullptr; + } + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto pass = std::shared_ptr( + new RenderPassGLES(context, target, reactor_)); + if (!pass->IsValid()) { + return nullptr; + } + return pass; +} + +// |CommandBuffer| +std::shared_ptr CommandBufferGLES::OnCreateBlitPass() { + if (!IsValid()) { + return nullptr; + } + auto pass = std::shared_ptr(new BlitPassGLES(reactor_)); + if (!pass->IsValid()) { + return nullptr; + } + return pass; +} + +// |CommandBuffer| +std::shared_ptr CommandBufferGLES::OnCreateComputePass() { + // Compute passes aren't supported until GLES 3.2, at which point Vulkan is + // available anyway. + return nullptr; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..5178d74ce161aa27551671ff2174eeae7066fbac --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/command_buffer_gles.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_COMMAND_BUFFER_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_COMMAND_BUFFER_GLES_H_ + +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +class CommandBufferGLES final : public CommandBuffer { + public: + // |CommandBuffer| + ~CommandBufferGLES() override; + + private: + friend class ContextGLES; + + std::shared_ptr reactor_; + bool is_valid_ = false; + + CommandBufferGLES(std::weak_ptr context, + std::shared_ptr reactor); + + // |CommandBuffer| + void SetLabel(std::string_view label) const override; + + // |CommandBuffer| + bool IsValid() const override; + + // |CommandBuffer| + bool OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) override; + + // |CommandBuffer| + void OnWaitUntilCompleted() override; + + // |CommandBuffer| + void OnWaitUntilScheduled() override; + + // |CommandBuffer| + std::shared_ptr OnCreateRenderPass(RenderTarget target) override; + + // |CommandBuffer| + std::shared_ptr OnCreateBlitPass() override; + + // |CommandBuffer| + std::shared_ptr OnCreateComputePass() override; + + CommandBufferGLES(const CommandBufferGLES&) = delete; + + CommandBufferGLES& operator=(const CommandBufferGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_COMMAND_BUFFER_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..084b74d4e0ec5fbb99463f9286f7fc20418d0e28 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.cc @@ -0,0 +1,197 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/context_gles.h" +#include + +#include "impeller/base/config.h" +#include "impeller/base/validation.h" +#include "impeller/base/version.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/gles/command_buffer_gles.h" +#include "impeller/renderer/backend/gles/gpu_tracer_gles.h" +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/render_pass_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" +#include "impeller/renderer/command_queue.h" + +namespace impeller { + +std::shared_ptr ContextGLES::Create( + const Flags& flags, + std::unique_ptr gl, + const std::vector>& shader_libraries, + bool enable_gpu_tracing) { + return std::shared_ptr(new ContextGLES( + flags, std::move(gl), shader_libraries, enable_gpu_tracing)); +} + +ContextGLES::ContextGLES( + const Flags& flags, + std::unique_ptr gl, + const std::vector>& shader_libraries_mappings, + bool enable_gpu_tracing) + : Context(flags) { + reactor_ = std::make_shared(std::move(gl)); + if (!reactor_->IsValid()) { + VALIDATION_LOG << "Could not create valid reactor."; + return; + } + + // Create the shader library. + { + auto library = std::shared_ptr( + new ShaderLibraryGLES(shader_libraries_mappings)); + if (!library->IsValid()) { + VALIDATION_LOG << "Could not create valid shader library."; + return; + } + shader_library_ = std::move(library); + } + + // Create the pipeline library. + { + pipeline_library_ = + std::shared_ptr(new PipelineLibraryGLES(reactor_)); + } + + // Create allocators. + { + resource_allocator_ = + std::shared_ptr(new AllocatorGLES(reactor_)); + if (!resource_allocator_->IsValid()) { + VALIDATION_LOG << "Could not create a resource allocator."; + return; + } + } + + device_capabilities_ = reactor_->GetProcTable().GetCapabilities(); + + // Create the sampler library. + { + sampler_library_ = + std::shared_ptr(new SamplerLibraryGLES( + device_capabilities_->SupportsDecalSamplerAddressMode())); + } + gpu_tracer_ = std::make_shared(GetReactor()->GetProcTable(), + enable_gpu_tracing); + command_queue_ = std::make_shared(); + is_valid_ = true; +} + +ContextGLES::~ContextGLES() = default; + +Context::BackendType ContextGLES::GetBackendType() const { + return Context::BackendType::kOpenGLES; +} + +const std::shared_ptr& ContextGLES::GetReactor() const { + return reactor_; +} + +std::optional ContextGLES::AddReactorWorker( + const std::shared_ptr& worker) { + if (!IsValid()) { + return std::nullopt; + } + return reactor_->AddWorker(worker); +} + +bool ContextGLES::RemoveReactorWorker(ReactorGLES::WorkerID id) { + if (!IsValid()) { + return false; + } + return reactor_->RemoveWorker(id); +} + +bool ContextGLES::IsValid() const { + return is_valid_; +} + +void ContextGLES::Shutdown() {} + +// |Context| +std::string ContextGLES::DescribeGpuModel() const { + return reactor_->GetProcTable().GetDescription()->GetString(); +} + +// |Context| +std::shared_ptr ContextGLES::GetResourceAllocator() const { + return resource_allocator_; +} + +// |Context| +std::shared_ptr ContextGLES::GetShaderLibrary() const { + return shader_library_; +} + +// |Context| +std::shared_ptr ContextGLES::GetSamplerLibrary() const { + return sampler_library_; +} + +// |Context| +std::shared_ptr ContextGLES::GetPipelineLibrary() const { + return pipeline_library_; +} + +// |Context| +std::shared_ptr ContextGLES::CreateCommandBuffer() const { + return std::shared_ptr( + new CommandBufferGLES(weak_from_this(), reactor_)); +} + +// |Context| +const std::shared_ptr& ContextGLES::GetCapabilities() + const { + return device_capabilities_; +} + +// |Context| +std::shared_ptr ContextGLES::GetCommandQueue() const { + return command_queue_; +} + +// |Context| +void ContextGLES::ResetThreadLocalState() const { + if (!IsValid()) { + return; + } + [[maybe_unused]] auto result = + reactor_->AddOperation([](const ReactorGLES& reactor) { + RenderPassGLES::ResetGLState(reactor.GetProcTable()); + }); +} + +bool ContextGLES::EnqueueCommandBuffer( + std::shared_ptr command_buffer) { + return true; +} + +// |Context| +[[nodiscard]] bool ContextGLES::FlushCommandBuffers() { + return reactor_->React(); +} + +// |Context| +bool ContextGLES::AddTrackingFence( + const std::shared_ptr& texture) const { + if (!reactor_->GetProcTable().FenceSync.IsAvailable()) { + return false; + } + HandleGLES fence = reactor_->CreateHandle(HandleType::kFence); + TextureGLES::Cast(*texture).SetFence(fence); + return true; +} + +// |Context| +RuntimeStageBackend ContextGLES::GetRuntimeStageBackend() const { + if (GetReactor()->GetProcTable().GetDescription()->GetGlVersion().IsAtLeast( + Version{3, 0, 0})) { + return RuntimeStageBackend::kOpenGLES3; + } + return RuntimeStageBackend::kOpenGLES; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..44f2f873bb23e9c498f6fe4ab51817dc8a996507 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/context_gles.h @@ -0,0 +1,122 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/gles/allocator_gles.h" +#include "impeller/renderer/backend/gles/capabilities_gles.h" +#include "impeller/renderer/backend/gles/gpu_tracer_gles.h" +#include "impeller/renderer/backend/gles/pipeline_library_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/sampler_library_gles.h" +#include "impeller/renderer/backend/gles/shader_library_gles.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +class ContextGLES final : public Context, + public BackendCast, + public std::enable_shared_from_this { + public: + static std::shared_ptr Create( + const Flags& flags, + std::unique_ptr gl, + const std::vector>& shader_libraries, + bool enable_gpu_tracing); + + // |Context| + ~ContextGLES() override; + + // |Context| + BackendType GetBackendType() const override; + + const std::shared_ptr& GetReactor() const; + + std::optional AddReactorWorker( + const std::shared_ptr& worker); + + bool RemoveReactorWorker(ReactorGLES::WorkerID id); + + std::shared_ptr GetGPUTracer() const { return gpu_tracer_; } + + private: + std::shared_ptr reactor_; + std::shared_ptr shader_library_; + std::shared_ptr pipeline_library_; + std::shared_ptr sampler_library_; + std::shared_ptr resource_allocator_; + std::shared_ptr command_queue_; + std::shared_ptr gpu_tracer_; + + // Note: This is stored separately from the ProcTableGLES CapabilitiesGLES + // in order to satisfy the Context::GetCapabilities signature which returns + // a reference. + std::shared_ptr device_capabilities_; + bool is_valid_ = false; + + ContextGLES( + const Flags& flags, + std::unique_ptr gl, + const std::vector>& shader_libraries, + bool enable_gpu_tracing); + + // |Context| + std::string DescribeGpuModel() const override; + + // |Context| + bool IsValid() const override; + + // |Context| + std::shared_ptr GetResourceAllocator() const override; + + // |Context| + std::shared_ptr GetShaderLibrary() const override; + + // |Context| + std::shared_ptr GetSamplerLibrary() const override; + + // |Context| + std::shared_ptr GetPipelineLibrary() const override; + + // |Context| + std::shared_ptr CreateCommandBuffer() const override; + + // |Context| + const std::shared_ptr& GetCapabilities() const override; + + // |Context| + std::shared_ptr GetCommandQueue() const override; + + // |Context| + void Shutdown() override; + + // |Context| + bool AddTrackingFence(const std::shared_ptr& texture) const override; + + // |Context| + void ResetThreadLocalState() const override; + + // |Context| + [[nodiscard]] bool EnqueueCommandBuffer( + std::shared_ptr command_buffer) override; + + // |Context| + [[nodiscard]] bool FlushCommandBuffers() override; + + // |Context| + RuntimeStageBackend GetRuntimeStageBackend() const override; + + ContextGLES(const ContextGLES&) = delete; + + ContextGLES& operator=(const ContextGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_CONTEXT_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa01bbb8705a34d1d20211ad78dffcc0fcb2b31d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.cc @@ -0,0 +1,187 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/description_gles.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { + +static std::string GetGLString(const ProcTableGLES& gl, GLenum name) { + auto str = gl.GetString(name); + if (str == nullptr) { + return ""; + } + return reinterpret_cast(str); +} + +static std::string GetGLStringi(const ProcTableGLES& gl, + GLenum name, + int index) { + auto str = gl.GetStringi(name, index); + if (str == nullptr) { + return ""; + } + return reinterpret_cast(str); +} + +static bool DetermineIfES(const std::string& version) { + return HasPrefix(version, "OpenGL ES"); +} + +static bool DetermineIfANGLE(const std::string& version) { + return version.find("ANGLE") != std::string::npos; +} + +static std::optional DetermineVersion(std::string version) { + // Format for OpenGL "OpenGLES". + // + // Format for OpenGL SL "OpenGLESGLSLES" + // + // The prefixes appear to be absent on Desktop GL. + + version = StripPrefix(version, "OpenGL ES "); + version = StripPrefix(version, "GLSL ES "); + + if (version.empty()) { + return std::nullopt; + } + + std::stringstream stream; + for (size_t i = 0; i < version.size(); i++) { + const auto character = version[i]; + if (std::isdigit(character) || character == '.') { + stream << character; + } else { + break; + } + } + std::istringstream istream; + istream.str(stream.str()); + std::vector version_components; + for (std::string version_component; + std::getline(istream, version_component, '.');) { + version_components.push_back(std::stoul(version_component)); + } + return Version::FromVector(version_components); +} + +DescriptionGLES::DescriptionGLES(const ProcTableGLES& gl) + : vendor_(GetGLString(gl, GL_VENDOR)), + renderer_(GetGLString(gl, GL_RENDERER)), + gl_version_string_(GetGLString(gl, GL_VERSION)), + sl_version_string_(GetGLString(gl, GL_SHADING_LANGUAGE_VERSION)) { + is_es_ = DetermineIfES(gl_version_string_); + is_angle_ = DetermineIfANGLE(gl_version_string_); + + auto gl_version = DetermineVersion(gl_version_string_); + if (!gl_version.has_value()) { + VALIDATION_LOG << "Could not determine GL version."; + return; + } + gl_version_ = gl_version.value(); + + // GL_NUM_EXTENSIONS is only available in OpenGL 3+ and OpenGL ES 3+ + if (gl_version_.IsAtLeast(Version(3, 0, 0))) { + int extension_count = 0; + gl.GetIntegerv(GL_NUM_EXTENSIONS, &extension_count); + for (auto i = 0; i < extension_count; i++) { + extensions_.insert(GetGLStringi(gl, GL_EXTENSIONS, i)); + } + } else { + const auto extensions = GetGLString(gl, GL_EXTENSIONS); + std::stringstream extensions_stream(extensions); + std::string extension; + while (std::getline(extensions_stream, extension, ' ')) { + extensions_.insert(extension); + } + } + + auto sl_version = DetermineVersion(sl_version_string_); + if (!sl_version.has_value()) { + VALIDATION_LOG << "Could not determine SL version."; + return; + } + sl_version_ = sl_version.value(); + + is_valid_ = true; +} + +DescriptionGLES::~DescriptionGLES() = default; + +bool DescriptionGLES::IsValid() const { + return is_valid_; +} + +std::string DescriptionGLES::GetString() const { + if (!IsValid()) { + return "Unknown Renderer."; + } + + std::vector> items; + + items.emplace_back(std::make_pair("Vendor", vendor_)); + items.emplace_back(std::make_pair("Renderer", renderer_)); + items.emplace_back(std::make_pair("GL Version", gl_version_string_)); + items.emplace_back( + std::make_pair("Shading Language Version", sl_version_string_)); + items.emplace_back( + std::make_pair("Extensions", std::to_string(extensions_.size()))); + + size_t max_width = 0u; + for (const auto& item : items) { + max_width = std::max(max_width, item.first.size()); + } + + std::stringstream stream; + stream << "OpenGL Renderer:" << std::endl; + for (const auto& item : items) { + stream << std::setw(max_width + 1) << item.first << ": " << item.second + << std::endl; + } + + const auto pad = std::string(max_width + 3, ' '); + for (const auto& extension : extensions_) { + stream << pad << extension << std::endl; + } + + return stream.str(); +} + +Version DescriptionGLES::GetGlVersion() const { + return gl_version_; +} + +bool DescriptionGLES::IsES() const { + return is_es_; +} + +bool DescriptionGLES::IsANGLE() const { + return is_angle_; +} + +bool DescriptionGLES::HasExtension(const std::string& ext) const { + return extensions_.find(ext) != extensions_.end(); +} + +bool DescriptionGLES::HasDebugExtension() const { + // Angle just logs calls instead of forwarding debug information to the + // backend. This just overwhelms the logs and is of limited use. Disable on + // Angle. + return HasExtension("GL_KHR_debug") && !IsANGLE(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..5572b8c57987ea72520e0fc68de1504cdb22d2e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/description_gles.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DESCRIPTION_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DESCRIPTION_GLES_H_ + +#include +#include + +#include "impeller/base/version.h" + +namespace impeller { + +class ProcTableGLES; + +class DescriptionGLES { + public: + explicit DescriptionGLES(const ProcTableGLES& gl); + + ~DescriptionGLES(); + + bool IsValid() const; + + bool IsES() const; + + std::string GetString() const; + + Version GetGlVersion() const; + + bool HasExtension(const std::string& ext) const; + + /// @brief Returns whether GLES includes the debug extension. + bool HasDebugExtension() const; + + bool IsANGLE() const; + + private: + Version gl_version_; + Version sl_version_; + bool is_es_ = true; + std::string vendor_; + std::string renderer_; + std::string gl_version_string_; + std::string sl_version_string_; + std::set extensions_; + bool is_angle_ = false; + bool is_valid_ = false; + + DescriptionGLES(const DescriptionGLES&) = delete; + + DescriptionGLES& operator=(const DescriptionGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DESCRIPTION_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a7478d8f7e9591d4c192d2d1e56bec1c0f93d5f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.cc @@ -0,0 +1,162 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/device_buffer_gles.h" + +#include +#include + +#include "impeller/base/allocation.h" +#include "impeller/base/config.h" + +namespace impeller { + +DeviceBufferGLES::DeviceBufferGLES(DeviceBufferDescriptor desc, + std::shared_ptr reactor, + std::shared_ptr backing_store) + : DeviceBuffer(desc), + reactor_(std::move(reactor)), + backing_store_(std::move(backing_store)) {} + +// |DeviceBuffer| +DeviceBufferGLES::~DeviceBufferGLES() { + if (handle_.has_value() && !handle_->IsDead()) { + reactor_->CollectHandle(*handle_); + } +} + +// |DeviceBuffer| +uint8_t* DeviceBufferGLES::OnGetContents() const { + if (!reactor_) { + return nullptr; + } + return backing_store_->GetBuffer(); +} + +// |DeviceBuffer| +bool DeviceBufferGLES::OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) { + if (!reactor_) { + return false; + } + + if (offset + source_range.length > + backing_store_->GetLength().GetByteSize()) { + return false; + } + + std::memmove(backing_store_->GetBuffer() + offset, + source + source_range.offset, source_range.length); + Flush(Range{offset, source_range.length}); + + return true; +} + +std::optional DeviceBufferGLES::GetHandle() const { + if (handle_.has_value()) { + return reactor_->GetGLHandle(*handle_); + } else { + return std::nullopt; + } +} + +void DeviceBufferGLES::Flush(std::optional range) const { + if (!range.has_value()) { + dirty_range_ = Range{ + 0, static_cast(backing_store_->GetLength().GetByteSize())}; + } else { + if (dirty_range_.has_value()) { + dirty_range_ = dirty_range_->Merge(range.value()); + } else { + dirty_range_ = range.value(); + } + } +} + +static GLenum ToTarget(DeviceBufferGLES::BindingType type) { + switch (type) { + case DeviceBufferGLES::BindingType::kArrayBuffer: + return GL_ARRAY_BUFFER; + case DeviceBufferGLES::BindingType::kElementArrayBuffer: + return GL_ELEMENT_ARRAY_BUFFER; + case DeviceBufferGLES::BindingType::kUniformBuffer: + return GL_UNIFORM_BUFFER; + } + FML_UNREACHABLE(); +} + +bool DeviceBufferGLES::BindAndUploadDataIfNecessary(BindingType type) const { + if (!reactor_) { + return false; + } + + if (!handle_.has_value()) { + handle_ = reactor_->CreateUntrackedHandle(HandleType::kBuffer); +#ifdef IMPELLER_DEBUG + if (handle_.has_value() && label_.has_value()) { + reactor_->SetDebugLabel(*handle_, *label_); + } +#endif + } + + auto buffer = reactor_->GetGLHandle(*handle_); + if (!buffer.has_value()) { + return false; + } + + const auto target_type = ToTarget(type); + const auto& gl = reactor_->GetProcTable(); + + gl.BindBuffer(target_type, buffer.value()); + if (!initialized_) { + gl.BufferData(target_type, backing_store_->GetLength().GetByteSize(), + nullptr, GL_DYNAMIC_DRAW); + initialized_ = true; + } + + if (dirty_range_.has_value()) { + auto range = dirty_range_.value(); + gl.BufferSubData(target_type, range.offset, range.length, + backing_store_->GetBuffer() + range.offset); + dirty_range_ = std::nullopt; + } + + return true; +} + +// |DeviceBuffer| +bool DeviceBufferGLES::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + label_ = label; + if (handle_.has_value()) { + reactor_->SetDebugLabel(*handle_, label); + } +#endif // IMPELLER_DEBUG + return true; +} + +// |DeviceBuffer| +bool DeviceBufferGLES::SetLabel(std::string_view label, Range range) { + // Cannot support debug label on the range. Set the label for the entire + // range. + return SetLabel(label); +} + +const uint8_t* DeviceBufferGLES::GetBufferData() const { + return backing_store_->GetBuffer(); +} + +void DeviceBufferGLES::UpdateBufferData( + const std::function& + update_buffer_data) { + if (update_buffer_data) { + update_buffer_data(backing_store_->GetBuffer(), + backing_store_->GetLength().GetByteSize()); + Flush(Range{ + 0, static_cast(backing_store_->GetLength().GetByteSize())}); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..f080d4e3e0ffeb7e5647bf70b261faee3196638b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles.h @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_ + +#include +#include + +#include "impeller/base/allocation.h" +#include "impeller/base/backend_cast.h" +#include "impeller/core/device_buffer.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" + +namespace impeller { + +class DeviceBufferGLES final + : public DeviceBuffer, + public BackendCast { + public: + DeviceBufferGLES(DeviceBufferDescriptor desc, + std::shared_ptr reactor, + std::shared_ptr backing_store); + + // |DeviceBuffer| + ~DeviceBufferGLES() override; + + const uint8_t* GetBufferData() const; + + void UpdateBufferData( + const std::function& update_buffer_data); + + enum class BindingType { + kArrayBuffer, + kElementArrayBuffer, + kUniformBuffer, + }; + + [[nodiscard]] bool BindAndUploadDataIfNecessary(BindingType type) const; + + void Flush(std::optional range = std::nullopt) const override; + + std::optional GetHandle() const; + + private: + std::shared_ptr reactor_; + std::optional label_; + // Mutable for lazy evaluation. + mutable std::optional handle_; + mutable std::shared_ptr backing_store_; + mutable std::optional dirty_range_ = std::nullopt; + mutable bool initialized_ = false; + + // |DeviceBuffer| + uint8_t* OnGetContents() const override; + + // |DeviceBuffer| + bool OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label, Range range) override; + + DeviceBufferGLES(const DeviceBufferGLES&) = delete; + + DeviceBufferGLES& operator=(const DeviceBufferGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_DEVICE_BUFFER_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..1fe910faab0d92f4df0b68cd5056a74c7082113a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/device_buffer_gles_unittests.cc @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +using ::testing::_; + +namespace { +class TestWorker : public ReactorGLES::Worker { + public: + bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const override { + return true; + } +}; +} // namespace + +TEST(DeviceBufferGLESTest, BindUniformData) { + auto mock_gles_impl = std::make_unique(); + + EXPECT_CALL(*mock_gles_impl, GenBuffers(1, _)).Times(1); + + std::shared_ptr mock_gled = + MockGLES::Init(std::move(mock_gles_impl)); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + std::shared_ptr backing_store = std::make_shared(); + ASSERT_TRUE(backing_store->Truncate(Bytes{sizeof(float)})); + DeviceBufferGLES device_buffer(DeviceBufferDescriptor{.size = sizeof(float)}, + reactor, backing_store); + EXPECT_FALSE(device_buffer.GetHandle().has_value()); + EXPECT_TRUE(device_buffer.BindAndUploadDataIfNecessary( + DeviceBufferGLES::BindingType::kUniformBuffer)); + EXPECT_TRUE(device_buffer.GetHandle().has_value()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f8b719b40869418e541a6a9aced2d5a136d87e8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.cc @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/formats_gles.h" + +namespace impeller { + +std::string DebugToFramebufferError(int status) { + switch (status) { + case GL_FRAMEBUFFER_UNDEFINED: + return "GL_FRAMEBUFFER_UNDEFINED"; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; + case GL_FRAMEBUFFER_UNSUPPORTED: + return "GL_FRAMEBUFFER_UNSUPPORTED"; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; + default: + return "Unknown error code: " + std::to_string(status); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..9b3c9ff82906773db1d89ed8debf48e78730bb63 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/formats_gles.h @@ -0,0 +1,203 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_ + +#include + +#include "flutter/fml/logging.h" +#include "impeller/core/formats.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/gles/gles.h" + +namespace impeller { + +constexpr GLenum ToMode(PrimitiveType primitive_type) { + switch (primitive_type) { + case PrimitiveType::kTriangle: + return GL_TRIANGLES; + case PrimitiveType::kTriangleStrip: + return GL_TRIANGLE_STRIP; + case PrimitiveType::kLine: + return GL_LINES; + case PrimitiveType::kLineStrip: + return GL_LINE_STRIP; + case PrimitiveType::kPoint: + return GL_POINTS; + case PrimitiveType::kTriangleFan: + return GL_TRIANGLE_FAN; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToIndexType(IndexType type) { + switch (type) { + case IndexType::kUnknown: + case IndexType::kNone: + FML_UNREACHABLE(); + case IndexType::k16bit: + return GL_UNSIGNED_SHORT; + case IndexType::k32bit: + return GL_UNSIGNED_INT; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToStencilOp(StencilOperation op) { + switch (op) { + case StencilOperation::kKeep: + return GL_KEEP; + case StencilOperation::kZero: + return GL_ZERO; + case StencilOperation::kSetToReferenceValue: + return GL_REPLACE; + case StencilOperation::kIncrementClamp: + return GL_INCR; + case StencilOperation::kDecrementClamp: + return GL_DECR; + case StencilOperation::kInvert: + return GL_INVERT; + case StencilOperation::kIncrementWrap: + return GL_INCR_WRAP; + case StencilOperation::kDecrementWrap: + return GL_DECR_WRAP; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToCompareFunction(CompareFunction func) { + switch (func) { + case CompareFunction::kNever: + return GL_NEVER; + case CompareFunction::kAlways: + return GL_ALWAYS; + case CompareFunction::kLess: + return GL_LESS; + case CompareFunction::kEqual: + return GL_EQUAL; + case CompareFunction::kLessEqual: + return GL_LEQUAL; + case CompareFunction::kGreater: + return GL_GREATER; + case CompareFunction::kNotEqual: + return GL_NOTEQUAL; + case CompareFunction::kGreaterEqual: + return GL_GEQUAL; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToBlendFactor(BlendFactor factor) { + switch (factor) { + case BlendFactor::kZero: + return GL_ZERO; + case BlendFactor::kOne: + return GL_ONE; + case BlendFactor::kSourceColor: + return GL_SRC_COLOR; + case BlendFactor::kOneMinusSourceColor: + return GL_ONE_MINUS_SRC_COLOR; + case BlendFactor::kSourceAlpha: + return GL_SRC_ALPHA; + case BlendFactor::kOneMinusSourceAlpha: + return GL_ONE_MINUS_SRC_ALPHA; + case BlendFactor::kDestinationColor: + return GL_DST_COLOR; + case BlendFactor::kOneMinusDestinationColor: + return GL_ONE_MINUS_DST_COLOR; + case BlendFactor::kDestinationAlpha: + return GL_DST_ALPHA; + case BlendFactor::kOneMinusDestinationAlpha: + return GL_ONE_MINUS_DST_ALPHA; + case BlendFactor::kSourceAlphaSaturated: + return GL_SRC_ALPHA_SATURATE; + case BlendFactor::kBlendColor: + return GL_CONSTANT_COLOR; + case BlendFactor::kOneMinusBlendColor: + return GL_ONE_MINUS_CONSTANT_COLOR; + case BlendFactor::kBlendAlpha: + return GL_CONSTANT_ALPHA; + case BlendFactor::kOneMinusBlendAlpha: + return GL_ONE_MINUS_CONSTANT_ALPHA; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToBlendOperation(BlendOperation op) { + switch (op) { + case BlendOperation::kAdd: + return GL_FUNC_ADD; + case BlendOperation::kSubtract: + return GL_FUNC_SUBTRACT; + case BlendOperation::kReverseSubtract: + return GL_FUNC_REVERSE_SUBTRACT; + } + FML_UNREACHABLE(); +} + +constexpr std::optional ToVertexAttribType(ShaderType type) { + switch (type) { + case ShaderType::kSignedByte: + return GL_BYTE; + case ShaderType::kUnsignedByte: + return GL_UNSIGNED_BYTE; + case ShaderType::kSignedShort: + return GL_SHORT; + case ShaderType::kUnsignedShort: + return GL_UNSIGNED_SHORT; + case ShaderType::kFloat: + return GL_FLOAT; + case ShaderType::kUnknown: + case ShaderType::kVoid: + case ShaderType::kBoolean: + case ShaderType::kSignedInt: + case ShaderType::kUnsignedInt: + case ShaderType::kSignedInt64: + case ShaderType::kUnsignedInt64: + case ShaderType::kAtomicCounter: + case ShaderType::kHalfFloat: + case ShaderType::kDouble: + case ShaderType::kStruct: + case ShaderType::kImage: + case ShaderType::kSampledImage: + case ShaderType::kSampler: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +constexpr GLenum ToTextureType(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + return GL_TEXTURE_2D; + case TextureType::kTexture2DMultisample: + return GL_TEXTURE_2D_MULTISAMPLE; + case TextureType::kTextureCube: + return GL_TEXTURE_CUBE_MAP; + case TextureType::kTextureExternalOES: + return GL_TEXTURE_EXTERNAL_OES; + } + FML_UNREACHABLE(); +} + +constexpr std::optional ToTextureTarget(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + return GL_TEXTURE_2D; + case TextureType::kTexture2DMultisample: + return GL_TEXTURE_2D; + case TextureType::kTextureCube: + return GL_TEXTURE_CUBE_MAP; + case TextureType::kTextureExternalOES: + return GL_TEXTURE_EXTERNAL_OES; + } + FML_UNREACHABLE(); +} + +std::string DebugToFramebufferError(int status); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_FORMATS_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gles.h new file mode 100644 index 0000000000000000000000000000000000000000..b3a512e0d23f502c687a6816382903dc486ac364 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gles.h @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GLES_H_ + +// IWYU pragma: begin_exports +#include "GLES3/gl3.h" + +// Defines for extension enums. +#define IMPELLER_GL_CLAMP_TO_BORDER 0x812D +#define IMPELLER_GL_TEXTURE_BORDER_COLOR 0x1004 + +#define GL_GLEXT_PROTOTYPES +#include "GLES2/gl2ext.h" +// IWYU pragma: end_exports + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e1e167877b3d3c89ab9108e1bc65bc8890b095a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.cc @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/gpu_tracer_gles.h" +#include +#include "fml/trace_event.h" + +namespace impeller { + +GPUTracerGLES::GPUTracerGLES(const ProcTableGLES& gl, bool enable_tracing) { +#ifdef IMPELLER_DEBUG + auto desc = gl.GetDescription(); + enabled_ = + enable_tracing && desc->HasExtension("GL_EXT_disjoint_timer_query"); +#endif // IMPELLER_DEBUG +} + +void GPUTracerGLES::MarkFrameStart(const ProcTableGLES& gl) { + if (!enabled_ || active_frame_.has_value() || + std::this_thread::get_id() != raster_thread_) { + return; + } + + // At the beginning of a frame, check the status of all pending + // previous queries. + ProcessQueries(gl); + + uint32_t query = 0; + gl.GenQueriesEXT(1, &query); + if (query == 0) { + return; + } + + active_frame_ = query; + gl.BeginQueryEXT(GL_TIME_ELAPSED_EXT, query); +} + +void GPUTracerGLES::RecordRasterThread() { + raster_thread_ = std::this_thread::get_id(); +} + +void GPUTracerGLES::ProcessQueries(const ProcTableGLES& gl) { + // For reasons unknown to me, querying the state of more than + // one query object per frame causes crashes on a Pixel 6 pro. + // It does not crash on an S10. + while (!pending_traces_.empty()) { + auto query = pending_traces_.front(); + + // First check if the query is complete without blocking + // on the result. Incomplete results are left in the pending + // trace vector and will not be checked again for another + // frame. + GLuint available = GL_FALSE; + gl.GetQueryObjectuivEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT, &available); + + if (available != GL_TRUE) { + // If a query is not available, then all subsequent queries will be + // unavailable. + return; + } + // Return the timer resolution in nanoseconds. + uint64_t duration = 0; + gl.GetQueryObjectui64vEXT(query, GL_QUERY_RESULT_EXT, &duration); + auto gpu_ms = duration / 1000000.0; + + FML_TRACE_COUNTER("flutter", "GPUTracer", + reinterpret_cast(this), // Trace Counter ID + "FrameTimeMS", gpu_ms); + gl.DeleteQueriesEXT(1, &query); + pending_traces_.pop_front(); + } +} + +void GPUTracerGLES::MarkFrameEnd(const ProcTableGLES& gl) { + if (!enabled_ || std::this_thread::get_id() != raster_thread_ || + !active_frame_.has_value()) { + return; + } + + auto query = active_frame_.value(); + gl.EndQueryEXT(GL_TIME_ELAPSED_EXT); + + pending_traces_.push_back(query); + active_frame_ = std::nullopt; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..f6b0de8ab9be66e89ac3491d7af88edb2faa821a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/gpu_tracer_gles.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GPU_TRACER_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GPU_TRACER_GLES_H_ + +#include +#include +#include + +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { + +/// @brief Trace GPU execution times using GL_EXT_disjoint_timer_query on GLES. +/// +/// Note: there are a substantial number of GPUs where usage of the this API is +/// known to cause crashes. As a result, this functionality is disabled by +/// default and can only be enabled in debug/profile mode via a specific opt-in +/// flag that is exposed in the Android manifest. +/// +/// To enable, add the following metadata to the application's Android manifest: +/// +class GPUTracerGLES { + public: + GPUTracerGLES(const ProcTableGLES& gl, bool enable_tracing); + + ~GPUTracerGLES() = default; + + /// @brief Record the thread id of the raster thread. + void RecordRasterThread(); + + /// @brief Record the start of a frame workload, if one hasn't already been + /// started. + void MarkFrameStart(const ProcTableGLES& gl); + + /// @brief Record the end of a frame workload. + void MarkFrameEnd(const ProcTableGLES& gl); + + private: + void ProcessQueries(const ProcTableGLES& gl); + + std::deque pending_traces_; + std::optional active_frame_ = std::nullopt; + std::thread::id raster_thread_; + + bool enabled_ = false; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_GPU_TRACER_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..f1ee08ac9b491cb65f7dbf07589d5d03f6e4746a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.cc @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/handle_gles.h" + +#include "flutter/fml/logging.h" + +namespace impeller { + +std::string HandleTypeToString(HandleType type) { + switch (type) { + case HandleType::kUnknown: + return "Unknown"; + case HandleType::kTexture: + return "Texture"; + case HandleType::kBuffer: + return "Buffer"; + case HandleType::kProgram: + return "Program"; + case HandleType::kRenderBuffer: + return "RenderBuffer"; + case HandleType::kFrameBuffer: + return "Framebuffer"; + case HandleType::kFence: + return "Fence"; + } + FML_UNREACHABLE(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..9d71b4c6e340e448df75985e67b58a05d0e8dd91 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/handle_gles.h @@ -0,0 +1,128 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_HANDLE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_HANDLE_GLES_H_ + +#include +#include +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "impeller/base/comparable.h" + +namespace impeller { + +enum class HandleType { + kUnknown, + kTexture, + kBuffer, + kProgram, + kRenderBuffer, + kFrameBuffer, + kFence, +}; + +std::string HandleTypeToString(HandleType type); + +class ReactorGLES; + +//------------------------------------------------------------------------------ +/// @brief Represents a handle to an underlying OpenGL object. Unlike +/// OpenGL object handles, these handles can be collected on any +/// thread as long as their destruction is scheduled in a reactor. +/// +class HandleGLES { + public: + //---------------------------------------------------------------------------- + /// @brief Creates a dead handle. + /// + /// @return The handle. + /// + static HandleGLES DeadHandle() { + return HandleGLES{HandleType::kUnknown, std::nullopt}; + } + + //---------------------------------------------------------------------------- + /// @brief Determines if the handle is dead. + /// + /// @return True if dead, False otherwise. + /// + constexpr bool IsDead() const { return !name_.has_value(); } + + //---------------------------------------------------------------------------- + /// @brief Get the hash value of this handle. Handles can be used as map + /// keys. + /// + struct Hash { + std::size_t operator()(const HandleGLES& handle) const { + return handle.GetHash(); + } + }; + + //---------------------------------------------------------------------------- + /// @brief A comparer used to test the equality of two handles. + /// + struct Equal { + bool operator()(const HandleGLES& lhs, const HandleGLES& rhs) const { + return lhs.type_ == rhs.type_ && lhs.name_ == rhs.name_; + } + }; + + HandleType GetType() const { return type_; } + const std::optional& GetName() const { return name_; } + std::size_t GetHash() const { return hash_; } + + private: + HandleType type_ = HandleType::kUnknown; + std::optional name_; + std::size_t hash_; + std::optional untracked_id_; + + friend class ReactorGLES; + + HandleGLES(HandleType p_type, UniqueID p_name) + : type_(p_type), + name_(p_name), + hash_(fml::HashCombine( + static_cast>(p_type), + p_name)) {} + + HandleGLES(HandleType p_type, std::optional p_name) + : type_(p_type), + name_(p_name), + hash_(fml::HashCombine( + static_cast>(p_type), + p_name)) {} + + static HandleGLES Create(HandleType type) { + return HandleGLES{type, UniqueID{}}; + } +}; + +} // namespace impeller + +namespace std { + +inline std::ostream& operator<<(std::ostream& out, + const impeller::HandleGLES& handle) { + out << HandleTypeToString(handle.GetType()) << "("; + if (handle.IsDead()) { + out << "DEAD"; + } else { + const std::optional& name = handle.GetName(); + if (name.has_value()) { + out << name.value().id; + } else { + out << "UNNAMED"; + } + } + out << ")"; + return out; +} + +} // namespace std + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_HANDLE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..e173ce167be85d93c4ffe5d4709c66ff9a2bf496 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.cc @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/pipeline_gles.h" + +namespace impeller { + +PipelineGLES::PipelineGLES(std::shared_ptr reactor, + std::weak_ptr library, + const PipelineDescriptor& desc, + std::shared_ptr handle) + : Pipeline(std::move(library), desc), + reactor_(std::move(reactor)), + handle_(std::move(handle)), + is_valid_(handle_->IsValid()) { + if (is_valid_) { + reactor_->SetDebugLabel(handle_->Get(), GetDescriptor().GetLabel()); + } +} + +// |Pipeline| +PipelineGLES::~PipelineGLES() = default; + +// |Pipeline| +bool PipelineGLES::IsValid() const { + return is_valid_; +} + +const HandleGLES& PipelineGLES::GetProgramHandle() const { + return handle_->Get(); +} + +const std::shared_ptr PipelineGLES::GetSharedHandle() const { + return handle_; +} + +BufferBindingsGLES* PipelineGLES::GetBufferBindings() const { + return buffer_bindings_.get(); +} + +bool PipelineGLES::BuildVertexDescriptor(const ProcTableGLES& gl, + GLuint program) { + if (buffer_bindings_) { + return false; + } + auto vtx_desc = std::make_unique(); + if (!vtx_desc->RegisterVertexStageInput( + gl, GetDescriptor().GetVertexDescriptor()->GetStageInputs(), + GetDescriptor().GetVertexDescriptor()->GetStageLayouts())) { + return false; + } + if (!vtx_desc->ReadUniformsBindings(gl, program)) { + return false; + } + buffer_bindings_ = std::move(vtx_desc); + return true; +} + +[[nodiscard]] bool PipelineGLES::BindProgram() const { + if (!handle_->IsValid()) { + return false; + } + auto handle = reactor_->GetGLHandle(handle_->Get()); + if (!handle.has_value()) { + return false; + } + reactor_->GetProcTable().UseProgram(handle.value()); + return true; +} + +[[nodiscard]] bool PipelineGLES::UnbindProgram() const { + if (reactor_) { + reactor_->GetProcTable().UseProgram(0u); + } + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..0db8414f9a418b27363db1bdac4e56cfb0baa090 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_gles.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/gles/buffer_bindings_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/unique_handle_gles.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +class PipelineLibraryGLES; + +class PipelineGLES final + : public Pipeline, + public BackendCast> { + public: + // |Pipeline| + ~PipelineGLES() override; + + const HandleGLES& GetProgramHandle() const; + + const std::shared_ptr GetSharedHandle() const; + + [[nodiscard]] bool BindProgram() const; + + [[nodiscard]] bool UnbindProgram() const; + + BufferBindingsGLES* GetBufferBindings() const; + + [[nodiscard]] bool BuildVertexDescriptor(const ProcTableGLES& gl, + GLuint program); + + private: + friend PipelineLibraryGLES; + + std::shared_ptr reactor_; + std::shared_ptr handle_; + std::unique_ptr buffer_bindings_; + bool is_valid_ = false; + + // |Pipeline| + bool IsValid() const override; + + PipelineGLES(std::shared_ptr reactor, + std::weak_ptr library, + const PipelineDescriptor& desc, + std::shared_ptr handle); + + PipelineGLES(const PipelineGLES&) = delete; + + PipelineGLES& operator=(const PipelineGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..199af7068ac26ebf1b7f082082a1e572c5befc31 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.cc @@ -0,0 +1,348 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/pipeline_library_gles.h" + +#include +#include + +#include "flutter/fml/container.h" +#include "flutter/fml/trace_event.h" +#include "fml/closure.h" +#include "impeller/base/promise.h" +#include "impeller/renderer/backend/gles/pipeline_gles.h" +#include "impeller/renderer/backend/gles/shader_function_gles.h" + +namespace impeller { + +PipelineLibraryGLES::PipelineLibraryGLES(std::shared_ptr reactor) + : reactor_(std::move(reactor)) {} + +static std::string GetShaderInfoLog(const ProcTableGLES& gl, GLuint shader) { + GLint log_length = 0; + gl.GetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length); + if (log_length == 0) { + return ""; + } + auto log_buffer = + reinterpret_cast(std::calloc(log_length, sizeof(char))); + gl.GetShaderInfoLog(shader, log_length, &log_length, log_buffer); + auto log_string = std::string(log_buffer, log_length); + std::free(log_buffer); + return log_string; +} + +static std::string GetShaderSource(const ProcTableGLES& gl, GLuint shader) { + // Arbitrarily chosen size that should be larger than most shaders. + // Since this only fires on compilation errors the performance shouldn't + // matter. + auto data = static_cast(malloc(10240)); + GLsizei length; + gl.GetShaderSource(shader, 10240, &length, data); + + auto result = std::string{data, static_cast(length)}; + free(data); + return result; +} + +static void LogShaderCompilationFailure(const ProcTableGLES& gl, + GLuint shader, + std::string_view name, + const fml::Mapping& source_mapping, + ShaderStage stage) { + std::stringstream stream; + stream << "Failed to compile "; + switch (stage) { + case ShaderStage::kUnknown: + stream << "unknown"; + break; + case ShaderStage::kVertex: + stream << "vertex"; + break; + case ShaderStage::kFragment: + stream << "fragment"; + break; + case ShaderStage::kCompute: + stream << "compute"; + break; + } + stream << " shader for '" << name << "' with error:" << std::endl; + stream << GetShaderInfoLog(gl, shader) << std::endl; + stream << "Shader source was: " << std::endl; + stream << GetShaderSource(gl, shader) << std::endl; + VALIDATION_LOG << stream.str(); +} + +static bool LinkProgram( + const ReactorGLES& reactor, + const std::shared_ptr& pipeline, + const std::shared_ptr& vert_function, + const std::shared_ptr& frag_function) { + TRACE_EVENT0("impeller", __FUNCTION__); + + const auto& descriptor = pipeline->GetDescriptor(); + + auto vert_mapping = + ShaderFunctionGLES::Cast(*vert_function).GetSourceMapping(); + auto frag_mapping = + ShaderFunctionGLES::Cast(*frag_function).GetSourceMapping(); + + const auto& gl = reactor.GetProcTable(); + + auto vert_shader = gl.CreateShader(GL_VERTEX_SHADER); + auto frag_shader = gl.CreateShader(GL_FRAGMENT_SHADER); + + if (vert_shader == 0 || frag_shader == 0) { + VALIDATION_LOG << "Could not create shader handles."; + return false; + } + + gl.SetDebugLabel(DebugResourceType::kShader, vert_shader, + SPrintF("%s Vertex Shader", descriptor.GetLabel().data())); + gl.SetDebugLabel(DebugResourceType::kShader, frag_shader, + SPrintF("%s Fragment Shader", descriptor.GetLabel().data())); + + fml::ScopedCleanupClosure delete_vert_shader( + [&gl, vert_shader]() { gl.DeleteShader(vert_shader); }); + fml::ScopedCleanupClosure delete_frag_shader( + [&gl, frag_shader]() { gl.DeleteShader(frag_shader); }); + + gl.ShaderSourceMapping(vert_shader, *vert_mapping, + descriptor.GetSpecializationConstants()); + gl.ShaderSourceMapping(frag_shader, *frag_mapping, + descriptor.GetSpecializationConstants()); + + gl.CompileShader(vert_shader); + gl.CompileShader(frag_shader); + + GLint vert_status = GL_FALSE; + GLint frag_status = GL_FALSE; + + gl.GetShaderiv(vert_shader, GL_COMPILE_STATUS, &vert_status); + gl.GetShaderiv(frag_shader, GL_COMPILE_STATUS, &frag_status); + + if (vert_status != GL_TRUE) { + LogShaderCompilationFailure(gl, vert_shader, descriptor.GetLabel(), + *vert_mapping, ShaderStage::kVertex); + return false; + } + + if (frag_status != GL_TRUE) { + LogShaderCompilationFailure(gl, frag_shader, descriptor.GetLabel(), + *frag_mapping, ShaderStage::kFragment); + return false; + } + + auto program = reactor.GetGLHandle(pipeline->GetProgramHandle()); + if (!program.has_value()) { + VALIDATION_LOG << "Could not get program handle from reactor."; + return false; + } + + gl.AttachShader(*program, vert_shader); + gl.AttachShader(*program, frag_shader); + + fml::ScopedCleanupClosure detach_vert_shader( + [&gl, program = *program, vert_shader]() { + gl.DetachShader(program, vert_shader); + }); + fml::ScopedCleanupClosure detach_frag_shader( + [&gl, program = *program, frag_shader]() { + gl.DetachShader(program, frag_shader); + }); + + for (const auto& stage_input : + descriptor.GetVertexDescriptor()->GetStageInputs()) { + gl.BindAttribLocation(*program, // + static_cast(stage_input.location), // + stage_input.name // + ); + } + + gl.LinkProgram(*program); + + GLint link_status = GL_FALSE; + gl.GetProgramiv(*program, GL_LINK_STATUS, &link_status); + + if (link_status != GL_TRUE) { + VALIDATION_LOG << "Could not link shader program: " + << gl.GetProgramInfoLogString(*program); + return false; + } + return true; +} + +// |PipelineLibrary| +bool PipelineLibraryGLES::IsValid() const { + return reactor_ != nullptr; +} + +std::shared_ptr PipelineLibraryGLES::CreatePipeline( + const std::weak_ptr& weak_library, + const PipelineDescriptor& desc, + const std::shared_ptr& vert_function, + const std::shared_ptr& frag_function) { + auto strong_library = weak_library.lock(); + + if (!strong_library) { + VALIDATION_LOG << "Library was collected before a pending pipeline " + "creation could finish."; + return nullptr; + } + + auto& library = PipelineLibraryGLES::Cast(*strong_library); + + const auto& reactor = library.GetReactor(); + + if (!reactor) { + return nullptr; + } + + auto program_key = ProgramKey{vert_function, frag_function, + desc.GetSpecializationConstants()}; + + auto cached_program = library.GetProgramForKey(program_key); + + const auto has_cached_program = !!cached_program; + + auto pipeline = std::shared_ptr(new PipelineGLES( + reactor, // + weak_library, // + desc, // + has_cached_program + ? std::move(cached_program) + : std::make_shared(UniqueHandleGLES::MakeUntracked( + reactor, HandleType::kProgram)))); + + auto program = reactor->GetGLHandle(pipeline->GetProgramHandle()); + + if (!program.has_value()) { + VALIDATION_LOG << "Could not obtain program handle."; + return nullptr; + } + + const auto link_result = !has_cached_program ? LinkProgram(*reactor, // + pipeline, // + vert_function, // + frag_function // + ) + : true; + + if (!link_result) { + VALIDATION_LOG << "Could not link pipeline program."; + return nullptr; + } + + if (!pipeline->BuildVertexDescriptor(reactor->GetProcTable(), + program.value())) { + VALIDATION_LOG << "Could not build pipeline vertex descriptors."; + return nullptr; + } + + if (!pipeline->IsValid()) { + VALIDATION_LOG << "Pipeline validation checks failed."; + return nullptr; + } + + if (!has_cached_program) { + library.SetProgramForKey(program_key, pipeline->GetSharedHandle()); + } + + return pipeline; +} + +// |PipelineLibrary| +PipelineFuture PipelineLibraryGLES::GetPipeline( + PipelineDescriptor descriptor, + bool async) { + if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) { + return found->second; + } + + if (!reactor_) { + return { + descriptor, + RealizedFuture>>(nullptr)}; + } + + auto vert_function = descriptor.GetEntrypointForStage(ShaderStage::kVertex); + auto frag_function = descriptor.GetEntrypointForStage(ShaderStage::kFragment); + + if (!vert_function || !frag_function) { + VALIDATION_LOG + << "Could not find stage entrypoint functions in pipeline descriptor."; + return { + descriptor, + RealizedFuture>>(nullptr)}; + } + + auto promise = std::make_shared< + std::promise>>>(); + auto pipeline_future = + PipelineFuture{descriptor, promise->get_future()}; + pipelines_[descriptor] = pipeline_future; + + const auto result = reactor_->AddOperation([promise, // + weak_this = weak_from_this(), // + descriptor, // + vert_function, // + frag_function // + ](const ReactorGLES& reactor) { + promise->set_value( + CreatePipeline(weak_this, descriptor, vert_function, frag_function)); + }); + FML_CHECK(result); + + return pipeline_future; +} + +// |PipelineLibrary| +PipelineFuture PipelineLibraryGLES::GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) { + auto promise = std::make_shared< + std::promise>>>(); + promise->set_value(nullptr); + return {descriptor, promise->get_future()}; +} + +// |PipelineLibrary| +bool PipelineLibraryGLES::HasPipeline(const PipelineDescriptor& descriptor) { + return pipelines_.find(descriptor) != pipelines_.end(); +} + +// |PipelineLibrary| +void PipelineLibraryGLES::RemovePipelinesWithEntryPoint( + std::shared_ptr function) { + fml::erase_if(pipelines_, [&](auto item) { + return item->first.GetEntrypointForStage(function->GetStage()) + ->IsEqual(*function); + }); +} + +// |PipelineLibrary| +PipelineLibraryGLES::~PipelineLibraryGLES() = default; + +const std::shared_ptr& PipelineLibraryGLES::GetReactor() const { + return reactor_; +} + +std::shared_ptr PipelineLibraryGLES::GetProgramForKey( + const ProgramKey& key) { + Lock lock(programs_mutex_); + auto found = programs_.find(key); + if (found != programs_.end()) { + return found->second; + } + return nullptr; +} + +void PipelineLibraryGLES::SetProgramForKey( + const ProgramKey& key, + std::shared_ptr program) { + Lock lock(programs_mutex_); + programs_[key] = std::move(program); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..3b9f29f7d2274a61750e23dbe4bab1b5b80f24ec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/pipeline_library_gles.h @@ -0,0 +1,132 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_LIBRARY_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_LIBRARY_GLES_H_ + +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/unique_handle_gles.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/shader_function.h" + +namespace impeller { + +class ContextGLES; +class PipelineGLES; + +class PipelineLibraryGLES final + : public PipelineLibrary, + public BackendCast { + public: + // |PipelineLibrary| + ~PipelineLibraryGLES() override; + + PipelineLibraryGLES(const PipelineLibraryGLES&) = delete; + + PipelineLibraryGLES& operator=(const PipelineLibraryGLES&) = delete; + + private: + friend ContextGLES; + + //---------------------------------------------------------------------------- + /// @brief A subset of the items in a pipeline descriptor (and the items + /// they reference in shader libraries) whose dynamism requires a + /// program object re-compilation and link. In all other cases, + /// creating a pipeline variant reuses an existing (compatible) + /// program object. + /// + struct ProgramKey { + std::shared_ptr vertex_shader; + std::shared_ptr fragment_shader; + //-------------------------------------------------------------------------- + /// Specialization constants used in the shaders affect defines used when + /// compiling and linking the program. + /// + std::vector specialization_constants; + + ProgramKey(std::shared_ptr p_vertex_shader, + std::shared_ptr p_fragment_shader, + std::vector p_specialization_constants) + : vertex_shader(std::move(p_vertex_shader)), + fragment_shader(std::move(p_fragment_shader)), + specialization_constants(std::move(p_specialization_constants)) {} + + struct Hash { + std::size_t operator()(const ProgramKey& key) const { + auto seed = fml::HashCombine(); + if (key.vertex_shader) { + fml::HashCombineSeed(seed, key.vertex_shader->GetHash()); + } + if (key.fragment_shader) { + fml::HashCombineSeed(seed, key.fragment_shader->GetHash()); + } + for (const auto& constant : key.specialization_constants) { + fml::HashCombineSeed(seed, constant); + } + return seed; + } + }; + + struct Equal { + bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const { + return DeepComparePointer(lhs.vertex_shader, rhs.vertex_shader) && + DeepComparePointer(lhs.fragment_shader, rhs.fragment_shader) && + lhs.specialization_constants == rhs.specialization_constants; + } + }; + }; + + using ProgramMap = std::unordered_map, + ProgramKey::Hash, + ProgramKey::Equal>; + + std::shared_ptr reactor_; + PipelineMap pipelines_; + Mutex programs_mutex_; + ProgramMap programs_ IPLR_GUARDED_BY(programs_mutex_); + + explicit PipelineLibraryGLES(std::shared_ptr reactor); + + // |PipelineLibrary| + bool IsValid() const override; + + // |PipelineLibrary| + PipelineFuture GetPipeline(PipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + PipelineFuture GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + bool HasPipeline(const PipelineDescriptor& descriptor) override; + + // |PipelineLibrary| + void RemovePipelinesWithEntryPoint( + std::shared_ptr function) override; + + const std::shared_ptr& GetReactor() const; + + static std::shared_ptr CreatePipeline( + const std::weak_ptr& weak_library, + const PipelineDescriptor& desc, + const std::shared_ptr& vert_shader, + const std::shared_ptr& frag_shader); + + std::shared_ptr GetProgramForKey(const ProgramKey& key); + + void SetProgramForKey(const ProgramKey& key, + std::shared_ptr program); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PIPELINE_LIBRARY_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..399b88c94fc5c7b72b1b021d3b56c72e5494da7d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.cc @@ -0,0 +1,448 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +#include + +#include "impeller/base/allocation.h" +#include "impeller/base/comparable.h" +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/gles/capabilities_gles.h" +#include "impeller/renderer/capabilities.h" + +namespace impeller { + +const char* GLErrorToString(GLenum value) { + switch (value) { + case GL_NO_ERROR: + return "GL_NO_ERROR"; + case GL_INVALID_ENUM: + return "GL_INVALID_ENUM"; + case GL_INVALID_VALUE: + return "GL_INVALID_VALUE"; + case GL_INVALID_OPERATION: + return "GL_INVALID_OPERATION"; + case GL_INVALID_FRAMEBUFFER_OPERATION: + return "GL_INVALID_FRAMEBUFFER_OPERATION"; + case GL_FRAMEBUFFER_COMPLETE: + return "GL_FRAMEBUFFER_COMPLETE"; + case GL_OUT_OF_MEMORY: + return "GL_OUT_OF_MEMORY"; + } + return "Unknown."; +} + +bool GLErrorIsFatal(GLenum value) { + switch (value) { + case GL_NO_ERROR: + return false; + case GL_INVALID_ENUM: + case GL_INVALID_VALUE: + case GL_INVALID_OPERATION: + case GL_INVALID_FRAMEBUFFER_OPERATION: + case GL_OUT_OF_MEMORY: + return true; + } + return false; +} + +ProcTableGLES::Resolver WrappedResolver( + const ProcTableGLES::Resolver& resolver) { + return [resolver](const char* function_name) -> void* { + auto resolved = resolver(function_name); + if (resolved) { + return resolved; + } + // If there are certain known suffixes (usually for extensions), strip them + // out and try to resolve the same proc addresses again. + auto function = std::string{function_name}; + if (function.find("KHR", function.size() - 3) != std::string::npos) { + auto truncated = function.substr(0u, function.size() - 3); + return resolver(truncated.c_str()); + } + if (function.find("EXT", function.size() - 3) != std::string::npos) { + auto truncated = function.substr(0u, function.size() - 3); + return resolver(truncated.c_str()); + } + return nullptr; + }; +} + +ProcTableGLES::ProcTableGLES( // NOLINT(google-readability-function-size) + Resolver resolver) { + // The reason this constructor has anywhere near enough code to tip off + // `google-readability-function-size` is the proc macros, so ignore the lint. + + if (!resolver) { + return; + } + + resolver = WrappedResolver(resolver); + + auto error_fn = reinterpret_cast(resolver("glGetError")); + if (!error_fn) { + VALIDATION_LOG << "Could not resolve " << "glGetError"; + return; + } + +#define IMPELLER_PROC(proc_ivar) \ + if (auto fn_ptr = resolver(proc_ivar.name)) { \ + proc_ivar.function = \ + reinterpret_cast(fn_ptr); \ + proc_ivar.error_fn = error_fn; \ + } else { \ + VALIDATION_LOG << "Could not resolve " << proc_ivar.name; \ + return; \ + } + + FOR_EACH_IMPELLER_PROC(IMPELLER_PROC); + + description_ = std::make_unique(*this); + + if (!description_->IsValid()) { + return; + } + + if (description_->IsES()) { + FOR_EACH_IMPELLER_ES_ONLY_PROC(IMPELLER_PROC); + } else { + FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(IMPELLER_PROC); + } + +#undef IMPELLER_PROC + +#define IMPELLER_PROC(proc_ivar) \ + if (auto fn_ptr = resolver(proc_ivar.name)) { \ + proc_ivar.function = \ + reinterpret_cast(fn_ptr); \ + proc_ivar.error_fn = error_fn; \ + } + + if (description_->GetGlVersion().IsAtLeast(Version(3))) { + FOR_EACH_IMPELLER_GLES3_PROC(IMPELLER_PROC); + } + + FOR_EACH_IMPELLER_EXT_PROC(IMPELLER_PROC); + +#undef IMPELLER_PROC + + if (!IP_ENABLE_GLES_LABELING || !description_->HasDebugExtension()) { + PushDebugGroupKHR.Reset(); + PopDebugGroupKHR.Reset(); + ObjectLabelKHR.Reset(); + } else { + GetIntegerv(GL_MAX_LABEL_LENGTH_KHR, &debug_label_max_length_); + } + + if (!description_->HasExtension("GL_EXT_discard_framebuffer")) { + DiscardFramebufferEXT.Reset(); + } + + if (!description_->HasExtension("GL_ANGLE_framebuffer_blit")) { + BlitFramebufferANGLE.Reset(); + } + + capabilities_ = std::make_shared(*this); + + is_valid_ = true; +} + +ProcTableGLES::~ProcTableGLES() = default; + +bool ProcTableGLES::IsValid() const { + return is_valid_; +} + +void ProcTableGLES::ShaderSourceMapping( + GLuint shader, + const fml::Mapping& mapping, + const std::vector& defines) const { + if (defines.empty()) { + const GLchar* sources[] = { + reinterpret_cast(mapping.GetMapping())}; + const GLint lengths[] = {static_cast(mapping.GetSize())}; + ShaderSource(shader, 1u, sources, lengths); + return; + } + const auto& shader_source = ComputeShaderWithDefines(mapping, defines); + if (!shader_source.has_value()) { + VALIDATION_LOG << "Failed to append constant data to shader"; + return; + } + + const GLchar* sources[] = { + reinterpret_cast(shader_source->c_str())}; + const GLint lengths[] = {static_cast(shader_source->size())}; + ShaderSource(shader, 1u, sources, lengths); +} + +// Visible For testing. +std::optional ProcTableGLES::ComputeShaderWithDefines( + const fml::Mapping& mapping, + const std::vector& defines) const { + std::string shader_source = std::string{ + reinterpret_cast(mapping.GetMapping()), mapping.GetSize()}; + + // Look for the first newline after the '#version' header, which impellerc + // will always emit as the first line of a compiled shader. + size_t index = shader_source.find('\n'); + if (index == std::string::npos) { + VALIDATION_LOG << "Failed to append constant data to shader"; + return std::nullopt; + } + + std::stringstream ss; + ss << std::fixed; + for (auto i = 0u; i < defines.size(); i++) { + ss << "#define SPIRV_CROSS_CONSTANT_ID_" << i << " " << defines[i] << '\n'; + } + auto define_string = ss.str(); + shader_source.insert(index + 1, define_string); + return shader_source; +} + +const DescriptionGLES* ProcTableGLES::GetDescription() const { + return description_.get(); +} + +const std::shared_ptr& ProcTableGLES::GetCapabilities() + const { + return capabilities_; +} + +static const char* FramebufferStatusToString(GLenum status) { + switch (status) { + case GL_FRAMEBUFFER_COMPLETE: + return "GL_FRAMEBUFFER_COMPLETE"; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; +#if GL_ES_VERSION_2_0 + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + return "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS"; +#endif + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; + case GL_FRAMEBUFFER_UNSUPPORTED: + return "GL_FRAMEBUFFER_UNSUPPORTED"; + case GL_INVALID_ENUM: + return "GL_INVALID_ENUM"; + } + + return "Unknown FBO Error Status"; +} + +static const char* AttachmentTypeString(GLint type) { + switch (type) { + case GL_RENDERBUFFER: + return "GL_RENDERBUFFER"; + case GL_TEXTURE: + return "GL_TEXTURE"; + case GL_NONE: + return "GL_NONE"; + } + + return "Unknown Type"; +} + +static std::string DescribeFramebufferAttachment(const ProcTableGLES& gl, + GLenum attachment) { + GLint type = GL_NONE; + gl.GetFramebufferAttachmentParameteriv( + GL_FRAMEBUFFER, // target + attachment, // attachment + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // parameter name + &type // parameter + ); + + if (type != GL_NONE) { + GLint object = GL_NONE; + gl.GetFramebufferAttachmentParameteriv( + GL_FRAMEBUFFER, // target + attachment, // attachment + GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // parameter name + &object // parameter + ); + std::stringstream stream; + stream << AttachmentTypeString(type) << "(" << object << ")"; + return stream.str(); + } + + return "No Attachment"; +} + +std::string ProcTableGLES::DescribeCurrentFramebuffer() const { + GLint framebuffer = GL_NONE; + GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer); + if (framebuffer == GL_NONE) { + return "The default framebuffer (FBO0) was bound."; + } + if (IsFramebuffer(framebuffer) == GL_FALSE) { + return SPrintF("The framebuffer binding (%d) was not a valid framebuffer.", + framebuffer); + } + + GLenum status = CheckFramebufferStatus(GL_FRAMEBUFFER); + std::stringstream stream; + stream << "FBO " + << ((framebuffer == GL_NONE) ? "(Default)" + : std::to_string(framebuffer)) + << ": " << FramebufferStatusToString(status) << std::endl; + if (IsCurrentFramebufferComplete()) { + stream << "Framebuffer is complete." << std::endl; + } else { + stream << "Framebuffer is incomplete." << std::endl; + } + stream << "Description: " << std::endl; + stream << "Color Attachment: " + << DescribeFramebufferAttachment(*this, GL_COLOR_ATTACHMENT0) + << std::endl; + stream << "Depth Attachment: " + << DescribeFramebufferAttachment(*this, GL_DEPTH_ATTACHMENT) + << std::endl; + stream << "Stencil Attachment: " + << DescribeFramebufferAttachment(*this, GL_STENCIL_ATTACHMENT) + << std::endl; + return stream.str(); +} + +bool ProcTableGLES::IsCurrentFramebufferComplete() const { + GLint framebuffer = GL_NONE; + GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer); + if (IsFramebuffer(framebuffer) == GL_FALSE) { + // The default framebuffer is always complete. + return true; + } + GLenum status = CheckFramebufferStatus(GL_FRAMEBUFFER); + return status == GL_FRAMEBUFFER_COMPLETE; +} + +static std::optional ToDebugIdentifier(DebugResourceType type) { + switch (type) { + case DebugResourceType::kTexture: + return GL_TEXTURE; + case DebugResourceType::kBuffer: + return GL_BUFFER_KHR; + case DebugResourceType::kProgram: + return GL_PROGRAM_KHR; + case DebugResourceType::kShader: + return GL_SHADER_KHR; + case DebugResourceType::kRenderBuffer: + return GL_RENDERBUFFER; + case DebugResourceType::kFrameBuffer: + return GL_FRAMEBUFFER; + case DebugResourceType::kFence: + return GL_SYNC_FENCE; + } + FML_UNREACHABLE(); +} + +static bool ResourceIsLive(const ProcTableGLES& gl, + DebugResourceType type, + GLint name) { + switch (type) { + case DebugResourceType::kTexture: + return gl.IsTexture(name); + case DebugResourceType::kBuffer: + return gl.IsBuffer(name); + case DebugResourceType::kProgram: + return gl.IsProgram(name); + case DebugResourceType::kShader: + return gl.IsShader(name); + case DebugResourceType::kRenderBuffer: + return gl.IsRenderbuffer(name); + case DebugResourceType::kFrameBuffer: + return gl.IsFramebuffer(name); + case DebugResourceType::kFence: + return true; + } + FML_UNREACHABLE(); +} + +bool ProcTableGLES::SupportsDebugLabels() const { + if (debug_label_max_length_ <= 0) { + return false; + } + if (!ObjectLabelKHR.IsAvailable()) { + return false; + } + return true; +} + +bool ProcTableGLES::SetDebugLabel(DebugResourceType type, + GLint name, + std::string_view label) const { + if (!SupportsDebugLabels()) { + return true; + } + if (!ResourceIsLive(*this, type, name)) { + return false; + } + const auto identifier = ToDebugIdentifier(type); + const auto label_length = + std::min(debug_label_max_length_ - 1, label.size()); + if (!identifier.has_value()) { + return true; + } + ObjectLabelKHR(identifier.value(), // identifier + name, // name + label_length, // length + label.data() // label + ); + return true; +} + +void ProcTableGLES::PushDebugGroup(const std::string& label) const { +#ifdef IMPELLER_DEBUG + if (debug_label_max_length_ <= 0) { + return; + } + + UniqueID id; + const auto label_length = + std::min(debug_label_max_length_ - 1, label.size()); + PushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, // source + static_cast(id.id), // id + label_length, // length + label.data() // message + ); +#endif // IMPELLER_DEBUG +} + +void ProcTableGLES::PopDebugGroup() const { +#ifdef IMPELLER_DEBUG + if (debug_label_max_length_ <= 0) { + return; + } + + PopDebugGroupKHR(); +#endif // IMPELLER_DEBUG +} + +std::string ProcTableGLES::GetProgramInfoLogString(GLuint program) const { + GLint length = 0; + GetProgramiv(program, GL_INFO_LOG_LENGTH, &length); + if (length <= 0) { + return ""; + } + + length = std::min(length, 1024); + Allocation allocation; + if (!allocation.Truncate(Bytes{length}, false)) { + return ""; + } + GetProgramInfoLog(program, // program + length, // max length + &length, // length written (excluding NULL terminator) + reinterpret_cast(allocation.GetBuffer()) // buffer + ); + if (length <= 0) { + return ""; + } + return std::string{reinterpret_cast(allocation.GetBuffer()), + static_cast(length)}; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..98871d18cb012be1d98d8bcf440f6740cb2c490f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/proc_table_gles.h @@ -0,0 +1,350 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PROC_TABLE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PROC_TABLE_GLES_H_ + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/mapping.h" +#include "impeller/renderer/backend/gles/capabilities_gles.h" +#include "impeller/renderer/backend/gles/description_gles.h" +#include "impeller/renderer/backend/gles/gles.h" + +/// Enable to allow GLES to push/pop labels for usage in GPU traces +#define IP_ENABLE_GLES_LABELING false + +namespace impeller { + +const char* GLErrorToString(GLenum value); +bool GLErrorIsFatal(GLenum value); + +struct AutoErrorCheck { + const PFNGLGETERRORPROC error_fn; + + // TODO(135922) Change to string_view. + const char* name; + + AutoErrorCheck(PFNGLGETERRORPROC error, const char* name) + : error_fn(error), name(name) {} + + ~AutoErrorCheck() { + if (error_fn) { + auto error = error_fn(); + if (error == GL_NO_ERROR) { + return; + } + if (GLErrorIsFatal(error)) { + FML_LOG(FATAL) << "Fatal GL Error " << GLErrorToString(error) << "(" + << error << ")" << " encountered on call to " << name; + } else { + FML_LOG(ERROR) << "GL Error " << GLErrorToString(error) << "(" << error + << ")" << " encountered on call to " << name; + } + } + } +}; + +template +void BuildGLArgumentsStream(std::stringstream& stream, Type arg) { + stream << arg; +} + +constexpr void BuildGLArgumentsStream(std::stringstream& stream) {} + +template +void BuildGLArgumentsStream(std::stringstream& stream, + Type arg, + Rest... other_args) { + BuildGLArgumentsStream(stream, arg); + stream << ", "; + BuildGLArgumentsStream(stream, other_args...); +} + +template +[[nodiscard]] std::string BuildGLArguments(Type... args) { + std::stringstream stream; + stream << "("; + BuildGLArgumentsStream(stream, args...); + stream << ")"; + return stream.str(); +} + +template +struct GLProc { + using GLFunctionType = T; + + //---------------------------------------------------------------------------- + /// The name of the GL function. + /// + // TODO(135922) Change to string_view. + const char* name = nullptr; + + //---------------------------------------------------------------------------- + /// The pointer to the GL function. + /// + GLFunctionType* function = nullptr; + + //---------------------------------------------------------------------------- + /// An optional error function. If present, all calls will be followed by an + /// error check. + /// + PFNGLGETERRORPROC error_fn = nullptr; + + //---------------------------------------------------------------------------- + /// Whether the OpenGL call and its arguments should be logged. + /// + /// Only works in IMPELLER_DEBUG and for environments where traditional + /// tracing is hard. Expect log spam and only use during development. + /// + bool log_calls = false; + + //---------------------------------------------------------------------------- + /// @brief Call the GL function with the appropriate parameters. Lookup + /// the documentation for the GL function being called to + /// understand the arguments and return types. The arguments + /// types must match and will be type checked. + /// + template + auto operator()(Args&&... args) const { +#if defined(IMPELLER_DEBUG) && !defined(NDEBUG) + AutoErrorCheck error(error_fn, name); + // We check for the existence of extensions, and reset the function pointer + // but it's still called unconditionally below, and will segfault. This + // validation log will at least give us a hint as to what's going on. + FML_CHECK(IsAvailable()) << "GL function " << name << " is not available. " + << "This is likely due to a missing extension."; + if (log_calls) { + FML_LOG(IMPORTANT) << name + << BuildGLArguments(std::forward(args)...); + } +#endif // defined(IMPELLER_DEBUG) && !defined(NDEBUG) + return function(std::forward(args)...); + } + + constexpr bool IsAvailable() const { return function != nullptr; } + + void Reset() { + function = nullptr; + error_fn = nullptr; + } +}; + +#define FOR_EACH_IMPELLER_PROC(PROC) \ + PROC(ActiveTexture); \ + PROC(AttachShader); \ + PROC(BindAttribLocation); \ + PROC(BindBuffer); \ + PROC(BindFramebuffer); \ + PROC(BindRenderbuffer); \ + PROC(BindTexture); \ + PROC(BindVertexArray); \ + PROC(BlendEquationSeparate); \ + PROC(BlendFuncSeparate); \ + PROC(BufferData); \ + PROC(BufferSubData); \ + PROC(CheckFramebufferStatus); \ + PROC(Clear); \ + PROC(ClearColor); \ + PROC(ClearStencil); \ + PROC(ColorMask); \ + PROC(CompileShader); \ + PROC(CreateProgram); \ + PROC(CreateShader); \ + PROC(CullFace); \ + PROC(DeleteBuffers); \ + PROC(DeleteFramebuffers); \ + PROC(DeleteProgram); \ + PROC(DeleteRenderbuffers); \ + PROC(DeleteShader); \ + PROC(DeleteTextures); \ + PROC(DeleteVertexArrays); \ + PROC(DepthFunc); \ + PROC(DepthMask); \ + PROC(DetachShader); \ + PROC(Disable); \ + PROC(DisableVertexAttribArray); \ + PROC(DrawArrays); \ + PROC(DrawElements); \ + PROC(Enable); \ + PROC(EnableVertexAttribArray); \ + PROC(Finish); \ + PROC(Flush); \ + PROC(FramebufferRenderbuffer); \ + PROC(FramebufferTexture2D); \ + PROC(FrontFace); \ + PROC(GenBuffers); \ + PROC(GenerateMipmap); \ + PROC(GenFramebuffers); \ + PROC(GenRenderbuffers); \ + PROC(GenTextures); \ + PROC(GenVertexArrays); \ + PROC(GetActiveUniform); \ + PROC(GetBooleanv); \ + PROC(GetFloatv); \ + PROC(GetFramebufferAttachmentParameteriv); \ + PROC(GetIntegerv); \ + PROC(GetProgramInfoLog); \ + PROC(GetProgramiv); \ + PROC(GetShaderInfoLog); \ + PROC(GetShaderiv); \ + PROC(GetString); \ + PROC(GetStringi); \ + PROC(GetUniformLocation); \ + PROC(IsBuffer); \ + PROC(IsFramebuffer); \ + PROC(IsProgram); \ + PROC(IsRenderbuffer); \ + PROC(IsShader); \ + PROC(IsTexture); \ + PROC(LinkProgram); \ + PROC(PixelStorei); \ + PROC(RenderbufferStorage); \ + PROC(Scissor); \ + PROC(ShaderBinary); \ + PROC(ShaderSource); \ + PROC(StencilFuncSeparate); \ + PROC(StencilMaskSeparate); \ + PROC(StencilOpSeparate); \ + PROC(TexImage2D); \ + PROC(TexSubImage2D); \ + PROC(TexParameteri); \ + PROC(TexParameterfv); \ + PROC(Uniform1fv); \ + PROC(Uniform1i); \ + PROC(Uniform2fv); \ + PROC(Uniform3fv); \ + PROC(Uniform4fv); \ + PROC(UniformMatrix4fv); \ + PROC(UseProgram); \ + PROC(VertexAttribPointer); \ + PROC(Viewport); \ + PROC(GetShaderSource); \ + PROC(ReadPixels); + +// Calls specific to OpenGLES. +void(glClearDepthf)(GLfloat depth); +void(glDepthRangef)(GLfloat n, GLfloat f); + +#define FOR_EACH_IMPELLER_ES_ONLY_PROC(PROC) \ + PROC(ClearDepthf); \ + PROC(DepthRangef); + +// Calls specific to desktop GL. +void(glClearDepth)(GLdouble depth); +void(glDepthRange)(GLdouble n, GLdouble f); + +#define FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(PROC) \ + PROC(ClearDepth); \ + PROC(DepthRange); + +#define FOR_EACH_IMPELLER_GLES3_PROC(PROC) \ + PROC(FenceSync); \ + PROC(DeleteSync); \ + PROC(GetActiveUniformBlockiv); \ + PROC(GetActiveUniformBlockName); \ + PROC(GetUniformBlockIndex); \ + PROC(UniformBlockBinding); \ + PROC(BindBufferRange); \ + PROC(WaitSync); \ + PROC(RenderbufferStorageMultisample) \ + PROC(BlitFramebuffer); + +#define FOR_EACH_IMPELLER_EXT_PROC(PROC) \ + PROC(DebugMessageControlKHR); \ + PROC(DiscardFramebufferEXT); \ + PROC(FramebufferTexture2DMultisampleEXT); \ + PROC(PushDebugGroupKHR); \ + PROC(PopDebugGroupKHR); \ + PROC(ObjectLabelKHR); \ + PROC(RenderbufferStorageMultisampleEXT); \ + PROC(GenQueriesEXT); \ + PROC(DeleteQueriesEXT); \ + PROC(GetQueryObjectui64vEXT); \ + PROC(BeginQueryEXT); \ + PROC(EndQueryEXT); \ + PROC(GetQueryObjectuivEXT); \ + PROC(BlitFramebufferANGLE); + +enum class DebugResourceType { + kTexture, + kBuffer, + kProgram, + kShader, + kRenderBuffer, + kFrameBuffer, + kFence, +}; + +class ProcTableGLES { + public: + using Resolver = std::function; + explicit ProcTableGLES(Resolver resolver); + ProcTableGLES(ProcTableGLES&& other) = default; + + ~ProcTableGLES(); + +#define IMPELLER_PROC(name) \ + GLProc name = {"gl" #name, nullptr}; + + FOR_EACH_IMPELLER_PROC(IMPELLER_PROC); + FOR_EACH_IMPELLER_ES_ONLY_PROC(IMPELLER_PROC); + FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(IMPELLER_PROC); + FOR_EACH_IMPELLER_GLES3_PROC(IMPELLER_PROC); + FOR_EACH_IMPELLER_EXT_PROC(IMPELLER_PROC); + +#undef IMPELLER_PROC + + bool IsValid() const; + + /// @brief Set the source for the attached [shader]. + /// + /// Optionally, [defines] may contain a string value that will be + /// append to the shader source after the version marker. This can be used to + /// support static specialization. For example, setting "#define Foo 1". + void ShaderSourceMapping(GLuint shader, + const fml::Mapping& mapping, + const std::vector& defines = {}) const; + + const DescriptionGLES* GetDescription() const; + + const std::shared_ptr& GetCapabilities() const; + + std::string DescribeCurrentFramebuffer() const; + + std::string GetProgramInfoLogString(GLuint program) const; + + bool IsCurrentFramebufferComplete() const; + + bool SupportsDebugLabels() const; + + bool SetDebugLabel(DebugResourceType type, + GLint name, + std::string_view label) const; + + void PushDebugGroup(const std::string& string) const; + + void PopDebugGroup() const; + + // Visible For testing. + std::optional ComputeShaderWithDefines( + const fml::Mapping& mapping, + const std::vector& defines) const; + + private: + bool is_valid_ = false; + std::unique_ptr description_; + std::shared_ptr capabilities_; + GLint debug_label_max_length_ = 0; + + ProcTableGLES(const ProcTableGLES&) = delete; + + ProcTableGLES& operator=(const ProcTableGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_PROC_TABLE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..2cb47560a74ef035ac69511c59e41e52de7ebf6e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.cc @@ -0,0 +1,428 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/reactor_gles.h" + +#include + +#include "flutter/fml/trace_event.h" +#include "fml/closure.h" +#include "fml/logging.h" +#include "impeller/base/validation.h" + +namespace impeller { + +// static +std::optional ReactorGLES::CreateGLHandle( + const ProcTableGLES& gl, + HandleType type) { + GLStorage handle = GLStorage{.handle = GL_NONE}; + switch (type) { + case HandleType::kUnknown: + return std::nullopt; + case HandleType::kTexture: + gl.GenTextures(1u, &handle.handle); + return handle; + case HandleType::kBuffer: + gl.GenBuffers(1u, &handle.handle); + return handle; + case HandleType::kProgram: + return GLStorage{.handle = gl.CreateProgram()}; + case HandleType::kRenderBuffer: + gl.GenRenderbuffers(1u, &handle.handle); + return handle; + case HandleType::kFrameBuffer: + gl.GenFramebuffers(1u, &handle.handle); + return handle; + case HandleType::kFence: + return GLStorage{.sync = gl.FenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0)}; + } + return std::nullopt; +} + +// static +bool ReactorGLES::CollectGLHandle(const ProcTableGLES& gl, + HandleType type, + ReactorGLES::GLStorage handle) { + switch (type) { + case HandleType::kUnknown: + return false; + case HandleType::kTexture: + gl.DeleteTextures(1u, &handle.handle); + return true; + case HandleType::kBuffer: + gl.DeleteBuffers(1u, &handle.handle); + return true; + case HandleType::kProgram: + gl.DeleteProgram(handle.handle); + return true; + case HandleType::kRenderBuffer: + gl.DeleteRenderbuffers(1u, &handle.handle); + return true; + case HandleType::kFrameBuffer: + gl.DeleteFramebuffers(1u, &handle.handle); + return true; + case HandleType::kFence: + gl.DeleteSync(handle.sync); + break; + } + return false; +} + +ReactorGLES::ReactorGLES(std::unique_ptr gl) + : proc_table_(std::move(gl)) { + if (!proc_table_ || !proc_table_->IsValid()) { + VALIDATION_LOG << "Proc table was invalid."; + return; + } + can_set_debug_labels_ = proc_table_->GetDescription()->HasDebugExtension(); + is_valid_ = true; +} + +ReactorGLES::~ReactorGLES() { + if (CanReactOnCurrentThread()) { + for (auto& handle : handles_) { + if (handle.second.name.has_value()) { + CollectGLHandle(*proc_table_, handle.first.GetType(), + handle.second.name.value()); + } + } + proc_table_->Flush(); + } +} + +bool ReactorGLES::IsValid() const { + return is_valid_; +} + +bool ReactorGLES::CanSetDebugLabels() const { + return can_set_debug_labels_; +} + +ReactorGLES::WorkerID ReactorGLES::AddWorker(std::weak_ptr worker) { + Lock lock(workers_mutex_); + auto id = WorkerID{}; + workers_[id] = std::move(worker); + return id; +} + +bool ReactorGLES::RemoveWorker(WorkerID worker) { + Lock lock(workers_mutex_); + return workers_.erase(worker) == 1; +} + +bool ReactorGLES::HasPendingOperations() const { + auto thread_id = std::this_thread::get_id(); + Lock ops_lock(ops_mutex_); + auto it = ops_.find(thread_id); + return it != ops_.end() ? !it->second.empty() : false; +} + +const ProcTableGLES& ReactorGLES::GetProcTable() const { + FML_DCHECK(IsValid()); + return *proc_table_; +} + +std::optional ReactorGLES::GetHandle( + const HandleGLES& handle) const { + if (handle.untracked_id_.has_value()) { + return ReactorGLES::GLStorage{.integer = handle.untracked_id_.value()}; + } + + ReaderLock handles_lock(handles_mutex_); + if (auto found = handles_.find(handle); found != handles_.end()) { + if (found->second.pending_collection) { + VALIDATION_LOG + << "Attempted to acquire a handle that was pending collection."; + return std::nullopt; + } + std::optional name = found->second.name; + if (!name.has_value()) { + VALIDATION_LOG << "Attempt to acquire a handle outside of an operation."; + return std::nullopt; + } + return name; + } + VALIDATION_LOG << "Attempted to acquire an invalid GL handle."; + return std::nullopt; +} + +std::optional ReactorGLES::GetGLHandle(const HandleGLES& handle) const { + if (handle.GetType() == HandleType::kFence) { + return std::nullopt; + } + std::optional gl_handle = GetHandle(handle); + if (gl_handle.has_value()) { + return gl_handle->handle; + } + return std::nullopt; +} + +std::optional ReactorGLES::GetGLFence(const HandleGLES& handle) const { + if (handle.GetType() != HandleType::kFence) { + return std::nullopt; + } + std::optional gl_handle = GetHandle(handle); + if (gl_handle.has_value()) { + return gl_handle->sync; + } + return std::nullopt; +} + +bool ReactorGLES::AddOperation(Operation operation, bool defer) { + if (!operation) { + return false; + } + auto thread_id = std::this_thread::get_id(); + { + Lock ops_lock(ops_mutex_); + ops_[thread_id].emplace_back(std::move(operation)); + } + // Attempt a reaction if able but it is not an error if this isn't possible. + if (!defer) { + [[maybe_unused]] auto result = React(); + } + return true; +} + +bool ReactorGLES::RegisterCleanupCallback(const HandleGLES& handle, + const fml::closure& callback) { + if (handle.IsDead()) { + return false; + } + FML_DCHECK(!handle.untracked_id_.has_value()); + WriterLock handles_lock(handles_mutex_); + if (auto found = handles_.find(handle); found != handles_.end()) { + found->second.callback = fml::ScopedCleanupClosure(callback); + return true; + } + return false; +} + +HandleGLES ReactorGLES::CreateUntrackedHandle(HandleType type) const { + FML_DCHECK(CanReactOnCurrentThread()); + auto new_handle = HandleGLES::Create(type); + std::optional gl_handle = + CreateGLHandle(GetProcTable(), type); + if (gl_handle.has_value()) { + new_handle.untracked_id_ = gl_handle.value().integer; + } + return new_handle; +} + +HandleGLES ReactorGLES::CreateHandle(HandleType type, GLuint external_handle) { + if (type == HandleType::kUnknown) { + return HandleGLES::DeadHandle(); + } + auto new_handle = HandleGLES::Create(type); + if (new_handle.IsDead()) { + return HandleGLES::DeadHandle(); + } + + std::optional gl_handle; + if (external_handle != GL_NONE) { + gl_handle = ReactorGLES::GLStorage{.handle = external_handle}; + } else if (CanReactOnCurrentThread()) { + gl_handle = CreateGLHandle(GetProcTable(), type); + } + + WriterLock handles_lock(handles_mutex_); + handles_[new_handle] = LiveHandle{gl_handle}; + return new_handle; +} + +void ReactorGLES::CollectHandle(HandleGLES handle) { + if (handle.untracked_id_.has_value()) { + LiveHandle live_handle(GLStorage{.integer = handle.untracked_id_.value()}); + live_handle.pending_collection = true; + WriterLock handles_lock(handles_mutex_); + handles_[handle] = std::move(live_handle); + } else { + WriterLock handles_lock(handles_mutex_); + if (auto found = handles_.find(handle); found != handles_.end()) { + if (!found->second.pending_collection) { + handles_to_collect_count_ += 1; + } + found->second.pending_collection = true; + } + } +} + +bool ReactorGLES::React() { + if (!CanReactOnCurrentThread()) { + return false; + } + TRACE_EVENT0("impeller", "ReactorGLES::React"); + while (HasPendingOperations()) { + if (!ReactOnce()) { + return false; + } + } + return true; +} + +static DebugResourceType ToDebugResourceType(HandleType type) { + switch (type) { + case HandleType::kUnknown: + FML_UNREACHABLE(); + case HandleType::kTexture: + return DebugResourceType::kTexture; + case HandleType::kBuffer: + return DebugResourceType::kBuffer; + case HandleType::kProgram: + return DebugResourceType::kProgram; + case HandleType::kRenderBuffer: + return DebugResourceType::kRenderBuffer; + case HandleType::kFrameBuffer: + return DebugResourceType::kFrameBuffer; + case HandleType::kFence: + return DebugResourceType::kFence; + } + FML_UNREACHABLE(); +} + +bool ReactorGLES::ReactOnce() { + if (!IsValid()) { + return false; + } + TRACE_EVENT0("impeller", __FUNCTION__); + return ConsolidateHandles() && FlushOps(); +} + +bool ReactorGLES::ConsolidateHandles() { + TRACE_EVENT0("impeller", __FUNCTION__); + const auto& gl = GetProcTable(); + std::vector>> + handles_to_delete; + std::vector> + handles_to_name; + { + WriterLock handles_lock(handles_mutex_); + handles_to_delete.reserve(handles_to_collect_count_); + handles_to_collect_count_ = 0; + for (auto& handle : handles_) { + // Collect dead handles. + if (handle.second.pending_collection) { + handles_to_delete.emplace_back( + std::make_tuple(handle.first, handle.second.name)); + continue; + } + // Create live handles. + if (!handle.second.name.has_value()) { + auto gl_handle = CreateGLHandle(gl, handle.first.GetType()); + if (!gl_handle) { + VALIDATION_LOG << "Could not create GL handle."; + return false; + } + handle.second.name = gl_handle; + } + // Set pending debug labels. + if (handle.second.pending_debug_label.has_value() && + handle.first.GetType() != HandleType::kFence) { + handles_to_name.emplace_back(std::make_tuple( + ToDebugResourceType(handle.first.GetType()), + handle.second.name.value().handle, + std::move(handle.second.pending_debug_label.value()))); + handle.second.pending_debug_label = std::nullopt; + } + } + for (const auto& handle_to_delete : handles_to_delete) { + handles_.erase(std::get<0>(handle_to_delete)); + } + } + + for (const auto& handle : handles_to_name) { + gl.SetDebugLabel(std::get<0>(handle), std::get<1>(handle), + std::get<2>(handle)); + } + for (const auto& handle : handles_to_delete) { + const std::optional& storage = std::get<1>(handle); + // This could be false if the handle was created and collected without + // use. We still need to get rid of map entry. + if (storage.has_value()) { + CollectGLHandle(gl, std::get<0>(handle).GetType(), storage.value()); + } + } + + return true; +} + +bool ReactorGLES::FlushOps() { + TRACE_EVENT0("impeller", __FUNCTION__); + +#ifdef IMPELLER_DEBUG + // glDebugMessageControl sometimes must be called before glPushDebugGroup: + // https://github.com/flutter/flutter/issues/135715#issuecomment-1740153506 + SetupDebugGroups(); +#endif + + // Do NOT hold the ops or handles locks while performing operations in case + // the ops enqueue more ops. + decltype(ops_)::mapped_type ops; + auto thread_id = std::this_thread::get_id(); + { + Lock ops_lock(ops_mutex_); + std::swap(ops_[thread_id], ops); + } + for (const auto& op : ops) { + TRACE_EVENT0("impeller", "ReactorGLES::Operation"); + op(*this); + } + return true; +} + +void ReactorGLES::SetupDebugGroups() { + // Setup of a default active debug group: Filter everything in. + if (can_set_debug_labels_) { + proc_table_->DebugMessageControlKHR(GL_DONT_CARE, // source + GL_DONT_CARE, // type + GL_DONT_CARE, // severity + 0, // count + nullptr, // ids + GL_TRUE); // enabled + } +} + +void ReactorGLES::SetDebugLabel(const HandleGLES& handle, + std::string_view label) { + FML_DCHECK(handle.GetType() != HandleType::kFence); + if (!can_set_debug_labels_) { + return; + } + if (handle.IsDead()) { + return; + } + if (handle.untracked_id_.has_value()) { + FML_DCHECK(CanReactOnCurrentThread()); + const auto& gl = GetProcTable(); + gl.SetDebugLabel(ToDebugResourceType(handle.GetType()), + handle.untracked_id_.value(), label); + } else { + WriterLock handles_lock(handles_mutex_); + if (auto found = handles_.find(handle); found != handles_.end()) { + found->second.pending_debug_label = label; + } + } +} + +bool ReactorGLES::CanReactOnCurrentThread() const { + std::vector dead_workers; + Lock lock(workers_mutex_); + for (const auto& worker : workers_) { + auto worker_ptr = worker.second.lock(); + if (!worker_ptr) { + dead_workers.push_back(worker.first); + continue; + } + if (worker_ptr->CanReactorReactOnCurrentThreadNow(*this)) { + return true; + } + } + for (const auto& worker_id : dead_workers) { + workers_.erase(worker_id); + } + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..b3eff12bbf7e3ee412bdc764e9c2f4c9ebf02bcc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/reactor_gles.h @@ -0,0 +1,333 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_ + +#include +#include +#include + +#include "flutter/third_party/abseil-cpp/absl/container/flat_hash_map.h" +#include "fml/closure.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief The reactor attempts to make thread-safe usage of OpenGL ES +/// easier to reason about. +/// +/// In the other Impeller backends (like Metal and Vulkan), +/// resources can be created, used, and deleted on any thread with +/// relatively few restrictions. However, OpenGL resources can only +/// be created, used, and deleted on a thread on which an OpenGL +/// context (or one in the same sharegroup) is current. +/// +/// There aren't too many OpenGL contexts to go around and making +/// the caller reason about the timing and threading requirement +/// only when the OpenGL backend is in use is tedious. To work +/// around this tedium, there is an abstraction between the +/// resources and their handles in OpenGL. The reactor is this +/// abstraction. +/// +/// The reactor is thread-safe and can created, used, and collected +/// on any thread. +/// +/// Reactor handles `HandleGLES` can be created, used, and collected +/// on any thread. These handles can be to textures, buffers, etc.. +/// +/// Operations added to the reactor are guaranteed to run on a +/// worker within a finite amount of time unless the reactor itself +/// is torn down or there are no workers. These operations may run +/// on the calling thread immediately if a worker is active on the +/// current thread and can perform reactions. The operations are +/// guaranteed to run with an OpenGL context current and all reactor +/// handles having live OpenGL handle counterparts. +/// +/// Creating a handle in the reactor doesn't mean an OpenGL handle +/// is created immediately. OpenGL handles become live before the +/// next reaction. Similarly, dropping the last reference to a +/// reactor handle means that the OpenGL handle will be deleted at +/// some point in the near future. +/// +class ReactorGLES { + public: + using WorkerID = UniqueID; + + //---------------------------------------------------------------------------- + /// @brief A delegate implemented by a thread on which an OpenGL context + /// is current. There may be multiple workers for the reactor to + /// perform reactions on. In that case, it is the workers + /// responsibility to ensure that all of them use either the same + /// OpenGL context or multiple OpenGL contexts in the same + /// sharegroup. + /// + class Worker { + public: + virtual ~Worker() = default; + + //-------------------------------------------------------------------------- + /// @brief Determines the ability of the worker to service a reaction + /// on the current thread. The OpenGL context must be current on + /// the thread if the worker says it is able to service a + /// reaction. + /// + /// @param[in] reactor The reactor + /// + /// @return If the worker is able to service a reaction. The reactor + /// assumes the context is already current if true. + /// + virtual bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const = 0; + }; + + //---------------------------------------------------------------------------- + /// @brief Create a new reactor. There are expensive and only one per + /// application instance is necessary. + /// + /// @param[in] gl The proc table for GL access. This is necessary for the + /// reactor to be able to create and collect OpenGL handles. + /// + explicit ReactorGLES(std::unique_ptr gl); + + //---------------------------------------------------------------------------- + /// @brief Destroy a reactor. + /// + ~ReactorGLES(); + + //---------------------------------------------------------------------------- + /// @brief If this is a valid reactor. Invalid reactors must be discarded + /// immediately. + /// + /// @return If this reactor is valid. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Adds a worker to the reactor. Each new worker must ensure that + /// the context it manages is the same as the other workers in the + /// reactor or in the same sharegroup. + /// + /// @param[in] worker The worker + /// + /// @return The worker identifier. This identifier can be used to remove + /// the worker from the reactor later. + /// + WorkerID AddWorker(std::weak_ptr worker); + + //---------------------------------------------------------------------------- + /// @brief Remove a previously added worker from the reactor. If the + /// reactor has no workers, pending added operations will never + /// run. + /// + /// @param[in] id The worker identifier previously returned by `AddWorker`. + /// + /// @return If a worker with the given identifer was successfully removed + /// from the reactor. + /// + bool RemoveWorker(WorkerID id); + + //---------------------------------------------------------------------------- + /// @brief Get the OpenGL proc. table the reactor uses to manage handles. + /// + /// @return The proc table. + /// + const ProcTableGLES& GetProcTable() const; + + //---------------------------------------------------------------------------- + /// @brief Returns the OpenGL handle for a reactor handle if one is + /// available. This is typically only safe to call within a + /// reaction. That is, within a `ReactorGLES::Operation`. + /// + /// Asking for the OpenGL handle before the reactor has a chance + /// to reactor will return `std::nullopt`. + /// + /// This can be called on any thread but is typically useless + /// outside of a reaction since the handle is useless outside of a + /// reactor operation. + /// + /// @param[in] handle The reactor handle. + /// + /// @return The OpenGL handle if the reactor has had a chance to react. + /// `std::nullopt` otherwise. + /// + std::optional GetGLHandle(const HandleGLES& handle) const; + + std::optional GetGLFence(const HandleGLES& handle) const; + + //---------------------------------------------------------------------------- + /// @brief Create a reactor handle. + /// + /// This can be called on any thread. Even one that doesn't have + /// an OpenGL context. + /// + /// @param[in] type The type of handle to create. + /// @param[in] external_handle An already created GL handle if one exists. + /// + /// @return The reactor handle. + /// + HandleGLES CreateHandle(HandleType type, GLuint external_handle = GL_NONE); + + /// @brief Create a handle that is not managed by `ReactorGLES`. + /// @details This behaves just like `CreateHandle` but it doesn't add the + /// handle to ReactorGLES::handles_ and the creation is executed + /// synchronously, so it must be called from a proper thread. The benefit of + /// this is that it avoid synchronization and hash table lookups when + /// creating/accessing the handle. + /// @param type The type of handle to create. + /// @return The reactor handle. + HandleGLES CreateUntrackedHandle(HandleType type) const; + + //---------------------------------------------------------------------------- + /// @brief Collect a reactor handle. + /// + /// This can be called on any thread. Even one that doesn't have + /// an OpenGL context. + /// + /// @param[in] handle The reactor handle handle + /// + void CollectHandle(HandleGLES handle); + + //---------------------------------------------------------------------------- + /// @brief Set the debug label on a reactor handle. + /// + /// This call ensures that the OpenGL debug label is propagated to + /// even the OpenGL handle hasn't been created at the time the + /// caller sets the label. + /// + /// @param[in] handle The handle + /// @param[in] label The label + /// + void SetDebugLabel(const HandleGLES& handle, std::string_view label); + + //---------------------------------------------------------------------------- + /// @brief Whether the device is capable of writing debug labels. + /// + /// This function is useful for short circuiting expensive debug + /// labeling. + bool CanSetDebugLabels() const; + + using Operation = std::function; + + //---------------------------------------------------------------------------- + /// @brief Adds an operation that the reactor runs on a worker that + /// ensures that an OpenGL context is current. + /// + /// This operation is not guaranteed to run immediately. It will + /// complete in a finite amount of time on any thread as long as + /// there is a reactor worker and the reactor itself is not being + /// torn down. + /// + /// @param[in] operation The operation + /// @param[in] defer If false, the reactor attempts to React after + /// adding this operation. + /// + /// @return If the operation was successfully queued for completion. + /// + [[nodiscard]] bool AddOperation(Operation operation, bool defer = false); + + //---------------------------------------------------------------------------- + /// @brief Register a cleanup callback that will be invokved with the + /// provided user data when the handle is destroyed. + /// + /// This operation is not guaranteed to run immediately. It will + /// complete in a finite amount of time on any thread as long as + /// there is a reactor worker and the reactor itself is not being + /// torn down. + /// + /// @param[in] handle The handle to attach the cleanup to. + /// @param[in] callback The cleanup callback to execute. + /// + /// @return If the operation was successfully queued for completion. + /// + bool RegisterCleanupCallback(const HandleGLES& handle, + const fml::closure& callback); + + //---------------------------------------------------------------------------- + /// @brief Perform a reaction on the current thread if able. + /// + /// It is safe to call this simultaneously from multiple threads + /// at the same time. + /// + /// @return If a reaction was performed on the calling thread. + /// + [[nodiscard]] bool React(); + + private: + /// @brief Storage for either a GL handle or sync fence. + struct GLStorage { + union { + GLuint handle; + GLsync sync; + uint64_t integer; + }; + }; + static_assert(sizeof(GLStorage) == sizeof(uint64_t)); + + struct LiveHandle { + std::optional name; + std::optional pending_debug_label; + bool pending_collection = false; + fml::ScopedCleanupClosure callback = {}; + + LiveHandle() = default; + + explicit LiveHandle(std::optional p_name) : name(p_name) {} + + constexpr bool IsLive() const { return name.has_value(); } + }; + + std::unique_ptr proc_table_; + + mutable Mutex ops_mutex_; + std::map> ops_ IPLR_GUARDED_BY( + ops_mutex_); + + using LiveHandles = absl::flat_hash_map; + mutable RWMutex handles_mutex_; + LiveHandles handles_ IPLR_GUARDED_BY(handles_mutex_); + int32_t handles_to_collect_count_ IPLR_GUARDED_BY(handles_mutex_) = 0; + + mutable Mutex workers_mutex_; + mutable std::map> workers_ IPLR_GUARDED_BY( + workers_mutex_); + + bool can_set_debug_labels_ = false; + bool is_valid_ = false; + + bool ReactOnce(); + + bool HasPendingOperations() const; + + bool CanReactOnCurrentThread() const; + + bool ConsolidateHandles(); + + bool FlushOps(); + + void SetupDebugGroups(); + + std::optional GetHandle(const HandleGLES& handle) const; + + static std::optional CreateGLHandle(const ProcTableGLES& gl, + HandleType type); + + static bool CollectGLHandle(const ProcTableGLES& gl, + HandleType type, + GLStorage handle); + + ReactorGLES(const ReactorGLES&) = delete; + + ReactorGLES& operator=(const ReactorGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_REACTOR_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c5aa202f2d0dae7f52c414f26e451218df2abf0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.cc @@ -0,0 +1,692 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/render_pass_gles.h" + +#include + +#include "flutter/fml/trace_event.h" +#include "fml/closure.h" +#include "fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/gles/buffer_bindings_gles.h" +#include "impeller/renderer/backend/gles/context_gles.h" +#include "impeller/renderer/backend/gles/device_buffer_gles.h" +#include "impeller/renderer/backend/gles/formats_gles.h" +#include "impeller/renderer/backend/gles/gpu_tracer_gles.h" +#include "impeller/renderer/backend/gles/pipeline_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" +#include "impeller/renderer/command.h" + +namespace impeller { + +RenderPassGLES::RenderPassGLES(std::shared_ptr context, + const RenderTarget& target, + std::shared_ptr reactor) + : RenderPass(std::move(context), target), + reactor_(std::move(reactor)), + is_valid_(reactor_ && reactor_->IsValid()) {} + +// |RenderPass| +RenderPassGLES::~RenderPassGLES() = default; + +// |RenderPass| +bool RenderPassGLES::IsValid() const { + return is_valid_; +} + +// |RenderPass| +void RenderPassGLES::OnSetLabel(std::string_view label) { + label_ = label; +} + +void ConfigureBlending(const ProcTableGLES& gl, + const ColorAttachmentDescriptor* color) { + if (color->blending_enabled) { + gl.Enable(GL_BLEND); + gl.BlendFuncSeparate( + ToBlendFactor(color->src_color_blend_factor), // src color + ToBlendFactor(color->dst_color_blend_factor), // dst color + ToBlendFactor(color->src_alpha_blend_factor), // src alpha + ToBlendFactor(color->dst_alpha_blend_factor) // dst alpha + ); + gl.BlendEquationSeparate( + ToBlendOperation(color->color_blend_op), // mode color + ToBlendOperation(color->alpha_blend_op) // mode alpha + ); + } else { + gl.Disable(GL_BLEND); + } + + { + const auto is_set = [](ColorWriteMask mask, + ColorWriteMask check) -> GLboolean { + return (mask & check) ? GL_TRUE : GL_FALSE; + }; + + gl.ColorMask( + is_set(color->write_mask, ColorWriteMaskBits::kRed), // red + is_set(color->write_mask, ColorWriteMaskBits::kGreen), // green + is_set(color->write_mask, ColorWriteMaskBits::kBlue), // blue + is_set(color->write_mask, ColorWriteMaskBits::kAlpha) // alpha + ); + } +} + +void ConfigureStencil(GLenum face, + const ProcTableGLES& gl, + const StencilAttachmentDescriptor& stencil, + uint32_t stencil_reference) { + gl.StencilOpSeparate( + face, // face + ToStencilOp(stencil.stencil_failure), // stencil fail + ToStencilOp(stencil.depth_failure), // depth fail + ToStencilOp(stencil.depth_stencil_pass) // depth stencil pass + ); + gl.StencilFuncSeparate(face, // face + ToCompareFunction(stencil.stencil_compare), // func + stencil_reference, // ref + stencil.read_mask // mask + ); + gl.StencilMaskSeparate(face, stencil.write_mask); +} + +void ConfigureStencil(const ProcTableGLES& gl, + const PipelineDescriptor& pipeline, + uint32_t stencil_reference) { + if (!pipeline.HasStencilAttachmentDescriptors()) { + gl.Disable(GL_STENCIL_TEST); + return; + } + + gl.Enable(GL_STENCIL_TEST); + const auto& front = pipeline.GetFrontStencilAttachmentDescriptor(); + const auto& back = pipeline.GetBackStencilAttachmentDescriptor(); + + if (front.has_value() && back.has_value() && front == back) { + ConfigureStencil(GL_FRONT_AND_BACK, gl, *front, stencil_reference); + return; + } + if (front.has_value()) { + ConfigureStencil(GL_FRONT, gl, *front, stencil_reference); + } + if (back.has_value()) { + ConfigureStencil(GL_BACK, gl, *back, stencil_reference); + } +} + +//------------------------------------------------------------------------------ +/// @brief Encapsulates data that will be needed in the reactor for the +/// encoding of commands for this render pass. +/// +struct RenderPassData { + Viewport viewport; + + Color clear_color; + uint32_t clear_stencil = 0u; + Scalar clear_depth = 1.0; + + std::shared_ptr color_attachment; + std::shared_ptr resolve_attachment; + std::shared_ptr depth_attachment; + std::shared_ptr stencil_attachment; + + bool clear_color_attachment = true; + bool clear_depth_attachment = true; + bool clear_stencil_attachment = true; + + bool discard_color_attachment = true; + bool discard_depth_attachment = true; + bool discard_stencil_attachment = true; + + std::string label; +}; + +static bool BindVertexBuffer(const ProcTableGLES& gl, + BufferBindingsGLES* vertex_desc_gles, + const BufferView& vertex_buffer_view, + size_t buffer_index) { + if (!vertex_buffer_view) { + return false; + } + + const DeviceBuffer* vertex_buffer = vertex_buffer_view.GetBuffer(); + + if (!vertex_buffer) { + return false; + } + + const auto& vertex_buffer_gles = DeviceBufferGLES::Cast(*vertex_buffer); + if (!vertex_buffer_gles.BindAndUploadDataIfNecessary( + DeviceBufferGLES::BindingType::kArrayBuffer)) { + return false; + } + + //-------------------------------------------------------------------------- + /// Bind the vertex attributes associated with vertex buffer. + /// + if (!vertex_desc_gles->BindVertexAttributes( + gl, buffer_index, vertex_buffer_view.GetRange().offset)) { + return false; + } + + return true; +} + +void RenderPassGLES::ResetGLState(const ProcTableGLES& gl) { + gl.Disable(GL_SCISSOR_TEST); + gl.Disable(GL_DEPTH_TEST); + gl.Disable(GL_STENCIL_TEST); + gl.Disable(GL_CULL_FACE); + gl.Disable(GL_BLEND); + gl.Disable(GL_DITHER); + gl.ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + gl.DepthMask(GL_TRUE); + gl.StencilMaskSeparate(GL_FRONT, 0xFFFFFFFF); + gl.StencilMaskSeparate(GL_BACK, 0xFFFFFFFF); +} + +[[nodiscard]] bool EncodeCommandsInReactor( + const RenderPassData& pass_data, + const ReactorGLES& reactor, + const std::vector& commands, + const std::vector& vertex_buffers, + const std::vector& bound_textures, + const std::vector& bound_buffers, + const std::shared_ptr& tracer) { + TRACE_EVENT0("impeller", "RenderPassGLES::EncodeCommandsInReactor"); + + const auto& gl = reactor.GetProcTable(); +#ifdef IMPELLER_DEBUG + tracer->MarkFrameStart(gl); + + fml::ScopedCleanupClosure pop_pass_debug_marker( + [&gl]() { gl.PopDebugGroup(); }); + if (!pass_data.label.empty()) { + gl.PushDebugGroup(pass_data.label); + } else { + pop_pass_debug_marker.Release(); + } +#endif // IMPELLER_DEBUG + + TextureGLES& color_gles = TextureGLES::Cast(*pass_data.color_attachment); + const bool is_default_fbo = color_gles.IsWrapped(); + + std::optional fbo = 0; + if (is_default_fbo) { + if (color_gles.GetFBO().has_value()) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + gl.BindFramebuffer(GL_FRAMEBUFFER, *color_gles.GetFBO()); + } + } else { + // Create and bind an offscreen FBO. + if (!color_gles.GetCachedFBO().IsDead()) { + fbo = reactor.GetGLHandle(color_gles.GetCachedFBO()); + if (!fbo.has_value()) { + return false; + } + gl.BindFramebuffer(GL_FRAMEBUFFER, fbo.value()); + } else { + HandleGLES cached_fbo = + reactor.CreateUntrackedHandle(HandleType::kFrameBuffer); + color_gles.SetCachedFBO(cached_fbo); + fbo = reactor.GetGLHandle(cached_fbo); + if (!fbo.has_value()) { + return false; + } + gl.BindFramebuffer(GL_FRAMEBUFFER, fbo.value()); + + if (!color_gles.SetAsFramebufferAttachment( + GL_FRAMEBUFFER, TextureGLES::AttachmentType::kColor0)) { + return false; + } + + if (auto depth = TextureGLES::Cast(pass_data.depth_attachment.get())) { + if (!depth->SetAsFramebufferAttachment( + GL_FRAMEBUFFER, TextureGLES::AttachmentType::kDepth)) { + return false; + } + } + if (auto stencil = + TextureGLES::Cast(pass_data.stencil_attachment.get())) { + if (!stencil->SetAsFramebufferAttachment( + GL_FRAMEBUFFER, TextureGLES::AttachmentType::kStencil)) { + return false; + } + } + + auto status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) { + VALIDATION_LOG << "Could not create a complete framebuffer: " + << DebugToFramebufferError(status); + return false; + } + } + } + + gl.ClearColor(pass_data.clear_color.red, // red + pass_data.clear_color.green, // green + pass_data.clear_color.blue, // blue + pass_data.clear_color.alpha // alpha + ); + if (pass_data.depth_attachment) { + if (gl.DepthRangef.IsAvailable()) { + gl.ClearDepthf(pass_data.clear_depth); + } else { + gl.ClearDepth(pass_data.clear_depth); + } + } + if (pass_data.stencil_attachment) { + gl.ClearStencil(pass_data.clear_stencil); + } + + GLenum clear_bits = 0u; + if (pass_data.clear_color_attachment) { + clear_bits |= GL_COLOR_BUFFER_BIT; + } + if (pass_data.clear_depth_attachment) { + clear_bits |= GL_DEPTH_BUFFER_BIT; + } + if (pass_data.clear_stencil_attachment) { + clear_bits |= GL_STENCIL_BUFFER_BIT; + } + + RenderPassGLES::ResetGLState(gl); + + gl.Clear(clear_bits); + + // Both the viewport and scissor are specified in framebuffer coordinates. + // Impeller's framebuffer coordinate system is top left origin, but OpenGL's + // is bottom left origin, so we convert the coordinates here. + ISize target_size = pass_data.color_attachment->GetSize(); + + //-------------------------------------------------------------------------- + /// Setup the viewport. + /// + const auto& viewport = pass_data.viewport; + gl.Viewport(viewport.rect.GetX(), // x + target_size.height - viewport.rect.GetY() - + viewport.rect.GetHeight(), // y + viewport.rect.GetWidth(), // width + viewport.rect.GetHeight() // height + ); + if (pass_data.depth_attachment) { + if (gl.DepthRangef.IsAvailable()) { + gl.DepthRangef(viewport.depth_range.z_near, viewport.depth_range.z_far); + } else { + gl.DepthRange(viewport.depth_range.z_near, viewport.depth_range.z_far); + } + } + + CullMode current_cull_mode = CullMode::kNone; + WindingOrder current_winding_order = WindingOrder::kClockwise; + gl.FrontFace(GL_CW); + + for (const auto& command : commands) { +#ifdef IMPELLER_DEBUG + fml::ScopedCleanupClosure pop_cmd_debug_marker( + [&gl]() { gl.PopDebugGroup(); }); + if (!command.label.empty()) { + gl.PushDebugGroup(command.label); + } else { + pop_cmd_debug_marker.Release(); + } +#endif // IMPELLER_DEBUG + + const auto& pipeline = PipelineGLES::Cast(*command.pipeline); + + const auto* color_attachment = + pipeline.GetDescriptor().GetLegacyCompatibleColorAttachment(); + if (!color_attachment) { + VALIDATION_LOG + << "Color attachment is too complicated for a legacy renderer."; + return false; + } + + //-------------------------------------------------------------------------- + /// Configure blending. + /// + ConfigureBlending(gl, color_attachment); + + //-------------------------------------------------------------------------- + /// Setup stencil. + /// + ConfigureStencil(gl, pipeline.GetDescriptor(), command.stencil_reference); + + //-------------------------------------------------------------------------- + /// Configure depth. + /// + if (auto depth = + pipeline.GetDescriptor().GetDepthStencilAttachmentDescriptor(); + depth.has_value()) { + gl.Enable(GL_DEPTH_TEST); + gl.DepthFunc(ToCompareFunction(depth->depth_compare)); + gl.DepthMask(depth->depth_write_enabled ? GL_TRUE : GL_FALSE); + } else { + gl.Disable(GL_DEPTH_TEST); + } + + //-------------------------------------------------------------------------- + /// Setup the viewport. + /// + if (command.viewport.has_value()) { + gl.Viewport(viewport.rect.GetX(), // x + target_size.height - viewport.rect.GetY() - + viewport.rect.GetHeight(), // y + viewport.rect.GetWidth(), // width + viewport.rect.GetHeight() // height + ); + if (pass_data.depth_attachment) { + if (gl.DepthRangef.IsAvailable()) { + gl.DepthRangef(viewport.depth_range.z_near, + viewport.depth_range.z_far); + } else { + gl.DepthRange(viewport.depth_range.z_near, + viewport.depth_range.z_far); + } + } + } + + //-------------------------------------------------------------------------- + /// Setup the scissor rect. + /// + if (command.scissor.has_value()) { + const auto& scissor = command.scissor.value(); + gl.Enable(GL_SCISSOR_TEST); + gl.Scissor( + scissor.GetX(), // x + target_size.height - scissor.GetY() - scissor.GetHeight(), // y + scissor.GetWidth(), // width + scissor.GetHeight() // height + ); + } + + //-------------------------------------------------------------------------- + /// Setup culling. + /// + CullMode pipeline_cull_mode = pipeline.GetDescriptor().GetCullMode(); + if (current_cull_mode != pipeline_cull_mode) { + switch (pipeline_cull_mode) { + case CullMode::kNone: + gl.Disable(GL_CULL_FACE); + break; + case CullMode::kFrontFace: + gl.Enable(GL_CULL_FACE); + gl.CullFace(GL_FRONT); + break; + case CullMode::kBackFace: + gl.Enable(GL_CULL_FACE); + gl.CullFace(GL_BACK); + break; + } + current_cull_mode = pipeline_cull_mode; + } + + //-------------------------------------------------------------------------- + /// Setup winding order. + /// + WindingOrder pipeline_winding_order = + pipeline.GetDescriptor().GetWindingOrder(); + if (current_winding_order != pipeline_winding_order) { + switch (pipeline.GetDescriptor().GetWindingOrder()) { + case WindingOrder::kClockwise: + gl.FrontFace(GL_CW); + break; + case WindingOrder::kCounterClockwise: + gl.FrontFace(GL_CCW); + break; + } + current_winding_order = pipeline_winding_order; + } + + BufferBindingsGLES* vertex_desc_gles = pipeline.GetBufferBindings(); + + //-------------------------------------------------------------------------- + /// Bind vertex buffers. + /// + /// Note: There is no need to run `RenderPass::ValidateVertexBuffers` or + /// `RenderPass::ValidateIndexBuffer` here, as validation already runs + /// when the vertex/index buffers are set on the command. + /// + for (size_t i = 0; i < command.vertex_buffers.length; i++) { + if (!BindVertexBuffer(gl, vertex_desc_gles, + vertex_buffers[i + command.vertex_buffers.offset], + i)) { + return false; + } + } + + //-------------------------------------------------------------------------- + /// Bind the pipeline program. + /// + if (!pipeline.BindProgram()) { + return false; + } + + //-------------------------------------------------------------------------- + /// Bind uniform data. + /// + if (!vertex_desc_gles->BindUniformData( + gl, // + bound_textures, // + bound_buffers, // + /*texture_range=*/command.bound_textures, // + /*buffer_range=*/command.bound_buffers // + )) { + return false; + } + + //-------------------------------------------------------------------------- + /// Determine the primitive type. + /// + // GLES doesn't support setting the fill mode, so override the primitive + // with GL_LINE_STRIP to somewhat emulate PolygonMode::kLine. This isn't + // correct; full triangle outlines won't be drawn and disconnected + // geometry may appear connected. However this can still be useful for + // wireframe debug views. + GLenum mode = + pipeline.GetDescriptor().GetPolygonMode() == PolygonMode::kLine + ? GL_LINE_STRIP + : ToMode(pipeline.GetDescriptor().GetPrimitiveType()); + + //-------------------------------------------------------------------------- + /// Finally! Invoke the draw call. + /// + if (command.index_type == IndexType::kNone) { + gl.DrawArrays(mode, command.base_vertex, command.element_count); + } else { + // Bind the index buffer if necessary. + auto index_buffer_view = command.index_buffer; + const DeviceBuffer* index_buffer = index_buffer_view.GetBuffer(); + const auto& index_buffer_gles = DeviceBufferGLES::Cast(*index_buffer); + if (!index_buffer_gles.BindAndUploadDataIfNecessary( + DeviceBufferGLES::BindingType::kElementArrayBuffer)) { + return false; + } + gl.DrawElements(mode, // mode + command.element_count, // count + ToIndexType(command.index_type), // type + reinterpret_cast(static_cast( + index_buffer_view.GetRange().offset)) // indices + ); + } + + //-------------------------------------------------------------------------- + /// Unbind vertex attribs. + /// + if (!vertex_desc_gles->UnbindVertexAttributes(gl)) { + return false; + } + } + + if (pass_data.resolve_attachment && + !gl.GetCapabilities()->SupportsImplicitResolvingMSAA() && + !is_default_fbo) { + FML_DCHECK(pass_data.resolve_attachment != pass_data.color_attachment); + // Perform multisample resolve via blit. + // Create and bind a resolve FBO. + GLuint resolve_fbo; + gl.GenFramebuffers(1u, &resolve_fbo); + gl.BindFramebuffer(GL_FRAMEBUFFER, resolve_fbo); + + if (!TextureGLES::Cast(*pass_data.resolve_attachment) + .SetAsFramebufferAttachment( + GL_FRAMEBUFFER, TextureGLES::AttachmentType::kColor0)) { + return false; + } + + auto status = gl.CheckFramebufferStatus(GL_FRAMEBUFFER); + if (gl.CheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + VALIDATION_LOG << "Could not create a complete frambuffer: " + << DebugToFramebufferError(status); + return false; + } + + // Bind MSAA renderbuffer to read framebuffer. + gl.BindFramebuffer(GL_READ_FRAMEBUFFER, fbo.value()); + gl.BindFramebuffer(GL_DRAW_FRAMEBUFFER, resolve_fbo); + + RenderPassGLES::ResetGLState(gl); + auto size = pass_data.color_attachment->GetSize(); + + gl.BlitFramebuffer(/*srcX0=*/0, + /*srcY0=*/0, + /*srcX1=*/size.width, + /*srcY1=*/size.height, + /*dstX0=*/0, + /*dstY0=*/0, + /*dstX1=*/size.width, + /*dstY1=*/size.height, + /*mask=*/GL_COLOR_BUFFER_BIT, + /*filter=*/GL_NEAREST); + + gl.BindFramebuffer(GL_DRAW_FRAMEBUFFER, GL_NONE); + gl.BindFramebuffer(GL_READ_FRAMEBUFFER, GL_NONE); + gl.DeleteFramebuffers(1u, &resolve_fbo); + // Rebind the original FBO so that we can discard it below. + gl.BindFramebuffer(GL_FRAMEBUFFER, fbo.value()); + } + + if (gl.DiscardFramebufferEXT.IsAvailable()) { + std::array attachments; + size_t attachment_count = 0; + + // TODO(130048): discarding stencil or depth on the default fbo causes Angle + // to discard the entire render target. Until we know the reason, default to + // storing. + bool angle_safe = gl.GetCapabilities()->IsANGLE() ? !is_default_fbo : true; + + if (pass_data.discard_color_attachment) { + attachments[attachment_count++] = + (is_default_fbo ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0); + } + if (pass_data.discard_depth_attachment && angle_safe) { + attachments[attachment_count++] = + (is_default_fbo ? GL_DEPTH_EXT : GL_DEPTH_ATTACHMENT); + } + + if (pass_data.discard_stencil_attachment && angle_safe) { + attachments[attachment_count++] = + (is_default_fbo ? GL_STENCIL_EXT : GL_STENCIL_ATTACHMENT); + } + gl.DiscardFramebufferEXT(GL_FRAMEBUFFER, // target + attachment_count, // attachments to discard + attachments.data() // size + ); + } + +#ifdef IMPELLER_DEBUG + if (is_default_fbo) { + tracer->MarkFrameEnd(gl); + } +#endif // IMPELLER_DEBUG + + return true; +} + +// |RenderPass| +bool RenderPassGLES::OnEncodeCommands(const Context& context) const { + if (!IsValid()) { + return false; + } + const auto& render_target = GetRenderTarget(); + if (!render_target.HasColorAttachment(0u)) { + return false; + } + const ColorAttachment& color0 = render_target.GetColorAttachment(0); + const std::optional& depth0 = + render_target.GetDepthAttachment(); + const std::optional& stencil0 = + render_target.GetStencilAttachment(); + + auto pass_data = std::make_shared(); + pass_data->label = label_; + pass_data->viewport.rect = Rect::MakeSize(GetRenderTargetSize()); + + //---------------------------------------------------------------------------- + /// Setup color data. + /// + pass_data->color_attachment = color0.texture; + pass_data->resolve_attachment = color0.resolve_texture; + pass_data->clear_color = color0.clear_color; + pass_data->clear_color_attachment = CanClearAttachment(color0.load_action); + pass_data->discard_color_attachment = + CanDiscardAttachmentWhenDone(color0.store_action); + + // When we are using EXT_multisampled_render_to_texture, it is implicitly + // resolved when we bind the texture to the framebuffer. We don't need to + // discard the attachment when we are done. If not using + // EXT_multisampled_render_to_texture but still using MSAA we discard the + // attachment as normal. + if (color0.resolve_texture) { + pass_data->discard_color_attachment = + pass_data->discard_color_attachment && + !context.GetCapabilities()->SupportsImplicitResolvingMSAA(); + } + + //---------------------------------------------------------------------------- + /// Setup depth data. + /// + if (depth0.has_value()) { + pass_data->depth_attachment = depth0->texture; + pass_data->clear_depth = depth0->clear_depth; + pass_data->clear_depth_attachment = CanClearAttachment(depth0->load_action); + pass_data->discard_depth_attachment = + CanDiscardAttachmentWhenDone(depth0->store_action); + } + + //---------------------------------------------------------------------------- + /// Setup stencil data. + /// + if (stencil0.has_value()) { + pass_data->stencil_attachment = stencil0->texture; + pass_data->clear_stencil = stencil0->clear_stencil; + pass_data->clear_stencil_attachment = + CanClearAttachment(stencil0->load_action); + pass_data->discard_stencil_attachment = + CanDiscardAttachmentWhenDone(stencil0->store_action); + } + + return reactor_->AddOperation( + [pass_data = std::move(pass_data), render_pass = shared_from_this(), + tracer = + ContextGLES::Cast(context).GetGPUTracer()](const auto& reactor) { + auto result = EncodeCommandsInReactor( + /*pass_data=*/*pass_data, // + /*reactor=*/reactor, // + /*commands=*/render_pass->commands_, // + /*vertex_buffers=*/render_pass->vertex_buffers_, // + /*bound_textures=*/render_pass->bound_textures_, // + /*bound_buffers=*/render_pass->bound_buffers_, // + /*tracer=*/tracer // + ); + FML_CHECK(result) + << "Must be able to encode GL commands without error."; + }, + /*defer=*/true); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..1d524fdc490a131f92946e3cf71419e959d960cd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/render_pass_gles.h @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_ + +#include + +#include "flutter/impeller/renderer/backend/gles/reactor_gles.h" +#include "flutter/impeller/renderer/render_pass.h" + +namespace impeller { + +class RenderPassGLES final + : public RenderPass, + public std::enable_shared_from_this { + public: + // |RenderPass| + ~RenderPassGLES() override; + + static void ResetGLState(const ProcTableGLES& gl); + + private: + friend class CommandBufferGLES; + + std::shared_ptr reactor_; + std::string label_; + bool is_valid_ = false; + + RenderPassGLES(std::shared_ptr context, + const RenderTarget& target, + std::shared_ptr reactor); + + // |RenderPass| + bool IsValid() const override; + + // |RenderPass| + void OnSetLabel(std::string_view label) override; + + // |RenderPass| + bool OnEncodeCommands(const Context& context) const override; + + RenderPassGLES(const RenderPassGLES&) = delete; + + RenderPassGLES& operator=(const RenderPassGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_RENDER_PASS_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..574c4e82d3d8027004ff1755e898933d3b5a601c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.cc @@ -0,0 +1,121 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/sampler_gles.h" + +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/gles/formats_gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" + +namespace impeller { + +SamplerGLES::SamplerGLES(const SamplerDescriptor& desc) : Sampler(desc) {} + +SamplerGLES::~SamplerGLES() = default; + +static GLint ToParam(MinMagFilter minmag_filter) { + switch (minmag_filter) { + case MinMagFilter::kNearest: + return GL_NEAREST; + case MinMagFilter::kLinear: + return GL_LINEAR; + } + FML_UNREACHABLE(); +} + +static GLint ToParam(MinMagFilter minmag_filter, MipFilter mip_filter) { + switch (mip_filter) { + case MipFilter::kBase: + return ToParam(minmag_filter); + case MipFilter::kNearest: + switch (minmag_filter) { + case MinMagFilter::kNearest: + return GL_NEAREST_MIPMAP_NEAREST; + case MinMagFilter::kLinear: + return GL_LINEAR_MIPMAP_NEAREST; + } + case MipFilter::kLinear: + switch (minmag_filter) { + case MinMagFilter::kNearest: + return GL_NEAREST_MIPMAP_LINEAR; + case MinMagFilter::kLinear: + return GL_LINEAR_MIPMAP_LINEAR; + } + } + FML_UNREACHABLE(); +} + +static GLint ToAddressMode(SamplerAddressMode mode, + bool supports_decal_sampler_address_mode) { + switch (mode) { + case SamplerAddressMode::kClampToEdge: + return GL_CLAMP_TO_EDGE; + case SamplerAddressMode::kRepeat: + return GL_REPEAT; + case SamplerAddressMode::kMirror: + return GL_MIRRORED_REPEAT; + case SamplerAddressMode::kDecal: + if (supports_decal_sampler_address_mode) { + return IMPELLER_GL_CLAMP_TO_BORDER; + } else { + return GL_CLAMP_TO_EDGE; + } + } + FML_UNREACHABLE(); +} + +bool SamplerGLES::ConfigureBoundTexture(const TextureGLES& texture, + const ProcTableGLES& gl) const { + if (texture.NeedsMipmapGeneration()) { + VALIDATION_LOG + << "Texture mip count is > 1, but the mipmap has not been generated. " + "Texture can not be sampled safely."; + return false; + } + + auto target = ToTextureTarget(texture.GetTextureDescriptor().type); + + if (!target.has_value()) { + return false; + } + const SamplerDescriptor& desc = GetDescriptor(); + + GLint mag_filter = ToParam(desc.mag_filter); + + // If the texture doesn't have mipmaps, we can't use mip filtering. + GLint min_filter; + if (texture.GetTextureDescriptor().mip_count > 1) { + min_filter = ToParam(desc.min_filter, desc.mip_filter); + } else { + min_filter = ToParam(desc.min_filter); + } + + gl.TexParameteri(*target, GL_TEXTURE_MIN_FILTER, min_filter); + gl.TexParameteri(*target, GL_TEXTURE_MAG_FILTER, mag_filter); + + const auto supports_decal_mode = + gl.GetCapabilities()->SupportsDecalSamplerAddressMode(); + + const auto wrap_s = + ToAddressMode(desc.width_address_mode, supports_decal_mode); + const auto wrap_t = + ToAddressMode(desc.height_address_mode, supports_decal_mode); + + gl.TexParameteri(*target, GL_TEXTURE_WRAP_S, wrap_s); + gl.TexParameteri(*target, GL_TEXTURE_WRAP_T, wrap_t); + + if (wrap_s == IMPELLER_GL_CLAMP_TO_BORDER || + wrap_t == IMPELLER_GL_CLAMP_TO_BORDER) { + // Transparent black. + const GLfloat border_color[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + gl.TexParameterfv(*target, IMPELLER_GL_TEXTURE_BORDER_COLOR, border_color); + } + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..837b50dabaa82a644ba3fde1d07ba8b2d129a4b0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_gles.h @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_GLES_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/core/sampler.h" + +namespace impeller { + +class TextureGLES; +class SamplerLibraryGLES; +class ProcTableGLES; + +class SamplerGLES final : public Sampler, + public BackendCast { + public: + ~SamplerGLES(); + + bool ConfigureBoundTexture(const TextureGLES& texture, + const ProcTableGLES& gl) const; + + private: + friend class SamplerLibraryGLES; + + explicit SamplerGLES(const SamplerDescriptor&); + + SamplerGLES(const SamplerGLES&) = delete; + + SamplerGLES& operator=(const SamplerGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..64b2b0b6bb6f2e98d6f10c76678ad4872b056893 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/sampler_library_gles.h" + +#include "impeller/base/config.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/gles/sampler_gles.h" + +namespace impeller { + +SamplerLibraryGLES::SamplerLibraryGLES(bool supports_decal_sampler_address_mode) + : supports_decal_sampler_address_mode_( + supports_decal_sampler_address_mode) {} + +// |SamplerLibrary| +SamplerLibraryGLES::~SamplerLibraryGLES() = default; + +// |SamplerLibrary| +raw_ptr SamplerLibraryGLES::GetSampler( + const SamplerDescriptor& descriptor) { + if (!supports_decal_sampler_address_mode_ && + (descriptor.width_address_mode == SamplerAddressMode::kDecal || + descriptor.height_address_mode == SamplerAddressMode::kDecal || + descriptor.depth_address_mode == SamplerAddressMode::kDecal)) { + VALIDATION_LOG << "SamplerAddressMode::kDecal is not supported by the " + "current OpenGLES backend."; + return raw_ptr{nullptr}; + } + uint64_t p_key = SamplerDescriptor::ToKey(descriptor); + for (const auto& [key, value] : samplers_) { + if (key == p_key) { + return raw_ptr(value); + } + } + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + auto sampler = std::unique_ptr(new SamplerGLES(descriptor)); + samplers_.push_back(std::make_pair(p_key, std::move(sampler))); + + return raw_ptr(samplers_.back().second); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..1cfc9a78443db8ac095549554fb71bf3d8f5eee2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/sampler_library_gles.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_LIBRARY_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_LIBRARY_GLES_H_ + +#include "impeller/core/sampler.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/gles/sampler_gles.h" +#include "impeller/renderer/sampler_library.h" + +namespace impeller { + +class SamplerLibraryGLES final : public SamplerLibrary { + public: + explicit SamplerLibraryGLES(bool supports_decal_sampler_address_mode); + // |SamplerLibrary| + ~SamplerLibraryGLES() override; + + private: + friend class ContextGLES; + + std::vector>> samplers_; + + SamplerLibraryGLES(); + + // |SamplerLibrary| + raw_ptr GetSampler( + const SamplerDescriptor& descriptor) override; + + bool supports_decal_sampler_address_mode_ = false; + + SamplerLibraryGLES(const SamplerLibraryGLES&) = delete; + + SamplerLibraryGLES& operator=(const SamplerLibraryGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SAMPLER_LIBRARY_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..d1ee80d674c5eb3c7b6b3efbfb51baf2f854cfe5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.cc @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/shader_function_gles.h" + +namespace impeller { + +ShaderFunctionGLES::ShaderFunctionGLES( + UniqueID library_id, + ShaderStage stage, + std::string name, + std::shared_ptr mapping) + : ShaderFunction(library_id, std::move(name), stage), + mapping_(std::move(mapping)) {} + +ShaderFunctionGLES::~ShaderFunctionGLES() = default; + +const std::shared_ptr& +ShaderFunctionGLES::GetSourceMapping() const { + return mapping_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..3dd5af073e6f3644035f00a75fa3ab960412283f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_function_gles.h @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_FUNCTION_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_FUNCTION_GLES_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/shader_function.h" + +namespace impeller { + +class ShaderLibraryGLES; + +class ShaderFunctionGLES final + : public ShaderFunction, + public BackendCast { + public: + // |ShaderFunction| + ~ShaderFunctionGLES() override; + + const std::shared_ptr& GetSourceMapping() const; + + private: + friend ShaderLibraryGLES; + + std::shared_ptr mapping_; + + ShaderFunctionGLES(UniqueID library_id, + ShaderStage stage, + std::string name, + std::shared_ptr mapping); + + ShaderFunctionGLES(const ShaderFunctionGLES&) = delete; + + ShaderFunctionGLES& operator=(const ShaderFunctionGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_FUNCTION_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d52f6c176bffbfca3e47f90e4ef7bb840db8ef9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.cc @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/shader_library_gles.h" + +#include + +#include "flutter/fml/closure.h" +#include "impeller/base/config.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/gles/shader_function_gles.h" +#include "impeller/shader_archive/shader_archive.h" + +namespace impeller { + +static ShaderStage ToShaderStage(ArchiveShaderType type) { + switch (type) { + case ArchiveShaderType::kVertex: + return ShaderStage::kVertex; + case ArchiveShaderType::kFragment: + return ShaderStage::kFragment; + case ArchiveShaderType::kCompute: + return ShaderStage::kCompute; + } + FML_UNREACHABLE(); +} + +static std::string GLESShaderNameToShaderKeyName(const std::string& name, + ShaderStage stage) { + std::stringstream stream; + stream << name; + switch (stage) { + case ShaderStage::kUnknown: + stream << "_unknown_"; + break; + case ShaderStage::kVertex: + stream << "_vertex_"; + break; + case ShaderStage::kFragment: + stream << "_fragment_"; + break; + case ShaderStage::kCompute: + stream << "_compute_"; + break; + } + stream << "main"; + return stream.str(); +} + +ShaderLibraryGLES::ShaderLibraryGLES( + const std::vector>& shader_libraries) { + ShaderFunctionMap functions; + auto iterator = [&functions, library_id = library_id_](auto type, // + const auto& name, // + const auto& mapping // + ) -> bool { + const auto stage = ToShaderStage(type); + const auto key_name = GLESShaderNameToShaderKeyName(name, stage); + functions[ShaderKey{key_name, stage}] = std::shared_ptr{ + new ShaderFunctionGLES(library_id, // + stage, // + key_name, // + mapping // + )}; + + return true; + }; + for (auto library : shader_libraries) { + auto blob_library = ShaderArchive{std::move(library)}; + if (!blob_library.IsValid()) { + VALIDATION_LOG << "Could not construct blob library for shaders."; + return; + } + blob_library.IterateAllShaders(iterator); + } + + functions_ = functions; + is_valid_ = true; +} + +// |ShaderLibrary| +ShaderLibraryGLES::~ShaderLibraryGLES() = default; + +// |ShaderLibrary| +bool ShaderLibraryGLES::IsValid() const { + return is_valid_; +} + +// |ShaderLibrary| +std::shared_ptr ShaderLibraryGLES::GetFunction( + std::string_view name, + ShaderStage stage) { + ReaderLock lock(functions_mutex_); + const auto key = ShaderKey{name, stage}; + if (auto found = functions_.find(key); found != functions_.end()) { + return found->second; + } + return nullptr; +} + +// |ShaderLibrary| +void ShaderLibraryGLES::RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback) { + if (!callback) { + callback = [](auto) {}; + } + fml::ScopedCleanupClosure auto_fail([callback]() { callback(false); }); + if (name.empty() || stage == ShaderStage::kUnknown || code == nullptr || + code->GetMapping() == nullptr) { + VALIDATION_LOG << "Invalid runtime stage registration."; + return; + } + const auto key = ShaderKey{name, stage}; + WriterLock lock(functions_mutex_); + if (functions_.count(key) != 0) { + VALIDATION_LOG << "Runtime stage named " << name + << " has already been registered."; + return; + } + functions_[key] = std::shared_ptr(new ShaderFunctionGLES( + library_id_, // + stage, // + GLESShaderNameToShaderKeyName(name, stage), // + code // + )); + auto_fail.Release(); + callback(true); +} + +// |ShaderLibrary| +void ShaderLibraryGLES::UnregisterFunction(std::string name, + ShaderStage stage) { + ReaderLock lock(functions_mutex_); + + const auto key = ShaderKey{name, stage}; + + auto found = functions_.find(key); + if (found == functions_.end()) { + VALIDATION_LOG << "Library function named " << name + << " was not found, so it couldn't be unregistered."; + return; + } + + functions_.erase(found); + + return; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..50ca0008b509b54767ab2d2cdea39a90cdf41823 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/shader_library_gles.h @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_ + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/comparable.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/shader_key.h" +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +class ShaderLibraryGLES final : public ShaderLibrary { + public: + // |ShaderLibrary| + ~ShaderLibraryGLES() override; + + // |ShaderLibrary| + bool IsValid() const override; + + private: + friend class ContextGLES; + const UniqueID library_id_; + mutable RWMutex functions_mutex_; + ShaderFunctionMap functions_ IPLR_GUARDED_BY(functions_mutex_); + bool is_valid_ = false; + + explicit ShaderLibraryGLES( + const std::vector>& shader_libraries); + + // |ShaderLibrary| + std::shared_ptr GetFunction(std::string_view name, + ShaderStage stage) override; + + // |ShaderLibrary| + void RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback) override; + + // |ShaderLibrary| + void UnregisterFunction(std::string name, ShaderStage stage) override; + + ShaderLibraryGLES(const ShaderLibraryGLES&) = delete; + + ShaderLibraryGLES& operator=(const ShaderLibraryGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SHADER_LIBRARY_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..4f0866cec8c3aa5959a9c436fe3f6f0c4802c381 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.cc @@ -0,0 +1,94 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/surface_gles.h" + +#include "flutter/fml/trace_event.h" +#include "impeller/base/config.h" +#include "impeller/renderer/backend/gles/context_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" + +namespace impeller { + +std::unique_ptr SurfaceGLES::WrapFBO( + const std::shared_ptr& context, + SwapCallback swap_callback, + GLuint fbo, + PixelFormat color_format, + ISize fbo_size) { + TRACE_EVENT0("impeller", "SurfaceGLES::WrapOnScreenFBO"); + + if (context == nullptr || !context->IsValid() || !swap_callback) { + return nullptr; + } + + const auto& gl_context = ContextGLES::Cast(*context); + + TextureDescriptor color0_tex; + color0_tex.type = TextureType::kTexture2D; + color0_tex.format = color_format; + color0_tex.size = fbo_size; + color0_tex.usage = TextureUsage::kRenderTarget; + color0_tex.sample_count = SampleCount::kCount1; + color0_tex.storage_mode = StorageMode::kDevicePrivate; + + ColorAttachment color0; + color0.texture = + TextureGLES::WrapFBO(gl_context.GetReactor(), color0_tex, fbo); + color0.clear_color = Color::DarkSlateGray(); + color0.load_action = LoadAction::kClear; + color0.store_action = StoreAction::kStore; + + TextureDescriptor depth_stencil_texture_desc; + depth_stencil_texture_desc.type = TextureType::kTexture2D; + depth_stencil_texture_desc.format = color_format; + depth_stencil_texture_desc.size = fbo_size; + depth_stencil_texture_desc.usage = TextureUsage::kRenderTarget; + depth_stencil_texture_desc.sample_count = SampleCount::kCount1; + + auto depth_stencil_tex = + TextureGLES::CreatePlaceholder(gl_context.GetReactor(), // + depth_stencil_texture_desc // + ); + + DepthAttachment depth0; + depth0.clear_depth = 0; + depth0.texture = depth_stencil_tex; + depth0.load_action = LoadAction::kClear; + depth0.store_action = StoreAction::kDontCare; + + StencilAttachment stencil0; + stencil0.clear_stencil = 0; + stencil0.texture = depth_stencil_tex; + stencil0.load_action = LoadAction::kClear; + stencil0.store_action = StoreAction::kDontCare; + + RenderTarget render_target_desc; + + render_target_desc.SetColorAttachment(color0, 0u); + render_target_desc.SetDepthAttachment(depth0); + render_target_desc.SetStencilAttachment(stencil0); + +#ifdef IMPELLER_DEBUG + gl_context.GetGPUTracer()->RecordRasterThread(); +#endif // IMPELLER_DEBUG + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return std::unique_ptr( + new SurfaceGLES(std::move(swap_callback), render_target_desc)); +} + +SurfaceGLES::SurfaceGLES(SwapCallback swap_callback, + const RenderTarget& target_desc) + : Surface(target_desc), swap_callback_(std::move(swap_callback)) {} + +// |Surface| +SurfaceGLES::~SurfaceGLES() = default; + +// |Surface| +bool SurfaceGLES::Present() const { + return swap_callback_ ? swap_callback_() : false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..c7f9572bc7a23ad5570d86292e521270ade52892 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/surface_gles.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SURFACE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SURFACE_GLES_H_ + +#include +#include + +#include "impeller/renderer/backend/gles/gles.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +class SurfaceGLES final : public Surface { + public: + using SwapCallback = std::function; + + static std::unique_ptr WrapFBO( + const std::shared_ptr& context, + SwapCallback swap_callback, + GLuint fbo, + PixelFormat color_format, + ISize fbo_size); + + // |Surface| + ~SurfaceGLES() override; + + private: + SwapCallback swap_callback_; + + SurfaceGLES(SwapCallback swap_callback, const RenderTarget& target_desc); + + // |Surface| + bool Present() const override; + + SurfaceGLES(const SurfaceGLES&) = delete; + + SurfaceGLES& operator=(const SurfaceGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_SURFACE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/README.md b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dd9d028e1b8bd6c4c3ba4f06f33030663906843d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/README.md @@ -0,0 +1,48 @@ +# `MockGLES` + +This directory contains a mock implementation of the GLES backend. + +Most functions are implemented as no-ops, have a default implementation that is not configurable, or just record the call. The latter is useful for testing: + +```cc +TEST(MockGLES, Example) { + // Creates a mock GLES implementation and sets it as the current one. + auto mock_gles = MockGLES::Init(); + auto& gl = mock_gles->GetProcTable(); + + // Call the proc table methods as usual, or pass the proc table to a class + // that needs it. + gl.PushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, 0, -1, "test"); + gl.PopDebugGroupKHR(); + + // Method names are recorded and can be inspected. + // + // Note that many built-ins, like glGetString, are not recorded (otherwise the // logs would be much bigger and less useful). + auto calls = mock_gles->GetCapturedCalls(); + EXPECT_EQ(calls, std::vector( + {"PushDebugGroupKHR", "PopDebugGroupKHR"})); +} +``` + +To add a new function, do the following: + +1. Add a new top-level method to [`mock_gles.cc`](mock_gles.cc): + + ```cc + void glFooBar() { + recordCall("glFooBar"); + } + ``` + +2. Edit the `kMockResolver`, and add a new `else if` clause: + + ```diff + + else if (strcmp(name, "glFooBar") == 0) { + + return reinterpret_cast(&glFooBar); + } else { + return reinterpret_cast(&glDoNothing); + } + ``` + +It's possible we'll want to add a more sophisticated mechanism for mocking +besides capturing calls, but this is a good start. PRs welcome! diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/capabilities_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/capabilities_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b0e69464cabbee3fd00b1814361785028294a3e8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/capabilities_unittests.cc @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +TEST(CapabilitiesGLES, CanInitializeWithDefaults) { + auto mock_gles = MockGLES::Init(); + + auto capabilities = mock_gles->GetProcTable().GetCapabilities(); + + EXPECT_FALSE(capabilities->SupportsOffscreenMSAA()); + EXPECT_FALSE(capabilities->SupportsSSBO()); + EXPECT_TRUE(capabilities->SupportsTextureToTextureBlits()); + EXPECT_FALSE(capabilities->SupportsFramebufferFetch()); + EXPECT_FALSE(capabilities->SupportsCompute()); + EXPECT_FALSE(capabilities->SupportsComputeSubgroups()); + EXPECT_FALSE(capabilities->SupportsReadFromResolve()); + EXPECT_FALSE(capabilities->SupportsDecalSamplerAddressMode()); + EXPECT_FALSE(capabilities->SupportsDeviceTransientTextures()); + + EXPECT_EQ(capabilities->GetDefaultColorFormat(), + PixelFormat::kR8G8B8A8UNormInt); + EXPECT_EQ(capabilities->GetDefaultStencilFormat(), PixelFormat::kS8UInt); + EXPECT_EQ(capabilities->GetDefaultDepthStencilFormat(), + PixelFormat::kD24UnormS8Uint); +} + +TEST(CapabilitiesGLES, SupportsDecalSamplerAddressMode) { + auto const extensions = std::vector{ + "GL_KHR_debug", // + "GL_EXT_texture_border_clamp", // + }; + auto mock_gles = MockGLES::Init(extensions); + auto capabilities = mock_gles->GetProcTable().GetCapabilities(); + EXPECT_TRUE(capabilities->SupportsDecalSamplerAddressMode()); +} + +TEST(CapabilitiesGLES, SupportsDecalSamplerAddressModeNotOES) { + auto const extensions = std::vector{ + "GL_KHR_debug", // + "GL_OES_texture_border_clamp", // + }; + auto mock_gles = MockGLES::Init(extensions); + auto capabilities = mock_gles->GetProcTable().GetCapabilities(); + EXPECT_FALSE(capabilities->SupportsDecalSamplerAddressMode()); +} + +TEST(CapabilitiesGLES, SupportsFramebufferFetch) { + auto const extensions = std::vector{ + "GL_KHR_debug", // + "GL_EXT_shader_framebuffer_fetch", // + }; + auto mock_gles = MockGLES::Init(extensions); + auto capabilities = mock_gles->GetProcTable().GetCapabilities(); + EXPECT_TRUE(capabilities->SupportsFramebufferFetch()); +} + +TEST(CapabilitiesGLES, SupportsMSAA) { + auto const extensions = std::vector{ + "GL_EXT_multisampled_render_to_texture", + }; + auto mock_gles = MockGLES::Init(extensions); + auto capabilities = mock_gles->GetProcTable().GetCapabilities(); + EXPECT_TRUE(capabilities->SupportsImplicitResolvingMSAA()); + EXPECT_FALSE(capabilities->SupportsOffscreenMSAA()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/formats_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/formats_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e0fd114e80e342a00f5a9851290471f25ecd283 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/formats_gles_unittests.cc @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/formats_gles.h" + +namespace impeller { +namespace testing { + +TEST(FormatsGLES, CanFormatFramebufferErrorMessage) { + ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_UNDEFINED), + "GL_FRAMEBUFFER_UNDEFINED"); + ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT), + "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + ASSERT_EQ( + DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT), + "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_UNSUPPORTED), + "GL_FRAMEBUFFER_UNSUPPORTED"); + ASSERT_EQ(DebugToFramebufferError(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE), + "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); + ASSERT_EQ(DebugToFramebufferError(0), "Unknown error code: 0"); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/gpu_tracer_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/gpu_tracer_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..2ee1da6c1b3861369177954ffbcb76dd55d4c95b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/gpu_tracer_gles_unittests.cc @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/gpu_tracer_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +using ::testing::_; + +#ifdef IMPELLER_DEBUG +TEST(GPUTracerGLES, CanFormatFramebufferErrorMessage) { + auto const extensions = std::vector{ + "GL_KHR_debug", // + "GL_EXT_disjoint_timer_query", // + }; + auto mock_gles_impl = std::make_unique(); + + { + ::testing::InSequence seq; + auto gen_queries = [](GLsizei n, GLuint* ids) { + for (int i = 0; i < n; ++i) { + ids[i] = i + 1; + } + }; + EXPECT_CALL(*mock_gles_impl, GenQueriesEXT(_, _)).WillOnce(gen_queries); + EXPECT_CALL(*mock_gles_impl, BeginQueryEXT(GL_TIME_ELAPSED_EXT, _)); + EXPECT_CALL(*mock_gles_impl, EndQueryEXT(GL_TIME_ELAPSED_EXT)); + EXPECT_CALL(*mock_gles_impl, + GetQueryObjectuivEXT(_, GL_QUERY_RESULT_AVAILABLE_EXT, _)) + .WillOnce([](GLuint id, GLenum target, GLuint* result) { + *result = GL_TRUE; + }); + EXPECT_CALL(*mock_gles_impl, + GetQueryObjectui64vEXT(_, GL_QUERY_RESULT_EXT, _)) + .WillOnce([](GLuint id, GLenum target, GLuint64* result) { + *result = 1000u; + }); + EXPECT_CALL(*mock_gles_impl, DeleteQueriesEXT(_, _)); + EXPECT_CALL(*mock_gles_impl, GenQueriesEXT(_, _)).WillOnce(gen_queries); + EXPECT_CALL(*mock_gles_impl, BeginQueryEXT(GL_TIME_ELAPSED_EXT, _)); + } + std::shared_ptr mock_gles = + MockGLES::Init(std::move(mock_gles_impl), extensions); + auto tracer = + std::make_shared(mock_gles->GetProcTable(), true); + tracer->RecordRasterThread(); + tracer->MarkFrameStart(mock_gles->GetProcTable()); + tracer->MarkFrameEnd(mock_gles->GetProcTable()); + tracer->MarkFrameStart(mock_gles->GetProcTable()); +} + +#endif // IMPELLER_DEBUG + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..71133e6f2f378b8373e28d301ed184998fd7e00e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.cc @@ -0,0 +1,292 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "GLES3/gl3.h" +#include "fml/logging.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +// OpenGLES is not thread safe. +// +// This mutex is used to ensure that only one test is using the mock at a time. +static std::mutex g_test_lock; + +static std::weak_ptr g_mock_gles; + +static std::vector g_extensions; + +static const char* g_version; + +template +struct CheckSameSignature : std::false_type {}; + +template +struct CheckSameSignature : std::true_type {}; + +// This is a stub function that does nothing/records nothing. +void doNothing() {} + +auto const kMockVendor = "MockGLES"; +const auto kMockShadingLanguageVersion = "GLSL ES 1.0"; +auto const kExtensions = std::vector{ + "GL_KHR_debug" // +}; + +namespace { + +template +struct function_traits; + +template +struct function_traits { + using return_type = Ret; +}; + +template +auto CallMockMethod(Func func, Args&&... args) { + if (auto mock_gles = g_mock_gles.lock()) { + if (mock_gles->GetImpl()) { + return (mock_gles->GetImpl()->*func)(std::forward(args)...); + } + } + return typename function_traits::return_type(); +} +} // namespace + +const unsigned char* mockGetString(GLenum name) { + switch (name) { + case GL_VENDOR: + return reinterpret_cast(kMockVendor); + case GL_VERSION: + return reinterpret_cast(g_version); + case GL_SHADING_LANGUAGE_VERSION: + return reinterpret_cast( + kMockShadingLanguageVersion); + default: + return reinterpret_cast(""); + } +} + +static_assert(CheckSameSignature::value); + +const unsigned char* mockGetStringi(GLenum name, GLuint index) { + switch (name) { + case GL_EXTENSIONS: + return reinterpret_cast(g_extensions[index]); + default: + return reinterpret_cast(""); + } +} + +static_assert(CheckSameSignature::value); + +void mockGetIntegerv(GLenum name, int* value) { + switch (name) { + case GL_NUM_EXTENSIONS: { + *value = g_extensions.size(); + } break; + case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: + *value = 8; + break; + case GL_MAX_LABEL_LENGTH_KHR: + *value = 64; + break; + default: + *value = 0; + break; + } +} + +static_assert(CheckSameSignature::value); + +GLenum mockGetError() { + return GL_NO_ERROR; +} + +static_assert(CheckSameSignature::value); + +void mockPopDebugGroupKHR() {} + +static_assert(CheckSameSignature::value); + +void mockPushDebugGroupKHR(GLenum source, + GLuint id, + GLsizei length, + const GLchar* message) {} + +static_assert(CheckSameSignature::value); + +void mockGenQueriesEXT(GLsizei n, GLuint* ids) { + CallMockMethod(&IMockGLESImpl::GenQueriesEXT, n, ids); +} + +static_assert(CheckSameSignature::value); + +void mockBeginQueryEXT(GLenum target, GLuint id) { + CallMockMethod(&IMockGLESImpl::BeginQueryEXT, target, id); +} + +static_assert(CheckSameSignature::value); + +void mockEndQueryEXT(GLuint id) { + CallMockMethod(&IMockGLESImpl::EndQueryEXT, id); +} + +static_assert(CheckSameSignature::value); + +void mockGetQueryObjectuivEXT(GLuint id, GLenum target, GLuint* result) { + CallMockMethod(&IMockGLESImpl::GetQueryObjectuivEXT, id, target, result); +} + +static_assert(CheckSameSignature::value); + +void mockGetQueryObjectui64vEXT(GLuint id, GLenum target, GLuint64* result) { + CallMockMethod(&IMockGLESImpl::GetQueryObjectui64vEXT, id, target, result); +} + +static_assert(CheckSameSignature::value); + +void mockDeleteQueriesEXT(GLsizei size, const GLuint* queries) { + CallMockMethod(&IMockGLESImpl::DeleteQueriesEXT, size, queries); +} + +void mockDeleteTextures(GLsizei size, const GLuint* queries) { + CallMockMethod(&IMockGLESImpl::DeleteTextures, size, queries); +} + +static_assert(CheckSameSignature::value); + +void mockUniform1fv(GLint location, GLsizei count, const GLfloat* value) { + CallMockMethod(&IMockGLESImpl::Uniform1fv, location, count, value); +} +static_assert(CheckSameSignature::value); + +void mockGenTextures(GLsizei n, GLuint* textures) { + CallMockMethod(&IMockGLESImpl::GenTextures, n, textures); +} + +static_assert(CheckSameSignature::value); + +void mockGenBuffers(GLsizei n, GLuint* buffers) { + CallMockMethod(&IMockGLESImpl::GenBuffers, n, buffers); +} + +static_assert(CheckSameSignature::value); + +void mockObjectLabelKHR(GLenum identifier, + GLuint name, + GLsizei length, + const GLchar* label) { + CallMockMethod(&IMockGLESImpl::ObjectLabelKHR, identifier, name, length, + label); +} +static_assert(CheckSameSignature::value); + +GLboolean mockIsTexture(GLuint texture) { + return CallMockMethod(&IMockGLESImpl::IsTexture, texture); +} + +static_assert(CheckSameSignature::value); + +// static +std::shared_ptr MockGLES::Init( + std::unique_ptr impl, + const std::optional>& extensions) { + FML_CHECK(g_test_lock.try_lock()) + << "MockGLES is already being used by another test."; + g_extensions = extensions.value_or(kExtensions); + g_version = "OpenGL ES 3.0"; + auto mock_gles = std::shared_ptr(new MockGLES()); + mock_gles->impl_ = std::move(impl); + g_mock_gles = mock_gles; + return mock_gles; +} + +std::shared_ptr MockGLES::Init( + const std::optional>& extensions, + const char* version_string, + ProcTableGLES::Resolver resolver) { + // If we cannot obtain a lock, MockGLES is already being used elsewhere. + FML_CHECK(g_test_lock.try_lock()) + << "MockGLES is already being used by another test."; + g_extensions = extensions.value_or(kExtensions); + g_version = version_string; + auto mock_gles = std::shared_ptr(new MockGLES(std::move(resolver))); + g_mock_gles = mock_gles; + return mock_gles; +} + +const ProcTableGLES::Resolver kMockResolverGLES = [](const char* name) { + if (strcmp(name, "glPopDebugGroupKHR") == 0) { + return reinterpret_cast(&mockPopDebugGroupKHR); + } else if (strcmp(name, "glPushDebugGroupKHR") == 0) { + return reinterpret_cast(&mockPushDebugGroupKHR); + } else if (strcmp(name, "glGetString") == 0) { + return reinterpret_cast(&mockGetString); + } else if (strcmp(name, "glGetStringi") == 0) { + return reinterpret_cast(&mockGetStringi); + } else if (strcmp(name, "glGetIntegerv") == 0) { + return reinterpret_cast(&mockGetIntegerv); + } else if (strcmp(name, "glGetError") == 0) { + return reinterpret_cast(&mockGetError); + } else if (strcmp(name, "glGenQueriesEXT") == 0) { + return reinterpret_cast(&mockGenQueriesEXT); + } else if (strcmp(name, "glBeginQueryEXT") == 0) { + return reinterpret_cast(&mockBeginQueryEXT); + } else if (strcmp(name, "glEndQueryEXT") == 0) { + return reinterpret_cast(&mockEndQueryEXT); + } else if (strcmp(name, "glDeleteQueriesEXT") == 0) { + return reinterpret_cast(&mockDeleteQueriesEXT); + } else if (strcmp(name, "glDeleteTextures") == 0) { + return reinterpret_cast(&mockDeleteTextures); + } else if (strcmp(name, "glGetQueryObjectui64vEXT") == 0) { + return reinterpret_cast(mockGetQueryObjectui64vEXT); + } else if (strcmp(name, "glGetQueryObjectuivEXT") == 0) { + return reinterpret_cast(mockGetQueryObjectuivEXT); + } else if (strcmp(name, "glUniform1fv") == 0) { + return reinterpret_cast(mockUniform1fv); + } else if (strcmp(name, "glGenTextures") == 0) { + return reinterpret_cast(mockGenTextures); + } else if (strcmp(name, "glObjectLabelKHR") == 0) { + return reinterpret_cast(mockObjectLabelKHR); + } else if (strcmp(name, "glGenBuffers") == 0) { + return reinterpret_cast(mockGenBuffers); + } else if (strcmp(name, "glIsTexture") == 0) { + return reinterpret_cast(mockIsTexture); + } else { + return reinterpret_cast(&doNothing); + } +}; + +MockGLES::MockGLES(ProcTableGLES::Resolver resolver) + : proc_table_(std::move(resolver)) {} + +MockGLES::~MockGLES() { + g_test_lock.unlock(); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..d7d424e6e7faa5bb09ed769e506d11759ec59977 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles.h @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_ + +#include +#include + +#include "gmock/gmock.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" + +namespace impeller { +namespace testing { + +extern const ProcTableGLES::Resolver kMockResolverGLES; + +class IMockGLESImpl { + public: + virtual ~IMockGLESImpl() = default; + virtual void DeleteTextures(GLsizei size, const GLuint* queries) {} + virtual void GenTextures(GLsizei n, GLuint* textures) {} + virtual void ObjectLabelKHR(GLenum identifier, + GLuint name, + GLsizei length, + const GLchar* label) {} + virtual void Uniform1fv(GLint location, GLsizei count, const GLfloat* value) { + } + virtual void GenQueriesEXT(GLsizei n, GLuint* ids) {} + virtual void BeginQueryEXT(GLenum target, GLuint id) {} + virtual void EndQueryEXT(GLuint id) {} + virtual void GetQueryObjectuivEXT(GLuint id, GLenum target, GLuint* result) {} + virtual void GetQueryObjectui64vEXT(GLuint id, + GLenum target, + GLuint64* result) {} + virtual void DeleteQueriesEXT(GLsizei size, const GLuint* queries) {} + virtual void GenBuffers(GLsizei n, GLuint* buffers) {} + virtual GLboolean IsTexture(GLuint texture) { return true; } +}; + +class MockGLESImpl : public IMockGLESImpl { + public: + MOCK_METHOD(void, + DeleteTextures, + (GLsizei size, const GLuint* queries), + (override)); + MOCK_METHOD(void, GenTextures, (GLsizei n, GLuint* textures), (override)); + MOCK_METHOD( + void, + ObjectLabelKHR, + (GLenum identifier, GLuint name, GLsizei length, const GLchar* label), + (override)); + MOCK_METHOD(void, + Uniform1fv, + (GLint location, GLsizei count, const GLfloat* value), + (override)); + MOCK_METHOD(void, GenQueriesEXT, (GLsizei n, GLuint* ids), (override)); + MOCK_METHOD(void, BeginQueryEXT, (GLenum target, GLuint id), (override)); + MOCK_METHOD(void, EndQueryEXT, (GLuint id), (override)); + MOCK_METHOD(void, + GetQueryObjectuivEXT, + (GLuint id, GLenum target, GLuint* result), + (override)); + MOCK_METHOD(void, + GetQueryObjectui64vEXT, + (GLuint id, GLenum target, GLuint64* result), + (override)); + MOCK_METHOD(void, + DeleteQueriesEXT, + (GLsizei size, const GLuint* queries), + (override)); + MOCK_METHOD(void, GenBuffers, (GLsizei n, GLuint* buffers), (override)); + MOCK_METHOD(GLboolean, IsTexture, (GLuint texture), (override)); +}; + +/// @brief Provides a mocked version of the |ProcTableGLES| class. +/// +/// Typically, Open GLES at runtime will be provided the host's GLES bindings +/// (as function pointers). This class maintains a set of function pointers that +/// appear to be GLES functions, but are actually just stubs that record +/// invocations. +/// +/// See `README.md` for more information. +class MockGLES final { + public: + static std::shared_ptr Init( + std::unique_ptr impl, + const std::optional>& extensions = std::nullopt); + + /// @brief Returns an initialized |MockGLES| instance. + /// + /// This method overwrites mocked global GLES function pointers to record + /// invocations on this instance of |MockGLES|. As such, it should only be + /// called once per test. + static std::shared_ptr Init( + const std::optional>& extensions = std::nullopt, + const char* version_string = "OpenGL ES 3.0", + ProcTableGLES::Resolver resolver = kMockResolverGLES); + + /// @brief Returns a configured |ProcTableGLES| instance. + const ProcTableGLES& GetProcTable() const { return proc_table_; } + + ~MockGLES(); + + IMockGLESImpl* GetImpl() { return impl_.get(); } + + private: + friend void RecordGLCall(const char* name); + friend void mockGenTextures(GLsizei n, GLuint* textures); + + explicit MockGLES(ProcTableGLES::Resolver resolver = kMockResolverGLES); + + ProcTableGLES proc_table_; + std::unique_ptr impl_; + + MockGLES(const MockGLES&) = delete; + + MockGLES& operator=(const MockGLES&) = delete; +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEST_MOCK_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..96dea6bffcbd98d4a114d87a59ab75c121c161a6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/mock_gles_unittests.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +// This test just checks that the proc table is initialized correctly. +// +// If this test doesn't pass, no test that uses the proc table will pass. +TEST(MockGLES, CanInitialize) { + auto mock_gles = MockGLES::Init(); + + std::string_view vendor(reinterpret_cast( + mock_gles->GetProcTable().GetString(GL_VENDOR))); + EXPECT_EQ(vendor, "MockGLES"); +} + +// Tests that if we call a function we have not mocked, it's OK. +TEST(MockGLES, CanCallUnmockedFunction) { + auto mock_gles = MockGLES::Init(); + + auto& gl = mock_gles->GetProcTable(); + gl.DeleteFramebuffers(1, nullptr); + + // Test should still complete. + // If we end up mocking DeleteFramebuffers, delete this test. +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/pipeline_library_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/pipeline_library_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..34dcff509b7af3d765d3bb1406a98d894abc00f3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/pipeline_library_gles_unittests.cc @@ -0,0 +1,71 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/fixtures/spec_constant.frag.h" +#include "impeller/fixtures/spec_constant.vert.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/gles/pipeline_gles.h" +#include "impeller/renderer/backend/gles/pipeline_library_gles.h" +#include "impeller/renderer/pipeline_library.h" + +namespace impeller::testing { + +using PipelineLibraryGLESTest = PlaygroundTest; +INSTANTIATE_OPENGLES_PLAYGROUND_SUITE(PipelineLibraryGLESTest); + +// NOLINTBEGIN(bugprone-unchecked-optional-access) +TEST_P(PipelineLibraryGLESTest, ProgramHandlesAreReused) { + using VS = SpecConstantVertexShader; + using FS = SpecConstantFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + auto new_desc = desc; + // Changing the sample counts should not result in a new program object. + new_desc->SetSampleCount(SampleCount::kCount4); + // Make sure we don't hit the top-level descriptor cache. This will cause + // caching irrespective of backends. + ASSERT_FALSE(desc->IsEqual(new_desc.value())); + auto new_pipeline = + context->GetPipelineLibrary()->GetPipeline(new_desc).Get(); + ASSERT_TRUE(new_pipeline && new_pipeline->IsValid()); + const auto& pipeline_gles = PipelineGLES::Cast(*pipeline); + const auto& new_pipeline_gles = PipelineGLES::Cast(*new_pipeline); + // The program handles should be live and equal. + ASSERT_FALSE(pipeline_gles.GetProgramHandle().IsDead()); + ASSERT_FALSE(new_pipeline_gles.GetProgramHandle().IsDead()); + ASSERT_EQ(pipeline_gles.GetProgramHandle().GetName().value(), + new_pipeline_gles.GetProgramHandle().GetName().value()); +} + +TEST_P(PipelineLibraryGLESTest, ChangingSpecConstantsCausesNewProgramObject) { + using VS = SpecConstantVertexShader; + using FS = SpecConstantFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSpecializationConstants({2.0f}); + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + auto new_desc = desc; + // Changing the spec. constants should result in a new program object. + new_desc->SetSpecializationConstants({4.0f}); + auto new_pipeline = + context->GetPipelineLibrary()->GetPipeline(new_desc).Get(); + ASSERT_TRUE(new_pipeline && new_pipeline->IsValid()); + const auto& pipeline_gles = PipelineGLES::Cast(*pipeline); + const auto& new_pipeline_gles = PipelineGLES::Cast(*new_pipeline); + // The program handles should be live and equal. + ASSERT_FALSE(pipeline_gles.GetProgramHandle().IsDead()); + ASSERT_FALSE(new_pipeline_gles.GetProgramHandle().IsDead()); + ASSERT_FALSE(pipeline_gles.GetProgramHandle().GetName().value() == + new_pipeline_gles.GetProgramHandle().GetName().value()); +} +// NOLINTEND(bugprone-unchecked-optional-access) + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/proc_table_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/proc_table_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7f188f95029990890b506af450b2259a5d4fc9e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/proc_table_gles_unittests.cc @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +#define EXPECT_AVAILABLE(proc_ivar) \ + EXPECT_TRUE(mock_gles->GetProcTable().proc_ivar.IsAvailable()); +#define EXPECT_UNAVAILABLE(proc_ivar) \ + EXPECT_FALSE(mock_gles->GetProcTable().proc_ivar.IsAvailable()); + +TEST(ProcTableGLES, ResolvesCorrectClearDepthProcOnES) { + auto mock_gles = MockGLES::Init(std::nullopt, "OpenGL ES 3.0"); + EXPECT_TRUE(mock_gles->GetProcTable().GetDescription()->IsES()); + + FOR_EACH_IMPELLER_ES_ONLY_PROC(EXPECT_AVAILABLE); + FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(EXPECT_UNAVAILABLE); +} + +TEST(ProcTableGLES, ResolvesCorrectClearDepthProcOnDesktopGL) { + auto mock_gles = MockGLES::Init(std::nullopt, "OpenGL 4.0"); + EXPECT_FALSE(mock_gles->GetProcTable().GetDescription()->IsES()); + + FOR_EACH_IMPELLER_DESKTOP_ONLY_PROC(EXPECT_AVAILABLE); + FOR_EACH_IMPELLER_ES_ONLY_PROC(EXPECT_UNAVAILABLE); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/reactor_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/reactor_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..3010e4c4806de6e697ce7b2d4f111558c64f1ecf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/reactor_unittests.cc @@ -0,0 +1,184 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +using ::testing::_; +using ::testing::NiceMock; + +class TestWorker : public ReactorGLES::Worker { + public: + bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const override { + return true; + } +}; + +TEST(ReactorGLES, CanAttachCleanupCallbacksToHandles) { + auto mock_gles = MockGLES::Init(); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + int value = 0; + auto handle = reactor->CreateHandle(HandleType::kTexture, 1123); + auto added = + reactor->RegisterCleanupCallback(handle, [&value]() { value++; }); + + EXPECT_TRUE(added); + EXPECT_TRUE(reactor->React()); + + reactor->CollectHandle(handle); + EXPECT_TRUE(reactor->AddOperation([](const ReactorGLES& reactor) {})); + EXPECT_TRUE(reactor->React()); + EXPECT_EQ(value, 1); +} + +TEST(ReactorGLES, DeletesHandlesDuringShutdown) { + auto mock_gles_impl = std::make_unique(); + + EXPECT_CALL(*mock_gles_impl, GenTextures(1, _)) + .WillOnce([](GLsizei size, GLuint* queries) { queries[0] = 1234; }); + EXPECT_CALL(*mock_gles_impl, DeleteTextures(1, ::testing::Pointee(1234))) + .Times(1); + + std::shared_ptr mock_gles = + MockGLES::Init(std::move(mock_gles_impl)); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + reactor->CreateHandle(HandleType::kTexture); + reactor.reset(); +} + +TEST(ReactorGLES, UntrackedHandle) { + auto mock_gles_impl = std::make_unique(); + + EXPECT_CALL(*mock_gles_impl, GenTextures(1, _)) + .WillOnce([](GLsizei size, GLuint* queries) { queries[0] = 1234; }); + EXPECT_CALL(*mock_gles_impl, DeleteTextures(1, ::testing::Pointee(1234))) + .Times(1); + + std::shared_ptr mock_gles = + MockGLES::Init(std::move(mock_gles_impl)); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + HandleGLES handle = reactor->CreateUntrackedHandle(HandleType::kTexture); + EXPECT_FALSE(handle.IsDead()); + std::optional glint = reactor->GetGLHandle(handle); + EXPECT_TRUE(glint.has_value()); + if (glint.has_value()) { + EXPECT_EQ(1234u, *glint); + } + reactor->CollectHandle(handle); + EXPECT_TRUE(reactor->AddOperation([&](const ReactorGLES&) {})); + EXPECT_TRUE(reactor->React()); +} + +TEST(ReactorGLES, NameUntrackedHandle) { + auto mock_gles_impl = std::make_unique>(); + NiceMock* raw_mock_gles = mock_gles_impl.get(); + + std::shared_ptr mock_gles = + MockGLES::Init(std::move(mock_gles_impl)); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + + if (!proc_table->SupportsDebugLabels()) { + GTEST_SKIP() << "This device doesn't support labelling."; + } + + EXPECT_CALL(*raw_mock_gles, GenTextures(1, _)) + .WillOnce([](GLsizei size, GLuint* queries) { queries[0] = 1234; }); + EXPECT_CALL(*raw_mock_gles, + ObjectLabelKHR(_, 1234, _, ::testing::StrEq("hello, joe!"))) + .Times(1); + ON_CALL(*raw_mock_gles, IsTexture).WillByDefault(::testing::Return(GL_TRUE)); + + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + HandleGLES handle = reactor->CreateUntrackedHandle(HandleType::kTexture); + reactor->SetDebugLabel(handle, "hello, joe!"); +} + +TEST(ReactorGLES, PerThreadOperationQueues) { + auto mock_gles = MockGLES::Init(); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + bool op1_called = false; + EXPECT_TRUE( + reactor->AddOperation([&](const ReactorGLES&) { op1_called = true; })); + + fml::AutoResetWaitableEvent event; + bool op2_called = false; + std::thread thread([&] { + EXPECT_TRUE(reactor->AddOperation( + [&](const ReactorGLES&) { op2_called = true; }, true)); + event.Wait(); + EXPECT_TRUE(reactor->React()); + }); + + // Reacting on the main thread should only run the main thread's operation. + EXPECT_TRUE(reactor->React()); + EXPECT_TRUE(op1_called); + EXPECT_FALSE(op2_called); + + // Reacting on the second thread will run the second thread's operation. + event.Signal(); + thread.join(); + EXPECT_TRUE(op2_called); +} + +TEST(ReactorGLES, CanDeferOperations) { + auto mock_gles = MockGLES::Init(); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + // Add operation executes tasks as long as the reactor can run tasks on + // the current thread. + bool did_run = false; + EXPECT_TRUE( + reactor->AddOperation([&](const ReactorGLES&) { did_run = true; })); + EXPECT_TRUE(did_run); + + //...unless defer=true is specified, which only enqueues in the reactor. + did_run = false; + EXPECT_TRUE(reactor->AddOperation([&](const ReactorGLES&) { did_run = true; }, + /*defer=*/true)); + EXPECT_FALSE(did_run); + EXPECT_TRUE(reactor->React()); + EXPECT_TRUE(did_run); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/specialization_constants_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/specialization_constants_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6975ccc99c1349bc8531fda257b795db9efd6ff --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/specialization_constants_unittests.cc @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "fml/mapping.h" +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller { +namespace testing { + +TEST(SpecConstant, CanCreateShaderWithSpecializationConstant) { + auto mock_gles = MockGLES::Init(); + auto& proc_table = mock_gles->GetProcTable(); + auto shader_source = + "#version 100\n" + "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" + "#endif\n" + "void main() { return vec4(0.0); }"; + auto test_shader = std::make_shared(shader_source); + + auto result = proc_table.ComputeShaderWithDefines(*test_shader, {0}); + + auto expected_shader_source = + "#version 100\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 0.000000\n" + "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" + "#endif\n" + "void main() { return vec4(0.0); }"; + + if (!result.has_value()) { + GTEST_FAIL() << "Expected shader source"; + } + ASSERT_EQ(result.value(), expected_shader_source); +} + +TEST(SpecConstant, CanCreateShaderWithSpecializationConstantMultipleValues) { + auto mock_gles = MockGLES::Init(); + auto& proc_table = mock_gles->GetProcTable(); + auto shader_source = + "#version 100\n" + "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" + "#endif\n" + "void main() { return vec4(0.0); }"; + auto test_shader = std::make_shared(shader_source); + + auto result = + proc_table.ComputeShaderWithDefines(*test_shader, {0, 1, 2, 3, 4, 5}); + + auto expected_shader_source = + "#version 100\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 0.000000\n" + "#define SPIRV_CROSS_CONSTANT_ID_1 1.000000\n" + "#define SPIRV_CROSS_CONSTANT_ID_2 2.000000\n" + "#define SPIRV_CROSS_CONSTANT_ID_3 3.000000\n" + "#define SPIRV_CROSS_CONSTANT_ID_4 4.000000\n" + "#define SPIRV_CROSS_CONSTANT_ID_5 5.000000\n" + "#ifndef SPIRV_CROSS_CONSTANT_ID_0\n" + "#define SPIRV_CROSS_CONSTANT_ID_0 1\n" + "#endif\n" + "void main() { return vec4(0.0); }"; + + if (!result.has_value()) { + GTEST_FAIL() << "Expected shader source"; + } + ASSERT_EQ(result.value(), expected_shader_source); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/surface_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/surface_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a039e03786c221c1bd2697fc608d4fc50e183e94 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/surface_gles_unittests.cc @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/playground/playground_test.h" +#include "flutter/impeller/renderer/backend/gles/context_gles.h" +#include "flutter/impeller/renderer/backend/gles/surface_gles.h" +#include "flutter/impeller/renderer/backend/gles/texture_gles.h" +#include "flutter/testing/testing.h" + +namespace impeller::testing { + +using SurfaceGLESTest = PlaygroundTest; +INSTANTIATE_OPENGLES_PLAYGROUND_SUITE(SurfaceGLESTest); + +TEST_P(SurfaceGLESTest, CanWrapNonZeroFBO) { + const GLuint fbo = 1988; + auto surface = + SurfaceGLES::WrapFBO(GetContext(), []() { return true; }, fbo, + PixelFormat::kR8G8B8A8UNormInt, {100, 100}); + ASSERT_TRUE(!!surface); + ASSERT_TRUE(surface->IsValid()); + ASSERT_TRUE(surface->GetRenderTarget().HasColorAttachment(0)); + const auto& texture = TextureGLES::Cast( + *(surface->GetRenderTarget().GetColorAttachment(0).texture)); + auto wrapped = texture.GetFBO(); + ASSERT_TRUE(wrapped.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ASSERT_EQ(wrapped.value(), fbo); +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/texture_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/texture_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0b52590117e681b9b825cf12bd8cc53423ed8c9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/test/texture_gles_unittests.cc @@ -0,0 +1,96 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/playground/playground_test.h" +#include "flutter/impeller/renderer/backend/gles/context_gles.h" +#include "flutter/impeller/renderer/backend/gles/texture_gles.h" +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" + +namespace impeller::testing { + +using TextureGLESTest = PlaygroundTest; +INSTANTIATE_OPENGLES_PLAYGROUND_SUITE(TextureGLESTest); + +TEST_P(TextureGLESTest, CanSetSyncFence) { + ContextGLES& context_gles = ContextGLES::Cast(*GetContext()); + if (!context_gles.GetReactor() + ->GetProcTable() + .GetDescription() + ->GetGlVersion() + .IsAtLeast(Version{3, 0, 0})) { + GTEST_SKIP() << "GL Version too low to test sync fence."; + } + + TextureDescriptor desc; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.size = {100, 100}; + desc.format = PixelFormat::kR8G8B8A8UNormInt; + + auto texture = GetContext()->GetResourceAllocator()->CreateTexture(desc); + ASSERT_TRUE(!!texture); + + EXPECT_TRUE(GetContext()->AddTrackingFence(texture)); + EXPECT_TRUE(context_gles.GetReactor()->React()); + + std::optional sync_fence = + TextureGLES::Cast(*texture).GetSyncFence(); + ASSERT_TRUE(sync_fence.has_value()); + if (!sync_fence.has_value()) { + return; + } + EXPECT_EQ(sync_fence.value().GetType(), HandleType::kFence); + + std::optional sync = + context_gles.GetReactor()->GetGLFence(sync_fence.value()); + ASSERT_TRUE(sync.has_value()); + if (!sync.has_value()) { + return; + } + + // Now queue up operation that binds texture to verify that sync fence is + // waited and removed. + + EXPECT_TRUE( + context_gles.GetReactor()->AddOperation([&](const ReactorGLES& reactor) { + return TextureGLES::Cast(*texture).Bind(); + })); + + sync_fence = TextureGLES::Cast(*texture).GetSyncFence(); + ASSERT_FALSE(sync_fence.has_value()); +} + +TEST_P(TextureGLESTest, Binds2DTexture) { + TextureDescriptor desc; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.size = {100, 100}; + desc.format = PixelFormat::kR8G8B8A8UNormInt; + desc.type = TextureType::kTexture2DMultisample; + desc.sample_count = SampleCount::kCount4; + + auto texture = GetContext()->GetResourceAllocator()->CreateTexture(desc); + + ASSERT_TRUE(texture); + + if (GetContext()->GetCapabilities()->SupportsImplicitResolvingMSAA()) { + EXPECT_EQ( + TextureGLES::Cast(*texture).ComputeTypeForBinding(GL_READ_FRAMEBUFFER), + TextureGLES::Type::kTexture); + EXPECT_EQ(TextureGLES::Cast(*texture).ComputeTypeForBinding(GL_FRAMEBUFFER), + TextureGLES::Type::kTextureMultisampled); + } else { + EXPECT_EQ( + TextureGLES::Cast(*texture).ComputeTypeForBinding(GL_READ_FRAMEBUFFER), + TextureGLES::Type::kRenderBufferMultisampled); + EXPECT_EQ(TextureGLES::Cast(*texture).ComputeTypeForBinding(GL_FRAMEBUFFER), + TextureGLES::Type::kRenderBufferMultisampled); + } +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..15292f3e7e73dcd689f44b1a3e6fe00cde22ed34 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.cc @@ -0,0 +1,687 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/texture_gles.h" + +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/allocation.h" +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/gles/formats_gles.h" + +namespace impeller { + +namespace { +static bool IsDepthStencilFormat(PixelFormat format) { + switch (format) { + case PixelFormat::kS8UInt: + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return true; + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return false; + } + FML_UNREACHABLE(); +} + +static TextureGLES::Type GetTextureTypeFromDescriptor( + const TextureDescriptor& desc, + const std::shared_ptr& capabilities) { + const auto usage = static_cast(desc.usage); + const auto render_target = TextureUsage::kRenderTarget; + const auto is_msaa = desc.sample_count == SampleCount::kCount4; + if (usage == render_target && IsDepthStencilFormat(desc.format)) { + return is_msaa ? TextureGLES::Type::kRenderBufferMultisampled + : TextureGLES::Type::kRenderBuffer; + } + return is_msaa ? (capabilities->SupportsImplicitResolvingMSAA() + ? TextureGLES::Type::kTextureMultisampled + : TextureGLES::Type::kRenderBufferMultisampled) + : TextureGLES::Type::kTexture; +} + +struct TexImage2DData { + GLint internal_format = 0; + GLenum external_format = GL_NONE; + GLenum type = GL_NONE; + std::shared_ptr data; + + explicit TexImage2DData(PixelFormat pixel_format) { + switch (pixel_format) { + case PixelFormat::kA8UNormInt: + internal_format = GL_ALPHA; + external_format = GL_ALPHA; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR8UNormInt: + internal_format = GL_RED; + external_format = GL_RED; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_UNSIGNED_BYTE; + break; + case PixelFormat::kR32G32B32A32Float: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_FLOAT; + break; + case PixelFormat::kR16G16B16A16Float: + internal_format = GL_RGBA; + external_format = GL_RGBA; + type = GL_HALF_FLOAT; + break; + case PixelFormat::kS8UInt: + // Pure stencil textures are only available in OpenGL 4.4+, which is + // ~0% of mobile devices. Instead, we use a depth-stencil texture and + // only use the stencil component. + // + // https://registry.khronos.org/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml + case PixelFormat::kD24UnormS8Uint: + internal_format = GL_DEPTH_STENCIL; + external_format = GL_DEPTH_STENCIL; + type = GL_UNSIGNED_INT_24_8; + break; + case PixelFormat::kUnknown: + case PixelFormat::kD32FloatS8UInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10A10XR: + return; + } + is_valid_ = true; + } + + TexImage2DData(PixelFormat pixel_format, + std::shared_ptr mapping) + : TexImage2DData(pixel_format) { + data = std::move(mapping); + } + + bool IsValid() const { return is_valid_; } + + private: + bool is_valid_ = false; +}; +} // namespace + +HandleType ToHandleType(TextureGLES::Type type) { + switch (type) { + case TextureGLES::Type::kTexture: + case TextureGLES::Type::kTextureMultisampled: + return HandleType::kTexture; + case TextureGLES::Type::kRenderBuffer: + case TextureGLES::Type::kRenderBufferMultisampled: + return HandleType::kRenderBuffer; + } + FML_UNREACHABLE(); +} + +std::shared_ptr TextureGLES::WrapFBO( + std::shared_ptr reactor, + TextureDescriptor desc, + GLuint fbo) { + auto texture = std::shared_ptr( + new TextureGLES(std::move(reactor), desc, fbo, std::nullopt)); + if (!texture->IsValid()) { + return nullptr; + } + return texture; +} + +std::shared_ptr TextureGLES::WrapTexture( + std::shared_ptr reactor, + TextureDescriptor desc, + HandleGLES external_handle) { + if (external_handle.IsDead()) { + VALIDATION_LOG << "Cannot wrap a dead handle."; + return nullptr; + } + if (external_handle.GetType() != HandleType::kTexture) { + VALIDATION_LOG << "Cannot wrap a non-texture handle."; + return nullptr; + } + auto texture = std::shared_ptr( + new TextureGLES(std::move(reactor), desc, std::nullopt, external_handle)); + if (!texture->IsValid()) { + return nullptr; + } + return texture; +} + +std::shared_ptr TextureGLES::CreatePlaceholder( + std::shared_ptr reactor, + TextureDescriptor desc) { + return TextureGLES::WrapFBO(std::move(reactor), desc, 0u); +} + +TextureGLES::TextureGLES(std::shared_ptr reactor, + TextureDescriptor desc) + : TextureGLES(std::move(reactor), // + desc, // + std::nullopt, // + std::nullopt // + ) {} + +TextureGLES::TextureGLES(std::shared_ptr reactor, + TextureDescriptor desc, + std::optional fbo, + std::optional external_handle) + : Texture(desc), + reactor_(std::move(reactor)), + type_(GetTextureTypeFromDescriptor( + GetTextureDescriptor(), + reactor_->GetProcTable().GetCapabilities())), + handle_(external_handle.has_value() + ? external_handle.value() + : reactor_->CreateUntrackedHandle(ToHandleType(type_))), + is_wrapped_(fbo.has_value() || external_handle.has_value()), + wrapped_fbo_(fbo) { + // Ensure the texture descriptor itself is valid. + if (!GetTextureDescriptor().IsValid()) { + VALIDATION_LOG << "Invalid texture descriptor."; + return; + } + // Ensure the texture doesn't exceed device capabilities. + const auto tex_size = GetTextureDescriptor().size; + const auto max_size = + reactor_->GetProcTable().GetCapabilities()->max_texture_size; + if (tex_size.Max(max_size) != max_size) { + VALIDATION_LOG << "Texture of size " << tex_size + << " would exceed max supported size of " << max_size << "."; + return; + } + + is_valid_ = true; +} + +// |Texture| +TextureGLES::~TextureGLES() { + reactor_->CollectHandle(handle_); + if (!cached_fbo_.IsDead()) { + reactor_->CollectHandle(cached_fbo_); + } +} + +// |Texture| +bool TextureGLES::IsValid() const { + return is_valid_; +} + +// |Texture| +void TextureGLES::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + reactor_->SetDebugLabel(handle_, label); +#endif // IMPELLER_DEBUG +} + +// |Texture| +void TextureGLES::SetLabel(std::string_view label, std::string_view trailing) { +#ifdef IMPELLER_DEBUG + if (reactor_->CanSetDebugLabels()) { + reactor_->SetDebugLabel(handle_, + SPrintF("%s %s", label.data(), trailing.data())); + } +#endif // IMPELLER_DEBUG +} + +// |Texture| +bool TextureGLES::OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) { + return OnSetContents(CreateMappingWithCopy(contents, Bytes{length}), slice); +} + +// |Texture| +bool TextureGLES::OnSetContents(std::shared_ptr mapping, + size_t slice) { + if (!mapping) { + return false; + } + + if (mapping->GetSize() == 0u) { + return true; + } + + if (mapping->GetMapping() == nullptr) { + return false; + } + + if (GetType() != Type::kTexture) { + VALIDATION_LOG << "Incorrect texture usage flags for setting contents on " + "this texture object."; + return false; + } + + if (is_wrapped_) { + VALIDATION_LOG << "Cannot set the contents of a wrapped texture."; + return false; + } + + const auto& tex_descriptor = GetTextureDescriptor(); + + if (tex_descriptor.size.IsEmpty()) { + return true; + } + + if (!tex_descriptor.IsValid() || + mapping->GetSize() < tex_descriptor.GetByteSizeOfBaseMipLevel()) { + return false; + } + + GLenum texture_type; + GLenum texture_target; + switch (tex_descriptor.type) { + case TextureType::kTexture2D: + texture_type = GL_TEXTURE_2D; + texture_target = GL_TEXTURE_2D; + break; + case TextureType::kTexture2DMultisample: + VALIDATION_LOG << "Multisample texture uploading is not supported for " + "the OpenGLES backend."; + return false; + case TextureType::kTextureCube: + texture_type = GL_TEXTURE_CUBE_MAP; + texture_target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice; + break; + case TextureType::kTextureExternalOES: + texture_type = GL_TEXTURE_EXTERNAL_OES; + texture_target = GL_TEXTURE_EXTERNAL_OES; + break; + } + + auto data = std::make_shared(tex_descriptor.format, + std::move(mapping)); + if (!data || !data->IsValid()) { + VALIDATION_LOG << "Invalid texture format."; + return false; + } + + ReactorGLES::Operation texture_upload = [handle = handle_, // + data, // + size = tex_descriptor.size, // + texture_type, // + texture_target // + ](const auto& reactor) { + auto gl_handle = reactor.GetGLHandle(handle); + if (!gl_handle.has_value()) { + VALIDATION_LOG + << "Texture was collected before it could be uploaded to the GPU."; + return; + } + const auto& gl = reactor.GetProcTable(); + gl.BindTexture(texture_type, gl_handle.value()); + const GLvoid* tex_data = nullptr; + if (data->data) { + tex_data = data->data->GetMapping(); + } + + { + TRACE_EVENT1("impeller", "TexImage2DUpload", "Bytes", + std::to_string(data->data->GetSize()).c_str()); + gl.PixelStorei(GL_UNPACK_ALIGNMENT, 1); + gl.TexImage2D(texture_target, // target + 0u, // LOD level + data->internal_format, // internal format + size.width, // width + size.height, // height + 0u, // border + data->external_format, // external format + data->type, // type + tex_data // data + ); + } + }; + + slices_initialized_ = reactor_->AddOperation(texture_upload); + return slices_initialized_[0]; +} + +// |Texture| +ISize TextureGLES::GetSize() const { + return GetTextureDescriptor().size; +} + +static std::optional ToRenderBufferFormat(PixelFormat format) { + switch (format) { + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + return GL_RGBA8; + case PixelFormat::kR32G32B32A32Float: + return GL_RGBA32F; + case PixelFormat::kR16G16B16A16Float: + return GL_RGBA16F; + case PixelFormat::kS8UInt: + return GL_STENCIL_INDEX8; + case PixelFormat::kD24UnormS8Uint: + return GL_DEPTH24_STENCIL8; + case PixelFormat::kD32FloatS8UInt: + return GL_DEPTH32F_STENCIL8; + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10A10XR: + return std::nullopt; + } + FML_UNREACHABLE(); +} + +TextureGLES::Type TextureGLES::ComputeTypeForBinding(GLenum target) const { + // When binding to a GL_READ_FRAMEBUFFER, any multisampled + // textures must be bound as single sampled. + if (target == GL_READ_FRAMEBUFFER && type_ == Type::kTextureMultisampled) { + return Type::kTexture; + } + return type_; +} + +void TextureGLES::InitializeContentsIfNecessary() const { + if (!IsValid() || slices_initialized_[0]) { + return; + } + slices_initialized_[0] = true; + + if (is_wrapped_) { + return; + } + + auto size = GetSize(); + + if (size.IsEmpty()) { + return; + } + + const auto& gl = reactor_->GetProcTable(); + std::optional handle = reactor_->GetGLHandle(handle_); + if (!handle.has_value()) { + VALIDATION_LOG << "Could not initialize the contents of texture."; + return; + } + + switch (type_) { + case Type::kTexture: + case Type::kTextureMultisampled: { + TexImage2DData tex_data(GetTextureDescriptor().format); + if (!tex_data.IsValid()) { + VALIDATION_LOG << "Invalid format for texture image."; + return; + } + gl.BindTexture(GL_TEXTURE_2D, handle.value()); + { + TRACE_EVENT0("impeller", "TexImage2DInitialization"); + gl.TexImage2D(GL_TEXTURE_2D, // target + 0u, // LOD level (base mip level size checked) + tex_data.internal_format, // internal format + size.width, // width + size.height, // height + 0u, // border + tex_data.external_format, // format + tex_data.type, // type + nullptr // data + ); + } + } break; + case Type::kRenderBuffer: + case Type::kRenderBufferMultisampled: { + auto render_buffer_format = + ToRenderBufferFormat(GetTextureDescriptor().format); + if (!render_buffer_format.has_value()) { + VALIDATION_LOG << "Invalid format for render-buffer image."; + return; + } + gl.BindRenderbuffer(GL_RENDERBUFFER, handle.value()); + { + if (type_ == Type::kRenderBufferMultisampled) { + // BEWARE: these functions are not at all equivalent! the extensions + // are from EXT_multisampled_render_to_texture and cannot be used + // with regular GLES 3.0 multisampled renderbuffers/textures. + if (gl.GetCapabilities()->SupportsImplicitResolvingMSAA()) { + gl.RenderbufferStorageMultisampleEXT( + /*target=*/GL_RENDERBUFFER, // + /*samples=*/4, // + /*internal_format=*/render_buffer_format.value(), // + /*width=*/size.width, // + /*height=*/size.height // + ); + } else { + gl.RenderbufferStorageMultisample( + /*target=*/GL_RENDERBUFFER, // + /*samples=*/4, // + /*internal_format=*/render_buffer_format.value(), // + /*width=*/size.width, // + /*height=*/size.height // + ); + } + } else { + gl.RenderbufferStorage( + /*target=*/GL_RENDERBUFFER, // + /*internal_format=*/render_buffer_format.value(), // + /*width=*/size.width, // + /*height=*/size.height // + ); + } + } + } break; + } +} + +std::optional TextureGLES::GetGLHandle() const { + if (!IsValid()) { + return std::nullopt; + } + return reactor_->GetGLHandle(handle_); +} + +bool TextureGLES::Bind() const { + auto handle = GetGLHandle(); + if (!handle.has_value()) { + return false; + } + const auto& gl = reactor_->GetProcTable(); + + if (fence_.has_value()) { + std::optional fence = reactor_->GetGLFence(fence_.value()); + if (fence.has_value()) { + gl.WaitSync(fence.value(), 0, GL_TIMEOUT_IGNORED); + } + reactor_->CollectHandle(fence_.value()); + fence_ = std::nullopt; + } + + switch (type_) { + case Type::kTexture: + case Type::kTextureMultisampled: { + const auto target = ToTextureTarget(GetTextureDescriptor().type); + if (!target.has_value()) { + VALIDATION_LOG << "Could not bind texture of this type."; + return false; + } + gl.BindTexture(target.value(), handle.value()); + } break; + case Type::kRenderBuffer: + case Type::kRenderBufferMultisampled: + gl.BindRenderbuffer(GL_RENDERBUFFER, handle.value()); + break; + } + InitializeContentsIfNecessary(); + return true; +} + +void TextureGLES::MarkContentsInitialized() { + for (size_t i = 0; i < slices_initialized_.size(); i++) { + slices_initialized_[i] = true; + } +} + +void TextureGLES::MarkSliceInitialized(size_t slice) const { + slices_initialized_[slice] = true; +} + +bool TextureGLES::IsSliceInitialized(size_t slice) const { + return slices_initialized_[slice]; +} + +bool TextureGLES::GenerateMipmap() { + if (!IsValid()) { + return false; + } + + auto type = GetTextureDescriptor().type; + switch (type) { + case TextureType::kTexture2D: + break; + case TextureType::kTexture2DMultisample: + VALIDATION_LOG << "Generating mipmaps for multisample textures is not " + "supported in the GLES backend."; + return false; + case TextureType::kTextureCube: + break; + case TextureType::kTextureExternalOES: + break; + } + + if (!Bind()) { + return false; + } + + auto handle = GetGLHandle(); + if (!handle.has_value()) { + return false; + } + + const auto& gl = reactor_->GetProcTable(); + gl.GenerateMipmap(ToTextureType(type)); + mipmap_generated_ = true; + return true; +} + +TextureGLES::Type TextureGLES::GetType() const { + return type_; +} + +static GLenum ToAttachmentType(TextureGLES::AttachmentType point) { + switch (point) { + case TextureGLES::AttachmentType::kColor0: + return GL_COLOR_ATTACHMENT0; + case TextureGLES::AttachmentType::kDepth: + return GL_DEPTH_ATTACHMENT; + case TextureGLES::AttachmentType::kStencil: + return GL_STENCIL_ATTACHMENT; + } +} + +bool TextureGLES::SetAsFramebufferAttachment( + GLenum target, + AttachmentType attachment_type) const { + if (!IsValid()) { + return false; + } + InitializeContentsIfNecessary(); + auto handle = GetGLHandle(); + if (!handle.has_value()) { + return false; + } + const auto& gl = reactor_->GetProcTable(); + + switch (ComputeTypeForBinding(target)) { + case Type::kTexture: + gl.FramebufferTexture2D(target, // target + ToAttachmentType(attachment_type), // attachment + GL_TEXTURE_2D, // textarget + handle.value(), // texture + 0 // level + ); + break; + case Type::kTextureMultisampled: + gl.FramebufferTexture2DMultisampleEXT( + target, // target + ToAttachmentType(attachment_type), // attachment + GL_TEXTURE_2D, // textarget + handle.value(), // texture + 0, // level + 4 // samples + ); + break; + case Type::kRenderBuffer: + case Type::kRenderBufferMultisampled: + gl.FramebufferRenderbuffer( + target, // target + ToAttachmentType(attachment_type), // attachment + GL_RENDERBUFFER, // render-buffer target + handle.value() // render-buffer + ); + break; + } + + return true; +} + +// |Texture| +Scalar TextureGLES::GetYCoordScale() const { + switch (GetCoordinateSystem()) { + case TextureCoordinateSystem::kUploadFromHost: + return 1.0; + case TextureCoordinateSystem::kRenderToTexture: + return -1.0; + } + FML_UNREACHABLE(); +} + +bool TextureGLES::IsWrapped() const { + return is_wrapped_; +} + +std::optional TextureGLES::GetFBO() const { + return wrapped_fbo_; +} + +void TextureGLES::SetFence(HandleGLES fence) { + FML_DCHECK(!fence_.has_value()); + fence_ = fence; +} + +// Visible for testing. +std::optional TextureGLES::GetSyncFence() const { + return fence_; +} + +void TextureGLES::SetCachedFBO(HandleGLES fbo) { + cached_fbo_ = fbo; +} + +const HandleGLES& TextureGLES::GetCachedFBO() const { + return cached_fbo_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..c1feb9030e9b1cebb4c03ec106457e221832076e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/texture_gles.h @@ -0,0 +1,196 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEXTURE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEXTURE_GLES_H_ + +#include + +#include "fml/logging.h" +#include "impeller/base/backend_cast.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" + +namespace impeller { + +class TextureGLES final : public Texture, + public BackendCast { + public: + enum class Type { + kTexture, + kTextureMultisampled, + kRenderBuffer, + kRenderBufferMultisampled, + }; + + //---------------------------------------------------------------------------- + /// @brief Create a texture by wrapping an external framebuffer object + /// whose lifecycle is owned by the caller. + /// + /// This is useful for creating a render target for the default + /// window managed framebuffer. + /// + /// @param[in] reactor The reactor + /// @param[in] desc The description + /// @param[in] fbo The fbo + /// + /// @return If a texture representation of the framebuffer could be + /// created. + /// + static std::shared_ptr WrapFBO( + std::shared_ptr reactor, + TextureDescriptor desc, + GLuint fbo); + + //---------------------------------------------------------------------------- + /// @brief Create a texture by wrapping an external OpenGL texture + /// handle. Ownership of the texture handle is assumed by the + /// reactor. + /// + /// @param[in] reactor The reactor + /// @param[in] desc The description + /// @param[in] external_handle The external handle + /// + /// @return If a texture representation of the framebuffer could be + /// created. + /// + static std::shared_ptr WrapTexture( + std::shared_ptr reactor, + TextureDescriptor desc, + HandleGLES external_handle); + + //---------------------------------------------------------------------------- + /// @brief Create a "texture" that is never expected to be bound/unbound + /// explicitly or initialized in any way. It only exists to setup + /// a render pass description. + /// + /// @param[in] reactor The reactor + /// @param[in] desc The description + /// + /// @return If a texture placeholder could be created. + /// + static std::shared_ptr CreatePlaceholder( + std::shared_ptr reactor, + TextureDescriptor desc); + + TextureGLES(std::shared_ptr reactor, TextureDescriptor desc); + + // |Texture| + ~TextureGLES() override; + + // |Texture| + bool IsValid() const override; + + std::optional GetGLHandle() const; + + [[nodiscard]] bool Bind() const; + + [[nodiscard]] bool GenerateMipmap(); + + enum class AttachmentType { + kColor0, + kDepth, + kStencil, + }; + [[nodiscard]] bool SetAsFramebufferAttachment( + GLenum target, + AttachmentType attachment_type) const; + + Type GetType() const; + + bool IsWrapped() const; + + std::optional GetFBO() const; + + //---------------------------------------------------------------------------- + /// @brief Indicates that all texture storage has already been allocated + /// and contents initialized. + /// + /// This is similar to calling `MarkSliceInitialized` with all + /// slices. + /// + /// @see MarkSliceInitialized. + /// + void MarkContentsInitialized(); + + //---------------------------------------------------------------------------- + /// @brief Indicates that a specific texture slice has been initialized. + /// + /// @param[in] slice The slice to mark as being initialized. + /// + void MarkSliceInitialized(size_t slice) const; + + bool IsSliceInitialized(size_t slice) const; + + //---------------------------------------------------------------------------- + /// @brief Attach a sync fence to this texture that will be waited on + /// before encoding a rendering operation that references it. + /// + /// @param[in] fence A handle to a sync fence. + /// + void SetFence(HandleGLES fence); + + /// Store the FBO object for recycling in the 2D renderer. + /// + /// The color0 texture used by the 2D renderer will use this texture + /// object to store the associated FBO the first time it is used. + void SetCachedFBO(HandleGLES fbo); + + /// Retrieve the cached FBO object, or a dead handle if there is no object. + const HandleGLES& GetCachedFBO() const; + + // Visible for testing. + std::optional GetSyncFence() const; + + // visible for testing + Type ComputeTypeForBinding(GLenum target) const; + + private: + std::shared_ptr reactor_; + const Type type_; + HandleGLES handle_; + mutable std::optional fence_ = std::nullopt; + mutable std::bitset<6> slices_initialized_ = 0; + const bool is_wrapped_; + const std::optional wrapped_fbo_; + HandleGLES cached_fbo_ = HandleGLES::DeadHandle(); + bool is_valid_ = false; + + TextureGLES(std::shared_ptr reactor, + TextureDescriptor desc, + std::optional fbo, + std::optional external_handle); + + // |Texture| + void SetLabel(std::string_view label) override; + + // |Texture| + void SetLabel(std::string_view label, std::string_view trailing) override; + + // |Texture| + bool OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) override; + + // |Texture| + bool OnSetContents(std::shared_ptr mapping, + size_t slice) override; + + // |Texture| + ISize GetSize() const override; + + // |Texture| + Scalar GetYCoordScale() const override; + + void InitializeContentsIfNecessary() const; + + TextureGLES(const TextureGLES&) = delete; + + TextureGLES& operator=(const TextureGLES&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_TEXTURE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..d45dd4d79a5508ab046929871144a1c60626a2b9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.cc @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/gles/unique_handle_gles.h" + +#include + +namespace impeller { + +UniqueHandleGLES::UniqueHandleGLES(std::shared_ptr reactor, + HandleType type) + : reactor_(std::move(reactor)) { + if (reactor_) { + handle_ = reactor_->CreateHandle(type); + } +} + +// static +UniqueHandleGLES UniqueHandleGLES::MakeUntracked( + std::shared_ptr reactor, + HandleType type) { + FML_DCHECK(reactor); + HandleGLES handle = reactor->CreateUntrackedHandle(type); + return UniqueHandleGLES(std::move(reactor), handle); +} + +UniqueHandleGLES::UniqueHandleGLES(std::shared_ptr reactor, + HandleGLES handle) + : reactor_(std::move(reactor)), handle_(handle) {} + +UniqueHandleGLES::~UniqueHandleGLES() { + if (!handle_.IsDead() && reactor_) { + reactor_->CollectHandle(handle_); + } +} + +const HandleGLES& UniqueHandleGLES::Get() const { + return handle_; +} + +bool UniqueHandleGLES::IsValid() const { + return !handle_.IsDead(); +} + +UniqueHandleGLES::UniqueHandleGLES(UniqueHandleGLES&& other) { + std::swap(reactor_, other.reactor_); + std::swap(handle_, other.handle_); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.h b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..e5bbc33293bdcd95502d4153c99de1a63d9f535e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_UNIQUE_HANDLE_GLES_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_UNIQUE_HANDLE_GLES_H_ + +#include "impeller/renderer/backend/gles/handle_gles.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A unique handle to an OpenGL object. The collection of this +/// handle scheduled the destruction of the associated OpenGL object +/// in the reactor. +/// +class UniqueHandleGLES { + public: + UniqueHandleGLES(std::shared_ptr reactor, HandleType type); + + static UniqueHandleGLES MakeUntracked(std::shared_ptr reactor, + HandleType type); + + UniqueHandleGLES(std::shared_ptr reactor, HandleGLES handle); + + ~UniqueHandleGLES(); + + UniqueHandleGLES(UniqueHandleGLES&&); + + UniqueHandleGLES(const UniqueHandleGLES&) = delete; + + UniqueHandleGLES& operator=(const UniqueHandleGLES&) = delete; + + const HandleGLES& Get() const; + + bool IsValid() const; + + private: + std::shared_ptr reactor_ = nullptr; + HandleGLES handle_ = HandleGLES::DeadHandle(); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_UNIQUE_HANDLE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..01ddf037f11877406323411e8417bf3b5d826c18 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/gles/unique_handle_gles_unittests.cc @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/gles/reactor_gles.h" +#include "impeller/renderer/backend/gles/test/mock_gles.h" +#include "impeller/renderer/backend/gles/unique_handle_gles.h" + +namespace impeller { +namespace testing { + +using ::testing::_; + +namespace { +class TestWorker : public ReactorGLES::Worker { + public: + bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const override { + return true; + } +}; +} // namespace + +TEST(UniqueHandleGLES, MakeUntracked) { + auto mock_gles_impl = std::make_unique(); + + EXPECT_CALL(*mock_gles_impl, GenTextures(1, _)).Times(1); + + std::shared_ptr mock_gled = + MockGLES::Init(std::move(mock_gles_impl)); + ProcTableGLES::Resolver resolver = kMockResolverGLES; + auto proc_table = std::make_unique(resolver); + auto worker = std::make_shared(); + auto reactor = std::make_shared(std::move(proc_table)); + reactor->AddWorker(worker); + + UniqueHandleGLES handle = + UniqueHandleGLES::MakeUntracked(reactor, HandleType::kTexture); + EXPECT_FALSE(handle.Get().IsDead()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/BUILD.gn b/flutter/engine/src/flutter/impeller/renderer/backend/metal/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d7242b852e08ffaea355df9f511a64869c072d8c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/BUILD.gn @@ -0,0 +1,90 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../../../tools/impeller.gni") + +impeller_component("metal") { + sources = [ + "allocator_mtl.h", + "allocator_mtl.mm", + "blit_pass_mtl.h", + "blit_pass_mtl.mm", + "command_buffer_mtl.h", + "command_buffer_mtl.mm", + "compute_pass_bindings_cache_mtl.h", + "compute_pass_bindings_cache_mtl.mm", + "compute_pass_mtl.h", + "compute_pass_mtl.mm", + "compute_pipeline_mtl.h", + "compute_pipeline_mtl.mm", + "context_mtl.h", + "context_mtl.mm", + "device_buffer_mtl.h", + "device_buffer_mtl.mm", + "formats_mtl.h", + "formats_mtl.mm", + "gpu_tracer_mtl.h", + "gpu_tracer_mtl.mm", + "lazy_drawable_holder.h", + "lazy_drawable_holder.mm", + "pass_bindings_cache_mtl.h", + "pass_bindings_cache_mtl.mm", + "pipeline_library_mtl.h", + "pipeline_library_mtl.mm", + "pipeline_mtl.h", + "pipeline_mtl.mm", + "render_pass_mtl.h", + "render_pass_mtl.mm", + "sampler_library_mtl.h", + "sampler_library_mtl.mm", + "sampler_mtl.h", + "sampler_mtl.mm", + "shader_function_mtl.h", + "shader_function_mtl.mm", + "shader_library_mtl.h", + "shader_library_mtl.mm", + "surface_mtl.h", + "surface_mtl.mm", + "swapchain_transients_mtl.h", + "swapchain_transients_mtl.mm", + "texture_mtl.h", + "texture_mtl.mm", + "texture_wrapper_mtl.h", + "texture_wrapper_mtl.mm", + "vertex_descriptor_mtl.h", + "vertex_descriptor_mtl.mm", + ] + + public_deps = [ + "../../:renderer", + "//flutter/fml", + ] + + frameworks = [ + "Metal.framework", + "MetalPerformanceShaders.framework", + ] +} + +impeller_component("metal_unittests") { + testonly = true + + sources = [ + "allocator_mtl_unittests.mm", + "context_mtl_unittests.mm", + "swapchain_transients_mtl_unittests.mm", + "texture_mtl_unittests.mm", + ] + + deps = [ + ":metal", + "//flutter/impeller/playground:playground_test", + "//flutter/testing:testing_lib", + ] + + frameworks = [ + "AppKit.framework", + "QuartzCore.framework", + ] +} diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..4764c00b41900c7590bbc2f4b87cebaae31befec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.h @@ -0,0 +1,95 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_ + +#include +#include + +#include "impeller/base/thread.h" +#include "impeller/core/allocator.h" + +namespace impeller { + +class DebugAllocatorStats { + public: + DebugAllocatorStats() {} + + ~DebugAllocatorStats() {} + + /// Increment the tracked allocation size in bytes. + void Increment(size_t size); + + /// Decrement the tracked allocation size in bytes. + void Decrement(size_t size); + + /// Get the current tracked allocation size. + Bytes GetAllocationSize(); + + private: + std::atomic size_ = 0; +}; + +ISize DeviceMaxTextureSizeSupported(id device); + +class AllocatorMTL final : public Allocator { + public: + AllocatorMTL(); + + // |Allocator| + ~AllocatorMTL() override; + + // |Allocator| + Bytes DebugGetHeapUsage() const override; + + // visible for testing. + void DebugSetSupportsUMA(bool value); + + AllocatorMTL(id device, std::string label); + + private: + friend class ContextMTL; + + id device_; + std::string allocator_label_; + bool supports_memoryless_targets_ = false; + bool supports_uma_ = false; + bool is_valid_ = false; + +#ifdef IMPELLER_DEBUG + std::shared_ptr debug_allocater_ = + std::make_shared(); +#endif // IMPELLER_DEBUG + + ISize max_texture_supported_; + + // |Allocator| + bool IsValid() const; + + // |Allocator| + std::shared_ptr OnCreateBuffer( + const DeviceBufferDescriptor& desc) override; + + // |Allocator| + std::shared_ptr OnCreateTexture( + const TextureDescriptor& desc) override; + + // |Allocator| + uint16_t MinimumBytesPerRow(PixelFormat format) const override; + + // |Allocator| + ISize GetMaxTextureSizeSupported() const override; + + // |Allocator| + void DebugTraceMemoryStatistics() const override; + + AllocatorMTL(const AllocatorMTL&) = delete; + + AllocatorMTL& operator=(const AllocatorMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_ALLOCATOR_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..6233f249ec333457778ab50f8076d3f88a5efd32 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl.mm @@ -0,0 +1,279 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/allocator_mtl.h" + +#include "flutter/fml/build_config.h" +#include "flutter/fml/logging.h" +#include "fml/trace_event.h" +#include "impeller/base/allocation_size.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/metal/device_buffer_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" + +namespace impeller { + +static bool DeviceSupportsDeviceTransientTargets(id device) { + // Refer to the "Memoryless render targets" feature in the table below: + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + if (@available(ios 13.0, tvos 13.0, macos 10.15, *)) { + return [device supportsFamily:MTLGPUFamilyApple2]; + } else { +#if FML_OS_IOS + // This is perhaps redundant. But, just in case we somehow get into a case + // where Impeller runs on iOS versions less than 8.0 and/or without A8 + // GPUs, we explicitly check feature set support. + return [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1]; +#else + // MacOS devices with Apple GPUs are only available with macos 10.15 and + // above. So, if we are here, it is safe to assume that memory-less targets + // are not supported. + return false; +#endif + } + FML_UNREACHABLE(); +} + +static bool DeviceHasUnifiedMemoryArchitecture(id device) { + if (@available(ios 13.0, tvos 13.0, macOS 10.15, *)) { + return [device hasUnifiedMemory]; + } else { +#if FML_OS_IOS + // iOS devices where the availability check can fail always have had UMA. + return true; +#else + // Mac devices where the availability check can fail have never had UMA. + return false; +#endif + } + FML_UNREACHABLE(); +} + +ISize DeviceMaxTextureSizeSupported(id device) { + // Since Apple didn't expose API for us to get the max texture size, we have + // to use hardcoded data from + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + // According to the feature set table, there are two supported max sizes : + // 16384 and 8192 for devices flutter support. The former is used on macs and + // latest ios devices. The latter is used on old ios devices. + if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { + if ([device supportsFamily:MTLGPUFamilyApple3] || + [device supportsFamily:MTLGPUFamilyMacCatalyst1] || + [device supportsFamily:MTLGPUFamilyMac1]) { + return {16384, 16384}; + } + return {8192, 8192}; + } else { +#if FML_OS_IOS + if ([device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1] || + [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) { + return {16384, 16384}; + } +#endif +#if FML_OS_MACOSX + return {16384, 16384}; +#endif + return {8192, 8192}; + } +} + +static bool SupportsLossyTextureCompression(id device) { +#ifdef FML_OS_IOS_SIMULATOR + return false; +#else + if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { + return [device supportsFamily:MTLGPUFamilyApple8]; + } + return false; +#endif +} + +void DebugAllocatorStats::Increment(size_t size) { + size_.fetch_add(size, std::memory_order_relaxed); +} + +void DebugAllocatorStats::Decrement(size_t size) { + size_.fetch_sub(size, std::memory_order_relaxed); +} + +Bytes DebugAllocatorStats::GetAllocationSize() { + return Bytes{size_.load()}; +} + +AllocatorMTL::AllocatorMTL(id device, std::string label) + : device_(device), allocator_label_(std::move(label)) { + if (!device_) { + return; + } + + supports_memoryless_targets_ = DeviceSupportsDeviceTransientTargets(device_); + supports_uma_ = DeviceHasUnifiedMemoryArchitecture(device_); + max_texture_supported_ = DeviceMaxTextureSizeSupported(device_); + + is_valid_ = true; +} + +AllocatorMTL::~AllocatorMTL() = default; + +bool AllocatorMTL::IsValid() const { + return is_valid_; +} + +static MTLResourceOptions ToMTLResourceOptions(StorageMode type, + bool supports_memoryless_targets, + bool supports_uma) { + switch (type) { + case StorageMode::kHostVisible: +#if FML_OS_IOS + return MTLResourceStorageModeShared; +#else + if (supports_uma) { + return MTLResourceStorageModeShared; + } else { + return MTLResourceStorageModeManaged; + } +#endif + case StorageMode::kDevicePrivate: + return MTLResourceStorageModePrivate; + case StorageMode::kDeviceTransient: + if (supports_memoryless_targets) { + // Device may support but the OS has not been updated. + if (@available(macOS 11.0, *)) { + return MTLResourceStorageModeMemoryless; + } else { + return MTLResourceStorageModePrivate; + } + } else { + return MTLResourceStorageModePrivate; + } + FML_UNREACHABLE(); + } + FML_UNREACHABLE(); +} + +static MTLStorageMode ToMTLStorageMode(StorageMode mode, + bool supports_memoryless_targets, + bool supports_uma) { + switch (mode) { + case StorageMode::kHostVisible: +#if FML_OS_IOS + return MTLStorageModeShared; +#else + if (supports_uma) { + return MTLStorageModeShared; + } else { + return MTLStorageModeManaged; + } +#endif + case StorageMode::kDevicePrivate: + return MTLStorageModePrivate; + case StorageMode::kDeviceTransient: + if (supports_memoryless_targets) { + // Device may support but the OS has not been updated. + if (@available(macOS 11.0, *)) { + return MTLStorageModeMemoryless; + } else { + return MTLStorageModePrivate; + } + } else { + return MTLStorageModePrivate; + } + FML_UNREACHABLE(); + } + FML_UNREACHABLE(); +} + +std::shared_ptr AllocatorMTL::OnCreateBuffer( + const DeviceBufferDescriptor& desc) { + const auto resource_options = ToMTLResourceOptions( + desc.storage_mode, supports_memoryless_targets_, supports_uma_); + const auto storage_mode = ToMTLStorageMode( + desc.storage_mode, supports_memoryless_targets_, supports_uma_); + + auto buffer = [device_ newBufferWithLength:desc.size + options:resource_options]; + if (!buffer) { + return nullptr; + } + return std::shared_ptr(new DeviceBufferMTL(desc, // + buffer, // + storage_mode // + )); +} + +std::shared_ptr AllocatorMTL::OnCreateTexture( + const TextureDescriptor& desc) { + if (!IsValid()) { + return nullptr; + } + + auto mtl_texture_desc = ToMTLTextureDescriptor(desc); + + if (!mtl_texture_desc) { + VALIDATION_LOG << "Texture descriptor was invalid."; + return nullptr; + } + + mtl_texture_desc.storageMode = ToMTLStorageMode( + desc.storage_mode, supports_memoryless_targets_, supports_uma_); + + if (@available(macOS 12.5, ios 15.0, *)) { + if (desc.compression_type == CompressionType::kLossy && + SupportsLossyTextureCompression(device_)) { + mtl_texture_desc.compressionType = MTLTextureCompressionTypeLossy; + } + } + +#ifdef IMPELLER_DEBUG + if (desc.storage_mode != StorageMode::kDeviceTransient) { + debug_allocater_->Increment(desc.GetByteSizeOfAllMipLevels()); + } +#endif // IMPELLER_DEBUG + + auto texture = [device_ newTextureWithDescriptor:mtl_texture_desc]; + if (!texture) { + return nullptr; + } + std::shared_ptr result_texture = + TextureMTL::Create(desc, texture); +#ifdef IMPELLER_DEBUG + result_texture->SetDebugAllocator(debug_allocater_); +#endif // IMPELLER_DEBUG + + return result_texture; +} + +uint16_t AllocatorMTL::MinimumBytesPerRow(PixelFormat format) const { + return static_cast([device_ + minimumLinearTextureAlignmentForPixelFormat:ToMTLPixelFormat(format)]); +} + +ISize AllocatorMTL::GetMaxTextureSizeSupported() const { + return max_texture_supported_; +} + +void AllocatorMTL::DebugSetSupportsUMA(bool value) { + supports_uma_ = value; +} + +Bytes AllocatorMTL::DebugGetHeapUsage() const { +#ifdef IMPELLER_DEBUG + return debug_allocater_->GetAllocationSize(); +#else + return {}; +#endif // IMPELLER_DEBUG +} + +void AllocatorMTL::DebugTraceMemoryStatistics() const { +#ifdef IMPELLER_DEBUG + FML_TRACE_COUNTER("flutter", "AllocatorMTL", + reinterpret_cast(this), // Trace Counter ID + "MemoryBudgetUsageMB", + DebugGetHeapUsage().ConvertTo().GetSize()); +#endif // IMPELLER_DEBUG +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl_unittests.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..b490b3af13cf840439362ba98b5e36dafcb4b248 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/allocator_mtl_unittests.mm @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/metal/allocator_mtl.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/lazy_drawable_holder.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/capabilities.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +namespace impeller { +namespace testing { + +using AllocatorMTLTest = PlaygroundTest; +INSTANTIATE_METAL_PLAYGROUND_SUITE(AllocatorMTLTest); + +TEST_P(AllocatorMTLTest, DebugTraceMemoryStatistics) { + auto& context_mtl = ContextMTL::Cast(*GetContext()); + const auto& allocator = context_mtl.GetResourceAllocator(); + + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 0u); + + // Memoryless texture does not increase allocated size. + { + TextureDescriptor desc; + desc.format = PixelFormat::kR8G8B8A8UNormInt; + desc.storage_mode = StorageMode::kDeviceTransient; + desc.size = {1024, 1024}; + auto texture_1 = allocator->CreateTexture(desc); + + // Private storage texture increases allocated size. + desc.storage_mode = StorageMode::kDevicePrivate; + auto texture_2 = allocator->CreateTexture(desc); + +#ifdef IMPELLER_DEBUG + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 4u); +#else + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 0u); +#endif // IMPELLER_DEBUG + + // Host storage texture increases allocated size. + desc.storage_mode = StorageMode::kHostVisible; + auto texture_3 = allocator->CreateTexture(desc); + +#ifdef IMPELLER_DEBUG + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 8u); +#else + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 0u); +#endif // IMPELLER_DEBUG + } + + // After all textures are out of scope, memory has been decremented. + EXPECT_EQ(allocator->DebugGetHeapUsage().ConvertTo().GetSize(), + 0u); +} + +TEST_P(AllocatorMTLTest, ManagedMemory) { + auto& context_mtl = ContextMTL::Cast(*GetContext()); + auto allocator = std::make_unique(context_mtl.GetMTLDevice(), + "test-allocator"); + allocator->DebugSetSupportsUMA(false); + + DeviceBufferDescriptor desc; + desc.size = 100; + desc.storage_mode = StorageMode::kHostVisible; + + auto buffer = allocator->CreateBuffer(desc); + ASSERT_TRUE(buffer); + + EXPECT_NE(buffer->OnGetContents(), nullptr); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..d2aff0ca27c8475ca6690323582eac05d7576814 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.h @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_ + +#include + +#include "impeller/renderer/blit_pass.h" + +namespace impeller { + +class BlitPassMTL final : public BlitPass { + public: + // |RenderPass| + ~BlitPassMTL() override; + + private: + friend class CommandBufferMTL; + + id encoder_ = nil; + id buffer_ = nil; + id device_ = nil; + bool is_valid_ = false; + bool is_metal_trace_active_ = false; + // Many parts of the codebase will start writing to a render pass but + // never submit them. This boolean is used to track if a submit happened + // so that in the dtor we can always ensure the render pass is finished. + mutable bool did_finish_encoding_ = false; + + explicit BlitPassMTL(id buffer, id device); + + // |BlitPass| + bool IsValid() const override; + + // |BlitPass| + void OnSetLabel(std::string_view label) override; + + // |BlitPass| + bool EncodeCommands() const override; + + // |BlitPass| + bool ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) override; + + // |BlitPass| + bool OnCopyTextureToTextureCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) override; + + // |BlitPass| + bool OnCopyTextureToBufferCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) override; + // |BlitPass| + bool OnCopyBufferToTextureCommand(BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) override; + + // |BlitPass| + bool OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) override; + + BlitPassMTL(const BlitPassMTL&) = delete; + + BlitPassMTL& operator=(const BlitPassMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_PASS_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..8c814cef3bb771b8c46393268b4cc4a58a65c1de --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/blit_pass_mtl.mm @@ -0,0 +1,259 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/blit_pass_mtl.h" + +#include +#import +#include +#include +#include +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/backend_cast.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/metal/device_buffer_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/pipeline_mtl.h" +#include "impeller/renderer/backend/metal/sampler_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" + +#include "impeller/renderer/blit_command.h" + +namespace impeller { + +BlitPassMTL::BlitPassMTL(id buffer, id device) + : buffer_(buffer), device_(device) { + if (!buffer_) { + return; + } + encoder_ = [buffer_ blitCommandEncoder]; +#ifdef IMPELLER_DEBUG + is_metal_trace_active_ = + [[MTLCaptureManager sharedCaptureManager] isCapturing]; +#endif // IMPELLER_DEBUG + is_valid_ = true; +} + +BlitPassMTL::~BlitPassMTL() { + if (!did_finish_encoding_) { + [encoder_ endEncoding]; + } +} + +bool BlitPassMTL::IsValid() const { + return is_valid_; +} + +void BlitPassMTL::OnSetLabel(std::string_view label) { + if (label.empty()) { + return; + } + [encoder_ setLabel:@(label.data())]; +} + +bool BlitPassMTL::EncodeCommands() const { + [encoder_ endEncoding]; + did_finish_encoding_ = true; + return true; +} + +// |BlitPass| +bool BlitPassMTL::OnCopyTextureToTextureCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) { + auto source_mtl = TextureMTL::Cast(*source).GetMTLTexture(); + if (!source_mtl) { + return false; + } + + auto destination_mtl = TextureMTL::Cast(*destination).GetMTLTexture(); + if (!destination_mtl) { + return false; + } + + auto source_origin_mtl = + MTLOriginMake(source_region.GetX(), source_region.GetY(), 0); + auto source_size_mtl = + MTLSizeMake(source_region.GetWidth(), source_region.GetHeight(), 1); + auto destination_origin_mtl = + MTLOriginMake(destination_origin.x, destination_origin.y, 0); + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ pushDebugGroup:@(label.data())]; + } +#endif // IMPELLER_DEBUG + [encoder_ copyFromTexture:source_mtl + sourceSlice:0 + sourceLevel:0 + sourceOrigin:source_origin_mtl + sourceSize:source_size_mtl + toTexture:destination_mtl + destinationSlice:0 + destinationLevel:0 + destinationOrigin:destination_origin_mtl]; + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ popDebugGroup]; + } +#endif // IMPELLER_DEBUG + return true; +} + +// |BlitPass| +bool BlitPassMTL::ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) { + auto source_mtl = TextureMTL::Cast(*source).GetMTLTexture(); + if (!source_mtl) { + return false; + } + + auto destination_mtl = TextureMTL::Cast(*destination).GetMTLTexture(); + if (!destination_mtl) { + return false; + } + + [encoder_ endEncoding]; + auto filter = [[MPSImageBilinearScale alloc] initWithDevice:device_]; + [filter encodeToCommandBuffer:buffer_ + sourceTexture:source_mtl + destinationTexture:destination_mtl]; + encoder_ = [buffer_ blitCommandEncoder]; + return true; +} + +// |BlitPass| +bool BlitPassMTL::OnCopyTextureToBufferCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) { + auto source_mtl = TextureMTL::Cast(*source).GetMTLTexture(); + if (!source_mtl) { + return false; + } + + auto destination_mtl = DeviceBufferMTL::Cast(*destination).GetMTLBuffer(); + if (!destination_mtl) { + return false; + } + + auto source_origin_mtl = + MTLOriginMake(source_region.GetX(), source_region.GetY(), 0); + auto source_size_mtl = + MTLSizeMake(source_region.GetWidth(), source_region.GetHeight(), 1); + + auto destination_bytes_per_pixel = + BytesPerPixelForPixelFormat(source->GetTextureDescriptor().format); + auto destination_bytes_per_row = + source_size_mtl.width * destination_bytes_per_pixel; + auto destination_bytes_per_image = + source_size_mtl.height * destination_bytes_per_row; + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ pushDebugGroup:@(label.data())]; + } +#endif // IMPELLER_DEBUG + [encoder_ copyFromTexture:source_mtl + sourceSlice:0 + sourceLevel:0 + sourceOrigin:source_origin_mtl + sourceSize:source_size_mtl + toBuffer:destination_mtl + destinationOffset:destination_offset + destinationBytesPerRow:destination_bytes_per_row + destinationBytesPerImage:destination_bytes_per_image]; + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ popDebugGroup]; + } +#endif // IMPELLER_DEBUG + return true; +} + +bool BlitPassMTL::OnCopyBufferToTextureCommand( + BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) { + auto source_mtl = DeviceBufferMTL::Cast(*source.GetBuffer()).GetMTLBuffer(); + if (!source_mtl) { + return false; + } + + auto destination_mtl = TextureMTL::Cast(*destination).GetMTLTexture(); + if (!destination_mtl) { + return false; + } + + auto destination_origin_mtl = + MTLOriginMake(destination_region.GetX(), destination_region.GetY(), 0); + auto source_size_mtl = MTLSizeMake(destination_region.GetWidth(), + destination_region.GetHeight(), 1); + + auto destination_bytes_per_pixel = + BytesPerPixelForPixelFormat(destination->GetTextureDescriptor().format); + auto source_bytes_per_row = + destination_region.GetWidth() * destination_bytes_per_pixel; + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ pushDebugGroup:@(label.data())]; + } +#endif // IMPELLER_DEBUG + [encoder_ + copyFromBuffer:source_mtl + sourceOffset:source.GetRange().offset + sourceBytesPerRow:source_bytes_per_row + sourceBytesPerImage: + 0 // 0 for 2D textures according to + // https://developer.apple.com/documentation/metal/mtlblitcommandencoder/1400752-copyfrombuffer + sourceSize:source_size_mtl + toTexture:destination_mtl + destinationSlice:slice + destinationLevel:mip_level + destinationOrigin:destination_origin_mtl]; + +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ popDebugGroup]; + } +#endif // IMPELLER_DEBUG + return true; +} + +// |BlitPass| +bool BlitPassMTL::OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) { +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ pushDebugGroup:@(label.data())]; + } +#endif // IMPELLER_DEBUG + auto result = TextureMTL::Cast(*texture).GenerateMipmap(encoder_); +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + [encoder_ popDebugGroup]; + } +#endif // IMPELLER_DEBUG + return result; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..b43e919d4a05b7834252ea8efb6b74954157e774 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_ + +#include + +#include "impeller/core/allocator.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +class CommandBufferMTL final : public CommandBuffer { + public: + // |CommandBuffer| + ~CommandBufferMTL() override; + + private: + friend class ContextMTL; + + id buffer_ = nil; + id device_ = nil; + + CommandBufferMTL(const std::weak_ptr& context, + id device, + id queue); + + // |CommandBuffer| + void SetLabel(std::string_view label) const override; + + // |CommandBuffer| + bool IsValid() const override; + + // |CommandBuffer| + bool OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) override; + + // |CommandBuffer| + void OnWaitUntilCompleted() override; + + // |CommandBuffer| + void OnWaitUntilScheduled() override; + + // |CommandBuffer| + std::shared_ptr OnCreateRenderPass(RenderTarget target) override; + + // |CommandBuffer| + std::shared_ptr OnCreateBlitPass() override; + + // |CommandBuffer| + std::shared_ptr OnCreateComputePass() override; + + CommandBufferMTL(const CommandBufferMTL&) = delete; + + CommandBufferMTL& operator=(const CommandBufferMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMMAND_BUFFER_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..8b6e5a3e26d8387e0ba83714eda81c043ce5b486 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/command_buffer_mtl.mm @@ -0,0 +1,248 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/command_buffer_mtl.h" + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/synchronization/semaphore.h" + +#include "impeller/renderer/backend/metal/blit_pass_mtl.h" +#include "impeller/renderer/backend/metal/compute_pass_mtl.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/render_pass_mtl.h" + +namespace impeller { + +API_AVAILABLE(ios(14.0), macos(11.0)) +static NSString* MTLCommandEncoderErrorStateToString( + MTLCommandEncoderErrorState state) { + switch (state) { + case MTLCommandEncoderErrorStateUnknown: + return @"unknown"; + case MTLCommandEncoderErrorStateCompleted: + return @"completed"; + case MTLCommandEncoderErrorStateAffected: + return @"affected"; + case MTLCommandEncoderErrorStatePending: + return @"pending"; + case MTLCommandEncoderErrorStateFaulted: + return @"faulted"; + } + return @"unknown"; +} + +static NSString* MTLCommandBufferErrorToString(MTLCommandBufferError code) { + switch (code) { + case MTLCommandBufferErrorNone: + return @"none"; + case MTLCommandBufferErrorInternal: + return @"internal"; + case MTLCommandBufferErrorTimeout: + return @"timeout"; + case MTLCommandBufferErrorPageFault: + return @"page fault"; + case MTLCommandBufferErrorNotPermitted: + return @"not permitted"; + case MTLCommandBufferErrorOutOfMemory: + return @"out of memory"; + case MTLCommandBufferErrorInvalidResource: + return @"invalid resource"; + case MTLCommandBufferErrorMemoryless: + return @"memory-less"; + default: + break; + } + + return [NSString stringWithFormat:@" %zu", code]; +} + +static bool LogMTLCommandBufferErrorIfPresent(id buffer) { + if (!buffer) { + return true; + } + + if (buffer.status == MTLCommandBufferStatusCompleted) { + return true; + } + + std::stringstream stream; + stream << ">>>>>>>" << std::endl; + stream << "Impeller command buffer could not be committed!" << std::endl; + + if (auto desc = buffer.error.localizedDescription) { + stream << desc.UTF8String << std::endl; + } + + if (buffer.error) { + stream << "Domain: " + << (buffer.error.domain.length > 0u ? buffer.error.domain.UTF8String + : "") + << " Code: " + << MTLCommandBufferErrorToString( + static_cast(buffer.error.code)) + .UTF8String + << std::endl; + } + + if (@available(iOS 14.0, macOS 11.0, *)) { + NSArray>* infos = + buffer.error.userInfo[MTLCommandBufferEncoderInfoErrorKey]; + for (id info in infos) { + stream << (info.label.length > 0u ? info.label.UTF8String + : "") + << ": " + << MTLCommandEncoderErrorStateToString(info.errorState).UTF8String + << std::endl; + + auto signposts = [info.debugSignposts componentsJoinedByString:@", "]; + if (signposts.length > 0u) { + stream << signposts.UTF8String << std::endl; + } + } + + for (id log in buffer.logs) { + auto desc = log.description; + if (desc.length > 0u) { + stream << desc.UTF8String << std::endl; + } + } + } + + stream << "<<<<<<<"; + VALIDATION_LOG << stream.str(); + return false; +} + +static id CreateCommandBuffer(id queue) { +#ifndef FLUTTER_RELEASE + if (@available(iOS 14.0, macOS 11.0, *)) { + auto desc = [[MTLCommandBufferDescriptor alloc] init]; + // Degrades CPU performance slightly but is well worth the cost for typical + // Impeller workloads. + desc.errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus; + return [queue commandBufferWithDescriptor:desc]; + } +#endif // FLUTTER_RELEASE + return [queue commandBuffer]; +} + +CommandBufferMTL::CommandBufferMTL(const std::weak_ptr& context, + id device, + id queue) + : CommandBuffer(context), + buffer_(CreateCommandBuffer(queue)), + device_(device) {} + +CommandBufferMTL::~CommandBufferMTL() = default; + +bool CommandBufferMTL::IsValid() const { + return buffer_ != nil; +} + +void CommandBufferMTL::SetLabel(std::string_view label) const { +#ifdef IMPELLER_DEBUG + if (label.empty()) { + return; + } + + [buffer_ setLabel:@(label.data())]; +#endif // IMPELLER_DEBUG +} + +static CommandBuffer::Status ToCommitResult(MTLCommandBufferStatus status) { + switch (status) { + case MTLCommandBufferStatusCompleted: + return CommandBufferMTL::Status::kCompleted; + case MTLCommandBufferStatusEnqueued: + return CommandBufferMTL::Status::kPending; + default: + break; + } + return CommandBufferMTL::Status::kError; +} + +bool CommandBufferMTL::OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) { + auto context = context_.lock(); + if (!context) { + return false; + } +#ifdef IMPELLER_DEBUG + ContextMTL::Cast(*context).GetGPUTracer()->RecordCmdBuffer(buffer_); +#endif // IMPELLER_DEBUG + if (callback) { + [buffer_ + addCompletedHandler:^(id buffer) { + [[maybe_unused]] auto result = + LogMTLCommandBufferErrorIfPresent(buffer); + FML_DCHECK(result) + << "Must not have errors during command buffer submission."; + callback(ToCommitResult(buffer.status)); + }]; + } + + [buffer_ commit]; + if (block_on_schedule) { + [buffer_ waitUntilScheduled]; + } + + buffer_ = nil; + return true; +} + +void CommandBufferMTL::OnWaitUntilCompleted() {} + +void CommandBufferMTL::OnWaitUntilScheduled() {} + +std::shared_ptr CommandBufferMTL::OnCreateRenderPass( + RenderTarget target) { + if (!buffer_) { + return nullptr; + } + + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto pass = std::shared_ptr( + new RenderPassMTL(context, target, buffer_)); + if (!pass->IsValid()) { + return nullptr; + } + + return pass; +} + +std::shared_ptr CommandBufferMTL::OnCreateBlitPass() { + if (!buffer_) { + return nullptr; + } + + auto pass = std::shared_ptr(new BlitPassMTL(buffer_, device_)); + if (!pass->IsValid()) { + return nullptr; + } + + return pass; +} + +std::shared_ptr CommandBufferMTL::OnCreateComputePass() { + if (!buffer_) { + return nullptr; + } + auto context = context_.lock(); + if (!context) { + return nullptr; + } + + auto pass = + std::shared_ptr(new ComputePassMTL(context, buffer_)); + if (!pass->IsValid()) { + return nullptr; + } + + return pass; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..b97eb58058d0b66ff5e876e22319a6ae486b6752 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_ + +#include + +#include "impeller/renderer/compute_pass.h" +#include "impeller/renderer/pipeline_descriptor.h" + +namespace impeller { + +//----------------------------------------------------------------------------- +/// @brief Ensures that bindings on the pass are not redundantly set or +/// updated. Avoids making the driver do additional checks and makes +/// the frame insights during profiling and instrumentation not +/// complain about the same. +/// +/// There should be no change to rendering if this caching was +/// absent. +/// +struct ComputePassBindingsCacheMTL { + explicit ComputePassBindingsCacheMTL() {} + + ComputePassBindingsCacheMTL(const ComputePassBindingsCacheMTL&) = delete; + + ComputePassBindingsCacheMTL(ComputePassBindingsCacheMTL&&) = delete; + + void SetComputePipelineState(id pipeline); + + id GetPipeline() const; + + void SetEncoder(id encoder); + + void SetBuffer(uint64_t index, uint64_t offset, id buffer); + + void SetTexture(uint64_t index, id texture); + + void SetSampler(uint64_t index, id sampler); + + private: + struct BufferOffsetPair { + id buffer = nullptr; + size_t offset = 0u; + }; + using BufferMap = std::map; + using TextureMap = std::map>; + using SamplerMap = std::map>; + + id encoder_; + id pipeline_ = nullptr; + BufferMap buffers_; + TextureMap textures_; + SamplerMap samplers_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_BINDINGS_CACHE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..50e91e7ce95a114095ec3be934262d4e4b25f77e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.mm @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h" + +namespace impeller { + +void ComputePassBindingsCacheMTL::SetComputePipelineState( + id pipeline) { + if (pipeline == pipeline_) { + return; + } + pipeline_ = pipeline; + [encoder_ setComputePipelineState:pipeline_]; +} + +id ComputePassBindingsCacheMTL::GetPipeline() const { + return pipeline_; +} + +void ComputePassBindingsCacheMTL::SetEncoder( + id encoder) { + encoder_ = encoder; +} + +void ComputePassBindingsCacheMTL::SetBuffer(uint64_t index, + uint64_t offset, + id buffer) { + auto found = buffers_.find(index); + if (found != buffers_.end() && found->second.buffer == buffer) { + // The right buffer is bound. Check if its offset needs to be updated. + if (found->second.offset == offset) { + // Buffer and its offset is identical. Nothing to do. + return; + } + + // Only the offset needs to be updated. + found->second.offset = offset; + + [encoder_ setBufferOffset:offset atIndex:index]; + return; + } + + buffers_[index] = {buffer, static_cast(offset)}; + [encoder_ setBuffer:buffer offset:offset atIndex:index]; +} + +void ComputePassBindingsCacheMTL::SetTexture(uint64_t index, + id texture) { + auto found = textures_.find(index); + if (found != textures_.end() && found->second == texture) { + // Already bound. + return; + } + textures_[index] = texture; + [encoder_ setTexture:texture atIndex:index]; + return; +} + +void ComputePassBindingsCacheMTL::SetSampler(uint64_t index, + id sampler) { + auto found = samplers_.find(index); + if (found != samplers_.end() && found->second == sampler) { + // Already bound. + return; + } + samplers_[index] = sampler; + [encoder_ setSamplerState:sampler atIndex:index]; + return; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..1358ce1e4eeeb2eed19af0e7778c18869f06edaa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.h @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_ + +#include + +#include "impeller/renderer/backend/metal/compute_pass_bindings_cache_mtl.h" +#include "impeller/renderer/compute_pass.h" +#include "impeller/renderer/pipeline_descriptor.h" + +namespace impeller { + +class ComputePassMTL final : public ComputePass { + public: + // |RenderPass| + ~ComputePassMTL() override; + + private: + friend class CommandBufferMTL; + + id buffer_ = nil; + id encoder_ = nil; + ComputePassBindingsCacheMTL pass_bindings_cache_ = + ComputePassBindingsCacheMTL(); + bool is_valid_ = false; + bool has_label_ = false; + + ComputePassMTL(std::shared_ptr context, + id buffer); + + // |ComputePass| + bool IsValid() const override; + + // |ComputePass| + fml::Status Compute(const ISize& grid_size) override; + + // |ComputePass| + void SetCommandLabel(std::string_view label) override; + + // |ComputePass| + void OnSetLabel(const std::string& label) override; + + // |ComputePass| + void SetPipeline(const std::shared_ptr>& + pipeline) override; + + // |ComputePass| + bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + // |ComputePass| + bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + // |ComputePass| + bool EncodeCommands() const override; + + // |ComputePass| + void AddBufferMemoryBarrier() override; + + // |ComputePass| + void AddTextureMemoryBarrier() override; + + ComputePassMTL(const ComputePassMTL&) = delete; + + ComputePassMTL& operator=(const ComputePassMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PASS_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..c5bc526e8819545f484dfb6e8666771a83f0e5ee --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pass_mtl.mm @@ -0,0 +1,172 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/compute_pass_mtl.h" + +#include +#include + +#include "flutter/fml/backtrace.h" +#include "flutter/fml/closure.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "fml/status.h" +#include "impeller/base/backend_cast.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/metal/compute_pipeline_mtl.h" +#include "impeller/renderer/backend/metal/device_buffer_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/sampler_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/command.h" + +namespace impeller { + +ComputePassMTL::ComputePassMTL(std::shared_ptr context, + id buffer) + : ComputePass(std::move(context)), buffer_(buffer) { + if (!buffer_) { + return; + } + encoder_ = [buffer_ computeCommandEncoderWithDispatchType: + MTLDispatchType::MTLDispatchTypeConcurrent]; + if (!encoder_) { + return; + } + pass_bindings_cache_.SetEncoder(encoder_); + is_valid_ = true; +} + +ComputePassMTL::~ComputePassMTL() = default; + +bool ComputePassMTL::IsValid() const { + return is_valid_; +} + +void ComputePassMTL::OnSetLabel(const std::string& label) { +#ifdef IMPELLER_DEBUG + if (label.empty()) { + return; + } + [encoder_ setLabel:@(label.c_str())]; +#endif // IMPELLER_DEBUG +} + +void ComputePassMTL::SetCommandLabel(std::string_view label) { + has_label_ = true; + [encoder_ pushDebugGroup:@(label.data())]; +} + +// |ComputePass| +void ComputePassMTL::SetPipeline( + const std::shared_ptr>& pipeline) { + pass_bindings_cache_.SetComputePipelineState( + ComputePipelineMTL::Cast(*pipeline).GetMTLComputePipelineState()); +} + +// |ComputePass| +void ComputePassMTL::AddBufferMemoryBarrier() { + [encoder_ memoryBarrierWithScope:MTLBarrierScopeBuffers]; +} + +// |ComputePass| +void ComputePassMTL::AddTextureMemoryBarrier() { + [encoder_ memoryBarrierWithScope:MTLBarrierScopeTextures]; +} + +// |ComputePass| +bool ComputePassMTL::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + if (!view.GetBuffer()) { + return false; + } + + const DeviceBuffer* device_buffer = view.GetBuffer(); + if (!device_buffer) { + return false; + } + + id buffer = DeviceBufferMTL::Cast(*device_buffer).GetMTLBuffer(); + // The Metal call is a void return and we don't want to make it on nil. + if (!buffer) { + return false; + } + + pass_bindings_cache_.SetBuffer(slot.ext_res_0, view.GetRange().offset, + buffer); + return true; +} + +// |ComputePass| +bool ComputePassMTL::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (!sampler || !texture->IsValid()) { + return false; + } + + pass_bindings_cache_.SetTexture(slot.texture_index, + TextureMTL::Cast(*texture).GetMTLTexture()); + pass_bindings_cache_.SetSampler( + slot.texture_index, SamplerMTL::Cast(*sampler).GetMTLSamplerState()); + return true; +} + +fml::Status ComputePassMTL::Compute(const ISize& grid_size) { + if (grid_size.IsEmpty()) { + return fml::Status(fml::StatusCode::kUnknown, + "Invalid grid size for compute command."); + } + + // Threadgroup sizes must be uniform. + auto width = grid_size.width; + auto height = grid_size.height; + + auto max_total_threads_per_threadgroup = static_cast( + pass_bindings_cache_.GetPipeline().maxTotalThreadsPerThreadgroup); + + // Special case for linear processing. + if (height == 1) { + int64_t thread_groups = std::max( + static_cast( + std::ceil(width * 1.0 / max_total_threads_per_threadgroup * 1.0)), + 1LL); + [encoder_ + dispatchThreadgroups:MTLSizeMake(thread_groups, 1, 1) + threadsPerThreadgroup:MTLSizeMake(max_total_threads_per_threadgroup, 1, + 1)]; + } else { + while (width * height > max_total_threads_per_threadgroup) { + width = std::max(1LL, width / 2); + height = std::max(1LL, height / 2); + } + + auto size = MTLSizeMake(width, height, 1); + [encoder_ dispatchThreadgroups:size threadsPerThreadgroup:size]; + } + +#ifdef IMPELLER_DEBUG + if (has_label_) { + [encoder_ popDebugGroup]; + } + has_label_ = false; +#endif // IMPELLER_DEBUG + return fml::Status(); +} + +bool ComputePassMTL::EncodeCommands() const { + [encoder_ endEncoding]; + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..36c1e67460cf229ee9b72cd48e550137c018a28b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +class ComputePipelineMTL final + : public Pipeline, + public BackendCast> { + public: + // |Pipeline| + ~ComputePipelineMTL() override; + + id GetMTLComputePipelineState() const; + + private: + friend class PipelineLibraryMTL; + + id pipeline_state_; + bool is_valid_ = false; + + ComputePipelineMTL(std::weak_ptr library, + const ComputePipelineDescriptor& desc, + id state); + + // |Pipeline| + bool IsValid() const override; + + ComputePipelineMTL(const ComputePipelineMTL&) = delete; + + ComputePipelineMTL& operator=(const ComputePipelineMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_COMPUTE_PIPELINE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..912b065b931667e221739a45446edca8dc12ddbb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/compute_pipeline_mtl.mm @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/compute_pipeline_mtl.h" + +namespace impeller { + +ComputePipelineMTL::ComputePipelineMTL(std::weak_ptr library, + const ComputePipelineDescriptor& desc, + id state) + : Pipeline(std::move(library), desc), pipeline_state_(state) { + if (!pipeline_state_) { + return; + } + is_valid_ = true; +} + +ComputePipelineMTL::~ComputePipelineMTL() = default; + +bool ComputePipelineMTL::IsValid() const { + return is_valid_; +} + +id ComputePipelineMTL::GetMTLComputePipelineState() + const { + return pipeline_state_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..348830d0fe7eea33d0ac2f5d030f3ee1381ecc53 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.h @@ -0,0 +1,204 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_CONTEXT_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_CONTEXT_MTL_H_ + +#include + +#include +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "fml/closure.h" +#include "impeller/base/backend_cast.h" +#include "impeller/core/sampler.h" +#include "impeller/renderer/backend/metal/allocator_mtl.h" +#include "impeller/renderer/backend/metal/command_buffer_mtl.h" +#include "impeller/renderer/backend/metal/gpu_tracer_mtl.h" +#include "impeller/renderer/backend/metal/pipeline_library_mtl.h" +#include "impeller/renderer/backend/metal/shader_library_mtl.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/context.h" + +#if TARGET_OS_SIMULATOR +#define IMPELLER_CA_METAL_LAYER_AVAILABLE API_AVAILABLE(macos(10.11), ios(13.0)) +#else // TARGET_OS_SIMULATOR +#define IMPELLER_CA_METAL_LAYER_AVAILABLE API_AVAILABLE(macos(10.11), ios(8.0)) +#endif // TARGET_OS_SIMULATOR + +namespace impeller { + +/// @brief Creates and manages a Metal capture scope that supports frame capture +/// when using the FlutterMetalLayer backed drawable. +class ImpellerMetalCaptureManager { + public: + /// @brief Construct a new capture manager from the provided Metal device. + explicit ImpellerMetalCaptureManager(id device); + + ~ImpellerMetalCaptureManager() = default; + + /// Whether or not the Impeller capture scope is active. + /// + /// This is distinct from whether or not there is a session recording the + /// capture. That can be checked with `[[MTLCaptureManager + /// sharedCaptureManager] isCapturing].` + bool CaptureScopeActive() const; + + /// @brief Begin a new capture scope, no-op if the scope has already started. + void StartCapture(); + + /// @brief End the current capture scope. + void FinishCapture(); + + private: + id current_capture_scope_; + bool scope_active_ = false; + + ImpellerMetalCaptureManager(const ImpellerMetalCaptureManager&) = default; + ImpellerMetalCaptureManager(ImpellerMetalCaptureManager&&) = delete; +}; + +class ContextMTL final : public Context, + public BackendCast, + public std::enable_shared_from_this { + public: + static std::shared_ptr Create( + const Flags& flags, + const std::vector& shader_library_paths, + std::shared_ptr is_gpu_disabled_sync_switch); + + static std::shared_ptr Create( + const Flags& flags, + const std::vector>& shader_libraries_data, + std::shared_ptr is_gpu_disabled_sync_switch, + const std::string& label, + std::optional pixel_format_override = std::nullopt); + + static std::shared_ptr Create( + const Flags& flags, + id device, + id command_queue, + const std::vector>& shader_libraries_data, + std::shared_ptr is_gpu_disabled_sync_switch, + const std::string& label); + + // |Context| + ~ContextMTL() override; + + // |Context| + BackendType GetBackendType() const override; + + id GetMTLDevice() const; + + // |Context| + std::string DescribeGpuModel() const override; + + // |Context| + bool IsValid() const override; + + // |Context| + std::shared_ptr GetResourceAllocator() const override; + + // |Context| + std::shared_ptr GetShaderLibrary() const override; + + // |Context| + std::shared_ptr GetSamplerLibrary() const override; + + // |Context| + std::shared_ptr GetPipelineLibrary() const override; + + // |Context| + std::shared_ptr CreateCommandBuffer() const override; + + // |Context| + std::shared_ptr GetCommandQueue() const override; + + // |Context| + const std::shared_ptr& GetCapabilities() const override; + + // |Context| + RuntimeStageBackend GetRuntimeStageBackend() const override; + + void SetCapabilities(const std::shared_ptr& capabilities); + + // |Context| + bool UpdateOffscreenLayerPixelFormat(PixelFormat format) override; + + // |Context| + void Shutdown() override; + + id CreateMTLCommandBuffer(const std::string& label) const; + + std::shared_ptr GetIsGpuDisabledSyncSwitch() const; + +#ifdef IMPELLER_DEBUG + std::shared_ptr GetGPUTracer() const; + + const std::shared_ptr GetCaptureManager() const; +#endif // IMPELLER_DEBUG + + // |Context| + void StoreTaskForGPU(const fml::closure& task, + const fml::closure& failure) override; + + // visible for testing. + void FlushTasksAwaitingGPU(); + + private: + class SyncSwitchObserver : public fml::SyncSwitch::Observer { + public: + explicit SyncSwitchObserver(ContextMTL& parent); + virtual ~SyncSwitchObserver() = default; + void OnSyncSwitchUpdate(bool new_value) override; + + private: + ContextMTL& parent_; + }; + + struct PendingTasks { + fml::closure task; + fml::closure failure; + }; + + id device_ = nullptr; + id command_queue_ = nullptr; + std::shared_ptr shader_library_; + std::shared_ptr pipeline_library_; + std::shared_ptr sampler_library_; + std::shared_ptr resource_allocator_; + std::shared_ptr device_capabilities_; + std::shared_ptr is_gpu_disabled_sync_switch_; + Mutex tasks_awaiting_gpu_mutex_; + std::deque tasks_awaiting_gpu_ IPLR_GUARDED_BY( + tasks_awaiting_gpu_mutex_); + std::unique_ptr sync_switch_observer_; + std::shared_ptr command_queue_ip_; +#ifdef IMPELLER_DEBUG + std::shared_ptr gpu_tracer_; + std::shared_ptr capture_manager_; +#endif // IMPELLER_DEBUG + bool is_valid_ = false; + + ContextMTL(const Flags& flags, + id device, + id command_queue, + NSArray>* shader_libraries, + std::shared_ptr is_gpu_disabled_sync_switch, + std::optional pixel_format_override = std::nullopt); + + std::shared_ptr CreateCommandBufferInQueue( + id queue) const; + + ContextMTL(const ContextMTL&) = delete; + + ContextMTL& operator=(const ContextMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_CONTEXT_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..1f3bcb073a016997d5ca126fdd0a81bd69dd14ea --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl.mm @@ -0,0 +1,504 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/context_mtl.h" +#include + +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/file.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/paths.h" +#include "flutter/fml/synchronization/sync_switch.h" +#include "impeller/core/formats.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/metal/gpu_tracer_mtl.h" +#include "impeller/renderer/backend/metal/sampler_library_mtl.h" +#include "impeller/renderer/capabilities.h" + +namespace impeller { + +static bool DeviceSupportsFramebufferFetch(id device) { + // The iOS simulator lies about supporting framebuffer fetch. +#if FML_OS_IOS_SIMULATOR + return false; +#else // FML_OS_IOS_SIMULATOR + + if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { + return [device supportsFamily:MTLGPUFamilyApple2]; + } + // According to + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf , Apple2 + // corresponds to iOS GPU family 2, which supports A8 devices. +#if FML_OS_IOS + return [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1]; +#else + return false; +#endif // FML_OS_IOS +#endif // FML_OS_IOS_SIMULATOR +} + +static bool DeviceSupportsComputeSubgroups(id device) { + bool supports_subgroups = false; + // Refer to the "SIMD-scoped reduction operations" feature in the table + // below: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + if (@available(ios 13.0, tvos 13.0, macos 10.15, *)) { + supports_subgroups = [device supportsFamily:MTLGPUFamilyApple7] || + [device supportsFamily:MTLGPUFamilyMac2]; + } + return supports_subgroups; +} + +// See "Extended Range and wide color pixel formats" in the metal feature set +// tables. +static bool DeviceSupportsExtendedRangeFormats(id device) { + if (@available(macOS 10.15, iOS 13, tvOS 13, *)) { + return [device supportsFamily:MTLGPUFamilyApple3]; + } + return false; +} + +static std::unique_ptr InferMetalCapabilities( + id device, + PixelFormat color_format) { + return CapabilitiesBuilder() + .SetSupportsOffscreenMSAA(true) + .SetSupportsSSBO(true) + .SetSupportsTextureToTextureBlits(true) + .SetSupportsDecalSamplerAddressMode(true) + .SetSupportsFramebufferFetch(DeviceSupportsFramebufferFetch(device)) + .SetDefaultColorFormat(color_format) + .SetDefaultStencilFormat(PixelFormat::kS8UInt) + .SetDefaultDepthStencilFormat(PixelFormat::kD32FloatS8UInt) + .SetSupportsCompute(true) + .SetSupportsComputeSubgroups(DeviceSupportsComputeSubgroups(device)) + .SetSupportsReadFromResolve(true) + .SetSupportsDeviceTransientTextures(true) + .SetDefaultGlyphAtlasFormat(PixelFormat::kA8UNormInt) + .SetSupportsTriangleFan(false) + .SetMaximumRenderPassAttachmentSize(DeviceMaxTextureSizeSupported(device)) + .SetSupportsExtendedRangeFormats( + DeviceSupportsExtendedRangeFormats(device)) + .Build(); +} + +ContextMTL::ContextMTL( + const Flags& flags, + id device, + id command_queue, + NSArray>* shader_libraries, + std::shared_ptr is_gpu_disabled_sync_switch, + std::optional pixel_format_override) + : Context(flags), + device_(device), + command_queue_(command_queue), + is_gpu_disabled_sync_switch_(std::move(is_gpu_disabled_sync_switch)) { + // Validate device. + if (!device_) { + VALIDATION_LOG << "Could not set up valid Metal device."; + return; + } + + sync_switch_observer_.reset(new SyncSwitchObserver(*this)); + is_gpu_disabled_sync_switch_->AddObserver(sync_switch_observer_.get()); + + // Setup the shader library. + { + if (shader_libraries == nil) { + VALIDATION_LOG << "Shader libraries were null."; + return; + } + + // std::make_shared disallowed because of private friend ctor. + auto library = std::shared_ptr( + new ShaderLibraryMTL(shader_libraries)); + if (!library->IsValid()) { + VALIDATION_LOG << "Could not create valid Metal shader library."; + return; + } + shader_library_ = std::move(library); + } + + // Setup the pipeline library. + { + pipeline_library_ = + std::shared_ptr(new PipelineLibraryMTL(device_)); + } + + // Setup the sampler library. + { + sampler_library_ = + std::shared_ptr(new SamplerLibraryMTL(device_)); + } + + // Setup the resource allocator. + { + resource_allocator_ = std::shared_ptr( + new AllocatorMTL(device_, "Impeller Permanents Allocator")); + if (!resource_allocator_) { + VALIDATION_LOG << "Could not set up the resource allocator."; + return; + } + } + + device_capabilities_ = + InferMetalCapabilities(device_, pixel_format_override.has_value() + ? pixel_format_override.value() + : PixelFormat::kB8G8R8A8UNormInt); + command_queue_ip_ = std::make_shared(); +#ifdef IMPELLER_DEBUG + gpu_tracer_ = std::make_shared(); + capture_manager_ = std::make_shared(device_); +#endif // IMPELLER_DEBUG + is_valid_ = true; +} + +static NSArray>* MTLShaderLibraryFromFilePaths( + id device, + const std::vector& libraries_paths) { + NSMutableArray>* found_libraries = [NSMutableArray array]; + for (const auto& library_path : libraries_paths) { + if (!fml::IsFile(library_path)) { + VALIDATION_LOG << "Shader library does not exist at path '" + << library_path << "'"; + return nil; + } + NSError* shader_library_error = nil; + auto library = [device newLibraryWithFile:@(library_path.c_str()) + error:&shader_library_error]; + if (!library) { + FML_LOG(ERROR) << "Could not create shader library: " + << shader_library_error.localizedDescription.UTF8String; + return nil; + } + [found_libraries addObject:library]; + } + return found_libraries; +} + +static NSArray>* MTLShaderLibraryFromFileData( + id device, + const std::vector>& libraries_data, + const std::string& label) { + NSMutableArray>* found_libraries = [NSMutableArray array]; + for (const auto& library_data : libraries_data) { + if (library_data == nullptr) { + FML_LOG(ERROR) << "Shader library data was null."; + return nil; + } + + __block auto data = library_data; + + auto dispatch_data = + ::dispatch_data_create(library_data->GetMapping(), // buffer + library_data->GetSize(), // size + dispatch_get_main_queue(), // queue + ^() { + // We just need a reference. + data.reset(); + } // destructor + ); + if (!dispatch_data) { + FML_LOG(ERROR) << "Could not wrap shader data in dispatch data."; + return nil; + } + + NSError* shader_library_error = nil; + auto library = [device newLibraryWithData:dispatch_data + error:&shader_library_error]; + if (!library) { + FML_LOG(ERROR) << "Could not create shader library: " + << shader_library_error.localizedDescription.UTF8String; + return nil; + } + if (!label.empty()) { + library.label = @(label.c_str()); + } + [found_libraries addObject:library]; + } + return found_libraries; +} + +static id CreateMetalDevice() { + return ::MTLCreateSystemDefaultDevice(); +} + +static id CreateMetalCommandQueue(id device) { + auto command_queue = device.newCommandQueue; + if (!command_queue) { + VALIDATION_LOG << "Could not set up the command queue."; + return nullptr; + } + command_queue.label = @"Impeller Command Queue"; + return command_queue; +} + +std::shared_ptr ContextMTL::Create( + const Flags& flags, + const std::vector& shader_library_paths, + std::shared_ptr is_gpu_disabled_sync_switch) { + auto device = CreateMetalDevice(); + auto command_queue = CreateMetalCommandQueue(device); + if (!command_queue) { + return nullptr; + } + auto context = std::shared_ptr(new ContextMTL( + flags, device, command_queue, + MTLShaderLibraryFromFilePaths(device, shader_library_paths), + std::move(is_gpu_disabled_sync_switch))); + if (!context->IsValid()) { + FML_LOG(ERROR) << "Could not create Metal context."; + return nullptr; + } + return context; +} + +std::shared_ptr ContextMTL::Create( + const Flags& flags, + const std::vector>& shader_libraries_data, + std::shared_ptr is_gpu_disabled_sync_switch, + const std::string& library_label, + std::optional pixel_format_override) { + auto device = CreateMetalDevice(); + auto command_queue = CreateMetalCommandQueue(device); + if (!command_queue) { + return nullptr; + } + auto context = std::shared_ptr(new ContextMTL( + flags, device, command_queue, + MTLShaderLibraryFromFileData(device, shader_libraries_data, + library_label), + std::move(is_gpu_disabled_sync_switch), pixel_format_override)); + if (!context->IsValid()) { + FML_LOG(ERROR) << "Could not create Metal context."; + return nullptr; + } + return context; +} + +std::shared_ptr ContextMTL::Create( + const Flags& flags, + id device, + id command_queue, + const std::vector>& shader_libraries_data, + std::shared_ptr is_gpu_disabled_sync_switch, + const std::string& library_label) { + auto context = std::shared_ptr( + new ContextMTL(flags, device, command_queue, + MTLShaderLibraryFromFileData(device, shader_libraries_data, + library_label), + std::move(is_gpu_disabled_sync_switch))); + if (!context->IsValid()) { + FML_LOG(ERROR) << "Could not create Metal context."; + return nullptr; + } + return context; +} + +ContextMTL::~ContextMTL() { + is_gpu_disabled_sync_switch_->RemoveObserver(sync_switch_observer_.get()); +} + +Context::BackendType ContextMTL::GetBackendType() const { + return Context::BackendType::kMetal; +} + +// |Context| +std::string ContextMTL::DescribeGpuModel() const { + return std::string([[device_ name] UTF8String]); +} + +// |Context| +bool ContextMTL::IsValid() const { + return is_valid_; +} + +// |Context| +std::shared_ptr ContextMTL::GetShaderLibrary() const { + return shader_library_; +} + +// |Context| +std::shared_ptr ContextMTL::GetPipelineLibrary() const { + return pipeline_library_; +} + +// |Context| +std::shared_ptr ContextMTL::GetSamplerLibrary() const { + return sampler_library_; +} + +// |Context| +std::shared_ptr ContextMTL::CreateCommandBuffer() const { + return CreateCommandBufferInQueue(command_queue_); +} + +// |Context| +void ContextMTL::Shutdown() {} + +#ifdef IMPELLER_DEBUG +std::shared_ptr ContextMTL::GetGPUTracer() const { + return gpu_tracer_; +} +#endif // IMPELLER_DEBUG + +std::shared_ptr ContextMTL::GetIsGpuDisabledSyncSwitch() + const { + return is_gpu_disabled_sync_switch_; +} + +std::shared_ptr ContextMTL::CreateCommandBufferInQueue( + id queue) const { + if (!IsValid()) { + return nullptr; + } + + auto buffer = std::shared_ptr( + new CommandBufferMTL(weak_from_this(), device_, queue)); + if (!buffer->IsValid()) { + return nullptr; + } + return buffer; +} + +std::shared_ptr ContextMTL::GetResourceAllocator() const { + return resource_allocator_; +} + +id ContextMTL::GetMTLDevice() const { + return device_; +} + +const std::shared_ptr& ContextMTL::GetCapabilities() const { + return device_capabilities_; +} + +void ContextMTL::SetCapabilities( + const std::shared_ptr& capabilities) { + device_capabilities_ = capabilities; +} + +// |Context| +bool ContextMTL::UpdateOffscreenLayerPixelFormat(PixelFormat format) { + device_capabilities_ = InferMetalCapabilities(device_, format); + return true; +} + +id ContextMTL::CreateMTLCommandBuffer( + const std::string& label) const { + auto buffer = [command_queue_ commandBuffer]; + if (!label.empty()) { + [buffer setLabel:@(label.data())]; + } + return buffer; +} + +void ContextMTL::StoreTaskForGPU(const fml::closure& task, + const fml::closure& failure) { + std::vector failed_tasks; + { + Lock lock(tasks_awaiting_gpu_mutex_); + tasks_awaiting_gpu_.push_back(PendingTasks{task, failure}); + int32_t failed_task_count = + tasks_awaiting_gpu_.size() - kMaxTasksAwaitingGPU; + if (failed_task_count > 0) { + failed_tasks.reserve(failed_task_count); + failed_tasks.insert(failed_tasks.end(), + std::make_move_iterator(tasks_awaiting_gpu_.begin()), + std::make_move_iterator(tasks_awaiting_gpu_.begin() + + failed_task_count)); + tasks_awaiting_gpu_.erase( + tasks_awaiting_gpu_.begin(), + tasks_awaiting_gpu_.begin() + failed_task_count); + } + } + for (const PendingTasks& task : failed_tasks) { + if (task.failure) { + task.failure(); + } + } +} + +void ContextMTL::FlushTasksAwaitingGPU() { + std::deque tasks_awaiting_gpu; + { + Lock lock(tasks_awaiting_gpu_mutex_); + std::swap(tasks_awaiting_gpu, tasks_awaiting_gpu_); + } + std::vector tasks_to_queue; + for (const auto& task : tasks_awaiting_gpu) { + is_gpu_disabled_sync_switch_->Execute(fml::SyncSwitch::Handlers() + .SetIfFalse([&] { task.task(); }) + .SetIfTrue([&] { + // Lost access to the GPU + // immediately after it was + // activated. This may happen if + // the app was quickly + // foregrounded/backgrounded + // from a push notification. + // Store the tasks on the + // context again. + tasks_to_queue.push_back(task); + })); + } + if (!tasks_to_queue.empty()) { + Lock lock(tasks_awaiting_gpu_mutex_); + tasks_awaiting_gpu_.insert(tasks_awaiting_gpu_.end(), + tasks_to_queue.begin(), tasks_to_queue.end()); + } +} + +ContextMTL::SyncSwitchObserver::SyncSwitchObserver(ContextMTL& parent) + : parent_(parent) {} + +void ContextMTL::SyncSwitchObserver::OnSyncSwitchUpdate(bool new_is_disabled) { + if (!new_is_disabled) { + parent_.FlushTasksAwaitingGPU(); + } +} + +// |Context| +std::shared_ptr ContextMTL::GetCommandQueue() const { + return command_queue_ip_; +} + +// |Context| +RuntimeStageBackend ContextMTL::GetRuntimeStageBackend() const { + return RuntimeStageBackend::kMetal; +} + +#ifdef IMPELLER_DEBUG +const std::shared_ptr +ContextMTL::GetCaptureManager() const { + return capture_manager_; +} +#endif // IMPELLER_DEBUG + +ImpellerMetalCaptureManager::ImpellerMetalCaptureManager(id device) { + current_capture_scope_ = [[MTLCaptureManager sharedCaptureManager] + newCaptureScopeWithDevice:device]; + [current_capture_scope_ setLabel:@"Impeller Frame"]; +} + +bool ImpellerMetalCaptureManager::CaptureScopeActive() const { + return scope_active_; +} + +void ImpellerMetalCaptureManager::StartCapture() { + if (scope_active_) { + return; + } + scope_active_ = true; + [current_capture_scope_ beginScope]; +} + +void ImpellerMetalCaptureManager::FinishCapture() { + FML_DCHECK(scope_active_); + [current_capture_scope_ endScope]; + scope_active_ = false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl_unittests.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..cb3ee72e599f7c9af605158d251c102bd2090524 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/context_mtl_unittests.mm @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/metal/allocator_mtl.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/capabilities.h" + +#include +#include +#include + +#include "gtest/gtest.h" + +namespace impeller { +namespace testing { + +using ContextMTLTest = PlaygroundTest; +INSTANTIATE_METAL_PLAYGROUND_SUITE(ContextMTLTest); + +TEST_P(ContextMTLTest, FlushTask) { + auto& context_mtl = ContextMTL::Cast(*GetContext()); + + int executed = 0; + int failed = 0; + context_mtl.StoreTaskForGPU([&]() { executed++; }, [&]() { failed++; }); + + context_mtl.FlushTasksAwaitingGPU(); + + EXPECT_EQ(executed, 1); + EXPECT_EQ(failed, 0); +} + +TEST_P(ContextMTLTest, FlushTaskWithGPULoss) { + auto& context_mtl = ContextMTL::Cast(*GetContext()); + + int executed = 0; + int failed = 0; + context_mtl.StoreTaskForGPU([&]() { executed++; }, [&]() { failed++; }); + + // If tasks are flushed while the GPU is disabled, then + // they should not be executed. + SetGPUDisabled(/*disabled=*/true); + context_mtl.FlushTasksAwaitingGPU(); + + EXPECT_EQ(executed, 0); + EXPECT_EQ(failed, 0); + + // Toggling availibility should flush tasks. + SetGPUDisabled(/*disabled=*/false); + + EXPECT_EQ(executed, 1); + EXPECT_EQ(failed, 0); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..dbc61e227b031b56705f4f75f2f7509e41d1d1c5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/device_buffer.h" + +namespace impeller { + +class DeviceBufferMTL final + : public DeviceBuffer, + public BackendCast { + public: + DeviceBufferMTL(); + + // |DeviceBuffer| + ~DeviceBufferMTL() override; + + id GetMTLBuffer() const; + + private: + friend class AllocatorMTL; + + const id buffer_; + const MTLStorageMode storage_mode_; + + DeviceBufferMTL(DeviceBufferDescriptor desc, + id buffer, + MTLStorageMode storage_mode); + + // |DeviceBuffer| + uint8_t* OnGetContents() const override; + + // |DeviceBuffer| + bool OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label, Range range) override; + + // |DeviceBuffer| + void Flush(std::optional range) const override; + + DeviceBufferMTL(const DeviceBufferMTL&) = delete; + + DeviceBufferMTL& operator=(const DeviceBufferMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_DEVICE_BUFFER_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..f01ccce5bc31efd08607b60eac37e0643de05e72 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/device_buffer_mtl.mm @@ -0,0 +1,96 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/device_buffer_mtl.h" + +#include "flutter/fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" + +namespace impeller { + +DeviceBufferMTL::DeviceBufferMTL(DeviceBufferDescriptor desc, + id buffer, + MTLStorageMode storage_mode) + : DeviceBuffer(desc), buffer_(buffer), storage_mode_(storage_mode) {} + +DeviceBufferMTL::~DeviceBufferMTL() = default; + +id DeviceBufferMTL::GetMTLBuffer() const { + return buffer_; +} + +uint8_t* DeviceBufferMTL::OnGetContents() const { +#if !FML_OS_IOS + if (storage_mode_ != MTLStorageModeShared && + storage_mode_ != MTLStorageModeManaged) { + return nullptr; + } +#else + if (storage_mode_ != MTLStorageModeShared) { + return nullptr; + } +#endif // !FML_OS_IOS + + return reinterpret_cast(buffer_.contents); +} + +[[nodiscard]] bool DeviceBufferMTL::OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) { + auto dest = static_cast(buffer_.contents); + + if (!dest) { + return false; + } + + if (source) { + ::memmove(dest + offset, source + source_range.offset, source_range.length); + } + +// MTLStorageModeManaged is never present on always returns false on iOS. But +// the compiler is mad that `didModifyRange:` appears in a TU meant for iOS. So, +// just compile it away. +#if !FML_OS_IOS + if (storage_mode_ == MTLStorageModeManaged) { + [buffer_ didModifyRange:NSMakeRange(offset, source_range.length)]; + } +#endif + + return true; +} + +void DeviceBufferMTL::Flush(std::optional range) const { +#if !FML_OS_IOS + auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size}); + if (storage_mode_ == MTLStorageModeManaged) { + [buffer_ + didModifyRange:NSMakeRange(flush_range.offset, flush_range.length)]; + } +#endif +} + +bool DeviceBufferMTL::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + if (label.empty()) { + return false; + } + [buffer_ setLabel:@(label.data())]; +#endif // IMPELLER_DEBUG + return true; +} + +bool DeviceBufferMTL::SetLabel(std::string_view label, Range range) { +#ifdef IMPELLER_DEBUG + if (label.empty()) { + return false; + } + [buffer_ addDebugMarker:@(label.data()) + range:NSMakeRange(range.offset, range.length)]; +#endif // IMPELLER_DEBUG + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..432a1cfa5c768609789055ac91b359527d039efb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.h @@ -0,0 +1,406 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_FORMATS_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_FORMATS_MTL_H_ + +#include + +#include + +#include "flutter/fml/build_config.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/geometry/color.h" + +namespace impeller { + +class RenderTarget; + +constexpr PixelFormat FromMTLPixelFormat(MTLPixelFormat format) { + switch (format) { + case MTLPixelFormatInvalid: + return PixelFormat::kUnknown; + case MTLPixelFormatBGRA8Unorm: + return PixelFormat::kB8G8R8A8UNormInt; + case MTLPixelFormatBGRA8Unorm_sRGB: + return PixelFormat::kB8G8R8A8UNormIntSRGB; + case MTLPixelFormatRGBA8Unorm: + return PixelFormat::kR8G8B8A8UNormInt; + case MTLPixelFormatRGBA8Unorm_sRGB: + return PixelFormat::kR8G8B8A8UNormIntSRGB; + case MTLPixelFormatRGBA32Float: + return PixelFormat::kR32G32B32A32Float; + case MTLPixelFormatRGBA16Float: + return PixelFormat::kR16G16B16A16Float; + case MTLPixelFormatStencil8: + return PixelFormat::kS8UInt; +#if !FML_OS_IOS + case MTLPixelFormatDepth24Unorm_Stencil8: + return PixelFormat::kD24UnormS8Uint; +#endif // FML_OS_IOS + case MTLPixelFormatDepth32Float_Stencil8: + return PixelFormat::kD32FloatS8UInt; + case MTLPixelFormatBGR10_XR_sRGB: + return PixelFormat::kB10G10R10XRSRGB; + case MTLPixelFormatBGR10_XR: + return PixelFormat::kB10G10R10XR; + case MTLPixelFormatBGRA10_XR: + return PixelFormat::kB10G10R10A10XR; + default: + return PixelFormat::kUnknown; + } + return PixelFormat::kUnknown; +} + +/// Safe accessor for MTLPixelFormatDepth24Unorm_Stencil8. +/// Returns PixelFormat::kUnknown if MTLPixelFormatDepth24Unorm_Stencil8 isn't +/// supported. +MTLPixelFormat SafeMTLPixelFormatDepth24Unorm_Stencil8(); + +/// Safe accessor for MTLPixelFormatBGR10_XR_sRGB. +/// Returns PixelFormat::kUnknown if MTLPixelFormatBGR10_XR_sRGB isn't +/// supported. +MTLPixelFormat SafeMTLPixelFormatBGR10_XR_sRGB(); + +/// Safe accessor for MTLPixelFormatBGR10_XR. +/// Returns PixelFormat::kUnknown if MTLPixelFormatBGR10_XR isn't supported. +MTLPixelFormat SafeMTLPixelFormatBGR10_XR(); + +/// Safe accessor for MTLPixelFormatBGRA10_XR. +/// Returns PixelFormat::kUnknown if MTLPixelFormatBGR10_XR isn't supported. +MTLPixelFormat SafeMTLPixelFormatBGRA10_XR(); + +constexpr MTLPixelFormat ToMTLPixelFormat(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + return MTLPixelFormatInvalid; + case PixelFormat::kA8UNormInt: + return MTLPixelFormatA8Unorm; + case PixelFormat::kR8UNormInt: + return MTLPixelFormatR8Unorm; + case PixelFormat::kR8G8UNormInt: + return MTLPixelFormatRG8Unorm; + case PixelFormat::kB8G8R8A8UNormInt: + return MTLPixelFormatBGRA8Unorm; + case PixelFormat::kB8G8R8A8UNormIntSRGB: + return MTLPixelFormatBGRA8Unorm_sRGB; + case PixelFormat::kR8G8B8A8UNormInt: + return MTLPixelFormatRGBA8Unorm; + case PixelFormat::kR8G8B8A8UNormIntSRGB: + return MTLPixelFormatRGBA8Unorm_sRGB; + case PixelFormat::kR32G32B32A32Float: + return MTLPixelFormatRGBA32Float; + case PixelFormat::kR16G16B16A16Float: + return MTLPixelFormatRGBA16Float; + case PixelFormat::kS8UInt: + return MTLPixelFormatStencil8; + case PixelFormat::kD24UnormS8Uint: + return SafeMTLPixelFormatDepth24Unorm_Stencil8(); + case PixelFormat::kD32FloatS8UInt: + return MTLPixelFormatDepth32Float_Stencil8; + case PixelFormat::kB10G10R10XRSRGB: + return SafeMTLPixelFormatBGR10_XR_sRGB(); + case PixelFormat::kB10G10R10XR: + return SafeMTLPixelFormatBGR10_XR(); + case PixelFormat::kB10G10R10A10XR: + return SafeMTLPixelFormatBGRA10_XR(); + } + return MTLPixelFormatInvalid; +}; + +constexpr MTLBlendFactor ToMTLBlendFactor(BlendFactor type) { + switch (type) { + case BlendFactor::kZero: + return MTLBlendFactorZero; + case BlendFactor::kOne: + return MTLBlendFactorOne; + case BlendFactor::kSourceColor: + return MTLBlendFactorSourceColor; + case BlendFactor::kOneMinusSourceColor: + return MTLBlendFactorOneMinusSourceColor; + case BlendFactor::kSourceAlpha: + return MTLBlendFactorSourceAlpha; + case BlendFactor::kOneMinusSourceAlpha: + return MTLBlendFactorOneMinusSourceAlpha; + case BlendFactor::kDestinationColor: + return MTLBlendFactorDestinationColor; + case BlendFactor::kOneMinusDestinationColor: + return MTLBlendFactorOneMinusDestinationColor; + case BlendFactor::kDestinationAlpha: + return MTLBlendFactorDestinationAlpha; + case BlendFactor::kOneMinusDestinationAlpha: + return MTLBlendFactorOneMinusDestinationAlpha; + case BlendFactor::kSourceAlphaSaturated: + return MTLBlendFactorSourceAlphaSaturated; + case BlendFactor::kBlendColor: + return MTLBlendFactorBlendColor; + case BlendFactor::kOneMinusBlendColor: + return MTLBlendFactorOneMinusBlendColor; + case BlendFactor::kBlendAlpha: + return MTLBlendFactorBlendAlpha; + case BlendFactor::kOneMinusBlendAlpha: + return MTLBlendFactorOneMinusBlendAlpha; + } + return MTLBlendFactorZero; +}; + +constexpr MTLPrimitiveType ToMTLPrimitiveType(PrimitiveType type) { + switch (type) { + case PrimitiveType::kTriangle: + return MTLPrimitiveTypeTriangle; + case PrimitiveType::kTriangleStrip: + return MTLPrimitiveTypeTriangleStrip; + case PrimitiveType::kLine: + return MTLPrimitiveTypeLine; + case PrimitiveType::kLineStrip: + return MTLPrimitiveTypeLineStrip; + case PrimitiveType::kPoint: + return MTLPrimitiveTypePoint; + case PrimitiveType::kTriangleFan: + // Callers are expected to perform a capability check for triangle fan + // support. + return MTLPrimitiveTypePoint; + } + return MTLPrimitiveTypePoint; +} + +constexpr MTLTriangleFillMode ToMTLTriangleFillMode(PolygonMode mode) { + switch (mode) { + case PolygonMode::kFill: + return MTLTriangleFillModeFill; + case PolygonMode::kLine: + return MTLTriangleFillModeLines; + } + return MTLTriangleFillModeFill; +} + +constexpr MTLIndexType ToMTLIndexType(IndexType type) { + switch (type) { + case IndexType::k16bit: + return MTLIndexTypeUInt16; + default: + return MTLIndexTypeUInt32; + } +} + +constexpr MTLCullMode ToMTLCullMode(CullMode mode) { + switch (mode) { + case CullMode::kNone: + return MTLCullModeNone; + case CullMode::kBackFace: + return MTLCullModeBack; + case CullMode::kFrontFace: + return MTLCullModeFront; + } + return MTLCullModeNone; +} + +constexpr MTLBlendOperation ToMTLBlendOperation(BlendOperation type) { + switch (type) { + case BlendOperation::kAdd: + return MTLBlendOperationAdd; + case BlendOperation::kSubtract: + return MTLBlendOperationSubtract; + case BlendOperation::kReverseSubtract: + return MTLBlendOperationReverseSubtract; + } + return MTLBlendOperationAdd; +}; + +constexpr MTLColorWriteMask ToMTLColorWriteMask(ColorWriteMask type) { + MTLColorWriteMask mask = MTLColorWriteMaskNone; + + if (type & ColorWriteMaskBits::kRed) { + mask |= MTLColorWriteMaskRed; + } + + if (type & ColorWriteMaskBits::kGreen) { + mask |= MTLColorWriteMaskGreen; + } + + if (type & ColorWriteMaskBits::kBlue) { + mask |= MTLColorWriteMaskBlue; + } + + if (type & ColorWriteMaskBits::kAlpha) { + mask |= MTLColorWriteMaskAlpha; + } + + return mask; +}; + +constexpr MTLCompareFunction ToMTLCompareFunction(CompareFunction func) { + switch (func) { + case CompareFunction::kNever: + return MTLCompareFunctionNever; + case CompareFunction::kLess: + return MTLCompareFunctionLess; + case CompareFunction::kEqual: + return MTLCompareFunctionEqual; + case CompareFunction::kLessEqual: + return MTLCompareFunctionLessEqual; + case CompareFunction::kGreater: + return MTLCompareFunctionGreater; + case CompareFunction::kNotEqual: + return MTLCompareFunctionNotEqual; + case CompareFunction::kGreaterEqual: + return MTLCompareFunctionGreaterEqual; + case CompareFunction::kAlways: + return MTLCompareFunctionAlways; + } + return MTLCompareFunctionAlways; +}; + +constexpr MTLStencilOperation ToMTLStencilOperation(StencilOperation op) { + switch (op) { + case StencilOperation::kKeep: + return MTLStencilOperationKeep; + case StencilOperation::kZero: + return MTLStencilOperationZero; + case StencilOperation::kSetToReferenceValue: + return MTLStencilOperationReplace; + case StencilOperation::kIncrementClamp: + return MTLStencilOperationIncrementClamp; + case StencilOperation::kDecrementClamp: + return MTLStencilOperationDecrementClamp; + case StencilOperation::kInvert: + return MTLStencilOperationInvert; + case StencilOperation::kIncrementWrap: + return MTLStencilOperationIncrementWrap; + case StencilOperation::kDecrementWrap: + return MTLStencilOperationDecrementWrap; + } + return MTLStencilOperationKeep; +}; + +constexpr MTLLoadAction ToMTLLoadAction(LoadAction action) { + switch (action) { + case LoadAction::kDontCare: + return MTLLoadActionDontCare; + case LoadAction::kLoad: + return MTLLoadActionLoad; + case LoadAction::kClear: + return MTLLoadActionClear; + } + + return MTLLoadActionDontCare; +} + +constexpr LoadAction FromMTLLoadAction(MTLLoadAction action) { + switch (action) { + case MTLLoadActionDontCare: + return LoadAction::kDontCare; + case MTLLoadActionLoad: + return LoadAction::kLoad; + case MTLLoadActionClear: + return LoadAction::kClear; + default: + break; + } + + return LoadAction::kDontCare; +} + +constexpr MTLStoreAction ToMTLStoreAction(StoreAction action) { + switch (action) { + case StoreAction::kDontCare: + return MTLStoreActionDontCare; + case StoreAction::kStore: + return MTLStoreActionStore; + case StoreAction::kMultisampleResolve: + return MTLStoreActionMultisampleResolve; + case StoreAction::kStoreAndMultisampleResolve: + return MTLStoreActionStoreAndMultisampleResolve; + } + return MTLStoreActionDontCare; +} + +constexpr StoreAction FromMTLStoreAction(MTLStoreAction action) { + switch (action) { + case MTLStoreActionDontCare: + return StoreAction::kDontCare; + case MTLStoreActionStore: + return StoreAction::kStore; + case MTLStoreActionMultisampleResolve: + return StoreAction::kMultisampleResolve; + case MTLStoreActionStoreAndMultisampleResolve: + return StoreAction::kStoreAndMultisampleResolve; + default: + break; + } + return StoreAction::kDontCare; +} + +constexpr MTLSamplerMinMagFilter ToMTLSamplerMinMagFilter(MinMagFilter filter) { + switch (filter) { + case MinMagFilter::kNearest: + return MTLSamplerMinMagFilterNearest; + case MinMagFilter::kLinear: + return MTLSamplerMinMagFilterLinear; + } + return MTLSamplerMinMagFilterNearest; +} + +constexpr MTLSamplerMipFilter ToMTLSamplerMipFilter(MipFilter filter) { + switch (filter) { + case MipFilter::kBase: + return MTLSamplerMipFilterNotMipmapped; + case MipFilter::kNearest: + return MTLSamplerMipFilterNearest; + case MipFilter::kLinear: + return MTLSamplerMipFilterLinear; + } + return MTLSamplerMipFilterNotMipmapped; +} + +constexpr MTLSamplerAddressMode ToMTLSamplerAddressMode( + SamplerAddressMode mode) { + switch (mode) { + case SamplerAddressMode::kClampToEdge: + return MTLSamplerAddressModeClampToEdge; + case SamplerAddressMode::kRepeat: + return MTLSamplerAddressModeRepeat; + case SamplerAddressMode::kMirror: + return MTLSamplerAddressModeMirrorRepeat; + case SamplerAddressMode::kDecal: + return MTLSamplerAddressModeClampToZero; + } + return MTLSamplerAddressModeClampToEdge; +} + +inline MTLClearColor ToMTLClearColor(const Color& color) { + return MTLClearColorMake(color.red, color.green, color.blue, color.alpha); +} + +constexpr MTLTextureType ToMTLTextureType(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + return MTLTextureType2D; + case TextureType::kTexture2DMultisample: + return MTLTextureType2DMultisample; + case TextureType::kTextureCube: + return MTLTextureTypeCube; + case TextureType::kTextureExternalOES: + VALIDATION_LOG + << "kTextureExternalOES can not be used with the Metal backend."; + } + return MTLTextureType2D; +} + +MTLRenderPipelineColorAttachmentDescriptor* +ToMTLRenderPipelineColorAttachmentDescriptor( + ColorAttachmentDescriptor descriptor); + +MTLDepthStencilDescriptor* ToMTLDepthStencilDescriptor( + std::optional depth, + std::optional front, + std::optional back); + +MTLTextureDescriptor* ToMTLTextureDescriptor(const TextureDescriptor& desc); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_FORMATS_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..256ffea93489512702d7963fa31b18b7b710163d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/formats_mtl.mm @@ -0,0 +1,146 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include + +#include + +#include "impeller/renderer/render_pass.h" + +namespace impeller { + +MTLRenderPipelineColorAttachmentDescriptor* +ToMTLRenderPipelineColorAttachmentDescriptor( + ColorAttachmentDescriptor descriptor) { + auto des = [[MTLRenderPipelineColorAttachmentDescriptor alloc] init]; + des.pixelFormat = ToMTLPixelFormat(descriptor.format); + + des.blendingEnabled = descriptor.blending_enabled; + + des.sourceRGBBlendFactor = + ToMTLBlendFactor(descriptor.src_color_blend_factor); + des.rgbBlendOperation = ToMTLBlendOperation(descriptor.color_blend_op); + des.destinationRGBBlendFactor = + ToMTLBlendFactor(descriptor.dst_color_blend_factor); + + des.sourceAlphaBlendFactor = + ToMTLBlendFactor(descriptor.src_alpha_blend_factor); + des.alphaBlendOperation = ToMTLBlendOperation(descriptor.alpha_blend_op); + des.destinationAlphaBlendFactor = + ToMTLBlendFactor(descriptor.dst_alpha_blend_factor); + + des.writeMask = ToMTLColorWriteMask(descriptor.write_mask); + return des; +} + +MTLStencilDescriptor* ToMTLStencilDescriptor( + const StencilAttachmentDescriptor& descriptor) { + auto des = [[MTLStencilDescriptor alloc] init]; + des.stencilCompareFunction = ToMTLCompareFunction(descriptor.stencil_compare); + des.stencilFailureOperation = + ToMTLStencilOperation(descriptor.stencil_failure); + des.depthFailureOperation = ToMTLStencilOperation(descriptor.depth_failure); + des.depthStencilPassOperation = + ToMTLStencilOperation(descriptor.depth_stencil_pass); + + des.readMask = descriptor.read_mask; + des.writeMask = descriptor.write_mask; + + return des; +} + +MTLDepthStencilDescriptor* ToMTLDepthStencilDescriptor( + std::optional depth, + std::optional front, + std::optional back) { + if (!depth) { + depth = DepthAttachmentDescriptor{ + // Always pass the depth test. + .depth_compare = CompareFunction::kAlways, + .depth_write_enabled = false, + }; + } + + auto des = [[MTLDepthStencilDescriptor alloc] init]; + + // These temporary variables are necessary for clang-tidy (Fuchsia LLVM + // version 17.0.0git) to not crash. + auto compare_function = ToMTLCompareFunction(depth->depth_compare); + auto depth_write_enabled = depth->depth_write_enabled; + + des.depthCompareFunction = compare_function; + des.depthWriteEnabled = depth_write_enabled; + + if (front.has_value()) { + des.frontFaceStencil = ToMTLStencilDescriptor(front.value()); + } + if (back.has_value()) { + des.backFaceStencil = ToMTLStencilDescriptor(back.value()); + } + + return des; +} + +MTLTextureDescriptor* ToMTLTextureDescriptor(const TextureDescriptor& desc) { + if (!desc.IsValid()) { + return nil; + } + auto mtl_desc = [[MTLTextureDescriptor alloc] init]; + mtl_desc.textureType = ToMTLTextureType(desc.type); + mtl_desc.pixelFormat = ToMTLPixelFormat(desc.format); + mtl_desc.sampleCount = static_cast(desc.sample_count); + mtl_desc.width = desc.size.width; + mtl_desc.height = desc.size.height; + mtl_desc.mipmapLevelCount = desc.mip_count; + mtl_desc.usage = MTLTextureUsageUnknown; + if (desc.usage & TextureUsage::kUnknown) { + mtl_desc.usage |= MTLTextureUsageUnknown; + } + if (desc.usage & TextureUsage::kShaderRead) { + mtl_desc.usage |= MTLTextureUsageShaderRead; + } + if (desc.usage & TextureUsage::kShaderWrite) { + mtl_desc.usage |= MTLTextureUsageShaderWrite; + } + if (desc.usage & TextureUsage::kRenderTarget) { + mtl_desc.usage |= MTLTextureUsageRenderTarget; + } + return mtl_desc; +} + +MTLPixelFormat SafeMTLPixelFormatDepth24Unorm_Stencil8() { +#if !FML_OS_IOS + if (@available(macOS 10.11, *)) { + return MTLPixelFormatDepth24Unorm_Stencil8; + } +#endif // FML_OS_IOS + return MTLPixelFormatInvalid; +} + +MTLPixelFormat SafeMTLPixelFormatBGR10_XR_sRGB() { + if (@available(iOS 11, macOS 11.0, *)) { + return MTLPixelFormatBGR10_XR_sRGB; + } else { + return MTLPixelFormatInvalid; + } +} + +MTLPixelFormat SafeMTLPixelFormatBGR10_XR() { + if (@available(iOS 10, macOS 11.0, *)) { + return MTLPixelFormatBGR10_XR; + } else { + return MTLPixelFormatInvalid; + } +} + +MTLPixelFormat SafeMTLPixelFormatBGRA10_XR() { + if (@available(iOS 10, macOS 11.0, *)) { + return MTLPixelFormatBGRA10_XR; + } else { + return MTLPixelFormatInvalid; + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..94ada1b97d47d44135800065822c6f97e5f83f3c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.h @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_ + +#include + +#include +#include +#include "impeller/base/thread.h" +#include "impeller/base/thread_safety.h" +#include "impeller/geometry/scalar.h" + +namespace impeller { + +class ContextMTL; + +/// @brief Approximate the GPU frame time by computing a difference between the +/// smallest GPUStartTime and largest GPUEndTime for all command buffers +/// submitted in a frame workload. +class GPUTracerMTL : public std::enable_shared_from_this { + public: + GPUTracerMTL() = default; + + ~GPUTracerMTL() = default; + + /// @brief Record that the current frame has ended. Any additional cmd buffers + /// will be attributed to the "next" frame. + void MarkFrameEnd(); + + /// @brief Record the current cmd buffer GPU execution timestamps into an + /// aggregate frame workload metric. + void RecordCmdBuffer(id buffer); + + private: + struct GPUTraceState { + Scalar smallest_timestamp = std::numeric_limits::max(); + Scalar largest_timestamp = 0; + size_t pending_buffers = 0; + }; + + mutable Mutex trace_state_mutex_; + GPUTraceState trace_states_[16] IPLR_GUARDED_BY(trace_state_mutex_); + size_t current_state_ IPLR_GUARDED_BY(trace_state_mutex_) = 0u; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_GPU_TRACER_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..41f1aa04a3328e8d5fa18f84731341306c2accd8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/gpu_tracer_mtl.mm @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "fml/trace_event.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" + +#include + +#include "impeller/renderer/backend/metal/gpu_tracer_mtl.h" + +namespace impeller { + +void GPUTracerMTL::MarkFrameEnd() { + if (@available(ios 10.3, tvos 10.2, macos 10.15, macCatalyst 13.0, *)) { + Lock lock(trace_state_mutex_); + current_state_ = (current_state_ + 1) % 16; + } +} + +void GPUTracerMTL::RecordCmdBuffer(id buffer) { + if (@available(ios 10.3, tvos 10.2, macos 10.15, macCatalyst 13.0, *)) { + Lock lock(trace_state_mutex_); + auto current_state = current_state_; + trace_states_[current_state].pending_buffers += 1; + + auto weak_self = weak_from_this(); + [buffer addCompletedHandler:^(id buffer) { + auto self = weak_self.lock(); + if (!self) { + return; + } + Lock lock(self->trace_state_mutex_); + auto& state = self->trace_states_[current_state]; + state.pending_buffers--; + state.smallest_timestamp = std::min( + state.smallest_timestamp, static_cast(buffer.GPUStartTime)); + state.largest_timestamp = std::max( + state.largest_timestamp, static_cast(buffer.GPUEndTime)); + + if (state.pending_buffers == 0) { + auto gpu_ms = + (state.largest_timestamp - state.smallest_timestamp) * 1000; + state.smallest_timestamp = std::numeric_limits::max(); + state.largest_timestamp = 0; + FML_TRACE_COUNTER("flutter", "GPUTracer", + reinterpret_cast(this), // Trace Counter ID + "FrameTimeMS", gpu_ms); + } + }]; + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.h new file mode 100644 index 0000000000000000000000000000000000000000..c01975b978a1e5a39befec4c7d4a4e38368e3711 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.h @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_ + +#include + +#include +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" + +@protocol CAMetalDrawable; +@class CAMetalLayer; + +namespace impeller { + +/// @brief Create a deferred drawable from a CAMetalLayer. +std::shared_future> GetDrawableDeferred( + CAMetalLayer* layer); + +/// @brief Create a TextureMTL from a deferred drawable. +/// +/// This function is safe to call multiple times and will only call +/// nextDrawable once. +std::shared_ptr CreateTextureFromDrawableFuture( + TextureDescriptor desc, + const std::shared_future>& drawble_future); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_LAZY_DRAWABLE_HOLDER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.mm new file mode 100644 index 0000000000000000000000000000000000000000..b847791a288b100f2b4c58b6c1db9fb6d8aeffe7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/lazy_drawable_holder.mm @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/lazy_drawable_holder.h" + +#include +#include +#include + +#include "flutter/fml/trace_event.h" +#include "impeller/base/validation.h" + +namespace impeller { + +#pragma GCC diagnostic push +// Disable the diagnostic for iOS Simulators. Metal without emulation isn't +// available prior to iOS 13 and that's what the simulator headers say when +// support for CAMetalLayer begins. CAMetalLayer is available on iOS 8.0 and +// above which is well below Flutters support level. +#pragma GCC diagnostic ignored "-Wunguarded-availability-new" + +std::shared_future> GetDrawableDeferred( + CAMetalLayer* layer) { + auto future = + std::async(std::launch::deferred, [layer]() -> id { + id current_drawable = nil; + { + TRACE_EVENT0("impeller", "WaitForNextDrawable"); + current_drawable = [layer nextDrawable]; + } + if (!current_drawable) { + VALIDATION_LOG << "Could not acquire current drawable."; + return nullptr; + } + return current_drawable; + }); + return std::shared_future>(std::move(future)); +} + +std::shared_ptr CreateTextureFromDrawableFuture( + TextureDescriptor desc, + const std::shared_future>& drawble_future) { + return std::make_shared( + desc, [drawble_future]() { return drawble_future.get().texture; }, + /*wrapped=*/false, /*drawable=*/true); +} + +#pragma GCC diagnostic pop + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..4728bee4b8612a8a058ee40a896db5c5a61229cf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_ + +#include + +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +//----------------------------------------------------------------------------- +/// @brief Ensures that bindings on the pass are not redundantly set or +/// updated. Avoids making the driver do additional checks and makes +/// the frame insights during profiling and instrumentation not +/// complain about the same. +/// +/// There should be no change to rendering if this caching was +/// absent. +/// +struct PassBindingsCacheMTL { + explicit PassBindingsCacheMTL() {} + + ~PassBindingsCacheMTL() = default; + + PassBindingsCacheMTL(const PassBindingsCacheMTL&) = delete; + + PassBindingsCacheMTL(PassBindingsCacheMTL&&) = delete; + + void SetEncoder(id encoder); + + void SetRenderPipelineState(id pipeline); + + void SetDepthStencilState(id depth_stencil); + + bool SetBuffer(ShaderStage stage, + uint64_t index, + uint64_t offset, + id buffer); + + bool SetTexture(ShaderStage stage, uint64_t index, id texture); + + bool SetSampler(ShaderStage stage, + uint64_t index, + id sampler); + + void SetViewport(const Viewport& viewport); + + void SetScissor(const IRect& scissor); + + private: + struct BufferOffsetPair { + id buffer = nullptr; + size_t offset = 0u; + }; + using BufferMap = std::map; + using TextureMap = std::map>; + using SamplerMap = std::map>; + + id encoder_; + id pipeline_ = nullptr; + id depth_stencil_ = nullptr; + std::map buffers_; + std::map textures_; + std::map samplers_; + std::optional viewport_; + std::optional scissor_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PASS_BINDINGS_CACHE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..ab5370a7a14efc0c58540cd6164dbe63c69dc4b7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pass_bindings_cache_mtl.mm @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/pass_bindings_cache_mtl.h" + +namespace impeller { + +void PassBindingsCacheMTL::SetEncoder(id encoder) { + encoder_ = encoder; +} + +void PassBindingsCacheMTL::SetRenderPipelineState( + id pipeline) { + if (pipeline == pipeline_) { + return; + } + pipeline_ = pipeline; + [encoder_ setRenderPipelineState:pipeline_]; +} + +void PassBindingsCacheMTL::SetDepthStencilState( + id depth_stencil) { + if (depth_stencil_ == depth_stencil) { + return; + } + depth_stencil_ = depth_stencil; + [encoder_ setDepthStencilState:depth_stencil_]; +} + +bool PassBindingsCacheMTL::SetBuffer(ShaderStage stage, + uint64_t index, + uint64_t offset, + id buffer) { + auto& buffers_map = buffers_[stage]; + auto found = buffers_map.find(index); + if (found != buffers_map.end() && found->second.buffer == buffer) { + // The right buffer is bound. Check if its offset needs to be updated. + if (found->second.offset == offset) { + // Buffer and its offset is identical. Nothing to do. + return true; + } + + // Only the offset needs to be updated. + found->second.offset = offset; + + switch (stage) { + case ShaderStage::kVertex: + [encoder_ setVertexBufferOffset:offset atIndex:index]; + return true; + case ShaderStage::kFragment: + [encoder_ setFragmentBufferOffset:offset atIndex:index]; + return true; + default: + VALIDATION_LOG << "Cannot update buffer offset of an unknown stage."; + return false; + } + return true; + } + buffers_map[index] = {buffer, static_cast(offset)}; + switch (stage) { + case ShaderStage::kVertex: + [encoder_ setVertexBuffer:buffer offset:offset atIndex:index]; + return true; + case ShaderStage::kFragment: + [encoder_ setFragmentBuffer:buffer offset:offset atIndex:index]; + return true; + default: + VALIDATION_LOG << "Cannot bind buffer to unknown shader stage."; + return false; + } + return false; +} + +bool PassBindingsCacheMTL::SetTexture(ShaderStage stage, + uint64_t index, + id texture) { + auto& texture_map = textures_[stage]; + auto found = texture_map.find(index); + if (found != texture_map.end() && found->second == texture) { + // Already bound. + return true; + } + texture_map[index] = texture; + switch (stage) { + case ShaderStage::kVertex: + [encoder_ setVertexTexture:texture atIndex:index]; + return true; + case ShaderStage::kFragment: + [encoder_ setFragmentTexture:texture atIndex:index]; + return true; + default: + VALIDATION_LOG << "Cannot bind buffer to unknown shader stage."; + return false; + } + return false; +} + +bool PassBindingsCacheMTL::SetSampler(ShaderStage stage, + uint64_t index, + id sampler) { + auto& sampler_map = samplers_[stage]; + auto found = sampler_map.find(index); + if (found != sampler_map.end() && found->second == sampler) { + // Already bound. + return true; + } + sampler_map[index] = sampler; + switch (stage) { + case ShaderStage::kVertex: + [encoder_ setVertexSamplerState:sampler atIndex:index]; + return true; + case ShaderStage::kFragment: + [encoder_ setFragmentSamplerState:sampler atIndex:index]; + return true; + default: + VALIDATION_LOG << "Cannot bind buffer to unknown shader stage."; + return false; + } + return false; +} + +void PassBindingsCacheMTL::SetViewport(const Viewport& viewport) { + if (viewport_.has_value() && viewport_.value() == viewport) { + return; + } + [encoder_ setViewport:MTLViewport{ + .originX = viewport.rect.GetX(), + .originY = viewport.rect.GetY(), + .width = viewport.rect.GetWidth(), + .height = viewport.rect.GetHeight(), + .znear = viewport.depth_range.z_near, + .zfar = viewport.depth_range.z_far, + }]; + viewport_ = viewport; +} + +void PassBindingsCacheMTL::SetScissor(const IRect& scissor) { + if (scissor_.has_value() && scissor_.value() == scissor) { + return; + } + [encoder_ + setScissorRect:MTLScissorRect{ + .x = static_cast(scissor.GetX()), + .y = static_cast(scissor.GetY()), + .width = static_cast(scissor.GetWidth()), + .height = static_cast(scissor.GetHeight()), + }]; + scissor_ = scissor; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..8d6a6bdcddc5f026e219fe442bfab15b0ab34a57 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_ + +#include + +#include "impeller/renderer/pipeline_library.h" + +namespace impeller { + +class ContextMTL; + +class PipelineLibraryMTL final : public PipelineLibrary { + public: + PipelineLibraryMTL(); + + // |PipelineLibrary| + ~PipelineLibraryMTL() override; + + private: + friend ContextMTL; + + id device_ = nullptr; + PipelineMap pipelines_; + ComputePipelineMap compute_pipelines_; + + explicit PipelineLibraryMTL(id device); + + // |PipelineLibrary| + bool IsValid() const override; + + // |PipelineLibrary| + PipelineFuture GetPipeline(PipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + PipelineFuture GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + bool HasPipeline(const PipelineDescriptor& descriptor) override; + + // |PipelineLibrary| + void RemovePipelinesWithEntryPoint( + std::shared_ptr function) override; + + PipelineLibraryMTL(const PipelineLibraryMTL&) = delete; + + PipelineLibraryMTL& operator=(const PipelineLibraryMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_LIBRARY_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..1e69aeb0a235738b352b33e302a26fc9f858c872 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_library_mtl.mm @@ -0,0 +1,274 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/pipeline_library_mtl.h" + +#include +#include + +#include "flutter/fml/build_config.h" +#include "flutter/fml/container.h" +#include "impeller/base/promise.h" +#include "impeller/renderer/backend/metal/compute_pipeline_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/pipeline_mtl.h" +#include "impeller/renderer/backend/metal/shader_function_mtl.h" +#include "impeller/renderer/backend/metal/vertex_descriptor_mtl.h" + +#if !__has_feature(objc_arc) +#error ARC must be enabled ! +#endif + +namespace impeller { + +PipelineLibraryMTL::PipelineLibraryMTL(id device) + : device_(device) {} + +PipelineLibraryMTL::~PipelineLibraryMTL() = default; + +using Callback = std::function; + +static void GetMTLRenderPipelineDescriptor(const PipelineDescriptor& desc, + const Callback& callback) { + auto descriptor = [[MTLRenderPipelineDescriptor alloc] init]; + descriptor.label = @(desc.GetLabel().data()); + descriptor.rasterSampleCount = static_cast(desc.GetSampleCount()); + bool created_specialized_function = false; + + if (const auto& vertex_descriptor = desc.GetVertexDescriptor()) { + VertexDescriptorMTL vertex_descriptor_mtl; + if (vertex_descriptor_mtl.SetStageInputsAndLayout( + vertex_descriptor->GetStageInputs(), + vertex_descriptor->GetStageLayouts())) { + descriptor.vertexDescriptor = + vertex_descriptor_mtl.GetMTLVertexDescriptor(); + } + } + + for (const auto& item : desc.GetColorAttachmentDescriptors()) { + descriptor.colorAttachments[item.first] = + ToMTLRenderPipelineColorAttachmentDescriptor(item.second); + } + + descriptor.depthAttachmentPixelFormat = + ToMTLPixelFormat(desc.GetDepthPixelFormat()); + descriptor.stencilAttachmentPixelFormat = + ToMTLPixelFormat(desc.GetStencilPixelFormat()); + + const auto& constants = desc.GetSpecializationConstants(); + for (const auto& entry : desc.GetStageEntrypoints()) { + if (entry.first == ShaderStage::kVertex) { + descriptor.vertexFunction = + ShaderFunctionMTL::Cast(*entry.second).GetMTLFunction(); + } + if (entry.first == ShaderStage::kFragment) { + if (constants.empty()) { + descriptor.fragmentFunction = + ShaderFunctionMTL::Cast(*entry.second).GetMTLFunction(); + } else { + // This code only expects a single specialized function per pipeline. + FML_CHECK(!created_specialized_function); + created_specialized_function = true; + ShaderFunctionMTL::Cast(*entry.second) + .GetMTLFunctionSpecialized( + constants, [callback, descriptor](id function) { + descriptor.fragmentFunction = function; + callback(descriptor); + }); + } + } + } + + if (!created_specialized_function) { + callback(descriptor); + } +} + +static MTLComputePipelineDescriptor* GetMTLComputePipelineDescriptor( + const ComputePipelineDescriptor& desc) { + auto descriptor = [[MTLComputePipelineDescriptor alloc] init]; + descriptor.label = @(desc.GetLabel().c_str()); + descriptor.computeFunction = + ShaderFunctionMTL::Cast(*desc.GetStageEntrypoint()).GetMTLFunction(); + return descriptor; +} + +static id CreateDepthStencilDescriptor( + const PipelineDescriptor& desc, + id device) { + auto descriptor = ToMTLDepthStencilDescriptor( + desc.GetDepthStencilAttachmentDescriptor(), // + desc.GetFrontStencilAttachmentDescriptor(), // + desc.GetBackStencilAttachmentDescriptor() // + ); + return [device newDepthStencilStateWithDescriptor:descriptor]; +} + +// |PipelineLibrary| +bool PipelineLibraryMTL::IsValid() const { + return device_ != nullptr; +} + +// |PipelineLibrary| +PipelineFuture PipelineLibraryMTL::GetPipeline( + PipelineDescriptor descriptor, + bool async) { + if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) { + return found->second; + } + + if (!IsValid()) { + return { + descriptor, + RealizedFuture>>(nullptr)}; + } + + auto promise = std::make_shared< + std::promise>>>(); + auto pipeline_future = + PipelineFuture{descriptor, promise->get_future()}; + pipelines_[descriptor] = pipeline_future; + auto weak_this = weak_from_this(); + + auto get_pipeline_descriptor = + [descriptor, + device = device_](MTLNewRenderPipelineStateCompletionHandler handler) { + GetMTLRenderPipelineDescriptor( + descriptor, + [device, handler](MTLRenderPipelineDescriptor* descriptor) { + [device newRenderPipelineStateWithDescriptor:descriptor + completionHandler:handler]; + }); + }; + + // Extra info for https://github.com/flutter/flutter/issues/148320. + std::optional thread_name = +#if FLUTTER_RELEASE + std::nullopt; +#else + [NSThread isMainThread] ? "main" + : [[[NSThread currentThread] name] UTF8String]; +#endif + auto completion_handler = ^( + id _Nullable render_pipeline_state, + NSError* _Nullable error) { + if (error != nil) { + VALIDATION_LOG << "Could not create render pipeline for " + << descriptor.GetLabel() << " :" + << error.localizedDescription.UTF8String << " (thread: " + << (thread_name.has_value() ? *thread_name : "unknown") + << ")"; + promise->set_value(nullptr); + return; + } + + auto strong_this = weak_this.lock(); + if (!strong_this) { + promise->set_value(nullptr); + return; + } + + auto new_pipeline = std::shared_ptr(new PipelineMTL( + weak_this, + descriptor, // + render_pipeline_state, // + CreateDepthStencilDescriptor(descriptor, device_) // + )); + promise->set_value(new_pipeline); + }; + auto retry_handler = + ^(id _Nullable render_pipeline_state, + NSError* _Nullable error) { + if (error) { + FML_LOG(INFO) << "pipeline creation retry"; + // The dispatch here is just to minimize the number of threads calling + // this. Executing on the platform thread matches the ContentContext + // path. It also serializes the retries. It may not be necessary. + dispatch_async(dispatch_get_main_queue(), ^{ + get_pipeline_descriptor(completion_handler); + }); + } else { + completion_handler(render_pipeline_state, error); + } + }; +#if defined(FML_ARCH_CPU_X86_64) + get_pipeline_descriptor(retry_handler); +#else + get_pipeline_descriptor(completion_handler); + (void)retry_handler; +#endif + return pipeline_future; +} + +PipelineFuture PipelineLibraryMTL::GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) { + if (auto found = compute_pipelines_.find(descriptor); + found != compute_pipelines_.end()) { + return found->second; + } + + if (!IsValid()) { + return { + descriptor, + RealizedFuture>>( + nullptr)}; + } + + auto promise = std::make_shared< + std::promise>>>(); + auto pipeline_future = PipelineFuture{ + descriptor, promise->get_future()}; + compute_pipelines_[descriptor] = pipeline_future; + auto weak_this = weak_from_this(); + + auto completion_handler = + ^(id _Nullable compute_pipeline_state, + MTLComputePipelineReflection* _Nullable reflection, + NSError* _Nullable error) { + if (error != nil) { + VALIDATION_LOG << "Could not create compute pipeline: " + << error.localizedDescription.UTF8String; + promise->set_value(nullptr); + return; + } + + auto strong_this = weak_this.lock(); + if (!strong_this) { + VALIDATION_LOG << "Library was collected before a pending pipeline " + "creation could finish."; + promise->set_value(nullptr); + return; + } + + auto new_pipeline = std::shared_ptr( + new ComputePipelineMTL(weak_this, + descriptor, // + compute_pipeline_state // + )); + promise->set_value(new_pipeline); + }; + [device_ + newComputePipelineStateWithDescriptor:GetMTLComputePipelineDescriptor( + descriptor) + options:MTLPipelineOptionNone + completionHandler:completion_handler]; + return pipeline_future; +} + +// |PipelineLibrary| +bool PipelineLibraryMTL::HasPipeline(const PipelineDescriptor& descriptor) { + return pipelines_.find(descriptor) != pipelines_.end(); +} + +// |PipelineLibrary| +void PipelineLibraryMTL::RemovePipelinesWithEntryPoint( + std::shared_ptr function) { + fml::erase_if(pipelines_, [&](auto item) { + return item->first.GetEntrypointForStage(function->GetStage()) + ->IsEqual(*function); + }); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..1ee1ac4ee0dffa45084cd7adb0104d21369ba013 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +class PipelineMTL final + : public Pipeline, + public BackendCast> { + public: + // |Pipeline| + ~PipelineMTL() override; + + id GetMTLRenderPipelineState() const; + + id GetMTLDepthStencilState() const; + + private: + friend class PipelineLibraryMTL; + + id pipeline_state_; + id depth_stencil_state_; + bool is_valid_ = false; + + PipelineMTL(std::weak_ptr library, + const PipelineDescriptor& desc, + id state, + id depth_stencil_state); + + // |Pipeline| + bool IsValid() const override; + + PipelineMTL(const PipelineMTL&) = delete; + + PipelineMTL& operator=(const PipelineMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_PIPELINE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..684ca305c5123097cd78dba2ec11775d14d7c62b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/pipeline_mtl.mm @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/pipeline_mtl.h" + +namespace impeller { + +PipelineMTL::PipelineMTL(std::weak_ptr library, + const PipelineDescriptor& desc, + id state, + id depth_stencil_state) + : Pipeline(std::move(library), desc), + pipeline_state_(state), + depth_stencil_state_(depth_stencil_state) { + if (!pipeline_state_) { + return; + } + is_valid_ = true; +} + +PipelineMTL::~PipelineMTL() = default; + +bool PipelineMTL::IsValid() const { + return is_valid_; +} + +id PipelineMTL::GetMTLRenderPipelineState() const { + return pipeline_state_; +} + +id PipelineMTL::GetMTLDepthStencilState() const { + return depth_stencil_state_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..9442eb193092d6a1493189fbe6ec2f7abad3f941 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.h @@ -0,0 +1,131 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_RENDER_PASS_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_RENDER_PASS_MTL_H_ + +#include + +#include "impeller/renderer/backend/metal/pass_bindings_cache_mtl.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +class RenderPassMTL final : public RenderPass { + public: + // |RenderPass| + ~RenderPassMTL() override; + + private: + friend class CommandBufferMTL; + + id buffer_ = nil; + id encoder_ = nil; + MTLRenderPassDescriptor* desc_ = nil; + std::string label_; + bool is_metal_trace_active_ = false; + bool is_valid_ = false; + // Many parts of the codebase will start writing to a render pass but + // never submit them. This boolean is used to track if a submit happened + // so that in the dtor we can always ensure the render pass is finished. + mutable bool did_finish_encoding_ = false; + + PassBindingsCacheMTL pass_bindings_; + + // Per-command state + size_t instance_count_ = 1u; + size_t base_vertex_ = 0u; + size_t vertex_count_ = 0u; + bool has_valid_pipeline_ = false; + bool has_label_ = false; + BufferView index_buffer_ = {}; + PrimitiveType primitive_type_ = {}; + MTLIndexType index_type_ = {}; + + RenderPassMTL(std::shared_ptr context, + const RenderTarget& target, + id buffer); + + // |RenderPass| + bool IsValid() const override; + + // |RenderPass| + void OnSetLabel(std::string_view label) override; + + // |RenderPass| + bool OnEncodeCommands(const Context& context) const override; + + // |RenderPass| + void SetPipeline(PipelineRef pipeline) override; + + // |RenderPass| + void SetCommandLabel(std::string_view label) override; + + // |RenderPass| + void SetStencilReference(uint32_t value) override; + + // |RenderPass| + void SetBaseVertex(uint64_t value) override; + + // |RenderPass| + void SetViewport(Viewport viewport) override; + + // |RenderPass| + void SetScissor(IRect scissor) override; + + // |RenderPass| + void SetElementCount(size_t count) override; + + // |RenderPass| + void SetInstanceCount(size_t count) override; + + // |RenderPass| + bool SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count) override; + + // |RenderPass| + bool SetIndexBuffer(BufferView index_buffer, IndexType index_type) override; + + // |RenderPass| + fml::Status Draw() override; + + // |RenderPass| + bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + // |RenderPass| + bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + RenderPassMTL(const RenderPassMTL&) = delete; + + RenderPassMTL& operator=(const RenderPassMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_RENDER_PASS_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..fb26a8d02a765ea4d71b96d5294202763e5f2297 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/render_pass_mtl.mm @@ -0,0 +1,428 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/render_pass_mtl.h" + +#include "flutter/fml/closure.h" +#include "flutter/fml/logging.h" +#include "flutter/fml/make_copyable.h" +#include "fml/status.h" + +#include "impeller/base/backend_cast.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/device_buffer_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/pipeline_mtl.h" +#include "impeller/renderer/backend/metal/sampler_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/command.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +static bool ConfigureResolveTextureAttachment( + const Attachment& desc, + MTLRenderPassAttachmentDescriptor* attachment) { + bool needs_resolve = + desc.store_action == StoreAction::kMultisampleResolve || + desc.store_action == StoreAction::kStoreAndMultisampleResolve; + + if (needs_resolve && !desc.resolve_texture) { + VALIDATION_LOG << "Resolve store action specified on attachment but no " + "resolve texture was specified."; + return false; + } + + if (desc.resolve_texture && !needs_resolve) { + VALIDATION_LOG << "A resolve texture was specified even though the store " + "action doesn't require it."; + return false; + } + + if (!desc.resolve_texture) { + return true; + } + + attachment.resolveTexture = + TextureMTL::Cast(*desc.resolve_texture).GetMTLTexture(); + + return true; +} + +static bool ConfigureAttachment(const Attachment& desc, + MTLRenderPassAttachmentDescriptor* attachment) { + if (!desc.texture) { + return false; + } + + attachment.texture = TextureMTL::Cast(*desc.texture).GetMTLTexture(); + attachment.loadAction = ToMTLLoadAction(desc.load_action); + attachment.storeAction = ToMTLStoreAction(desc.store_action); + + if (!ConfigureResolveTextureAttachment(desc, attachment)) { + return false; + } + + return true; +} + +static bool ConfigureColorAttachment( + const ColorAttachment& desc, + MTLRenderPassColorAttachmentDescriptor* attachment) { + if (!ConfigureAttachment(desc, attachment)) { + return false; + } + attachment.clearColor = ToMTLClearColor(desc.clear_color); + return true; +} + +static bool ConfigureDepthAttachment( + const DepthAttachment& desc, + MTLRenderPassDepthAttachmentDescriptor* attachment) { + if (!ConfigureAttachment(desc, attachment)) { + return false; + } + attachment.clearDepth = desc.clear_depth; + return true; +} + +static bool ConfigureStencilAttachment( + const StencilAttachment& desc, + MTLRenderPassStencilAttachmentDescriptor* attachment) { + if (!ConfigureAttachment(desc, attachment)) { + return false; + } + attachment.clearStencil = desc.clear_stencil; + return true; +} + +static MTLRenderPassDescriptor* ToMTLRenderPassDescriptor( + const RenderTarget& desc) { + auto result = [MTLRenderPassDescriptor renderPassDescriptor]; + + bool configured_attachment = desc.IterateAllColorAttachments( + [&result](size_t index, const ColorAttachment& attachment) -> bool { + return ConfigureColorAttachment(attachment, + result.colorAttachments[index]); + }); + + if (!configured_attachment) { + VALIDATION_LOG << "Could not configure color attachments"; + return nil; + } + + const auto& depth = desc.GetDepthAttachment(); + + if (depth.has_value() && + !ConfigureDepthAttachment(depth.value(), result.depthAttachment)) { + VALIDATION_LOG << "Could not configure depth attachment."; + return nil; + } + + const auto& stencil = desc.GetStencilAttachment(); + + if (stencil.has_value() && + !ConfigureStencilAttachment(stencil.value(), result.stencilAttachment)) { + VALIDATION_LOG << "Could not configure stencil attachment."; + return nil; + } + + return result; +} + +RenderPassMTL::RenderPassMTL(std::shared_ptr context, + const RenderTarget& target, + id buffer) + : RenderPass(std::move(context), target), + buffer_(buffer), + desc_(ToMTLRenderPassDescriptor(GetRenderTarget())) { + if (!buffer_ || !desc_ || !render_target_.IsValid()) { + return; + } + encoder_ = [buffer_ renderCommandEncoderWithDescriptor:desc_]; + + if (!encoder_) { + return; + } +#ifdef IMPELLER_DEBUG + is_metal_trace_active_ = + [[MTLCaptureManager sharedCaptureManager] isCapturing]; +#endif // IMPELLER_DEBUG + pass_bindings_.SetEncoder(encoder_); + pass_bindings_.SetViewport( + Viewport{.rect = Rect::MakeSize(GetRenderTargetSize())}); + pass_bindings_.SetScissor(IRect::MakeSize(GetRenderTargetSize())); + is_valid_ = true; +} + +RenderPassMTL::~RenderPassMTL() { + if (!did_finish_encoding_) { + [encoder_ endEncoding]; + did_finish_encoding_ = true; + } +} + +bool RenderPassMTL::IsValid() const { + return is_valid_; +} + +void RenderPassMTL::OnSetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + if (label.empty()) { + return; + } + encoder_.label = @(std::string(label).c_str()); +#endif // IMPELLER_DEBUG +} + +bool RenderPassMTL::OnEncodeCommands(const Context& context) const { + did_finish_encoding_ = true; + [encoder_ endEncoding]; + return true; +} + +static bool Bind(PassBindingsCacheMTL& pass, + ShaderStage stage, + size_t bind_index, + const BufferView& view) { + if (!view.GetBuffer()) { + return false; + } + + const DeviceBuffer* device_buffer = view.GetBuffer(); + if (!device_buffer) { + return false; + } + + auto buffer = DeviceBufferMTL::Cast(*device_buffer).GetMTLBuffer(); + // The Metal call is a void return and we don't want to make it on nil. + if (!buffer) { + return false; + } + + return pass.SetBuffer(stage, bind_index, view.GetRange().offset, buffer); +} + +static bool Bind(PassBindingsCacheMTL& pass, + ShaderStage stage, + size_t bind_index, + raw_ptr sampler, + const Texture& texture) { + if (!sampler || !texture.IsValid()) { + return false; + } + + if (texture.NeedsMipmapGeneration()) { + // TODO(127697): generate mips when the GPU is available on iOS. +#if !FML_OS_IOS + VALIDATION_LOG + << "Texture at binding index " << bind_index + << " has a mip count > 1, but the mipmap has not been generated."; + return false; +#endif // !FML_OS_IOS + } + + return pass.SetTexture(stage, bind_index, + TextureMTL::Cast(texture).GetMTLTexture()) && + pass.SetSampler(stage, bind_index, + SamplerMTL::Cast(*sampler).GetMTLSamplerState()); +} + +// |RenderPass| +void RenderPassMTL::SetPipeline(PipelineRef pipeline) { + const PipelineDescriptor& pipeline_desc = pipeline->GetDescriptor(); + primitive_type_ = pipeline_desc.GetPrimitiveType(); + pass_bindings_.SetRenderPipelineState( + PipelineMTL::Cast(*pipeline).GetMTLRenderPipelineState()); + pass_bindings_.SetDepthStencilState( + PipelineMTL::Cast(*pipeline).GetMTLDepthStencilState()); + + [encoder_ setFrontFacingWinding:pipeline_desc.GetWindingOrder() == + WindingOrder::kClockwise + ? MTLWindingClockwise + : MTLWindingCounterClockwise]; + [encoder_ setCullMode:ToMTLCullMode(pipeline_desc.GetCullMode())]; + [encoder_ setTriangleFillMode:ToMTLTriangleFillMode( + pipeline_desc.GetPolygonMode())]; + has_valid_pipeline_ = true; +} + +// |RenderPass| +void RenderPassMTL::SetCommandLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + if (is_metal_trace_active_) { + has_label_ = true; + std::string label_copy(label); + [encoder_ pushDebugGroup:@(label_copy.c_str())]; + } +#endif // IMPELLER_DEBUG +} + +// |RenderPass| +void RenderPassMTL::SetStencilReference(uint32_t value) { + [encoder_ setStencilReferenceValue:value]; +} + +// |RenderPass| +void RenderPassMTL::SetBaseVertex(uint64_t value) { + base_vertex_ = value; +} + +// |RenderPass| +void RenderPassMTL::SetViewport(Viewport viewport) { + pass_bindings_.SetViewport(viewport); +} + +// |RenderPass| +void RenderPassMTL::SetScissor(IRect scissor) { + pass_bindings_.SetScissor(scissor); +} + +// |RenderPass| +void RenderPassMTL::SetElementCount(size_t count) { + vertex_count_ = count; +} + +// |RenderPass| +void RenderPassMTL::SetInstanceCount(size_t count) { + instance_count_ = count; +} + +// |RenderPass| +bool RenderPassMTL::SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count) { + if (!ValidateVertexBuffers(vertex_buffers, vertex_buffer_count)) { + return false; + } + + for (size_t i = 0; i < vertex_buffer_count; i++) { + if (!Bind(pass_bindings_, ShaderStage::kVertex, + VertexDescriptor::kReservedVertexBufferIndex - i, + vertex_buffers[i])) { + return false; + } + } + + return true; +} + +// |RenderPass| +bool RenderPassMTL::SetIndexBuffer(BufferView index_buffer, + IndexType index_type) { + if (!ValidateIndexBuffer(index_buffer, index_type)) { + return false; + } + + if (index_type != IndexType::kNone) { + index_type_ = ToMTLIndexType(index_type); + index_buffer_ = std::move(index_buffer); + } + + return true; +} + +// |RenderPass| +fml::Status RenderPassMTL::Draw() { + if (!has_valid_pipeline_) { + return fml::Status(fml::StatusCode::kCancelled, "Invalid pipeline."); + } + + if (!index_buffer_) { + if (instance_count_ != 1u) { + [encoder_ drawPrimitives:ToMTLPrimitiveType(primitive_type_) + vertexStart:base_vertex_ + vertexCount:vertex_count_ + instanceCount:instance_count_ + baseInstance:0u]; + } else { + [encoder_ drawPrimitives:ToMTLPrimitiveType(primitive_type_) + vertexStart:base_vertex_ + vertexCount:vertex_count_]; + } + } else { + id mtl_index_buffer = + DeviceBufferMTL::Cast(*index_buffer_.GetBuffer()).GetMTLBuffer(); + if (instance_count_ != 1u) { + [encoder_ drawIndexedPrimitives:ToMTLPrimitiveType(primitive_type_) + indexCount:vertex_count_ + indexType:index_type_ + indexBuffer:mtl_index_buffer + indexBufferOffset:index_buffer_.GetRange().offset + instanceCount:instance_count_ + baseVertex:base_vertex_ + baseInstance:0u]; + } else { + [encoder_ drawIndexedPrimitives:ToMTLPrimitiveType(primitive_type_) + indexCount:vertex_count_ + indexType:index_type_ + indexBuffer:mtl_index_buffer + indexBufferOffset:index_buffer_.GetRange().offset]; + } + } + +#ifdef IMPELLER_DEBUG + if (has_label_) { + [encoder_ popDebugGroup]; + } +#endif // IMPELLER_DEBUG + + vertex_count_ = 0u; + base_vertex_ = 0u; + instance_count_ = 1u; + index_buffer_ = {}; + has_valid_pipeline_ = false; + has_label_ = false; + + return fml::Status(); +} + +// |RenderPass| +bool RenderPassMTL::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + return Bind(pass_bindings_, stage, slot.ext_res_0, view); +} + +// |RenderPass| +bool RenderPassMTL::BindDynamicResource( + ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) { + return Bind(pass_bindings_, stage, slot.ext_res_0, view); +} + +// |RenderPass| +bool RenderPassMTL::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (!texture) { + return false; + } + return Bind(pass_bindings_, stage, slot.texture_index, sampler, *texture); +} + +bool RenderPassMTL::BindDynamicResource( + ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (!texture) { + return false; + } + return Bind(pass_bindings_, stage, slot.texture_index, sampler, *texture); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..d826dc86cef667b89facea2c2a1f49953892980e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_ + +#include + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/base/comparable.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/sampler_library.h" + +namespace impeller { + +class SamplerLibraryMTL final + : public SamplerLibrary, + public BackendCast { + public: + // |SamplerLibrary| + ~SamplerLibraryMTL() override; + + private: + friend class ContextMTL; + + id device_ = nullptr; + std::vector>> samplers_; + + explicit SamplerLibraryMTL(id device); + + // |SamplerLibrary| + raw_ptr GetSampler( + const SamplerDescriptor& descriptor) override; + + SamplerLibraryMTL(const SamplerLibraryMTL&) = delete; + + SamplerLibraryMTL& operator=(const SamplerLibraryMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_LIBRARY_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..65caef79baee6683c752047574ced4350d40d347 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_library_mtl.mm @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/sampler_library_mtl.h" + +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/sampler_mtl.h" + +namespace impeller { + +SamplerLibraryMTL::SamplerLibraryMTL(id device) : device_(device) {} + +SamplerLibraryMTL::~SamplerLibraryMTL() = default; + +raw_ptr SamplerLibraryMTL::GetSampler( + const SamplerDescriptor& descriptor) { + uint64_t p_key = SamplerDescriptor::ToKey(descriptor); + for (const auto& [key, value] : samplers_) { + if (key == p_key) { + return raw_ptr(value); + } + } + if (!device_) { + return raw_ptr(nullptr); + } + auto desc = [[MTLSamplerDescriptor alloc] init]; + desc.minFilter = ToMTLSamplerMinMagFilter(descriptor.min_filter); + desc.magFilter = ToMTLSamplerMinMagFilter(descriptor.mag_filter); + desc.mipFilter = ToMTLSamplerMipFilter(descriptor.mip_filter); + desc.sAddressMode = ToMTLSamplerAddressMode(descriptor.width_address_mode); + desc.tAddressMode = ToMTLSamplerAddressMode(descriptor.height_address_mode); + desc.rAddressMode = ToMTLSamplerAddressMode(descriptor.depth_address_mode); + if (@available(iOS 14.0, macos 10.12, *)) { + desc.borderColor = MTLSamplerBorderColorTransparentBlack; + } +#ifdef IMPELLER_DEBUG + if (!descriptor.label.empty()) { + desc.label = @(descriptor.label.data()); + } +#endif // IMPELLER_DEBUG + + auto mtl_sampler = [device_ newSamplerStateWithDescriptor:desc]; + if (!mtl_sampler) { + return raw_ptr(nullptr); + ; + } + auto sampler = + std::shared_ptr(new SamplerMTL(descriptor, mtl_sampler)); + samplers_.push_back(std::make_pair(p_key, std::move(sampler))); + return raw_ptr(samplers_.back().second); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..ab95f04b309e730a8beb5d3f273c2c4a0eec8bc6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/sampler.h" + +namespace impeller { + +class SamplerLibraryMTL; + +class SamplerMTL final : public Sampler, + public BackendCast { + public: + SamplerMTL(); + + // |Sampler| + ~SamplerMTL() override; + + id GetMTLSamplerState() const; + + private: + friend SamplerLibraryMTL; + + id state_ = nullptr; + + SamplerMTL(const SamplerDescriptor& desc, id state); + + SamplerMTL(const SamplerMTL&) = delete; + + SamplerMTL& operator=(const SamplerMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..2d2d40c9b18b9f0d7ce5c6624203404501971f80 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/sampler_mtl.mm @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/sampler_mtl.h" + +namespace impeller { + +SamplerMTL::SamplerMTL(const SamplerDescriptor& desc, id state) + : Sampler(desc), state_(state) { + FML_DCHECK(state_); +} + +SamplerMTL::~SamplerMTL() = default; + +id SamplerMTL::GetMTLSamplerState() const { + return state_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..057f6f89a8417a7476fa8ff21c73d8a1d9605d72 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/shader_function.h" + +namespace impeller { + +class ShaderFunctionMTL final + : public ShaderFunction, + public BackendCast { + public: + // |ShaderFunction| + ~ShaderFunctionMTL() override; + + id GetMTLFunction() const; + + using CompileCallback = std::function)>; + + void GetMTLFunctionSpecialized(const std::vector& constants, + const CompileCallback& callback) const; + + private: + friend class ShaderLibraryMTL; + + id function_ = nullptr; + id library_ = nullptr; + + ShaderFunctionMTL(UniqueID parent_library_id, + id function, + id library, + std::string name, + ShaderStage stage); + + ShaderFunctionMTL(const ShaderFunctionMTL&) = delete; + + ShaderFunctionMTL& operator=(const ShaderFunctionMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_FUNCTION_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..39910a6301c1f9f5253c88077efce07fed286f5d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_function_mtl.mm @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/shader_function_mtl.h" + +namespace impeller { + +ShaderFunctionMTL::ShaderFunctionMTL(UniqueID parent_library_id, + id function, + id library, + std::string name, + ShaderStage stage) + : ShaderFunction(parent_library_id, std::move(name), stage), + function_(function), + library_(library) {} + +ShaderFunctionMTL::~ShaderFunctionMTL() = default; + +void ShaderFunctionMTL::GetMTLFunctionSpecialized( + const std::vector& constants, + const CompileCallback& callback) const { + MTLFunctionConstantValues* constantValues = + [[MTLFunctionConstantValues alloc] init]; + size_t index = 0; + for (const auto value : constants) { + Scalar copied_value = value; + [constantValues setConstantValue:&copied_value + type:MTLDataTypeFloat + atIndex:index]; + index++; + } + CompileCallback callback_value = callback; + [library_ newFunctionWithName:@(GetName().data()) + constantValues:constantValues + completionHandler:^(id _Nullable function, + NSError* _Nullable error) { + callback_value(function); + }]; +} + +id ShaderFunctionMTL::GetMTLFunction() const { + return function_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..b38cd6139d30dd842c210080991dbf5e4b30d42c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.h @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_ + +#include +#include + +#include +#include +#include + +#include "impeller/base/comparable.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/shader_key.h" +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +class ShaderLibraryMTL final : public ShaderLibrary { + public: + ShaderLibraryMTL(); + + // |ShaderLibrary| + ~ShaderLibraryMTL() override; + + // |ShaderLibrary| + bool IsValid() const override; + + private: + friend class ContextMTL; + + UniqueID library_id_; + mutable RWMutex libraries_mutex_; + NSMutableArray>* libraries_ IPLR_GUARDED_BY(libraries_mutex_) = + nullptr; + ShaderFunctionMap functions_; + bool is_valid_ = false; + + explicit ShaderLibraryMTL(NSArray>* libraries); + + // |ShaderLibrary| + std::shared_ptr GetFunction(std::string_view name, + ShaderStage stage) override; + + // |ShaderLibrary| + void RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback) override; + + // |ShaderLibrary| + void UnregisterFunction(std::string name, ShaderStage stage) override; + + id GetDevice() const; + + void RegisterLibrary(id library); + + ShaderLibraryMTL(const ShaderLibraryMTL&) = delete; + + ShaderLibraryMTL& operator=(const ShaderLibraryMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SHADER_LIBRARY_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..a1aedd9a54857c45ab3695da1ef2e24b43d09923 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/shader_library_mtl.mm @@ -0,0 +1,186 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/shader_library_mtl.h" + +#include "flutter/fml/closure.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/metal/shader_function_mtl.h" + +namespace impeller { + +ShaderLibraryMTL::ShaderLibraryMTL(NSArray>* libraries) + : libraries_([libraries mutableCopy]) { + if (libraries_ == nil || libraries_.count == 0) { + return; + } + + is_valid_ = true; +} + +ShaderLibraryMTL::~ShaderLibraryMTL() = default; + +bool ShaderLibraryMTL::IsValid() const { + return is_valid_; +} + +static MTLFunctionType ToMTLFunctionType(ShaderStage stage) { + switch (stage) { + case ShaderStage::kVertex: + return MTLFunctionTypeVertex; + case ShaderStage::kFragment: + return MTLFunctionTypeFragment; + case ShaderStage::kUnknown: + case ShaderStage::kCompute: + return MTLFunctionTypeKernel; + } + FML_UNREACHABLE(); +} + +std::shared_ptr ShaderLibraryMTL::GetFunction( + std::string_view name, + ShaderStage stage) { + if (!IsValid()) { + return nullptr; + } + + if (name.empty()) { + VALIDATION_LOG << "Library function name was empty."; + return nullptr; + } + + ShaderKey key(name, stage); + + id function = nil; + id library = nil; + + { + ReaderLock lock(libraries_mutex_); + + if (auto found = functions_.find(key); found != functions_.end()) { + return found->second; + } + + for (size_t i = 0, count = [libraries_ count]; i < count; i++) { + library = libraries_[i]; + function = [library newFunctionWithName:@(name.data())]; + if (function) { + break; + } + } + + if (function == nil) { + return nullptr; + } + + if (function.functionType != ToMTLFunctionType(stage)) { + VALIDATION_LOG << "Library function named " << name + << " was for an unexpected shader stage."; + return nullptr; + } + + auto func = std::shared_ptr(new ShaderFunctionMTL( + library_id_, function, library, {name.data(), name.size()}, stage)); + functions_[key] = func; + + return func; + } +} + +id ShaderLibraryMTL::GetDevice() const { + ReaderLock lock(libraries_mutex_); + if (libraries_.count > 0u) { + return libraries_[0].device; + } + return nil; +} + +// |ShaderLibrary| +void ShaderLibraryMTL::RegisterFunction(std::string name, // unused + ShaderStage stage, // unused + std::shared_ptr code, + RegistrationCallback callback) { + if (!callback) { + callback = [](auto) {}; + } + auto failure_callback = std::make_shared( + [callback]() { callback(false); }); + if (!IsValid()) { + return; + } + if (code == nullptr || code->GetMapping() == nullptr) { + return; + } + auto device = GetDevice(); + if (device == nil) { + return; + } + + auto source = [[NSString alloc] initWithBytes:code->GetMapping() + length:code->GetSize() + encoding:NSUTF8StringEncoding]; + + auto weak_this = weak_from_this(); + [device newLibraryWithSource:source + options:NULL + completionHandler:^(id library, NSError* error) { + auto strong_this = weak_this.lock(); + if (!strong_this) { + VALIDATION_LOG << "Shader library was collected before " + "dynamic shader stage could be registered."; + return; + } + if (!library) { + VALIDATION_LOG << "Could not register dynamic stage library: " + << error.localizedDescription.UTF8String; + return; + } + reinterpret_cast(strong_this.get()) + ->RegisterLibrary(library); + failure_callback->Release(); + callback(true); + }]; +} + +// |ShaderLibrary| +void ShaderLibraryMTL::UnregisterFunction(std::string name, ShaderStage stage) { + ReaderLock lock(libraries_mutex_); + + // Find the shader library containing this function name and remove it. + + bool found_library = false; + for (size_t i = [libraries_ count] - 1; i >= 0; i--) { + id function = + [libraries_[i] newFunctionWithName:@(name.data())]; + if (function) { + [libraries_ removeObjectAtIndex:i]; + found_library = true; + break; + } + } + if (!found_library) { + VALIDATION_LOG << "Library containing function " << name + << " was not found, so it couldn't be unregistered."; + } + + // Remove the shader from the function cache. + + ShaderKey key(name, stage); + + auto found = functions_.find(key); + if (found == functions_.end()) { + VALIDATION_LOG << "Library function named " << name + << " was not found, so it couldn't be unregistered."; + return; + } + + functions_.erase(found); +} + +void ShaderLibraryMTL::RegisterLibrary(id library) { + WriterLock lock(libraries_mutex_); + [libraries_ addObject:library]; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..b27bd77627c7640123c40e70e93d1aff2a5da649 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.h @@ -0,0 +1,111 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_ + +#include +#include + +#include "impeller/geometry/rect.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +class SurfaceMTL final : public Surface { + public: +#pragma GCC diagnostic push + // Disable the diagnostic for iOS Simulators. Metal without emulation isn't + // available prior to iOS 13 and that's what the simulator headers say when + // support for CAMetalLayer begins. CAMetalLayer is available on iOS 8.0 and + // above which is well below Flutters support level. +#pragma GCC diagnostic ignored "-Wunguarded-availability-new" + //---------------------------------------------------------------------------- + /// @brief Wraps the current drawable of the given Metal layer to create + /// a surface Impeller can render to. The surface must be created + /// as late as possible and discarded immediately after rendering + /// to it. + /// + /// @param[in] context The context + /// @param[in] layer The layer whose current drawable to wrap to create a + /// surface. + /// + /// @return A pointer to the wrapped surface or null. + /// + static id GetMetalDrawableAndValidate( + const std::shared_ptr& context, + CAMetalLayer* layer); + + static std::unique_ptr MakeFromMetalLayerDrawable( + const std::shared_ptr& context, + id drawable, + const std::shared_ptr& transients, + std::optional clip_rect = std::nullopt); + + static std::unique_ptr MakeFromTexture( + const std::shared_ptr& context, + id texture, + const std::shared_ptr& transients, + std::optional clip_rect, + id drawable = nil); +#pragma GCC diagnostic pop + + // |Surface| + ~SurfaceMTL() override; + + id drawable() const { return drawable_; } + + // Returns a Rect defining the area of the surface in device pixels + IRect coverage() const; + + /// Mark this surface as presenting with a transaction. + /// + /// If true, [Present] will block on the scheduling of a command buffer. + void PresentWithTransaction(bool present_with_transaction) { + present_with_transaction_ = present_with_transaction; + } + + /// @brief Perform the final blit and trigger end of frame workloads. + bool PreparePresent() const; + + // |Surface| + bool Present() const override; + + void SetFrameBoundary(bool frame_boundary) { + frame_boundary_ = frame_boundary; + } + + private: + std::weak_ptr context_; + std::shared_ptr resolve_texture_; + id drawable_ = nil; + std::shared_ptr source_texture_; + std::shared_ptr destination_texture_; + bool requires_blit_ = false; + std::optional clip_rect_; + bool frame_boundary_ = false; + bool present_with_transaction_ = false; + mutable bool prepared_ = false; + + static bool ShouldPerformPartialRepaint(std::optional damage_rect); + + SurfaceMTL(const std::weak_ptr& context, + const RenderTarget& target, + std::shared_ptr resolve_texture, + id drawable, + std::shared_ptr source_texture, + std::shared_ptr destination_texture, + bool requires_blit, + std::optional clip_rect); + + SurfaceMTL(const SurfaceMTL&) = delete; + + SurfaceMTL& operator=(const SurfaceMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SURFACE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..24e820d69852df20c21982676d9bfc6702fe4369 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/surface_mtl.mm @@ -0,0 +1,318 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/surface_mtl.h" + +#include "flutter/fml/trace_event.h" +#include "flutter/impeller/renderer/command_buffer.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/render_target.h" + +static_assert(__has_feature(objc_arc), "ARC must be enabled."); + +@protocol FlutterMetalDrawable +- (void)flutterPrepareForPresent:(nonnull id)commandBuffer; +@end + +namespace impeller { + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunguarded-availability-new" + +id SurfaceMTL::GetMetalDrawableAndValidate( + const std::shared_ptr& context, + CAMetalLayer* layer) { + TRACE_EVENT0("impeller", "SurfaceMTL::WrapCurrentMetalLayerDrawable"); + + if (context == nullptr || !context->IsValid() || layer == nil) { + return nullptr; + } + + id current_drawable = nil; + { + TRACE_EVENT0("impeller", "WaitForNextDrawable"); + current_drawable = [layer nextDrawable]; + } + + if (!current_drawable) { + VALIDATION_LOG << "Could not acquire current drawable."; + return nullptr; + } + return current_drawable; +} + +static std::optional WrapTextureWithRenderTarget( + const std::shared_ptr& transients, + id texture, + bool requires_blit, + std::optional clip_rect) { + ISize root_size = {static_cast(texture.width), + static_cast(texture.height)}; + PixelFormat format = FromMTLPixelFormat(texture.pixelFormat); + if (format == PixelFormat::kUnknown) { + VALIDATION_LOG << "Unknown drawable color format."; + return std::nullopt; + } + + transients->SetSizeAndFormat(root_size, format); + + TextureDescriptor resolve_tex_desc; + resolve_tex_desc.format = FromMTLPixelFormat(texture.pixelFormat); + resolve_tex_desc.size = root_size; + resolve_tex_desc.usage = + TextureUsage::kRenderTarget | TextureUsage::kShaderRead; + resolve_tex_desc.sample_count = SampleCount::kCount1; + resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; + + // Create color resolve texture. + std::shared_ptr resolve_tex; + if (requires_blit) { + resolve_tex = transients->GetResolveTexture(); + } else { + resolve_tex = TextureMTL::Create(resolve_tex_desc, texture); + } + + ColorAttachment color0; + color0.texture = transients->GetMSAATexture(); + color0.clear_color = Color::DarkSlateGray(); + color0.load_action = LoadAction::kClear; + color0.store_action = StoreAction::kMultisampleResolve; + color0.resolve_texture = std::move(resolve_tex); + + DepthAttachment depth0; + depth0.load_action = + RenderTarget::kDefaultStencilAttachmentConfig.load_action; + depth0.store_action = + RenderTarget::kDefaultStencilAttachmentConfig.store_action; + depth0.clear_depth = 0u; + depth0.texture = transients->GetDepthStencilTexture(); + + StencilAttachment stencil0; + stencil0.load_action = + RenderTarget::kDefaultStencilAttachmentConfig.load_action; + stencil0.store_action = + RenderTarget::kDefaultStencilAttachmentConfig.store_action; + stencil0.clear_stencil = 0u; + stencil0.texture = transients->GetDepthStencilTexture(); + + RenderTarget render_target; + render_target.SetColorAttachment(color0, 0u); + render_target.SetDepthAttachment(std::move(depth0)); + render_target.SetStencilAttachment(std::move(stencil0)); + + return render_target; +} + +std::unique_ptr SurfaceMTL::MakeFromMetalLayerDrawable( + const std::shared_ptr& context, + id drawable, + const std::shared_ptr& transients, + std::optional clip_rect) { + return SurfaceMTL::MakeFromTexture(context, drawable.texture, transients, + clip_rect, drawable); +} + +std::unique_ptr SurfaceMTL::MakeFromTexture( + const std::shared_ptr& context, + id texture, + const std::shared_ptr& transients, + std::optional clip_rect, + id drawable) { + bool partial_repaint_blit_required = ShouldPerformPartialRepaint(clip_rect); + + // The returned render target is the texture that Impeller will render the + // root pass to. If partial repaint is in use, this may be a new texture which + // is smaller than the given MTLTexture. + auto render_target = WrapTextureWithRenderTarget( + transients, texture, partial_repaint_blit_required, clip_rect); + if (!render_target) { + return nullptr; + } + + // If partial repainting, set a "source" texture. The presence of a source + // texture and clip rect instructs the surface to blit this texture to the + // destination texture. + auto source_texture = partial_repaint_blit_required + ? render_target->GetRenderTargetTexture() + : nullptr; + + // The final "destination" texture is the texture that will be presented. In + // this case, it's always the given drawable. + std::shared_ptr destination_texture; + if (partial_repaint_blit_required) { + // If blitting for partial repaint, we need to wrap the drawable. Simply + // reuse the texture descriptor that was already formed for the new render + // target, but override the size with the drawable's size. + auto destination_descriptor = + render_target->GetRenderTargetTexture()->GetTextureDescriptor(); + destination_descriptor.size = {static_cast(texture.width), + static_cast(texture.height)}; + destination_texture = TextureMTL::Wrapper(destination_descriptor, texture); + } else { + // When not partial repaint blit is needed, the render target texture _is_ + // the drawable texture. + destination_texture = render_target->GetRenderTargetTexture(); + } + + return std::unique_ptr(new SurfaceMTL( + context, // context + *render_target, // target + render_target->GetRenderTargetTexture(), // resolve_texture + drawable, // drawable + source_texture, // source_texture + destination_texture, // destination_texture + partial_repaint_blit_required, // requires_blit + clip_rect // clip_rect + )); +} + +SurfaceMTL::SurfaceMTL(const std::weak_ptr& context, + const RenderTarget& target, + std::shared_ptr resolve_texture, + id drawable, + std::shared_ptr source_texture, + std::shared_ptr destination_texture, + bool requires_blit, + std::optional clip_rect) + : Surface(target), + context_(context), + resolve_texture_(std::move(resolve_texture)), + drawable_(drawable), + source_texture_(std::move(source_texture)), + destination_texture_(std::move(destination_texture)), + requires_blit_(requires_blit), + clip_rect_(clip_rect) {} + +// |Surface| +SurfaceMTL::~SurfaceMTL() = default; + +bool SurfaceMTL::ShouldPerformPartialRepaint(std::optional damage_rect) { + // compositor_context.cc will conditionally disable partial repaint if the + // damage region is large. If that happened, then a nullopt damage rect + // will be provided here. + if (!damage_rect.has_value()) { + return false; + } + // If the damage rect is 0 in at least one dimension, partial repaint isn't + // performed as we skip right to present. + if (damage_rect->IsEmpty()) { + return false; + } + return true; +} + +// |Surface| +IRect SurfaceMTL::coverage() const { + return IRect::MakeSize(resolve_texture_->GetSize()); +} + +bool SurfaceMTL::PreparePresent() const { + auto context = context_.lock(); + if (!context) { + return false; + } + +#ifdef IMPELLER_DEBUG + context->GetResourceAllocator()->DebugTraceMemoryStatistics(); + if (frame_boundary_) { + ContextMTL::Cast(context.get())->GetCaptureManager()->FinishCapture(); + } +#endif // IMPELLER_DEBUG + + if (requires_blit_) { + if (!(source_texture_ && destination_texture_)) { + return false; + } + + auto blit_command_buffer = context->CreateCommandBuffer(); + if (!blit_command_buffer) { + return false; + } + auto blit_pass = blit_command_buffer->CreateBlitPass(); + if (!clip_rect_.has_value()) { + VALIDATION_LOG << "Missing clip rectangle."; + return false; + } + blit_pass->AddCopy(source_texture_, destination_texture_, clip_rect_, + clip_rect_->GetOrigin()); + blit_pass->EncodeCommands(); + if (!context->GetCommandQueue()->Submit({blit_command_buffer}).ok()) { + return false; + } + } +#ifdef IMPELLER_DEBUG + ContextMTL::Cast(context.get())->GetGPUTracer()->MarkFrameEnd(); +#endif // IMPELLER_DEBUG + prepared_ = true; + return true; +} + +// |Surface| +bool SurfaceMTL::Present() const { + if (!prepared_) { + PreparePresent(); + } + auto context = context_.lock(); + if (!context) { + return false; + } + + if (drawable_) { + id command_buffer = + ContextMTL::Cast(context.get()) + ->CreateMTLCommandBuffer("Present Waiter Command Buffer"); + + id metal_drawable = + reinterpret_cast>(drawable_); + if ([metal_drawable conformsToProtocol:@protocol(FlutterMetalDrawable)]) { + [(id)metal_drawable + flutterPrepareForPresent:command_buffer]; + } + + // Intel iOS simulators do not seem to give backpressure on Metal drawable + // aquisition, which can result in Impeller running head of the GPU + // workload by dozens of frames. Slow this process down by blocking + // on submit until the last command buffer is at least scheduled. +#if defined(FML_OS_IOS_SIMULATOR) && defined(FML_ARCH_CPU_X86_64) + constexpr bool alwaysWaitForScheduling = true; +#else + constexpr bool alwaysWaitForScheduling = false; +#endif // defined(FML_OS_IOS_SIMULATOR) && defined(FML_ARCH_CPU_X86_64) + + // If the threads have been merged, or there is a pending frame capture, + // then block on cmd buffer scheduling to ensure that the + // transaction/capture work correctly. + if (present_with_transaction_ || [[NSThread currentThread] isMainThread] || + [[MTLCaptureManager sharedCaptureManager] isCapturing] || + alwaysWaitForScheduling) { + TRACE_EVENT0("flutter", "waitUntilScheduled"); + [command_buffer commit]; +#if defined(FML_OS_IOS_SIMULATOR) && defined(FML_ARCH_CPU_X86_64) + [command_buffer waitUntilCompleted]; +#else + [command_buffer waitUntilScheduled]; +#endif // defined(FML_OS_IOS_SIMULATOR) && defined(FML_ARCH_CPU_X86_64) + [drawable_ present]; + } else { + // The drawable may come from a FlutterMetalLayer, so it can't be + // presented through the command buffer. + id drawable = drawable_; + [command_buffer addScheduledHandler:^(id buffer) { + [drawable present]; + }]; + [command_buffer commit]; + } + } + + return true; +} +#pragma GCC diagnostic pop + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..812bb6cb4639c5367dec91370d61be6907436e45 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.h @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SWAPCHAIN_TRANSIENTS_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SWAPCHAIN_TRANSIENTS_MTL_H_ + +#include + +#include "impeller/core/formats.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +/// @brief A cache for the onscreen texture attachments used in surface_mtl. +/// +/// Typically the onscreen resolve texture is created from a Metal drawable and +/// this cache is only used for the MSAA texture and the depth+stencil +/// attachment. When partial repaint is active, this class also provides a cache +/// for an offscreen resolve texture that is blitted to the real onscreen during +/// present. +class SwapchainTransientsMTL { + public: + explicit SwapchainTransientsMTL(const std::shared_ptr& allocator); + + ~SwapchainTransientsMTL(); + + /// @brief Update the size and pixel format of the onscreens. + /// + /// Note: this will invalidate any cached textures if either property changes. + void SetSizeAndFormat(ISize size, PixelFormat format); + + /// @brief Retrieve the resolve texture, creating one if needed. + std::shared_ptr GetResolveTexture(); + + /// @brief Retrieve the MSAA texture, creating one if needed. + std::shared_ptr GetMSAATexture(); + + /// @brief Retrieve the depth+stencil texture, creating one if needed. + std::shared_ptr GetDepthStencilTexture(); + + private: + std::shared_ptr allocator_; + ISize size_ = {0, 0}; + PixelFormat format_ = PixelFormat::kUnknown; + std::shared_ptr resolve_tex_; + std::shared_ptr msaa_tex_; + std::shared_ptr depth_stencil_tex_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SWAPCHAIN_TRANSIENTS_MTL_H_ \ No newline at end of file diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..6527dd588ef1fb240fbf083586cbf4638fa41850 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl.mm @@ -0,0 +1,92 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" + +namespace impeller { + +SwapchainTransientsMTL::SwapchainTransientsMTL( + const std::shared_ptr& allocator) + : allocator_(allocator) {} + +SwapchainTransientsMTL::~SwapchainTransientsMTL() = default; + +void SwapchainTransientsMTL::SetSizeAndFormat(ISize size, PixelFormat format) { + if (size != size_ || format != format_) { + resolve_tex_ = nullptr; + msaa_tex_ = nullptr; + depth_stencil_tex_ = nullptr; + } + size_ = size; + format_ = format; +} + +std::shared_ptr SwapchainTransientsMTL::GetResolveTexture() { + if (!resolve_tex_) { + TextureDescriptor desc; + desc.size = size_; + desc.sample_count = SampleCount::kCount1; + desc.format = format_; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.usage = TextureUsage::kShaderRead | TextureUsage::kRenderTarget; + desc.compression_type = CompressionType::kLossy; + desc.type = TextureType::kTexture2D; + + resolve_tex_ = allocator_->CreateTexture(desc); + if (!resolve_tex_) { + VALIDATION_LOG << "Failed to allocate resolve texture."; + return nullptr; + } + resolve_tex_->SetLabel("ImpellerOnscreenResolve"); + } + + return resolve_tex_; +} + +std::shared_ptr SwapchainTransientsMTL::GetMSAATexture() { + if (!msaa_tex_) { + TextureDescriptor desc; + desc.size = size_; + desc.sample_count = SampleCount::kCount4; + desc.format = format_; + desc.storage_mode = StorageMode::kDeviceTransient; + desc.usage = TextureUsage::kRenderTarget; + desc.type = TextureType::kTexture2DMultisample; + + msaa_tex_ = allocator_->CreateTexture(desc); + if (!msaa_tex_) { + VALIDATION_LOG << "Failed to allocate MSAA texture."; + return nullptr; + } + msaa_tex_->SetLabel("ImpellerOnscreenMSAA"); + } + + return msaa_tex_; +} + +std::shared_ptr SwapchainTransientsMTL::GetDepthStencilTexture() { + if (!depth_stencil_tex_) { + TextureDescriptor desc; + desc.size = size_; + desc.sample_count = SampleCount::kCount4; + desc.format = PixelFormat::kD32FloatS8UInt; + desc.storage_mode = StorageMode::kDeviceTransient; + desc.usage = TextureUsage::kRenderTarget; + desc.type = TextureType::kTexture2DMultisample; + + depth_stencil_tex_ = allocator_->CreateTexture(desc); + if (!depth_stencil_tex_) { + VALIDATION_LOG << "Failed to allocate depth-stencil texture."; + return nullptr; + } + depth_stencil_tex_->SetLabel("ImpellerOnscreenDepth+Stencil"); + } + + return depth_stencil_tex_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl_unittests.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..40a393084a0444bacfcb6e8a489826461c784847 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/swapchain_transients_mtl_unittests.mm @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/metal/allocator_mtl.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/capabilities.h" + +#include +#include + +#include "gtest/gtest.h" + +namespace impeller { +namespace testing { + +using SwapchainTransientsMTLTest = PlaygroundTest; +INSTANTIATE_METAL_PLAYGROUND_SUITE(SwapchainTransientsMTLTest); + +TEST_P(SwapchainTransientsMTLTest, CanAllocateSwapchainTextures) { + const auto& transients = std::make_shared( + GetContext()->GetResourceAllocator()); + + transients->SetSizeAndFormat({1, 1}, PixelFormat::kB8G8R8A8UNormInt); + + auto resolve = transients->GetResolveTexture(); + EXPECT_NE(resolve, nullptr); + EXPECT_NE(transients->GetMSAATexture(), nullptr); + EXPECT_NE(transients->GetDepthStencilTexture(), nullptr); + + // Texture properties are correct for resolve. + EXPECT_EQ(resolve->GetTextureDescriptor().size, ISize(1, 1)); + EXPECT_EQ(resolve->GetTextureDescriptor().format, + PixelFormat::kB8G8R8A8UNormInt); + EXPECT_EQ(resolve->GetTextureDescriptor().sample_count, SampleCount::kCount1); + EXPECT_EQ(resolve->GetTextureDescriptor().storage_mode, + StorageMode::kDevicePrivate); + + // Texture properties are correct for MSAA. + auto msaa = transients->GetMSAATexture(); + EXPECT_EQ(msaa->GetTextureDescriptor().size, ISize(1, 1)); + EXPECT_EQ(msaa->GetTextureDescriptor().format, + PixelFormat::kB8G8R8A8UNormInt); + EXPECT_EQ(msaa->GetTextureDescriptor().sample_count, SampleCount::kCount4); + EXPECT_EQ(msaa->GetTextureDescriptor().storage_mode, + StorageMode::kDeviceTransient); + + // Texture properties are correct for Depth+Stencil. + auto depth_stencil = transients->GetDepthStencilTexture(); + EXPECT_EQ(depth_stencil->GetTextureDescriptor().size, ISize(1, 1)); + EXPECT_EQ(depth_stencil->GetTextureDescriptor().format, + PixelFormat::kD32FloatS8UInt); + EXPECT_EQ(depth_stencil->GetTextureDescriptor().sample_count, + SampleCount::kCount4); + EXPECT_EQ(depth_stencil->GetTextureDescriptor().storage_mode, + StorageMode::kDeviceTransient); + + // Textures are cached. + EXPECT_EQ(transients->GetResolveTexture(), resolve); + + // Texture cache is invalidated when size changes. + transients->SetSizeAndFormat({2, 2}, PixelFormat::kB8G8R8A8UNormInt); + EXPECT_NE(resolve, transients->GetResolveTexture()); + resolve = transients->GetResolveTexture(); + + // Texture cache is invalidated when pixel format changes. + transients->SetSizeAndFormat({2, 2}, PixelFormat::kB10G10R10A10XR); + EXPECT_NE(resolve, transients->GetResolveTexture()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..3651c0bdc60579c9ef7e0591bfc001d08e6e5970 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.h @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/backend/metal/allocator_mtl.h" + +namespace impeller { + +class TextureMTL final : public Texture, + public BackendCast { + public: + /// @brief This callback needs to always return the same texture when called + /// multiple times. + using AcquireTextureProc = std::function()>; + + TextureMTL(TextureDescriptor desc, + const AcquireTextureProc& aquire_proc, + bool wrapped = false, + bool drawable = false); + + static std::shared_ptr Wrapper( + TextureDescriptor desc, + id texture, + std::function deletion_proc = nullptr); + + static std::shared_ptr Create(TextureDescriptor desc, + id texture); + + // |Texture| + ~TextureMTL() override; + + id GetMTLTexture() const; + + bool IsWrapped() const; + + /// @brief Whether or not this texture is wrapping a Metal drawable. + bool IsDrawable() const; + + // |Texture| + bool IsValid() const override; + + bool GenerateMipmap(id encoder); + +#ifdef IMPELLER_DEBUG + void SetDebugAllocator( + const std::shared_ptr& debug_allocator); +#endif // IMPELLER_DEBUG + + private: +#ifdef IMPELLER_DEBUG + std::shared_ptr debug_allocator_ = nullptr; +#endif // IMPELLER_DEBUG + + AcquireTextureProc aquire_proc_ = {}; + bool is_valid_ = false; + bool is_wrapped_ = false; + bool is_drawable_ = false; + + // |Texture| + void SetLabel(std::string_view label) override; + + // |Texture| + void SetLabel(std::string_view label, std::string_view trailing) override; + + // |Texture| + bool OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) override; + + // |Texture| + bool OnSetContents(std::shared_ptr mapping, + size_t slice) override; + // |Texture| + ISize GetSize() const override; + + TextureMTL(const TextureMTL&) = delete; + + TextureMTL& operator=(const TextureMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..4aebc3190c78b75cad3215d62bdcd3cbb3dbce37 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl.mm @@ -0,0 +1,179 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" + +namespace impeller { + +std::shared_ptr WrapperMTL(TextureDescriptor desc, + const void* mtl_texture, + std::function deletion_proc) { + return TextureMTL::Wrapper(desc, (__bridge id)mtl_texture, + std::move(deletion_proc)); +} + +TextureMTL::TextureMTL(TextureDescriptor p_desc, + const AcquireTextureProc& aquire_proc, + bool wrapped, + bool drawable) + : Texture(p_desc), aquire_proc_(aquire_proc), is_drawable_(drawable) { + const auto& desc = GetTextureDescriptor(); + + if (!desc.IsValid() || !aquire_proc) { + return; + } + + if (desc.size != GetSize()) { + VALIDATION_LOG << "The texture and its descriptor disagree about its size."; + return; + } + + is_wrapped_ = wrapped; + is_valid_ = true; +} + +std::shared_ptr TextureMTL::Wrapper( + TextureDescriptor desc, + id texture, + std::function deletion_proc) { + if (deletion_proc) { + return std::shared_ptr( + new TextureMTL( + desc, [texture]() { return texture; }, true), + [deletion_proc = std::move(deletion_proc)](TextureMTL* t) { + deletion_proc(); + delete t; + }); + } + return std::shared_ptr( + new TextureMTL(desc, [texture]() { return texture; }, true)); +} + +std::shared_ptr TextureMTL::Create(TextureDescriptor desc, + id texture) { + return std::make_shared(desc, [texture]() { return texture; }); +} + +TextureMTL::~TextureMTL() { +#ifdef IMPELLER_DEBUG + if (debug_allocator_) { + auto desc = GetTextureDescriptor(); + if (desc.storage_mode == StorageMode::kDeviceTransient) { + return; + } + debug_allocator_->Decrement(desc.GetByteSizeOfBaseMipLevel()); + } +#endif // IMPELLER_DEBUG +} + +void TextureMTL::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + if (is_drawable_) { + return; + } + [aquire_proc_() setLabel:@(label.data())]; +#endif // IMPELLER_DEBUG +} + +void TextureMTL::SetLabel(std::string_view label, std::string_view trailing) { +#ifdef IMPELLER_DEBUG + if (is_drawable_) { + return; + } + std::string combined = SPrintF("%s %s", label.data(), trailing.data()); + [aquire_proc_() setLabel:@(combined.data())]; +#endif // IMPELLER_DEBUG +} + +// |Texture| +bool TextureMTL::OnSetContents(std::shared_ptr mapping, + size_t slice) { + // Metal has no threading restrictions. So we can pass this data along to the + // client rendering API immediately. + return OnSetContents(mapping->GetMapping(), mapping->GetSize(), slice); +} + +#ifdef IMPELLER_DEBUG +void TextureMTL::SetDebugAllocator( + const std::shared_ptr& debug_allocator) { + debug_allocator_ = debug_allocator; +} +#endif // IMPELLER_DEBUG + +// |Texture| +bool TextureMTL::OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) { + if (!IsValid() || !contents || is_wrapped_ || is_drawable_) { + return false; + } + + const auto& desc = GetTextureDescriptor(); + + // Out of bounds access. + if (length != desc.GetByteSizeOfBaseMipLevel()) { + return false; + } + + const auto region = + MTLRegionMake2D(0u, 0u, desc.size.width, desc.size.height); + [aquire_proc_() replaceRegion:region // + mipmapLevel:0u // + slice:slice // + withBytes:contents // + bytesPerRow:desc.GetBytesPerRow() // + bytesPerImage:desc.GetByteSizeOfBaseMipLevel() // + ]; + + return true; +} + +ISize TextureMTL::GetSize() const { + if (is_drawable_) { + return GetTextureDescriptor().size; + } + const auto& texture = aquire_proc_(); + return {static_cast(texture.width), + static_cast(texture.height)}; +} + +id TextureMTL::GetMTLTexture() const { + return aquire_proc_(); +} + +bool TextureMTL::IsValid() const { + return is_valid_; +} + +bool TextureMTL::IsWrapped() const { + return is_wrapped_; +} + +bool TextureMTL::IsDrawable() const { + return is_drawable_; +} + +bool TextureMTL::GenerateMipmap(id encoder) { + if (is_drawable_) { + return false; + } + + auto texture = aquire_proc_(); + if (!texture) { + return false; + } + + [encoder generateMipmapsForTexture:texture]; + mipmap_generated_ = true; + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl_unittests.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl_unittests.mm new file mode 100644 index 0000000000000000000000000000000000000000..2e263eb0e7db4e958d7a9ab21308ee7cdc7881ea --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_mtl_unittests.mm @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/lazy_drawable_holder.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" +#include "impeller/renderer/capabilities.h" + +#include +#include + +#include "gtest/gtest.h" + +namespace impeller { +namespace testing { + +TEST(TextureMTL, CreateFromDrawable) { + auto device = MTLCreateSystemDefaultDevice(); + auto layer = [[CAMetalLayer alloc] init]; + layer.device = device; + layer.drawableSize = CGSize{100, 100}; + layer.pixelFormat = ToMTLPixelFormat(PixelFormat::kB8G8R8A8UNormInt); + + TextureDescriptor desc; + desc.size = {100, 100}; + desc.format = PixelFormat::kB8G8R8A8UNormInt; + auto drawable_future = GetDrawableDeferred(layer); + auto drawable_texture = + CreateTextureFromDrawableFuture(desc, drawable_future); + + ASSERT_TRUE(drawable_texture->IsValid()); + EXPECT_TRUE(drawable_texture->IsDrawable()); + + // Spawn a thread and acquire the drawable in the thread. + auto thread = std::thread([&drawable_texture]() { + // Force the drawable to be acquired. + drawable_texture->GetMTLTexture(); + }); + thread.join(); + // Block until drawable is acquired. + EXPECT_TRUE(drawable_future.get() != nil); + // Drawable is cached. + EXPECT_TRUE(drawable_texture->GetMTLTexture() != nil); + // Once more for good measure. + EXPECT_TRUE(drawable_texture->GetMTLTexture() != nil); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..1402bd79dc1ff971feceb0322e0f8594f8796c27 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.h @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_WRAPPER_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_WRAPPER_MTL_H_ + +#include "impeller/core/texture.h" + +namespace impeller { + +std::shared_ptr WrapTextureMTL( + TextureDescriptor desc, + const void* mtl_texture, + std::function deletion_proc = nullptr); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_TEXTURE_WRAPPER_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..2b6a908f6d7cb3c8ddd64132c1bcbf2a0e516930 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/texture_wrapper_mtl.mm @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/texture_wrapper_mtl.h" + +#include + +#include "impeller/renderer/backend/metal/formats_mtl.h" +#include "impeller/renderer/backend/metal/texture_mtl.h" + +namespace impeller { + +std::shared_ptr WrapTextureMTL(TextureDescriptor desc, + const void* mtl_texture, + std::function deletion_proc) { + auto texture = (__bridge id)mtl_texture; + desc.format = FromMTLPixelFormat(texture.pixelFormat); + return TextureMTL::Wrapper(desc, texture, std::move(deletion_proc)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h b/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..6c01ac14949b2b5cae6ff6ba03f4fc950e3f7b0d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.h @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_VERTEX_DESCRIPTOR_MTL_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_VERTEX_DESCRIPTOR_MTL_H_ + +#include + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +class VertexDescriptorMTL { + public: + VertexDescriptorMTL(); + + ~VertexDescriptorMTL(); + + bool SetStageInputsAndLayout( + const std::vector& inputs, + const std::vector& layouts); + + MTLVertexDescriptor* GetMTLVertexDescriptor() const; + + private: + MTLVertexDescriptor* descriptor_; + + VertexDescriptorMTL(const VertexDescriptorMTL&) = delete; + + VertexDescriptorMTL& operator=(const VertexDescriptorMTL&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_VERTEX_DESCRIPTOR_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm b/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..6bac6687880c64bf3331de2a84a191eb42c08e61 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/metal/vertex_descriptor_mtl.mm @@ -0,0 +1,210 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/metal/vertex_descriptor_mtl.h" + +#include "flutter/fml/logging.h" +#include "impeller/base/validation.h" + +namespace impeller { + +VertexDescriptorMTL::VertexDescriptorMTL() = default; + +VertexDescriptorMTL::~VertexDescriptorMTL() = default; + +static MTLVertexFormat ReadStageInputFormat(const ShaderStageIOSlot& input) { + if (input.columns != 1) { + // All matrix types are unsupported as vertex inputs. + return MTLVertexFormatInvalid; + } + + switch (input.type) { + case ShaderType::kFloat: { + if (input.bit_width == 8 * sizeof(float)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatFloat; + case 2: + return MTLVertexFormatFloat2; + case 3: + return MTLVertexFormatFloat3; + case 4: + return MTLVertexFormatFloat4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kHalfFloat: { + if (input.bit_width == 8 * sizeof(float) / 2) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatHalf; + case 2: + return MTLVertexFormatHalf2; + case 3: + return MTLVertexFormatHalf3; + case 4: + return MTLVertexFormatHalf4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kDouble: { + // Unsupported. + return MTLVertexFormatInvalid; + } + case ShaderType::kBoolean: { + if (input.bit_width == 8 * sizeof(bool) && input.vec_size == 1) { + return MTLVertexFormatChar; + } + return MTLVertexFormatInvalid; + } + case ShaderType::kSignedByte: { + if (input.bit_width == 8 * sizeof(char)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatChar; + case 2: + return MTLVertexFormatChar2; + case 3: + return MTLVertexFormatChar3; + case 4: + return MTLVertexFormatChar4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kUnsignedByte: { + if (input.bit_width == 8 * sizeof(char)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatUChar; + case 2: + return MTLVertexFormatUChar2; + case 3: + return MTLVertexFormatUChar3; + case 4: + return MTLVertexFormatUChar4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kSignedShort: { + if (input.bit_width == 8 * sizeof(short)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatShort; + case 2: + return MTLVertexFormatShort2; + case 3: + return MTLVertexFormatShort3; + case 4: + return MTLVertexFormatShort4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kUnsignedShort: { + if (input.bit_width == 8 * sizeof(ushort)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatUShort; + case 2: + return MTLVertexFormatUShort2; + case 3: + return MTLVertexFormatUShort3; + case 4: + return MTLVertexFormatUShort4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kSignedInt: { + if (input.bit_width == 8 * sizeof(int32_t)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatInt; + case 2: + return MTLVertexFormatInt2; + case 3: + return MTLVertexFormatInt3; + case 4: + return MTLVertexFormatInt4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kUnsignedInt: { + if (input.bit_width == 8 * sizeof(uint32_t)) { + switch (input.vec_size) { + case 1: + return MTLVertexFormatUInt; + case 2: + return MTLVertexFormatUInt2; + case 3: + return MTLVertexFormatUInt3; + case 4: + return MTLVertexFormatUInt4; + } + } + return MTLVertexFormatInvalid; + } + case ShaderType::kSignedInt64: { + // Unsupported. + return MTLVertexFormatInvalid; + } + case ShaderType::kUnsignedInt64: { + // Unsupported. + return MTLVertexFormatInvalid; + } + case ShaderType::kAtomicCounter: + case ShaderType::kStruct: + case ShaderType::kImage: + case ShaderType::kSampledImage: + case ShaderType::kUnknown: + case ShaderType::kVoid: + case ShaderType::kSampler: + return MTLVertexFormatInvalid; + } +} + +bool VertexDescriptorMTL::SetStageInputsAndLayout( + const std::vector& inputs, + const std::vector& layouts) { + auto descriptor = descriptor_ = [MTLVertexDescriptor vertexDescriptor]; + + // TODO(jonahwilliams): its odd that we offset buffers from the max index on + // metal but not on GLES or Vulkan. We should probably consistently start + // these at zero? + for (size_t i = 0; i < inputs.size(); i++) { + const auto& input = inputs[i]; + auto vertex_format = ReadStageInputFormat(input); + if (vertex_format == MTLVertexFormatInvalid) { + VALIDATION_LOG << "Format for input " << input.name << " not supported."; + return false; + } + auto attrib = descriptor.attributes[input.location]; + attrib.format = vertex_format; + attrib.offset = input.offset; + attrib.bufferIndex = + VertexDescriptor::kReservedVertexBufferIndex - input.binding; + } + + for (size_t i = 0; i < layouts.size(); i++) { + const auto& layout = layouts[i]; + auto vertex_layout = + descriptor.layouts[VertexDescriptor::kReservedVertexBufferIndex - + layout.binding]; + vertex_layout.stride = layout.stride; + vertex_layout.stepRate = 1u; + vertex_layout.stepFunction = MTLVertexStepFunctionPerVertex; + } + return true; +} + +MTLVertexDescriptor* VertexDescriptorMTL::GetMTLVertexDescriptor() const { + return descriptor_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2f31d4f80ed43cd5e2c3b039cca1440e84245bee --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/BUILD.gn @@ -0,0 +1,212 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/testing/android/native_activity/native_activity.gni") +import("//flutter/vulkan/config.gni") +import("../../../tools/impeller.gni") + +impeller_component("vulkan_unittests") { + testonly = true + sources = [ + "allocator_vk_unittests.cc", + "command_encoder_vk_unittests.cc", + "command_pool_vk_unittests.cc", + "context_vk_unittests.cc", + "descriptor_pool_vk_unittests.cc", + "driver_info_vk_unittests.cc", + "fence_waiter_vk_unittests.cc", + "formats_vk_unittests.cc", + "pipeline_cache_data_vk_unittests.cc", + "render_pass_builder_vk_unittests.cc", + "render_pass_cache_unittests.cc", + "render_pass_vk_unittests.cc", + "resource_manager_vk_unittests.cc", + "surface_context_vk_unittests.cc", + "test/gpu_tracer_unittests.cc", + "test/mock_vulkan.cc", + "test/mock_vulkan.h", + "test/mock_vulkan_unittests.cc", + "test/sampler_library_vk_unittests.cc", + "test/swapchain_unittests.cc", + ] + deps = [ + ":vulkan", + "../../../playground:playground_test", + "//flutter/testing:testing_lib", + ] +} + +impeller_component("vulkan") { + sources = [ + "allocator_vk.cc", + "allocator_vk.h", + "barrier_vk.cc", + "barrier_vk.h", + "blit_pass_vk.cc", + "blit_pass_vk.h", + "capabilities_vk.cc", + "capabilities_vk.h", + "command_buffer_vk.cc", + "command_buffer_vk.h", + "command_pool_vk.cc", + "command_pool_vk.h", + "command_queue_vk.cc", + "command_queue_vk.h", + "compute_pass_vk.cc", + "compute_pass_vk.h", + "compute_pipeline_vk.cc", + "compute_pipeline_vk.h", + "context_vk.cc", + "context_vk.h", + "debug_report_vk.cc", + "debug_report_vk.h", + "descriptor_pool_vk.cc", + "descriptor_pool_vk.h", + "device_buffer_vk.cc", + "device_buffer_vk.h", + "device_holder_vk.h", + "driver_info_vk.cc", + "driver_info_vk.h", + "fence_waiter_vk.cc", + "fence_waiter_vk.h", + "formats_vk.cc", + "formats_vk.h", + "gpu_tracer_vk.cc", + "gpu_tracer_vk.h", + "limits_vk.h", + "pipeline_cache_data_vk.cc", + "pipeline_cache_data_vk.h", + "pipeline_cache_vk.cc", + "pipeline_cache_vk.h", + "pipeline_library_vk.cc", + "pipeline_library_vk.h", + "pipeline_vk.cc", + "pipeline_vk.h", + "queue_vk.cc", + "queue_vk.h", + "render_pass_builder_vk.cc", + "render_pass_builder_vk.h", + "render_pass_vk.cc", + "render_pass_vk.h", + "resource_manager_vk.cc", + "resource_manager_vk.h", + "sampler_library_vk.cc", + "sampler_library_vk.h", + "sampler_vk.cc", + "sampler_vk.h", + "shader_function_vk.cc", + "shader_function_vk.h", + "shader_library_vk.cc", + "shader_library_vk.h", + "shared_object_vk.cc", + "shared_object_vk.h", + "surface_context_vk.cc", + "surface_context_vk.h", + "swapchain/khr/khr_swapchain_image_vk.cc", + "swapchain/khr/khr_swapchain_image_vk.h", + "swapchain/khr/khr_swapchain_impl_vk.cc", + "swapchain/khr/khr_swapchain_impl_vk.h", + "swapchain/khr/khr_swapchain_vk.cc", + "swapchain/khr/khr_swapchain_vk.h", + "swapchain/surface_vk.cc", + "swapchain/surface_vk.h", + "swapchain/swapchain_transients_vk.cc", + "swapchain/swapchain_transients_vk.h", + "swapchain/swapchain_vk.cc", + "swapchain/swapchain_vk.h", + "texture_source_vk.cc", + "texture_source_vk.h", + "texture_vk.cc", + "texture_vk.h", + "tracked_objects_vk.cc", + "tracked_objects_vk.h", + "vertex_descriptor_vk.cc", + "vertex_descriptor_vk.h", + "vk.h", + "vma.cc", + "vma.h", + "workarounds_vk.cc", + "workarounds_vk.h", + "yuv_conversion_library_vk.cc", + "yuv_conversion_library_vk.h", + "yuv_conversion_vk.cc", + "yuv_conversion_vk.h", + ] + + if (is_android) { + sources += [ + "android/ahb_texture_source_vk.cc", + "android/ahb_texture_source_vk.h", + "swapchain/ahb/ahb_formats.h", + "swapchain/ahb/ahb_swapchain_impl_vk.cc", + "swapchain/ahb/ahb_swapchain_impl_vk.h", + "swapchain/ahb/ahb_swapchain_vk.cc", + "swapchain/ahb/ahb_swapchain_vk.h", + "swapchain/ahb/ahb_texture_pool_vk.cc", + "swapchain/ahb/ahb_texture_pool_vk.h", + "swapchain/ahb/external_semaphore_vk.cc", + "swapchain/ahb/external_semaphore_vk.h", + ] + } + + public_deps = [ + "../../:renderer", + "../../../shader_archive", + "//flutter/flutter_vma", + "//flutter/fml", + "//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers", + "//flutter/third_party/vulkan_memory_allocator", + ] + + if (is_android) { + public_deps += [ "../../../toolkit/android" ] + } +} + +if (is_android) { + config("public_android_config") { + defines = [ "__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__" ] + } + + test_fixtures("unittests_fixtures") { + fixtures = [] + } + + source_set("unittests_lib") { + visibility = [ ":*" ] + + testonly = true + + sources = [ "android/ahb_texture_source_vk_unittests.cc" ] + + deps = [ + ":unittests_fixtures", + ":vulkan", + "//flutter/testing", + ] + + defines = [ "TESTING" ] + } + + executable("vulkan_android_unittests") { + assert(is_android) + + testonly = true + + output_name = "impeller_vulkan_android_unittests" + + deps = [ ":unittests_lib" ] + } + + native_activity_apk("vulkan_android_apk_unittests") { + apk_name = "impeller_vulkan_android_unittests" + + testonly = true + + deps = [ + ":unittests_lib", + "//flutter/testing/android/native_activity:gtest_activity", + ] + } +} diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..9bd546340a841d2e4251b9ca60e574f6bab273c9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.cc @@ -0,0 +1,573 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/allocator_vk.h" + +#include +#include + +#include "flutter/fml/memory/ref_ptr.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/allocation_size.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { + +static constexpr vk::Flags +ToVKBufferMemoryPropertyFlags(StorageMode mode) { + switch (mode) { + case StorageMode::kHostVisible: + return vk::MemoryPropertyFlagBits::eHostVisible; + case StorageMode::kDevicePrivate: + return vk::MemoryPropertyFlagBits::eDeviceLocal; + case StorageMode::kDeviceTransient: + return vk::MemoryPropertyFlagBits::eLazilyAllocated; + } + FML_UNREACHABLE(); +} + +static VmaAllocationCreateFlags ToVmaAllocationBufferCreateFlags( + StorageMode mode, + bool readback) { + VmaAllocationCreateFlags flags = 0; + switch (mode) { + case StorageMode::kHostVisible: + if (!readback) { + flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; + } else { + flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; + } + flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT; + return flags; + case StorageMode::kDevicePrivate: + FML_DCHECK(!readback); + return flags; + case StorageMode::kDeviceTransient: + FML_DCHECK(!readback); + return flags; + } + FML_UNREACHABLE(); +} + +static PoolVMA CreateBufferPool(VmaAllocator allocator) { + vk::BufferCreateInfo buffer_info; + buffer_info.usage = vk::BufferUsageFlagBits::eVertexBuffer | + vk::BufferUsageFlagBits::eIndexBuffer | + vk::BufferUsageFlagBits::eUniformBuffer | + vk::BufferUsageFlagBits::eStorageBuffer | + vk::BufferUsageFlagBits::eTransferSrc | + vk::BufferUsageFlagBits::eTransferDst; + buffer_info.size = 1u; // doesn't matter + buffer_info.sharingMode = vk::SharingMode::eExclusive; + auto buffer_info_native = + static_cast(buffer_info); + + VmaAllocationCreateInfo allocation_info = {}; + allocation_info.usage = VMA_MEMORY_USAGE_AUTO; + allocation_info.preferredFlags = static_cast( + ToVKBufferMemoryPropertyFlags(StorageMode::kHostVisible)); + allocation_info.flags = ToVmaAllocationBufferCreateFlags( + StorageMode::kHostVisible, /*readback=*/false); + + uint32_t memTypeIndex; + auto result = vk::Result{vmaFindMemoryTypeIndexForBufferInfo( + allocator, &buffer_info_native, &allocation_info, &memTypeIndex)}; + if (result != vk::Result::eSuccess) { + return {}; + } + + VmaPoolCreateInfo pool_create_info = {}; + pool_create_info.memoryTypeIndex = memTypeIndex; + pool_create_info.flags = VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT; + pool_create_info.minBlockCount = 1; + + VmaPool pool = {}; + result = vk::Result{::vmaCreatePool(allocator, &pool_create_info, &pool)}; + if (result != vk::Result::eSuccess) { + return {}; + } + return {allocator, pool}; +} + +AllocatorVK::AllocatorVK(std::weak_ptr context, + uint32_t vulkan_api_version, + const vk::PhysicalDevice& physical_device, + const std::shared_ptr& device_holder, + const vk::Instance& instance, + const CapabilitiesVK& capabilities) + : context_(std::move(context)), device_holder_(device_holder) { + auto limits = physical_device.getProperties().limits; + max_texture_size_.width = max_texture_size_.height = + limits.maxImageDimension2D; + physical_device.getMemoryProperties(&memory_properties_); + + VmaVulkanFunctions proc_table = {}; + +#define BIND_VMA_PROC(x) proc_table.x = VULKAN_HPP_DEFAULT_DISPATCHER.x; +#define BIND_VMA_PROC_KHR(x) \ + proc_table.x##KHR = VULKAN_HPP_DEFAULT_DISPATCHER.x \ + ? VULKAN_HPP_DEFAULT_DISPATCHER.x \ + : VULKAN_HPP_DEFAULT_DISPATCHER.x##KHR; + BIND_VMA_PROC(vkGetInstanceProcAddr); + BIND_VMA_PROC(vkGetDeviceProcAddr); + BIND_VMA_PROC(vkGetPhysicalDeviceProperties); + BIND_VMA_PROC(vkGetPhysicalDeviceMemoryProperties); + BIND_VMA_PROC(vkAllocateMemory); + BIND_VMA_PROC(vkFreeMemory); + BIND_VMA_PROC(vkMapMemory); + BIND_VMA_PROC(vkUnmapMemory); + BIND_VMA_PROC(vkFlushMappedMemoryRanges); + BIND_VMA_PROC(vkInvalidateMappedMemoryRanges); + BIND_VMA_PROC(vkBindBufferMemory); + BIND_VMA_PROC(vkBindImageMemory); + BIND_VMA_PROC(vkGetBufferMemoryRequirements); + BIND_VMA_PROC(vkGetImageMemoryRequirements); + BIND_VMA_PROC(vkCreateBuffer); + BIND_VMA_PROC(vkDestroyBuffer); + BIND_VMA_PROC(vkCreateImage); + BIND_VMA_PROC(vkDestroyImage); + BIND_VMA_PROC(vkCmdCopyBuffer); + BIND_VMA_PROC_KHR(vkGetBufferMemoryRequirements2); + BIND_VMA_PROC_KHR(vkGetImageMemoryRequirements2); + BIND_VMA_PROC_KHR(vkBindBufferMemory2); + BIND_VMA_PROC_KHR(vkBindImageMemory2); + BIND_VMA_PROC_KHR(vkGetPhysicalDeviceMemoryProperties2); +#undef BIND_VMA_PROC_KHR +#undef BIND_VMA_PROC + + VmaAllocatorCreateInfo allocator_info = {}; + allocator_info.vulkanApiVersion = vulkan_api_version; + allocator_info.physicalDevice = physical_device; + allocator_info.device = device_holder->GetDevice(); + allocator_info.instance = instance; + // 4 MB, matching the default used by Skia Vulkan. + allocator_info.preferredLargeHeapBlockSize = 4 * 1024 * 1024; + allocator_info.pVulkanFunctions = &proc_table; + + VmaAllocator allocator = {}; + auto result = vk::Result{::vmaCreateAllocator(&allocator_info, &allocator)}; + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create memory allocator"; + return; + } + staging_buffer_pool_.reset(CreateBufferPool(allocator)); + created_buffer_pool_ &= staging_buffer_pool_.is_valid(); + allocator_.reset(allocator); + supports_memoryless_textures_ = + capabilities.SupportsDeviceTransientTextures(); + is_valid_ = true; +} + +AllocatorVK::~AllocatorVK() = default; + +// |Allocator| +bool AllocatorVK::IsValid() const { + return is_valid_; +} + +// |Allocator| +ISize AllocatorVK::GetMaxTextureSizeSupported() const { + return max_texture_size_; +} + +int32_t AllocatorVK::FindMemoryTypeIndex( + uint32_t memory_type_bits_requirement, + vk::PhysicalDeviceMemoryProperties& memory_properties) { + int32_t type_index = -1; + vk::MemoryPropertyFlagBits required_properties = + vk::MemoryPropertyFlagBits::eDeviceLocal; + + const uint32_t memory_count = memory_properties.memoryTypeCount; + for (uint32_t memory_index = 0; memory_index < memory_count; ++memory_index) { + const uint32_t memory_type_bits = (1 << memory_index); + const bool is_required_memory_type = + memory_type_bits_requirement & memory_type_bits; + + const auto properties = + memory_properties.memoryTypes[memory_index].propertyFlags; + const bool has_required_properties = + (properties & required_properties) == required_properties; + + if (is_required_memory_type && has_required_properties) { + return static_cast(memory_index); + } + } + + return type_index; +} + +vk::ImageUsageFlags AllocatorVK::ToVKImageUsageFlags( + PixelFormat format, + TextureUsageMask usage, + StorageMode mode, + bool supports_memoryless_textures) { + vk::ImageUsageFlags vk_usage; + + switch (mode) { + case StorageMode::kHostVisible: + case StorageMode::kDevicePrivate: + break; + case StorageMode::kDeviceTransient: + if (supports_memoryless_textures) { + vk_usage |= vk::ImageUsageFlagBits::eTransientAttachment; + } + break; + } + + if (usage & TextureUsage::kRenderTarget) { + if (PixelFormatIsDepthStencil(format)) { + vk_usage |= vk::ImageUsageFlagBits::eDepthStencilAttachment; + } else { + vk_usage |= vk::ImageUsageFlagBits::eColorAttachment; + vk_usage |= vk::ImageUsageFlagBits::eInputAttachment; + } + } + + if (usage & TextureUsage::kShaderRead) { + vk_usage |= vk::ImageUsageFlagBits::eSampled; + } + + if (usage & TextureUsage::kShaderWrite) { + vk_usage |= vk::ImageUsageFlagBits::eStorage; + } + + if (mode != StorageMode::kDeviceTransient) { + // Add transfer usage flags to support blit passes only if image isn't + // device transient. + vk_usage |= vk::ImageUsageFlagBits::eTransferSrc | + vk::ImageUsageFlagBits::eTransferDst; + } + + return vk_usage; +} + +static constexpr VmaMemoryUsage ToVMAMemoryUsage() { + return VMA_MEMORY_USAGE_AUTO; +} + +static constexpr vk::Flags +ToVKTextureMemoryPropertyFlags(StorageMode mode, + bool supports_memoryless_textures) { + switch (mode) { + case StorageMode::kHostVisible: + return vk::MemoryPropertyFlagBits::eHostVisible | + vk::MemoryPropertyFlagBits::eDeviceLocal; + case StorageMode::kDevicePrivate: + return vk::MemoryPropertyFlagBits::eDeviceLocal; + case StorageMode::kDeviceTransient: + if (supports_memoryless_textures) { + return vk::MemoryPropertyFlagBits::eLazilyAllocated | + vk::MemoryPropertyFlagBits::eDeviceLocal; + } + return vk::MemoryPropertyFlagBits::eDeviceLocal; + } + FML_UNREACHABLE(); +} + +static VmaAllocationCreateFlags ToVmaAllocationCreateFlags(StorageMode mode) { + VmaAllocationCreateFlags flags = 0; + switch (mode) { + case StorageMode::kHostVisible: + return flags; + case StorageMode::kDevicePrivate: + return flags; + case StorageMode::kDeviceTransient: + return flags; + } + FML_UNREACHABLE(); +} + +class AllocatedTextureSourceVK final : public TextureSourceVK { + public: + AllocatedTextureSourceVK(const ContextVK& context, + const TextureDescriptor& desc, + VmaAllocator allocator, + vk::Device device, + bool supports_memoryless_textures) + : TextureSourceVK(desc), resource_(context.GetResourceManager()) { + FML_DCHECK(desc.format != PixelFormat::kUnknown); + vk::StructureChain + image_info_chain; + auto& image_info = image_info_chain.get(); + image_info.flags = ToVKImageCreateFlags(desc.type); + image_info.imageType = vk::ImageType::e2D; + image_info.format = ToVKImageFormat(desc.format); + image_info.extent = VkExtent3D{ + static_cast(desc.size.width), // width + static_cast(desc.size.height), // height + 1u // depth + }; + image_info.samples = ToVKSampleCount(desc.sample_count); + image_info.mipLevels = desc.mip_count; + image_info.arrayLayers = ToArrayLayerCount(desc.type); + image_info.tiling = vk::ImageTiling::eOptimal; + image_info.initialLayout = vk::ImageLayout::eUndefined; + image_info.usage = AllocatorVK::ToVKImageUsageFlags( + desc.format, desc.usage, desc.storage_mode, + supports_memoryless_textures); + image_info.sharingMode = vk::SharingMode::eExclusive; + + vk::ImageCompressionFixedRateFlagsEXT frc_rates[1] = { + vk::ImageCompressionFixedRateFlagBitsEXT::eNone}; + + const auto frc_rate = + CapabilitiesVK::Cast(*context.GetCapabilities()) + .GetSupportedFRCRate(desc.compression_type, + FRCFormatDescriptor{image_info}); + if (frc_rate.has_value()) { + // This array must not be in a temporary scope. + frc_rates[0] = frc_rate.value(); + + auto& compression_info = + image_info_chain.get(); + compression_info.pFixedRateFlags = frc_rates; + compression_info.compressionControlPlaneCount = 1u; + compression_info.flags = + vk::ImageCompressionFlagBitsEXT::eFixedRateExplicit; + } else { + image_info_chain.unlink(); + } + + VmaAllocationCreateInfo alloc_nfo = {}; + + alloc_nfo.usage = ToVMAMemoryUsage(); + alloc_nfo.preferredFlags = + static_cast(ToVKTextureMemoryPropertyFlags( + desc.storage_mode, supports_memoryless_textures)); + alloc_nfo.flags = ToVmaAllocationCreateFlags(desc.storage_mode); + + auto create_info_native = + static_cast(image_info); + + VkImage vk_image = VK_NULL_HANDLE; + VmaAllocation allocation = {}; + VmaAllocationInfo allocation_info = {}; + { + auto result = vk::Result{::vmaCreateImage(allocator, // + &create_info_native, // + &alloc_nfo, // + &vk_image, // + &allocation, // + &allocation_info // + )}; + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to allocate Vulkan Image: " + << vk::to_string(result) + << " Type: " << TextureTypeToString(desc.type) + << " Mode: " << StorageModeToString(desc.storage_mode) + << " Usage: " << TextureUsageMaskToString(desc.usage) + << " [VK]Flags: " << vk::to_string(image_info.flags) + << " [VK]Format: " << vk::to_string(image_info.format) + << " [VK]Usage: " << vk::to_string(image_info.usage) + << " [VK]Mem. Flags: " + << vk::to_string(vk::MemoryPropertyFlags( + alloc_nfo.preferredFlags)); + return; + } + } + + auto image = vk::Image{vk_image}; + + vk::ImageViewCreateInfo view_info = {}; + view_info.image = image; + view_info.viewType = ToVKImageViewType(desc.type); + view_info.format = image_info.format; + view_info.subresourceRange.aspectMask = ToVKImageAspectFlags(desc.format); + view_info.subresourceRange.levelCount = image_info.mipLevels; + view_info.subresourceRange.layerCount = ToArrayLayerCount(desc.type); + + // Vulkan does not have an image format that is equivalent to + // `MTLPixelFormatA8Unorm`, so we use `R8Unorm` instead. Given that the + // shaders expect that alpha channel to be set in the cases, we swizzle. + // See: https://github.com/flutter/flutter/issues/115461 for more details. + if (desc.format == PixelFormat::kA8UNormInt) { + view_info.components.a = vk::ComponentSwizzle::eR; + view_info.components.r = vk::ComponentSwizzle::eA; + } + + auto [result, image_view] = device.createImageViewUnique(view_info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to create an image view for allocation: " + << vk::to_string(result); + return; + } + // Create a specialized view for render target attachments. + view_info.subresourceRange.levelCount = 1u; + auto [rt_result, rt_image_view] = device.createImageViewUnique(view_info); + if (rt_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to create an image view for allocation: " + << vk::to_string(rt_result); + return; + } + + resource_.Swap(ImageResource( + ImageVMA{allocator, allocation, image}, std::move(image_view), + std::move(rt_image_view), context.GetResourceAllocator(), + context.GetDeviceHolder())); + is_valid_ = true; + } + + ~AllocatedTextureSourceVK() = default; + + bool IsValid() const { return is_valid_; } + + vk::Image GetImage() const override { return resource_->image.get().image; } + + vk::ImageView GetImageView() const override { + return resource_->image_view.get(); + } + + vk::ImageView GetRenderTargetView() const override { + return resource_->rt_image_view.get(); + } + + bool IsSwapchainImage() const override { return false; } + + private: + struct ImageResource { + std::shared_ptr device_holder; + std::shared_ptr allocator; + UniqueImageVMA image; + vk::UniqueImageView image_view; + vk::UniqueImageView rt_image_view; + + ImageResource() = default; + + ImageResource(ImageVMA p_image, + vk::UniqueImageView p_image_view, + vk::UniqueImageView p_rt_image_view, + std::shared_ptr allocator, + std::shared_ptr device_holder) + : device_holder(std::move(device_holder)), + allocator(std::move(allocator)), + image(p_image), + image_view(std::move(p_image_view)), + rt_image_view(std::move(p_rt_image_view)) {} + + ImageResource(ImageResource&& o) = default; + + ImageResource(const ImageResource&) = delete; + + ImageResource& operator=(const ImageResource&) = delete; + }; + + UniqueResourceVKT resource_; + bool is_valid_ = false; + + AllocatedTextureSourceVK(const AllocatedTextureSourceVK&) = delete; + + AllocatedTextureSourceVK& operator=(const AllocatedTextureSourceVK&) = delete; +}; + +// |Allocator| +std::shared_ptr AllocatorVK::OnCreateTexture( + const TextureDescriptor& desc) { + if (!IsValid()) { + return nullptr; + } + auto device_holder = device_holder_.lock(); + if (!device_holder) { + return nullptr; + } + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto source = std::make_shared( + ContextVK::Cast(*context), // + desc, // + allocator_.get(), // + device_holder->GetDevice(), // + supports_memoryless_textures_ // + ); + if (!source->IsValid()) { + return nullptr; + } + return std::make_shared(context_, std::move(source)); +} + +// |Allocator| +std::shared_ptr AllocatorVK::OnCreateBuffer( + const DeviceBufferDescriptor& desc) { + vk::BufferCreateInfo buffer_info; + buffer_info.usage = vk::BufferUsageFlagBits::eVertexBuffer | + vk::BufferUsageFlagBits::eIndexBuffer | + vk::BufferUsageFlagBits::eUniformBuffer | + vk::BufferUsageFlagBits::eStorageBuffer | + vk::BufferUsageFlagBits::eTransferSrc | + vk::BufferUsageFlagBits::eTransferDst; + buffer_info.size = desc.size; + buffer_info.sharingMode = vk::SharingMode::eExclusive; + auto buffer_info_native = + static_cast(buffer_info); + + VmaAllocationCreateInfo allocation_info = {}; + allocation_info.usage = ToVMAMemoryUsage(); + allocation_info.preferredFlags = static_cast( + ToVKBufferMemoryPropertyFlags(desc.storage_mode)); + allocation_info.flags = + ToVmaAllocationBufferCreateFlags(desc.storage_mode, desc.readback); + if (created_buffer_pool_ && desc.storage_mode == StorageMode::kHostVisible && + !desc.readback) { + allocation_info.pool = staging_buffer_pool_.get().pool; + } + VkBuffer buffer = {}; + VmaAllocation buffer_allocation = {}; + VmaAllocationInfo buffer_allocation_info = {}; + auto result = vk::Result{::vmaCreateBuffer(allocator_.get(), // + &buffer_info_native, // + &allocation_info, // + &buffer, // + &buffer_allocation, // + &buffer_allocation_info // + )}; + + auto type = memory_properties_.memoryTypes[buffer_allocation_info.memoryType]; + bool is_host_coherent = + !!(type.propertyFlags & vk::MemoryPropertyFlagBits::eHostCoherent); + + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to allocate a device buffer: " + << vk::to_string(result); + return {}; + } + + return std::make_shared( + desc, // + context_, // + UniqueBufferVMA{BufferVMA{allocator_.get(), // + buffer_allocation, // + vk::Buffer{buffer}}}, // + buffer_allocation_info, // + is_host_coherent); +} + +Bytes AllocatorVK::DebugGetHeapUsage() const { + auto count = memory_properties_.memoryHeapCount; + std::vector budgets(count); + vmaGetHeapBudgets(allocator_.get(), budgets.data()); + size_t total_usage = 0; + for (auto i = 0u; i < count; i++) { + const VmaBudget& budget = budgets[i]; + total_usage += budget.usage; + } + return Bytes{static_cast(total_usage)}; +} + +void AllocatorVK::DebugTraceMemoryStatistics() const { +#ifdef IMPELLER_DEBUG + FML_TRACE_COUNTER("flutter", "AllocatorVK", + reinterpret_cast(this), // Trace Counter ID + "MemoryBudgetUsageMB", + DebugGetHeapUsage().ConvertTo().GetSize()); +#endif // IMPELLER_DEBUG +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..53e2772e740a66810117dbe44450456b25ffcdcd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk.h @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ALLOCATOR_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ALLOCATOR_VK_H_ + +#include "impeller/core/allocator.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +#include +#include + +namespace impeller { + +class AllocatorVK final : public Allocator { + public: + // |Allocator| + ~AllocatorVK() override; + + // |Allocator| + Bytes DebugGetHeapUsage() const override; + + /// @brief Select a matching memory type for the given + /// [memory_type_bits_requirement], or -1 if none is found. + /// + /// This only returns memory types with deviceLocal allocations. + static int32_t FindMemoryTypeIndex( + uint32_t memory_type_bits_requirement, + vk::PhysicalDeviceMemoryProperties& memory_properties); + + // Visible for testing. + static vk::ImageUsageFlags ToVKImageUsageFlags( + PixelFormat format, + TextureUsageMask usage, + StorageMode mode, + bool supports_memoryless_textures); + + private: + friend class ContextVK; + + UniqueAllocatorVMA allocator_; + UniquePoolVMA staging_buffer_pool_; + std::weak_ptr context_; + std::weak_ptr device_holder_; + ISize max_texture_size_; + bool is_valid_ = false; + bool supports_memoryless_textures_ = false; + // TODO(jonahwilliams): figure out why CI can't create these buffer pools. + bool created_buffer_pool_ = true; + vk::PhysicalDeviceMemoryProperties memory_properties_; + + AllocatorVK(std::weak_ptr context, + uint32_t vulkan_api_version, + const vk::PhysicalDevice& physical_device, + const std::shared_ptr& device_holder, + const vk::Instance& instance, + const CapabilitiesVK& capabilities); + + // |Allocator| + bool IsValid() const; + + // |Allocator| + std::shared_ptr OnCreateBuffer( + const DeviceBufferDescriptor& desc) override; + + // |Allocator| + std::shared_ptr OnCreateTexture( + const TextureDescriptor& desc) override; + + // |Allocator| + ISize GetMaxTextureSizeSupported() const override; + + // |Allocator| + void DebugTraceMemoryStatistics() const override; + + AllocatorVK(const AllocatorVK&) = delete; + + AllocatorVK& operator=(const AllocatorVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ALLOCATOR_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0cf893020721558c8ab04a096d06090417720d4b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/allocator_vk_unittests.cc @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/base/allocation_size.h" +#include "impeller/core/allocator.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/allocator_vk.h" +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { +namespace testing { + +TEST(AllocatorVKTest, ToVKImageUsageFlags) { + EXPECT_EQ(AllocatorVK::ToVKImageUsageFlags( + PixelFormat::kR8G8B8A8UNormInt, + static_cast(TextureUsage::kRenderTarget), + StorageMode::kDeviceTransient, + /*supports_memoryless_textures=*/true), + vk::ImageUsageFlagBits::eInputAttachment | + vk::ImageUsageFlagBits::eColorAttachment | + vk::ImageUsageFlagBits::eTransientAttachment); + + EXPECT_EQ(AllocatorVK::ToVKImageUsageFlags( + PixelFormat::kD24UnormS8Uint, + static_cast(TextureUsage::kRenderTarget), + StorageMode::kDeviceTransient, + /*supports_memoryless_textures=*/true), + vk::ImageUsageFlagBits::eDepthStencilAttachment | + vk::ImageUsageFlagBits::eTransientAttachment); +} + +TEST(AllocatorVKTest, MemoryTypeSelectionSingleHeap) { + vk::PhysicalDeviceMemoryProperties properties; + properties.memoryTypeCount = 1; + properties.memoryHeapCount = 1; + properties.memoryTypes[0].heapIndex = 0; + properties.memoryTypes[0].propertyFlags = + vk::MemoryPropertyFlagBits::eDeviceLocal; + properties.memoryHeaps[0].size = 1024 * 1024 * 1024; + properties.memoryHeaps[0].flags = vk::MemoryHeapFlagBits::eDeviceLocal; + + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(1, properties), 0); + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(2, properties), -1); + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(3, properties), 0); +} + +TEST(AllocatorVKTest, MemoryTypeSelectionTwoHeap) { + vk::PhysicalDeviceMemoryProperties properties; + properties.memoryTypeCount = 2; + properties.memoryHeapCount = 2; + properties.memoryTypes[0].heapIndex = 0; + properties.memoryTypes[0].propertyFlags = + vk::MemoryPropertyFlagBits::eHostVisible; + properties.memoryHeaps[0].size = 1024 * 1024 * 1024; + properties.memoryHeaps[0].flags = vk::MemoryHeapFlagBits::eDeviceLocal; + + properties.memoryTypes[1].heapIndex = 1; + properties.memoryTypes[1].propertyFlags = + vk::MemoryPropertyFlagBits::eDeviceLocal; + properties.memoryHeaps[1].size = 1024 * 1024 * 1024; + properties.memoryHeaps[1].flags = vk::MemoryHeapFlagBits::eDeviceLocal; + + // First fails because this only looks for eDeviceLocal. + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(1, properties), -1); + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(2, properties), 1); + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(3, properties), 1); + EXPECT_EQ(AllocatorVK::FindMemoryTypeIndex(4, properties), -1); +} + +TEST(AllocatorVKTest, ImageResourceKeepsVulkanDeviceAlive) { + std::shared_ptr texture; + std::weak_ptr weak_allocator; + { + auto const context = MockVulkanContextBuilder().Build(); + weak_allocator = context->GetResourceAllocator(); + auto allocator = context->GetResourceAllocator(); + + texture = allocator->CreateTexture(TextureDescriptor{ + .storage_mode = StorageMode::kDevicePrivate, + .format = PixelFormat::kR8G8B8A8UNormInt, + .size = {1, 1}, + }); + context->Shutdown(); + } + + ASSERT_TRUE(weak_allocator.lock()); +} + +#ifdef IMPELLER_DEBUG + +TEST(AllocatorVKTest, RecreateSwapchainWhenSizeChanges) { + auto const context = MockVulkanContextBuilder().Build(); + auto allocator = context->GetResourceAllocator(); + + EXPECT_EQ(reinterpret_cast(allocator.get()) + ->DebugGetHeapUsage() + .GetByteSize(), + 0u); + + allocator->CreateBuffer(DeviceBufferDescriptor{ + .storage_mode = StorageMode::kDevicePrivate, + .size = 1024, + }); + + // Usage increases beyond the size of the allocated buffer since VMA will + // first allocate large blocks of memory and then suballocate small memory + // allocations. + EXPECT_EQ(reinterpret_cast(allocator.get()) + ->DebugGetHeapUsage() + .ConvertTo() + .GetSize(), + 16u); +} + +#endif // IMPELLER_DEBUG + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..8fe476644830a14f394f87b95a90f5213fbe89e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.cc @@ -0,0 +1,442 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" + +#include "impeller/renderer/backend/vulkan/allocator_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h" + +namespace impeller { + +namespace { + +bool RequiresYCBCRConversion(vk::Format format) { + switch (format) { + case vk::Format::eG8B8R83Plane420Unorm: + case vk::Format::eG8B8R82Plane420Unorm: + case vk::Format::eG8B8R83Plane422Unorm: + case vk::Format::eG8B8R82Plane422Unorm: + case vk::Format::eG8B8R83Plane444Unorm: + return true; + default: + // NOTE: NOT EXHAUSTIVE. + break; + } + return false; +} + +using AHBProperties = vk::StructureChain< + // For VK_ANDROID_external_memory_android_hardware_buffer + vk::AndroidHardwareBufferPropertiesANDROID, + // For VK_ANDROID_external_memory_android_hardware_buffer + vk::AndroidHardwareBufferFormatPropertiesANDROID>; + +vk::UniqueImage CreateVKImageWrapperForAndroidHarwareBuffer( + const vk::Device& device, + const AHBProperties& ahb_props, + const AHardwareBuffer_Desc& ahb_desc) { + const auto& ahb_format = + ahb_props.get(); + + vk::StructureChain + image_chain; + + auto& image_info = image_chain.get(); + + vk::ImageUsageFlags image_usage_flags; + if (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE) { + image_usage_flags |= vk::ImageUsageFlagBits::eSampled; + } + if (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER) { + image_usage_flags |= vk::ImageUsageFlagBits::eColorAttachment; + image_usage_flags |= vk::ImageUsageFlagBits::eInputAttachment; + } + + vk::ImageCreateFlags image_create_flags; + if (ahb_desc.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT) { + image_create_flags |= vk::ImageCreateFlagBits::eProtected; + } + if (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP) { + image_create_flags |= vk::ImageCreateFlagBits::eCubeCompatible; + } + + image_info.imageType = vk::ImageType::e2D; + image_info.format = ahb_format.format; + image_info.extent.width = ahb_desc.width; + image_info.extent.height = ahb_desc.height; + image_info.extent.depth = 1; + image_info.mipLevels = + (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE) + ? ISize{ahb_desc.width, ahb_desc.height}.MipCount() + : 1u; + image_info.arrayLayers = ahb_desc.layers; + image_info.samples = vk::SampleCountFlagBits::e1; + image_info.tiling = vk::ImageTiling::eOptimal; + image_info.usage = image_usage_flags; + image_info.flags = image_create_flags; + image_info.sharingMode = vk::SharingMode::eExclusive; + image_info.initialLayout = vk::ImageLayout::eUndefined; + + image_chain.get().handleTypes = + vk::ExternalMemoryHandleTypeFlagBits::eAndroidHardwareBufferANDROID; + + // If the format isn't natively supported by Vulkan (i.e, be a part of the + // base vkFormat enum), an untyped "external format" must be specified when + // creating the image and the image views. Usually includes YUV formats. + if (ahb_format.format == vk::Format::eUndefined) { + image_chain.get().externalFormat = + ahb_format.externalFormat; + } else { + image_chain.unlink(); + } + + auto image = device.createImageUnique(image_chain.get()); + if (image.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create image for external buffer: " + << vk::to_string(image.result); + return {}; + } + + return std::move(image.value); +} + +vk::UniqueDeviceMemory ImportVKDeviceMemoryFromAndroidHarwareBuffer( + const vk::Device& device, + const vk::PhysicalDevice& physical_device, + const vk::Image& image, + struct AHardwareBuffer* hardware_buffer, + const AHBProperties& ahb_props) { + vk::PhysicalDeviceMemoryProperties memory_properties; + physical_device.getMemoryProperties(&memory_properties); + int memory_type_index = AllocatorVK::FindMemoryTypeIndex( + ahb_props.get().memoryTypeBits, memory_properties); + if (memory_type_index < 0) { + VALIDATION_LOG << "Could not find memory type of external image."; + return {}; + } + + vk::StructureChain + memory_chain; + + auto& mem_alloc_info = memory_chain.get(); + mem_alloc_info.allocationSize = ahb_props.get().allocationSize; + mem_alloc_info.memoryTypeIndex = memory_type_index; + + auto& dedicated_alloc_info = + memory_chain.get(); + dedicated_alloc_info.image = image; + + auto& ahb_import_info = + memory_chain.get(); + ahb_import_info.buffer = hardware_buffer; + + auto device_memory = device.allocateMemoryUnique(memory_chain.get()); + if (device_memory.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not allocate device memory for external image : " + << vk::to_string(device_memory.result); + return {}; + } + + return std::move(device_memory.value); +} + +std::shared_ptr CreateYUVConversion( + const ContextVK& context, + const AHBProperties& ahb_props) { + YUVConversionDescriptorVK conversion_chain; + + const auto& ahb_format = + ahb_props.get(); + + // See https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5806 + // Both features are required. + const bool supports_linear_filtering = + !!(ahb_format.formatFeatures & + vk::FormatFeatureFlagBits::eSampledImageYcbcrConversionLinearFilter) && + !!(ahb_format.formatFeatures & + vk::FormatFeatureFlagBits::eSampledImageFilterLinear); + auto& conversion_info = conversion_chain.get(); + + conversion_info.format = ahb_format.format; + conversion_info.ycbcrModel = ahb_format.suggestedYcbcrModel; + conversion_info.ycbcrRange = ahb_format.suggestedYcbcrRange; + conversion_info.components = ahb_format.samplerYcbcrConversionComponents; + conversion_info.xChromaOffset = ahb_format.suggestedXChromaOffset; + conversion_info.yChromaOffset = ahb_format.suggestedYChromaOffset; + conversion_info.chromaFilter = + supports_linear_filtering ? vk::Filter::eLinear : vk::Filter::eNearest; + + conversion_info.forceExplicitReconstruction = false; + + if (conversion_info.format == vk::Format::eUndefined) { + auto& external_format = conversion_chain.get(); + external_format.externalFormat = ahb_format.externalFormat; + } else { + conversion_chain.unlink(); + } + + return context.GetYUVConversionLibrary()->GetConversion(conversion_chain); +} + +vk::UniqueImageView CreateVKImageView( + const vk::Device& device, + const vk::Image& image, + const std::shared_ptr& yuv_conversion_wrapper, + const AHBProperties& ahb_props, + const AHardwareBuffer_Desc& ahb_desc) { + const auto& ahb_format = + ahb_props.get(); + + vk::StructureChain + view_chain; + + auto& view_info = view_chain.get(); + + view_info.image = image; + view_info.viewType = vk::ImageViewType::e2D; + view_info.format = ahb_format.format; + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + view_info.subresourceRange.baseMipLevel = 0u; + view_info.subresourceRange.baseArrayLayer = 0u; + view_info.subresourceRange.levelCount = + (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE) + ? ISize{ahb_desc.width, ahb_desc.height}.MipCount() + : 1u; + view_info.subresourceRange.layerCount = ahb_desc.layers; + + // We need a custom YUV conversion only if we don't recognize the format. + if (view_info.format == vk::Format::eUndefined || + RequiresYCBCRConversion(view_info.format)) { + view_chain.get().conversion = + yuv_conversion_wrapper->GetConversion(); + } else { + view_chain.unlink(); + } + + auto image_view = device.createImageViewUnique(view_info); + if (image_view.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create external image view: " + << vk::to_string(image_view.result); + return {}; + } + + return std::move(image_view.value); +} + +PixelFormat ToPixelFormat(AHardwareBuffer_Format format) { + switch (format) { + case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: + return PixelFormat::kR8G8B8A8UNormInt; + case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT: + return PixelFormat::kR16G16B16A16Float; + case AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT: + return PixelFormat::kD24UnormS8Uint; + case AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT: + return PixelFormat::kD32FloatS8UInt; + case AHARDWAREBUFFER_FORMAT_S8_UINT: + return PixelFormat::kS8UInt; + case AHARDWAREBUFFER_FORMAT_R8_UNORM: + return PixelFormat::kR8UNormInt; + case AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM: + case AHARDWAREBUFFER_FORMAT_R16G16_UINT: + case AHARDWAREBUFFER_FORMAT_D32_FLOAT: + case AHARDWAREBUFFER_FORMAT_R16_UINT: + case AHARDWAREBUFFER_FORMAT_D24_UNORM: + case AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420: + case AHARDWAREBUFFER_FORMAT_YCbCr_P010: + case AHARDWAREBUFFER_FORMAT_BLOB: + case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM: + case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: + case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: + case AHARDWAREBUFFER_FORMAT_D16_UNORM: + case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM: + // Not understood by the rest of Impeller. Use a placeholder but create + // the native image and image views using the right external format. + break; + } + return PixelFormat::kR8G8B8A8UNormInt; +} + +TextureType ToTextureType(const AHardwareBuffer_Desc& ahb_desc) { + if (ahb_desc.layers == 1u) { + return TextureType::kTexture2D; + } + if (ahb_desc.layers % 6u == 0 && + (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP)) { + return TextureType::kTextureCube; + } + // Our texture types seem to understand external OES textures. Should these be + // wired up instead? + return TextureType::kTexture2D; +} + +TextureDescriptor ToTextureDescriptor(const AHardwareBuffer_Desc& ahb_desc) { + const auto ahb_size = ISize{ahb_desc.width, ahb_desc.height}; + TextureDescriptor desc; + // We are not going to touch hardware buffers on the CPU or use them as + // transient attachments. Just treat them as device private. + desc.storage_mode = StorageMode::kDevicePrivate; + desc.format = + ToPixelFormat(static_cast(ahb_desc.format)); + desc.size = ahb_size; + desc.type = ToTextureType(ahb_desc); + desc.sample_count = SampleCount::kCount1; + desc.compression_type = CompressionType::kLossless; + desc.mip_count = (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE) + ? ahb_size.MipCount() + : 1u; + if (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER) { + desc.usage = TextureUsage::kRenderTarget; + } + return desc; +} +} // namespace + +AHBTextureSourceVK::AHBTextureSourceVK( + const std::shared_ptr& p_context, + struct AHardwareBuffer* ahb, + const AHardwareBuffer_Desc& ahb_desc) + : TextureSourceVK(ToTextureDescriptor(ahb_desc)) { + if (!p_context) { + return; + } + + const auto& context = ContextVK::Cast(*p_context); + const auto& device = context.GetDevice(); + const auto& physical_device = context.GetPhysicalDevice(); + + AHBProperties ahb_props; + + if (device.getAndroidHardwareBufferPropertiesANDROID(ahb, &ahb_props.get()) != + vk::Result::eSuccess) { + VALIDATION_LOG << "Could not determine properties of the Android hardware " + "buffer."; + return; + } + + const auto& ahb_format = + ahb_props.get(); + + // Create an image to refer to our external image. + auto image = + CreateVKImageWrapperForAndroidHarwareBuffer(device, ahb_props, ahb_desc); + if (!image) { + return; + } + + // Create a device memory allocation to refer to our external image. + auto device_memory = ImportVKDeviceMemoryFromAndroidHarwareBuffer( + device, physical_device, image.get(), ahb, ahb_props); + if (!device_memory) { + return; + } + + // Bind the image to the image memory. + if (auto result = device.bindImageMemory(image.get(), device_memory.get(), 0); + result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not bind external device memory to image : " + << vk::to_string(result); + return; + } + + // Figure out how to perform YUV conversions. + needs_yuv_conversion_ = ahb_format.format == vk::Format::eUndefined || + RequiresYCBCRConversion(ahb_format.format); + std::shared_ptr yuv_conversion; + if (needs_yuv_conversion_) { + yuv_conversion = CreateYUVConversion(context, ahb_props); + if (!yuv_conversion || !yuv_conversion->IsValid()) { + return; + } + } + + // Create image view for the newly created image. + auto image_view = CreateVKImageView(device, // + image.get(), // + yuv_conversion, // + ahb_props, // + ahb_desc // + ); + if (!image_view) { + return; + } + + device_memory_ = std::move(device_memory); + image_ = std::move(image); + yuv_conversion_ = std::move(yuv_conversion); + image_view_ = std::move(image_view); + +#ifdef IMPELLER_DEBUG + context.SetDebugName(device_memory_.get(), "AHB Device Memory"); + context.SetDebugName(image_.get(), "AHB Image"); + if (yuv_conversion_) { + context.SetDebugName(yuv_conversion_->GetConversion(), + "AHB YUV Conversion"); + } + context.SetDebugName(image_view_.get(), "AHB ImageView"); +#endif // IMPELLER_DEBUG + + is_valid_ = true; +} + +AHBTextureSourceVK::AHBTextureSourceVK( + const std::shared_ptr& context, + std::unique_ptr backing_store, + bool is_swapchain_image) + : AHBTextureSourceVK(context, + backing_store->GetHandle(), + backing_store->GetAndroidDescriptor()) { + backing_store_ = std::move(backing_store); + is_swapchain_image_ = is_swapchain_image; +} + +// |TextureSourceVK| +AHBTextureSourceVK::~AHBTextureSourceVK() = default; + +bool AHBTextureSourceVK::IsValid() const { + return is_valid_; +} + +// |TextureSourceVK| +vk::Image AHBTextureSourceVK::GetImage() const { + return image_.get(); +} + +// |TextureSourceVK| +vk::ImageView AHBTextureSourceVK::GetImageView() const { + return image_view_.get(); +} + +// |TextureSourceVK| +vk::ImageView AHBTextureSourceVK::GetRenderTargetView() const { + return image_view_.get(); +} + +// |TextureSourceVK| +bool AHBTextureSourceVK::IsSwapchainImage() const { + return is_swapchain_image_; +} + +// |TextureSourceVK| +std::shared_ptr AHBTextureSourceVK::GetYUVConversion() const { + return needs_yuv_conversion_ ? yuv_conversion_ : nullptr; +} + +const android::HardwareBuffer* AHBTextureSourceVK::GetBackingStore() const { + return backing_store_.get(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..79013a4e751088cc2e1c51e98c649aaaf946df3d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_ + +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" +#include "impeller/toolkit/android/hardware_buffer.h" + +#include +#include + +namespace impeller { + +class ContextVK; + +//------------------------------------------------------------------------------ +/// @brief A texture source that wraps an instance of AHardwareBuffer. +/// +/// The formats and conversions supported by Android Hardware +/// Buffers are a superset of those supported by Impeller (and +/// Vulkan for that matter). Impeller and Vulkan descriptors +/// obtained from the these texture sources are advisory and it +/// usually isn't possible to create copies of images and image +/// views held in these texture sources using the inferred +/// descriptors. The objects are meant to be used directly (either +/// as render targets or sources for sampling), not copied. +/// +class AHBTextureSourceVK final : public TextureSourceVK { + public: + AHBTextureSourceVK(const std::shared_ptr& context, + struct AHardwareBuffer* hardware_buffer, + const AHardwareBuffer_Desc& hardware_buffer_desc); + + AHBTextureSourceVK(const std::shared_ptr& context, + std::unique_ptr backing_store, + bool is_swapchain_image); + + // |TextureSourceVK| + ~AHBTextureSourceVK() override; + + // |TextureSourceVK| + vk::Image GetImage() const override; + + // |TextureSourceVK| + vk::ImageView GetImageView() const override; + + // |TextureSourceVK| + vk::ImageView GetRenderTargetView() const override; + + bool IsValid() const; + + // |TextureSourceVK| + bool IsSwapchainImage() const override; + + // |TextureSourceVK| + std::shared_ptr GetYUVConversion() const override; + + const android::HardwareBuffer* GetBackingStore() const; + + private: + std::unique_ptr backing_store_; + vk::UniqueDeviceMemory device_memory_ = {}; + vk::UniqueImage image_ = {}; + vk::UniqueImageView image_view_ = {}; + std::shared_ptr yuv_conversion_ = {}; + bool needs_yuv_conversion_ = false; + bool is_swapchain_image_ = false; + bool is_valid_ = false; + + AHBTextureSourceVK(const AHBTextureSourceVK&) = delete; + + AHBTextureSourceVK& operator=(const AHBTextureSourceVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_ANDROID_AHB_TEXTURE_SOURCE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e40da07f5949e4cf705337dc4aab77a915b179f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/android/ahb_texture_source_vk_unittests.cc @@ -0,0 +1,97 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/toolkit/android/hardware_buffer.h" +#include "impeller/toolkit/android/surface_transaction.h" + +namespace impeller::android::testing { + +// Set up context. +std::shared_ptr CreateContext() { + auto vulkan_dylib = fml::NativeLibrary::Create("libvulkan.so"); + auto instance_proc_addr = + vulkan_dylib->ResolveFunction( + "vkGetInstanceProcAddr"); + + if (!instance_proc_addr.has_value()) { + VALIDATION_LOG << "Could not setup Vulkan proc table."; + return nullptr; + } + + impeller::ContextVK::Settings settings; + settings.proc_address_callback = instance_proc_addr.value(); + settings.shader_libraries_data = {}; + settings.enable_validation = false; + settings.enable_gpu_tracing = false; + settings.enable_surface_control = false; + + return ContextVK::Create(std::move(settings)); +} + +TEST(AndroidVulkanTest, CanImportRGBA) { + if (!HardwareBuffer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Hardware buffers are not supported on this platform."; + } + + HardwareBufferDescriptor desc; + desc.size = ISize{1, 1}; + desc.format = HardwareBufferFormat::kR8G8B8A8UNormInt; + desc.usage = HardwareBufferUsageFlags::kSampledImage; + + auto ahb = std::make_unique(desc); + ASSERT_TRUE(ahb); + auto context_vk = CreateContext(); + ASSERT_TRUE(context_vk); + + AHBTextureSourceVK source(context_vk, std::move(ahb), + /*is_swapchain_image=*/false); + + EXPECT_TRUE(source.IsValid()); + EXPECT_EQ(source.GetYUVConversion(), nullptr); + + context_vk->Shutdown(); +} + +TEST(AndroidVulkanTest, CanImportWithYUB) { + if (!HardwareBuffer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Hardware buffers are not supported on this platform."; + } + + AHardwareBuffer_Desc desc; + desc.width = 16; + desc.height = 16; + desc.format = AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420; + desc.stride = 0; + desc.layers = 1; + desc.rfu0 = 0; + desc.rfu1 = 0; + desc.usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK | + AHARDWAREBUFFER_USAGE_CPU_READ_MASK; + + EXPECT_EQ(AHardwareBuffer_isSupported(&desc), 1); + + AHardwareBuffer* buffer = nullptr; + ASSERT_EQ(AHardwareBuffer_allocate(&desc, &buffer), 0); + + auto context_vk = CreateContext(); + ASSERT_TRUE(context_vk); + + AHBTextureSourceVK source(context_vk, buffer, desc); + + EXPECT_TRUE(source.IsValid()); + EXPECT_NE(source.GetYUVConversion(), nullptr); + + context_vk->Shutdown(); +} + +} // namespace impeller::android::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..e318de5787592f29de7b181bf15e1f1c22d4f574 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.cc @@ -0,0 +1,7 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/barrier_vk.h" + +namespace impeller {} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..7f124fd2014ea2f0e8a6bb4f30e9b03d3cd12dfd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/barrier_vk.h @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_ + +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Defines an operations and memory access barrier on a resource. +/// +/// For further reading, see +/// https://www.khronos.org/events/vulkan-how-to-use-synchronisation-validation-across-multiple-queues-and-command-buffers +/// and the Vulkan spec. The docs for the various member of this +/// class are based on verbiage in the spec. +/// +/// A useful mnemonic for building a mental model of how to add +/// these barriers is to build a sentence like so; "All commands +/// before this barrier may continue till they encounter a in the . And, all commands after +/// this barrier may proceed till in the ." +/// +struct BarrierVK { + vk::CommandBuffer cmd_buffer = {}; + vk::ImageLayout new_layout = vk::ImageLayout::eUndefined; + + // The first synchronization scope defines what operations the barrier waits + // for to be done. In the Vulkan spec, this is usually referred to as the src + // scope. + vk::PipelineStageFlags src_stage = vk::PipelineStageFlagBits::eNone; + + // The first access scope defines what memory operations are guaranteed to + // happen before the barrier. In the Vulkan spec, this is usually referred to + // as the src scope. + vk::AccessFlags src_access = vk::AccessFlagBits::eNone; + + // The second synchronization scope defines what operations wait for the + // barrier to be done. In the Vulkan spec, this is usually referred to as the + // dst scope. + vk::PipelineStageFlags dst_stage = vk::PipelineStageFlagBits::eNone; + + // The second access scope defines what memory operations are prevented from + // running till after the barrier. In the Vulkan spec, this is usually + // referred to as the dst scope. + vk::AccessFlags dst_access = vk::AccessFlagBits::eNone; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BARRIER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..8dbae970e149c7003b53a3f8b46a34c119af27b1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.cc @@ -0,0 +1,530 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/blit_pass_vk.h" + +#include "impeller/renderer/backend/vulkan/barrier_vk.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "vulkan/vulkan_core.h" +#include "vulkan/vulkan_enums.hpp" +#include "vulkan/vulkan_structs.hpp" + +namespace impeller { + +static void InsertImageMemoryBarrier(const vk::CommandBuffer& cmd, + const vk::Image& image, + vk::AccessFlags src_access_mask, + vk::AccessFlags dst_access_mask, + vk::ImageLayout old_layout, + vk::ImageLayout new_layout, + vk::PipelineStageFlags src_stage, + vk::PipelineStageFlags dst_stage, + uint32_t base_mip_level, + uint32_t mip_level_count = 1u) { + if (old_layout == new_layout) { + return; + } + + vk::ImageMemoryBarrier barrier; + barrier.srcAccessMask = src_access_mask; + barrier.dstAccessMask = dst_access_mask; + barrier.oldLayout = old_layout; + barrier.newLayout = new_layout; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + barrier.subresourceRange.baseMipLevel = base_mip_level; + barrier.subresourceRange.levelCount = mip_level_count; + barrier.subresourceRange.baseArrayLayer = 0u; + barrier.subresourceRange.layerCount = 1u; + + cmd.pipelineBarrier(src_stage, dst_stage, {}, nullptr, nullptr, barrier); +} + +BlitPassVK::BlitPassVK(std::shared_ptr command_buffer, + const WorkaroundsVK& workarounds) + : command_buffer_(std::move(command_buffer)), workarounds_(workarounds) {} + +BlitPassVK::~BlitPassVK() = default; + +void BlitPassVK::OnSetLabel(std::string_view label) {} + +// |BlitPass| +bool BlitPassVK::IsValid() const { + return true; +} + +// |BlitPass| +bool BlitPassVK::EncodeCommands() const { + return true; +} + +// |BlitPass| +bool BlitPassVK::OnCopyTextureToTextureCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) { + const auto& cmd_buffer = command_buffer_->GetCommandBuffer(); + + const auto& src = TextureVK::Cast(*source); + const auto& dst = TextureVK::Cast(*destination); + + if (!command_buffer_->Track(source) || !command_buffer_->Track(destination)) { + return false; + } + + BarrierVK src_barrier; + src_barrier.cmd_buffer = cmd_buffer; + src_barrier.new_layout = vk::ImageLayout::eTransferSrcOptimal; + src_barrier.src_access = vk::AccessFlagBits::eTransferWrite | + vk::AccessFlagBits::eShaderWrite | + vk::AccessFlagBits::eColorAttachmentWrite; + src_barrier.src_stage = vk::PipelineStageFlagBits::eTransfer | + vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eColorAttachmentOutput; + src_barrier.dst_access = vk::AccessFlagBits::eTransferRead; + src_barrier.dst_stage = vk::PipelineStageFlagBits::eTransfer; + + BarrierVK dst_barrier; + dst_barrier.cmd_buffer = cmd_buffer; + dst_barrier.new_layout = vk::ImageLayout::eTransferDstOptimal; + dst_barrier.src_access = {}; + dst_barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + dst_barrier.dst_access = + vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eTransferWrite; + dst_barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eTransfer; + + if (!src.SetLayout(src_barrier) || !dst.SetLayout(dst_barrier)) { + VALIDATION_LOG << "Could not complete layout transitions."; + return false; + } + + vk::ImageCopy image_copy; + + image_copy.setSrcSubresource( + vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1)); + image_copy.setDstSubresource( + vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1)); + + image_copy.srcOffset = + vk::Offset3D(source_region.GetX(), source_region.GetY(), 0); + image_copy.dstOffset = + vk::Offset3D(destination_origin.x, destination_origin.y, 0); + image_copy.extent = + vk::Extent3D(source_region.GetWidth(), source_region.GetHeight(), 1); + + // Issue the copy command now that the images are already in the right + // layouts. + cmd_buffer.copyImage(src.GetImage(), // + src_barrier.new_layout, // + dst.GetImage(), // + dst_barrier.new_layout, // + image_copy // + ); + + // If this is an onscreen texture, do not transition the layout + // back to shader read. + if (dst.IsSwapchainImage()) { + return true; + } + + BarrierVK barrier; + barrier.cmd_buffer = cmd_buffer; + barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; + barrier.src_access = {}; + barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; + + return dst.SetLayout(barrier); +} + +// |BlitPass| +bool BlitPassVK::OnCopyTextureToBufferCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) { + const auto& cmd_buffer = command_buffer_->GetCommandBuffer(); + + // cast source and destination to TextureVK + const auto& src = TextureVK::Cast(*source); + + if (!command_buffer_->Track(source) || !command_buffer_->Track(destination)) { + return false; + } + + BarrierVK barrier; + barrier.cmd_buffer = cmd_buffer; + barrier.new_layout = vk::ImageLayout::eTransferSrcOptimal; + barrier.src_access = vk::AccessFlagBits::eShaderWrite | + vk::AccessFlagBits::eTransferWrite | + vk::AccessFlagBits::eColorAttachmentWrite; + barrier.src_stage = vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eTransfer | + vk::PipelineStageFlagBits::eColorAttachmentOutput; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eVertexShader | + vk::PipelineStageFlagBits::eFragmentShader; + + const auto& dst = DeviceBufferVK::Cast(*destination); + + vk::BufferImageCopy image_copy; + image_copy.setBufferOffset(destination_offset); + image_copy.setBufferRowLength(0); + image_copy.setBufferImageHeight(0); + image_copy.setImageSubresource( + vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1)); + image_copy.setImageOffset( + vk::Offset3D(source_region.GetX(), source_region.GetY(), 0)); + image_copy.setImageExtent( + vk::Extent3D(source_region.GetWidth(), source_region.GetHeight(), 1)); + + if (!src.SetLayout(barrier)) { + VALIDATION_LOG << "Could not encode layout transition."; + return false; + } + + cmd_buffer.copyImageToBuffer(src.GetImage(), // + barrier.new_layout, // + dst.GetBuffer(), // + image_copy // + ); + + // If the buffer is used for readback, then apply a transfer -> host memory + // barrier. + if (destination->GetDeviceBufferDescriptor().readback) { + vk::MemoryBarrier barrier; + barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eHostRead; + + cmd_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eHost, {}, 1, + &barrier, 0, {}, 0, {}); + } + + return true; +} + +bool BlitPassVK::ConvertTextureToShaderRead( + const std::shared_ptr& texture) { + const auto& cmd_buffer = command_buffer_->GetCommandBuffer(); + + BarrierVK barrier; + barrier.cmd_buffer = cmd_buffer; + barrier.src_access = vk::AccessFlagBits::eTransferWrite; + barrier.src_stage = vk::PipelineStageFlagBits::eTransfer; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; + + barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; + + const auto& texture_vk = TextureVK::Cast(*texture); + + if (!command_buffer_->Track(texture)) { + return false; + } + + return texture_vk.SetLayout(barrier); +} + +// |BlitPass| +bool BlitPassVK::OnCopyBufferToTextureCommand( + BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) { + const auto& cmd_buffer = command_buffer_->GetCommandBuffer(); + + // cast destination to TextureVK + const auto& dst = TextureVK::Cast(*destination); + const auto& src = DeviceBufferVK::Cast(*source.GetBuffer()); + + std::shared_ptr source_buffer = source.TakeBuffer(); + if ((source_buffer && !command_buffer_->Track(source_buffer)) || + !command_buffer_->Track(destination)) { + return false; + } + + BarrierVK dst_barrier; + dst_barrier.cmd_buffer = cmd_buffer; + dst_barrier.new_layout = vk::ImageLayout::eTransferDstOptimal; + dst_barrier.src_access = {}; + dst_barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + dst_barrier.dst_access = + vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eTransferWrite; + dst_barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eTransfer; + + vk::BufferImageCopy image_copy; + image_copy.setBufferOffset(source.GetRange().offset); + image_copy.setBufferRowLength(0); + image_copy.setBufferImageHeight(0); + image_copy.setImageSubresource(vk::ImageSubresourceLayers( + vk::ImageAspectFlagBits::eColor, mip_level, slice, 1)); + image_copy.imageOffset.x = destination_region.GetX(); + image_copy.imageOffset.y = destination_region.GetY(); + image_copy.imageOffset.z = 0u; + image_copy.imageExtent.width = destination_region.GetWidth(); + image_copy.imageExtent.height = destination_region.GetHeight(); + image_copy.imageExtent.depth = 1u; + + // Note: this barrier should do nothing if we're already in the transfer dst + // optimal state. This is important for performance of repeated blit pass + // encoding. + if (!dst.SetLayout(dst_barrier)) { + VALIDATION_LOG << "Could not encode layout transition."; + return false; + } + + cmd_buffer.copyBufferToImage(src.GetBuffer(), // + dst.GetImage(), // + dst_barrier.new_layout, // + image_copy // + ); + + // Transition to shader-read. + if (convert_to_read) { + BarrierVK barrier; + barrier.cmd_buffer = cmd_buffer; + barrier.src_access = vk::AccessFlagBits::eTransferWrite; + barrier.src_stage = vk::PipelineStageFlagBits::eTransfer; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; + + barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; + + if (!dst.SetLayout(barrier)) { + return false; + } + } + + return true; +} + +// |BlitPass| +bool BlitPassVK::ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) { + const auto& cmd_buffer = command_buffer_->GetCommandBuffer(); + + const auto& src = TextureVK::Cast(*source); + const auto& dst = TextureVK::Cast(*destination); + + if (!command_buffer_->Track(source) || !command_buffer_->Track(destination)) { + return false; + } + + BarrierVK src_barrier; + src_barrier.cmd_buffer = cmd_buffer; + src_barrier.new_layout = vk::ImageLayout::eTransferSrcOptimal; + src_barrier.src_access = vk::AccessFlagBits::eTransferWrite | + vk::AccessFlagBits::eShaderWrite | + vk::AccessFlagBits::eColorAttachmentWrite; + src_barrier.src_stage = vk::PipelineStageFlagBits::eTransfer | + vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eColorAttachmentOutput; + src_barrier.dst_access = vk::AccessFlagBits::eTransferRead; + src_barrier.dst_stage = vk::PipelineStageFlagBits::eTransfer; + + BarrierVK dst_barrier; + dst_barrier.cmd_buffer = cmd_buffer; + dst_barrier.new_layout = vk::ImageLayout::eTransferDstOptimal; + dst_barrier.src_access = {}; + dst_barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + dst_barrier.dst_access = + vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eTransferWrite; + dst_barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader | + vk::PipelineStageFlagBits::eTransfer; + + if (!src.SetLayout(src_barrier) || !dst.SetLayout(dst_barrier)) { + VALIDATION_LOG << "Could not complete layout transitions."; + return false; + } + + vk::ImageBlit blit; + blit.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; + blit.srcSubresource.baseArrayLayer = 0u; + blit.srcSubresource.layerCount = 1u; + blit.srcSubresource.mipLevel = 0; + + blit.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; + blit.dstSubresource.baseArrayLayer = 0u; + blit.dstSubresource.layerCount = 1u; + blit.dstSubresource.mipLevel = 0; + + // offsets[0] is origin. + blit.srcOffsets[1].x = std::max(source->GetSize().width, 1u); + blit.srcOffsets[1].y = std::max(source->GetSize().height, 1u); + blit.srcOffsets[1].z = 1u; + + // offsets[0] is origin. + blit.dstOffsets[1].x = std::max(destination->GetSize().width, 1u); + blit.dstOffsets[1].y = std::max(destination->GetSize().height, 1u); + blit.dstOffsets[1].z = 1u; + + cmd_buffer.blitImage(src.GetImage(), // + src_barrier.new_layout, // + dst.GetImage(), // + dst_barrier.new_layout, // + 1, // + &blit, // + vk::Filter::eLinear + + ); + + // Convert back to shader read + + BarrierVK barrier; + barrier.cmd_buffer = cmd_buffer; + barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; + barrier.src_access = {}; + barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; + + return dst.SetLayout(barrier); +} + +// |BlitPass| +bool BlitPassVK::OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) { + auto& src = TextureVK::Cast(*texture); + + const auto size = src.GetTextureDescriptor().size; + uint32_t mip_count = src.GetTextureDescriptor().mip_count; + + if (mip_count < 2u) { + return true; + } + + const auto& image = src.GetImage(); + const auto& cmd = command_buffer_->GetCommandBuffer(); + + if (!command_buffer_->Track(texture)) { + return false; + } + + // Initialize all mip levels to be in TransferDst mode. Later, in a loop, + // after writing to that mip level, we'll first switch its layout to + // TransferSrc to prepare the mip level after it, use the image as the source + // of the blit, before finally switching it to ShaderReadOnly so its available + // for sampling in a shader. + InsertImageMemoryBarrier( + /*cmd=*/cmd, + /*image=*/image, + /*src_access_mask=*/vk::AccessFlagBits::eTransferWrite | + vk::AccessFlagBits::eColorAttachmentWrite, + /*dst_access_mask=*/vk::AccessFlagBits::eTransferRead, + /*old_layout=*/src.GetLayout(), + /*new_layout=*/vk::ImageLayout::eTransferDstOptimal, + /*src_stage=*/vk::PipelineStageFlagBits::eTransfer | + vk::PipelineStageFlagBits::eColorAttachmentOutput, + /*dst_stage=*/vk::PipelineStageFlagBits::eTransfer, + /*base_mip_level=*/0u, + /*mip_level_count=*/mip_count); + + vk::ImageMemoryBarrier barrier; + barrier.image = image; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + barrier.subresourceRange.baseArrayLayer = 0; + barrier.subresourceRange.layerCount = 1; + barrier.subresourceRange.levelCount = 1; + + // Blit from the mip level N - 1 to mip level N. + size_t width = size.width; + size_t height = size.height; + for (size_t mip_level = 1u; mip_level < mip_count; mip_level++) { + barrier.subresourceRange.baseMipLevel = mip_level - 1; + barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal; + barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal; + barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead; + + // We just finished writing to the previous (N-1) mip level or it was the + // base mip level. These were initialized to TransferDst earler. We are now + // going to read from it to write to the current level (N) . So it must be + // converted to TransferSrc. + cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eTransfer, {}, {}, {}, + {barrier}); + + vk::ImageBlit blit; + blit.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; + blit.srcSubresource.baseArrayLayer = 0u; + blit.srcSubresource.layerCount = 1u; + blit.srcSubresource.mipLevel = mip_level - 1; + + blit.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor; + blit.dstSubresource.baseArrayLayer = 0u; + blit.dstSubresource.layerCount = 1u; + blit.dstSubresource.mipLevel = mip_level; + + // offsets[0] is origin. + blit.srcOffsets[1].x = std::max(width, 1u); + blit.srcOffsets[1].y = std::max(height, 1u); + blit.srcOffsets[1].z = 1u; + + width = width / 2; + height = height / 2; + if (width <= 1 || height <= 1) { + break; + } + + // offsets[0] is origin. + blit.dstOffsets[1].x = std::max(width, 1u); + blit.dstOffsets[1].y = std::max(height, 1u); + blit.dstOffsets[1].z = 1u; + + cmd.blitImage(image, // src image + vk::ImageLayout::eTransferSrcOptimal, // src layout + image, // dst image + vk::ImageLayout::eTransferDstOptimal, // dst layout + 1u, // region count + &blit, // regions + vk::Filter::eLinear // filter + ); + + barrier.oldLayout = vk::ImageLayout::eTransferSrcOptimal; + barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + + // Now that the blit is done, the image at the previous level (N-1) + // is done reading from (TransferSrc)/ Now we must prepare it to be read + // from a shader (ShaderReadOnly). + cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader, {}, {}, {}, + {barrier}); + } + + barrier.subresourceRange.baseMipLevel = mip_count - 1; + barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal; + barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + + cmd.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader, {}, {}, {}, + {barrier}); + + // We modified the layouts of this image from underneath it. Tell it its new + // state so it doesn't try to perform redundant transitions under the hood. + src.SetLayoutWithoutEncoding(vk::ImageLayout::eShaderReadOnlyOptimal); + src.SetMipMapGenerated(); + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..44896f6f55d4e158203aeb398bbacb08e4b87139 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/blit_pass_vk.h @@ -0,0 +1,82 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_PASS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_PASS_VK_H_ + +#include "flutter/impeller/base/config.h" +#include "impeller/geometry/rect.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/blit_pass.h" + +namespace impeller { + +class CommandEncoderVK; +class CommandBufferVK; + +class BlitPassVK final : public BlitPass { + public: + // |BlitPass| + ~BlitPassVK() override; + + private: + friend class CommandBufferVK; + + std::shared_ptr command_buffer_; + const WorkaroundsVK workarounds_; + + explicit BlitPassVK(std::shared_ptr command_buffer, + const WorkaroundsVK& workarounds); + + // |BlitPass| + bool IsValid() const override; + + // |BlitPass| + void OnSetLabel(std::string_view label) override; + + // |BlitPass| + bool EncodeCommands() const override; + + // |BlitPass| + bool ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) override; + + // |BlitPass| + bool ConvertTextureToShaderRead( + const std::shared_ptr& texture) override; + + // |BlitPass| + bool OnCopyTextureToTextureCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) override; + + // |BlitPass| + bool OnCopyTextureToBufferCommand(std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) override; + + // |BlitPass| + bool OnCopyBufferToTextureCommand(BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) override; + // |BlitPass| + bool OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) override; + + BlitPassVK(const BlitPassVK&) = delete; + + BlitPassVK& operator=(const BlitPassVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_BLIT_PASS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..7cd75c70631446e078114525de257b616e137409 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.cc @@ -0,0 +1,819 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" + +#include +#include + +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" + +namespace impeller { + +static constexpr const char* kInstanceLayer = "ImpellerInstance"; + +CapabilitiesVK::CapabilitiesVK(bool enable_validations, + bool fatal_missing_validations, + bool use_embedder_extensions, + std::vector instance_extensions, + std::vector device_extensions) + : use_embedder_extensions_(use_embedder_extensions), + embedder_instance_extensions_(std::move(instance_extensions)), + embedder_device_extensions_(std::move(device_extensions)) { + if (!use_embedder_extensions_) { + auto extensions = vk::enumerateInstanceExtensionProperties(); + auto layers = vk::enumerateInstanceLayerProperties(); + + if (extensions.result != vk::Result::eSuccess || + layers.result != vk::Result::eSuccess) { + return; + } + + for (const auto& ext : extensions.value) { + exts_[kInstanceLayer].insert(ext.extensionName); + } + + for (const auto& layer : layers.value) { + const std::string layer_name = layer.layerName; + auto layer_exts = vk::enumerateInstanceExtensionProperties(layer_name); + if (layer_exts.result != vk::Result::eSuccess) { + return; + } + for (const auto& layer_ext : layer_exts.value) { + exts_[layer_name].insert(layer_ext.extensionName); + } + } + } else { + for (const auto& ext : embedder_instance_extensions_) { + exts_[kInstanceLayer].insert(ext); + } + } + + validations_enabled_ = + enable_validations && HasLayer("VK_LAYER_KHRONOS_validation"); + if (enable_validations && !validations_enabled_) { + FML_LOG(ERROR) + << "Requested Impeller context creation with validations but the " + "validation layers could not be found. Expect no Vulkan validation " + "checks!"; + if (fatal_missing_validations) { + FML_LOG(FATAL) << "Validation missing. Exiting."; + } + } + if (validations_enabled_) { + FML_LOG(INFO) << "Vulkan validations are enabled."; + } + is_valid_ = true; +} + +CapabilitiesVK::~CapabilitiesVK() = default; + +bool CapabilitiesVK::IsValid() const { + return is_valid_; +} + +bool CapabilitiesVK::AreValidationsEnabled() const { + return validations_enabled_; +} + +std::optional> CapabilitiesVK::GetEnabledLayers() + const { + std::vector required; + + if (validations_enabled_) { + // The presence of this layer is already checked in the ctor. + required.push_back("VK_LAYER_KHRONOS_validation"); + } + + return required; +} + +std::optional> +CapabilitiesVK::GetEnabledInstanceExtensions() const { + std::vector required; + + if (!HasExtension("VK_KHR_surface")) { + // Swapchain support is required and this is a dependency of + // VK_KHR_swapchain. + VALIDATION_LOG << "Could not find the surface extension."; + return std::nullopt; + } + required.push_back("VK_KHR_surface"); + + auto has_wsi = false; + if (HasExtension("VK_MVK_macos_surface")) { + required.push_back("VK_MVK_macos_surface"); + has_wsi = true; + } + + if (HasExtension("VK_EXT_metal_surface")) { + required.push_back("VK_EXT_metal_surface"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_portability_enumeration")) { + required.push_back("VK_KHR_portability_enumeration"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_win32_surface")) { + required.push_back("VK_KHR_win32_surface"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_android_surface")) { + required.push_back("VK_KHR_android_surface"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_xcb_surface")) { + required.push_back("VK_KHR_xcb_surface"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_xlib_surface")) { + required.push_back("VK_KHR_xlib_surface"); + has_wsi = true; + } + + if (HasExtension("VK_KHR_wayland_surface")) { + required.push_back("VK_KHR_wayland_surface"); + has_wsi = true; + } + + if (!has_wsi) { + // Don't really care which WSI extension there is as long there is at least + // one. + VALIDATION_LOG << "Could not find a WSI extension."; + return std::nullopt; + } + + if (validations_enabled_) { + if (!HasExtension("VK_EXT_debug_utils")) { + VALIDATION_LOG << "Requested validations but could not find the " + "VK_EXT_debug_utils extension."; + return std::nullopt; + } + required.push_back("VK_EXT_debug_utils"); + + if (HasExtension("VK_EXT_validation_features")) { + // It's valid to not have `VK_EXT_validation_features` available. That's + // the case when using AGI as a frame debugger. + required.push_back("VK_EXT_validation_features"); + } + } + + return required; +} + +static const char* GetExtensionName(RequiredCommonDeviceExtensionVK ext) { + switch (ext) { + case RequiredCommonDeviceExtensionVK::kKHRSwapchain: + return VK_KHR_SWAPCHAIN_EXTENSION_NAME; + case RequiredCommonDeviceExtensionVK::kLast: + return "Unknown"; + } + FML_UNREACHABLE(); +} + +static const char* GetExtensionName(RequiredAndroidDeviceExtensionVK ext) { + switch (ext) { + case RequiredAndroidDeviceExtensionVK:: + kANDROIDExternalMemoryAndroidHardwareBuffer: + return "VK_ANDROID_external_memory_android_hardware_buffer"; + case RequiredAndroidDeviceExtensionVK::kKHRSamplerYcbcrConversion: + return VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME; + case RequiredAndroidDeviceExtensionVK::kKHRExternalMemory: + return VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME; + case RequiredAndroidDeviceExtensionVK::kEXTQueueFamilyForeign: + return VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME; + case RequiredAndroidDeviceExtensionVK::kKHRDedicatedAllocation: + return VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME; + case RequiredAndroidDeviceExtensionVK::kLast: + return "Unknown"; + } + FML_UNREACHABLE(); +} + +static const char* GetExtensionName(OptionalAndroidDeviceExtensionVK ext) { + switch (ext) { + case OptionalAndroidDeviceExtensionVK::kKHRExternalFenceFd: + return VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME; + case OptionalAndroidDeviceExtensionVK::kKHRExternalFence: + return VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME; + case OptionalAndroidDeviceExtensionVK::kKHRExternalSemaphoreFd: + return VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME; + case OptionalAndroidDeviceExtensionVK::kKHRExternalSemaphore: + return VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME; + case OptionalAndroidDeviceExtensionVK::kLast: + return "Unknown"; + } +} + +static const char* GetExtensionName(OptionalDeviceExtensionVK ext) { + switch (ext) { + case OptionalDeviceExtensionVK::kEXTPipelineCreationFeedback: + return VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME; + case OptionalDeviceExtensionVK::kVKKHRPortabilitySubset: + return "VK_KHR_portability_subset"; + case OptionalDeviceExtensionVK::kEXTImageCompressionControl: + return VK_EXT_IMAGE_COMPRESSION_CONTROL_EXTENSION_NAME; + case OptionalDeviceExtensionVK::kLast: + return "Unknown"; + } + FML_UNREACHABLE(); +} + +template +static bool IterateExtensions(const std::function& it) { + if (!it) { + return false; + } + for (size_t i = 0; i < static_cast(T::kLast); i++) { + if (!it(static_cast(i))) { + return false; + } + } + return true; +} + +static std::optional> GetSupportedDeviceExtensions( + const vk::PhysicalDevice& physical_device) { + auto device_extensions = physical_device.enumerateDeviceExtensionProperties(); + if (device_extensions.result != vk::Result::eSuccess) { + return std::nullopt; + } + + std::set exts; + for (const auto& device_extension : device_extensions.value) { + exts.insert(device_extension.extensionName); + }; + + return exts; +} + +std::optional> +CapabilitiesVK::GetEnabledDeviceExtensions( + const vk::PhysicalDevice& physical_device) const { + std::set exts; + + if (!use_embedder_extensions_) { + auto maybe_exts = GetSupportedDeviceExtensions(physical_device); + + if (!maybe_exts.has_value()) { + return std::nullopt; + } + exts = maybe_exts.value(); + } else { + exts = std::set(embedder_device_extensions_.begin(), + embedder_device_extensions_.end()); + } + + std::vector enabled; + + auto for_each_common_extension = [&](RequiredCommonDeviceExtensionVK ext) { + auto name = GetExtensionName(ext); + if (exts.find(name) == exts.end()) { + VALIDATION_LOG << "Device does not support required extension: " << name; + return false; + } + enabled.push_back(name); + return true; + }; + + auto for_each_android_extension = [&](RequiredAndroidDeviceExtensionVK ext) { +#ifdef FML_OS_ANDROID + auto name = GetExtensionName(ext); + if (exts.find(name) == exts.end()) { + VALIDATION_LOG << "Device does not support required Android extension: " + << name; + return false; + } + enabled.push_back(name); +#endif // FML_OS_ANDROID + return true; + }; + + auto for_each_optional_android_extension = + [&](OptionalAndroidDeviceExtensionVK ext) { +#ifdef FML_OS_ANDROID + auto name = GetExtensionName(ext); + if (exts.find(name) != exts.end()) { + enabled.push_back(name); + } +#endif // FML_OS_ANDROID + return true; + }; + + auto for_each_optional_extension = [&](OptionalDeviceExtensionVK ext) { + auto name = GetExtensionName(ext); + if (exts.find(name) != exts.end()) { + enabled.push_back(name); + } + return true; + }; + + const auto iterate_extensions = + IterateExtensions( + for_each_common_extension) && + IterateExtensions( + for_each_android_extension) && + IterateExtensions( + for_each_optional_extension) && + IterateExtensions( + for_each_optional_android_extension); + + if (!iterate_extensions) { + VALIDATION_LOG << "Device not suitable since required extensions are not " + "supported."; + return std::nullopt; + } + + return enabled; +} + +static bool HasSuitableColorFormat(const vk::PhysicalDevice& device, + vk::Format format) { + const auto props = device.getFormatProperties(format); + // This needs to be more comprehensive. + return !!(props.optimalTilingFeatures & + vk::FormatFeatureFlagBits::eColorAttachment); +} + +static bool HasSuitableDepthStencilFormat(const vk::PhysicalDevice& device, + vk::Format format) { + const auto props = device.getFormatProperties(format); + return !!(props.optimalTilingFeatures & + vk::FormatFeatureFlagBits::eDepthStencilAttachment); +} + +static bool PhysicalDeviceSupportsRequiredFormats( + const vk::PhysicalDevice& device) { + const auto has_color_format = + HasSuitableColorFormat(device, vk::Format::eR8G8B8A8Unorm); + const auto has_stencil_format = + HasSuitableDepthStencilFormat(device, vk::Format::eD32SfloatS8Uint) || + HasSuitableDepthStencilFormat(device, vk::Format::eD24UnormS8Uint); + return has_color_format && has_stencil_format; +} + +static bool HasRequiredProperties(const vk::PhysicalDevice& physical_device) { + auto properties = physical_device.getProperties(); + if (!(properties.limits.framebufferColorSampleCounts & + (vk::SampleCountFlagBits::e1 | vk::SampleCountFlagBits::e4))) { + return false; + } + return true; +} + +static bool HasRequiredQueues(const vk::PhysicalDevice& physical_device) { + auto queue_flags = vk::QueueFlags{}; + for (const auto& queue : physical_device.getQueueFamilyProperties()) { + if (queue.queueCount == 0) { + continue; + } + queue_flags |= queue.queueFlags; + } + return static_cast(queue_flags & + (vk::QueueFlagBits::eGraphics | + vk::QueueFlagBits::eCompute | + vk::QueueFlagBits::eTransfer)); +} + +template +static bool IsExtensionInList(const std::vector& list, + ExtensionEnum ext) { + const std::string name = GetExtensionName(ext); + return std::find(list.begin(), list.end(), name) != list.end(); +} + +std::optional +CapabilitiesVK::GetEnabledDeviceFeatures( + const vk::PhysicalDevice& device) const { + if (!PhysicalDeviceSupportsRequiredFormats(device)) { + VALIDATION_LOG << "Device doesn't support the required formats."; + return std::nullopt; + } + + if (!HasRequiredProperties(device)) { + VALIDATION_LOG << "Device doesn't support the required properties."; + return std::nullopt; + } + + if (!HasRequiredQueues(device)) { + VALIDATION_LOG << "Device doesn't support the required queues."; + return std::nullopt; + } + + const auto enabled_extensions = GetEnabledDeviceExtensions(device); + if (!enabled_extensions.has_value()) { + VALIDATION_LOG << "Device doesn't support the required queues."; + return std::nullopt; + } + + PhysicalDeviceFeatures supported_chain; + + // Swiftshader seems to be fussy about just this structure even being in the + // chain. Just unlink it if its not supported. We already perform an + // extensions check on the other side when reading. + if (!IsExtensionInList( + enabled_extensions.value(), + OptionalDeviceExtensionVK::kEXTImageCompressionControl)) { + supported_chain + .unlink(); + } + + device.getFeatures2(&supported_chain.get()); + + PhysicalDeviceFeatures required_chain; + + // Base features. + { + auto& required = required_chain.get().features; + const auto& supported = supported_chain.get().features; + + // We require this for enabling wireframes in the playground. But its not + // necessarily a big deal if we don't have this feature. + required.fillModeNonSolid = supported.fillModeNonSolid; + } + // VK_KHR_sampler_ycbcr_conversion features. + if (IsExtensionInList( + enabled_extensions.value(), + RequiredAndroidDeviceExtensionVK::kKHRSamplerYcbcrConversion)) { + auto& required = + required_chain + .get(); + const auto& supported = + supported_chain + .get(); + + required.samplerYcbcrConversion = supported.samplerYcbcrConversion; + } + + // VK_EXT_image_compression_control + if (IsExtensionInList( + enabled_extensions.value(), + OptionalDeviceExtensionVK::kEXTImageCompressionControl)) { + auto& required = + required_chain + .get(); + const auto& supported = + supported_chain + .get(); + + required.imageCompressionControl = supported.imageCompressionControl; + } else { + required_chain + .unlink(); + } + + // Vulkan 1.1 + { + auto& required = + required_chain.get(); + const auto& supported = + supported_chain.get(); + + required.uniformAndStorageBuffer16BitAccess = + supported.uniformAndStorageBuffer16BitAccess; + } + + return required_chain; +} + +bool CapabilitiesVK::HasLayer(const std::string& layer) const { + for (const auto& [found_layer, exts] : exts_) { + if (found_layer == layer) { + return true; + } + } + return false; +} + +bool CapabilitiesVK::HasExtension(const std::string& ext) const { + for (const auto& [layer, exts] : exts_) { + if (exts.find(ext) != exts.end()) { + return true; + } + } + return false; +} + +bool CapabilitiesVK::SupportsPrimitiveRestart() const { + return has_primitive_restart_; +} + +void CapabilitiesVK::SetOffscreenFormat(PixelFormat pixel_format) const { + default_color_format_ = pixel_format; +} + +bool CapabilitiesVK::SetPhysicalDevice( + const vk::PhysicalDevice& device, + const PhysicalDeviceFeatures& enabled_features) { + if (HasSuitableColorFormat(device, vk::Format::eR8G8B8A8Unorm)) { + default_color_format_ = PixelFormat::kR8G8B8A8UNormInt; + } else { + default_color_format_ = PixelFormat::kUnknown; + } + + if (HasSuitableDepthStencilFormat(device, vk::Format::eD32SfloatS8Uint)) { + default_depth_stencil_format_ = PixelFormat::kD32FloatS8UInt; + } else if (HasSuitableDepthStencilFormat(device, + vk::Format::eD24UnormS8Uint)) { + default_depth_stencil_format_ = PixelFormat::kD24UnormS8Uint; + } else { + default_depth_stencil_format_ = PixelFormat::kUnknown; + } + + if (HasSuitableDepthStencilFormat(device, vk::Format::eS8Uint)) { + default_stencil_format_ = PixelFormat::kS8UInt; + } else if (default_depth_stencil_format_ != PixelFormat::kUnknown) { + default_stencil_format_ = default_depth_stencil_format_; + } + + physical_device_ = device; + device_properties_ = device.getProperties(); + + auto physical_properties_2 = + device.getProperties2(); + + // Currently shaders only want access to arithmetic subgroup features. + // If that changes this needs to get updated, and so does Metal (which right + // now assumes it from compile time flags based on the MSL target version). + + supports_compute_subgroups_ = + !!(physical_properties_2.get() + .supportedOperations & + vk::SubgroupFeatureFlagBits::eArithmetic); + + { + // Query texture support. + // TODO(129784): Add a capability check for expected memory types. + vk::PhysicalDeviceMemoryProperties memory_properties; + device.getMemoryProperties(&memory_properties); + + for (auto i = 0u; i < memory_properties.memoryTypeCount; i++) { + if (memory_properties.memoryTypes[i].propertyFlags & + vk::MemoryPropertyFlagBits::eLazilyAllocated) { + supports_device_transient_textures_ = true; + } + } + } + + // Determine the optional device extensions this physical device supports. + { + required_common_device_extensions_.clear(); + required_android_device_extensions_.clear(); + optional_device_extensions_.clear(); + optional_android_device_extensions_.clear(); + + std::set exts; + if (!use_embedder_extensions_) { + auto maybe_exts = GetSupportedDeviceExtensions(device); + if (!maybe_exts.has_value()) { + return false; + } + exts = maybe_exts.value(); + } else { + exts = std::set(embedder_device_extensions_.begin(), + embedder_device_extensions_.end()); + } + + IterateExtensions([&](auto ext) -> bool { + auto ext_name = GetExtensionName(ext); + if (exts.find(ext_name) != exts.end()) { + required_common_device_extensions_.insert(ext); + } + return true; + }); + IterateExtensions([&](auto ext) -> bool { + auto ext_name = GetExtensionName(ext); + if (exts.find(ext_name) != exts.end()) { + required_android_device_extensions_.insert(ext); + } + return true; + }); + IterateExtensions([&](auto ext) -> bool { + auto ext_name = GetExtensionName(ext); + if (exts.find(ext_name) != exts.end()) { + optional_device_extensions_.insert(ext); + } + return true; + }); + IterateExtensions( + [&](OptionalAndroidDeviceExtensionVK ext) { + auto name = GetExtensionName(ext); + if (exts.find(name) != exts.end()) { + optional_android_device_extensions_.insert(ext); + } + return true; + }); + } + + supports_texture_fixed_rate_compression_ = + enabled_features + .isLinked() && + enabled_features + .get() + .imageCompressionControl; + + max_render_pass_attachment_size_ = + ISize{device_properties_.limits.maxFramebufferWidth, + device_properties_.limits.maxFramebufferHeight}; + + // Molten, Vulkan on Metal, cannot support triangle fans because Metal doesn't + // support triangle fans. + // See VUID-VkPipelineInputAssemblyStateCreateInfo-triangleFans-04452. + has_triangle_fans_ = + !HasExtension(OptionalDeviceExtensionVK::kVKKHRPortabilitySubset); + + // External Fence/Semaphore for AHB swapchain + if (HasExtension(OptionalAndroidDeviceExtensionVK::kKHRExternalFenceFd) && + HasExtension(OptionalAndroidDeviceExtensionVK::kKHRExternalFence) && + HasExtension(OptionalAndroidDeviceExtensionVK::kKHRExternalSemaphore) && + HasExtension(OptionalAndroidDeviceExtensionVK::kKHRExternalSemaphoreFd)) { + supports_external_fence_and_semaphore_ = true; + } + + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsOffscreenMSAA() const { + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsImplicitResolvingMSAA() const { + return false; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsSSBO() const { + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsTextureToTextureBlits() const { + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsFramebufferFetch() const { + return has_framebuffer_fetch_; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsCompute() const { + // Vulkan 1.1 requires support for compute. + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsComputeSubgroups() const { + // Set by |SetPhysicalDevice|. + return supports_compute_subgroups_; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsReadFromResolve() const { + return false; +} + +bool CapabilitiesVK::SupportsDecalSamplerAddressMode() const { + return true; +} + +// |Capabilities| +bool CapabilitiesVK::SupportsDeviceTransientTextures() const { + return supports_device_transient_textures_; +} + +// |Capabilities| +PixelFormat CapabilitiesVK::GetDefaultColorFormat() const { + return default_color_format_; +} + +// |Capabilities| +PixelFormat CapabilitiesVK::GetDefaultStencilFormat() const { + return default_stencil_format_; +} + +// |Capabilities| +PixelFormat CapabilitiesVK::GetDefaultDepthStencilFormat() const { + return default_depth_stencil_format_; +} + +const vk::PhysicalDeviceProperties& +CapabilitiesVK::GetPhysicalDeviceProperties() const { + return device_properties_; +} + +PixelFormat CapabilitiesVK::GetDefaultGlyphAtlasFormat() const { + return PixelFormat::kR8UNormInt; +} + +bool CapabilitiesVK::HasExtension(RequiredCommonDeviceExtensionVK ext) const { + return required_common_device_extensions_.find(ext) != + required_common_device_extensions_.end(); +} + +bool CapabilitiesVK::HasExtension(RequiredAndroidDeviceExtensionVK ext) const { + return required_android_device_extensions_.find(ext) != + required_android_device_extensions_.end(); +} + +bool CapabilitiesVK::HasExtension(OptionalDeviceExtensionVK ext) const { + return optional_device_extensions_.find(ext) != + optional_device_extensions_.end(); +} + +bool CapabilitiesVK::HasExtension(OptionalAndroidDeviceExtensionVK ext) const { + return optional_android_device_extensions_.find(ext) != + optional_android_device_extensions_.end(); +} + +bool CapabilitiesVK::SupportsTextureFixedRateCompression() const { + return supports_texture_fixed_rate_compression_; +} + +std::optional +CapabilitiesVK::GetSupportedFRCRate(CompressionType compression_type, + const FRCFormatDescriptor& desc) const { + if (compression_type != CompressionType::kLossy) { + return std::nullopt; + } + if (!supports_texture_fixed_rate_compression_) { + return std::nullopt; + } + // There are opportunities to hash and cache the FRCFormatDescriptor if + // needed. + vk::StructureChain + format_chain; + + auto& format_info = format_chain.get(); + + format_info.format = desc.format; + format_info.type = desc.type; + format_info.tiling = desc.tiling; + format_info.usage = desc.usage; + format_info.flags = desc.flags; + + const auto kIdealFRCRate = vk::ImageCompressionFixedRateFlagBitsEXT::e4Bpc; + + std::array rates = {kIdealFRCRate}; + + auto& compression = format_chain.get(); + compression.flags = vk::ImageCompressionFlagBitsEXT::eFixedRateExplicit; + compression.compressionControlPlaneCount = rates.size(); + compression.pFixedRateFlags = rates.data(); + + const auto [result, supported] = physical_device_.getImageFormatProperties2< + vk::ImageFormatProperties2, vk::ImageCompressionPropertiesEXT>( + format_chain.get()); + + if (result != vk::Result::eSuccess || + !supported.isLinked()) { + return std::nullopt; + } + + const auto& compression_props = + supported.get(); + + if ((compression_props.imageCompressionFlags & + vk::ImageCompressionFlagBitsEXT::eFixedRateExplicit) && + (compression_props.imageCompressionFixedRateFlags & kIdealFRCRate)) { + return kIdealFRCRate; + } + + return std::nullopt; +} + +bool CapabilitiesVK::SupportsTriangleFan() const { + return has_triangle_fans_; +} + +ISize CapabilitiesVK::GetMaximumRenderPassAttachmentSize() const { + return max_render_pass_attachment_size_; +} + +void CapabilitiesVK::ApplyWorkarounds(const WorkaroundsVK& workarounds) { + has_primitive_restart_ = !workarounds.slow_primitive_restart_performance; + has_framebuffer_fetch_ = !workarounds.input_attachment_self_dependency_broken; +} + +bool CapabilitiesVK::SupportsExternalSemaphoreExtensions() const { + return supports_external_fence_and_semaphore_; +} + +bool CapabilitiesVK::SupportsExtendedRangeFormats() const { + return false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..5b99f704289a94ef3c0c2948b5ce151b676d1d50 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/capabilities_vk.h @@ -0,0 +1,349 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CAPABILITIES_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CAPABILITIES_VK_H_ + +#include +#include +#include +#include +#include +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/capabilities.h" + +namespace impeller { + +class ContextVK; + +//------------------------------------------------------------------------------ +/// @brief A device extension available on all platforms. Without the +/// presence of these extensions, context creation will fail. +/// +enum class RequiredCommonDeviceExtensionVK : uint32_t { + //---------------------------------------------------------------------------- + /// For displaying content in the window system. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_swapchain.html + /// + kKHRSwapchain, + + kLast, +}; + +//------------------------------------------------------------------------------ +/// @brief A device extension available on all Android platforms. Without +/// the presence of these extensions on Android, context creation +/// will fail. +/// +/// Platform agnostic code can still check if these Android +/// extensions are present. +/// +enum class RequiredAndroidDeviceExtensionVK : uint32_t { + //---------------------------------------------------------------------------- + /// For importing hardware buffers used in external texture composition. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_ANDROID_external_memory_android_hardware_buffer.html + /// + kANDROIDExternalMemoryAndroidHardwareBuffer, + + //---------------------------------------------------------------------------- + /// Dependency of kANDROIDExternalMemoryAndroidHardwareBuffer. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_sampler_ycbcr_conversion.html + /// + kKHRSamplerYcbcrConversion, + + //---------------------------------------------------------------------------- + /// Dependency of kANDROIDExternalMemoryAndroidHardwareBuffer. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_external_memory.html + /// + kKHRExternalMemory, + + //---------------------------------------------------------------------------- + /// Dependency of kANDROIDExternalMemoryAndroidHardwareBuffer. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_queue_family_foreign.html + /// + kEXTQueueFamilyForeign, + + //---------------------------------------------------------------------------- + /// Dependency of kANDROIDExternalMemoryAndroidHardwareBuffer. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_dedicated_allocation.html + /// + kKHRDedicatedAllocation, + + kLast, +}; + +//------------------------------------------------------------------------------ +/// @brief A device extension available on some Android platforms. +/// +/// Platform agnostic code can still check if these Android +/// extensions are present. +/// +enum class OptionalAndroidDeviceExtensionVK : uint32_t { + //---------------------------------------------------------------------------- + /// For exporting file descriptors from fences to interact with platform APIs. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_external_fence_fd.html + /// + kKHRExternalFenceFd, + + //---------------------------------------------------------------------------- + /// Dependency of kKHRExternalFenceFd. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_external_fence.html + /// + kKHRExternalFence, + + //---------------------------------------------------------------------------- + /// For importing sync file descriptors as semaphores so the GPU can wait for + /// semaphore to be signaled. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_external_semaphore_fd.html + kKHRExternalSemaphoreFd, + + //---------------------------------------------------------------------------- + /// Dependency of kKHRExternalSemaphoreFd + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_external_semaphore.html + kKHRExternalSemaphore, + + kLast, +}; + +//------------------------------------------------------------------------------ +/// @brief A device extension enabled if available. Subsystems cannot +/// assume availability and must check if these extensions are +/// available. +/// +/// @see `CapabilitiesVK::HasExtension`. +/// +enum class OptionalDeviceExtensionVK : uint32_t { + //---------------------------------------------------------------------------- + /// To instrument and profile PSO creation. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_pipeline_creation_feedback.html + /// + kEXTPipelineCreationFeedback, + + //---------------------------------------------------------------------------- + /// To enable context creation on MoltenVK. A non-conformant Vulkan + /// implementation. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_portability_subset.html + /// + kVKKHRPortabilitySubset, + + //---------------------------------------------------------------------------- + /// For fixed-rate compression of images. + /// + /// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_image_compression_control.html + /// + kEXTImageCompressionControl, + + kLast, +}; + +//------------------------------------------------------------------------------ +/// @brief A pixel format and usage that is sufficient to check if images +/// of that format and usage are suitable for use with fixed-rate +/// compression. +/// +struct FRCFormatDescriptor { + vk::Format format = vk::Format::eUndefined; + vk::ImageType type = {}; + vk::ImageTiling tiling = {}; + vk::ImageUsageFlags usage = {}; + vk::ImageCreateFlags flags = {}; + + explicit FRCFormatDescriptor(const vk::ImageCreateInfo& image_info) + : format(image_info.format), + type(image_info.imageType), + tiling(image_info.tiling), + usage(image_info.usage), + flags(image_info.flags) {} +}; + +//------------------------------------------------------------------------------ +/// @brief The Vulkan layers and extensions wrangler. +/// +class CapabilitiesVK final : public Capabilities, + public BackendCast { + public: + explicit CapabilitiesVK(bool enable_validations, + bool fatal_missing_validations = false, + bool use_embedder_extensions = false, + std::vector instance_extensions = {}, + std::vector device_extensions = {}); + + ~CapabilitiesVK(); + + bool IsValid() const; + + bool AreValidationsEnabled() const; + + bool HasExtension(RequiredCommonDeviceExtensionVK ext) const; + + bool HasExtension(RequiredAndroidDeviceExtensionVK ext) const; + + bool HasExtension(OptionalDeviceExtensionVK ext) const; + + bool HasExtension(OptionalAndroidDeviceExtensionVK ext) const; + + std::optional> GetEnabledLayers() const; + + std::optional> GetEnabledInstanceExtensions() const; + + std::optional> GetEnabledDeviceExtensions( + const vk::PhysicalDevice& physical_device) const; + + using PhysicalDeviceFeatures = + vk::StructureChain; + + std::optional GetEnabledDeviceFeatures( + const vk::PhysicalDevice& physical_device) const; + + [[nodiscard]] bool SetPhysicalDevice( + const vk::PhysicalDevice& physical_device, + const PhysicalDeviceFeatures& enabled_features); + + const vk::PhysicalDeviceProperties& GetPhysicalDeviceProperties() const; + + void SetOffscreenFormat(PixelFormat pixel_format) const; + + // |Capabilities| + bool SupportsOffscreenMSAA() const override; + + // |Capabilities| + bool SupportsImplicitResolvingMSAA() const override; + + // |Capabilities| + bool SupportsSSBO() const override; + + // |Capabilities| + bool SupportsTextureToTextureBlits() const override; + + // |Capabilities| + bool SupportsFramebufferFetch() const override; + + // |Capabilities| + bool SupportsCompute() const override; + + // |Capabilities| + bool SupportsComputeSubgroups() const override; + + // |Capabilities| + bool SupportsReadFromResolve() const override; + + // |Capabilities| + bool SupportsDecalSamplerAddressMode() const override; + + // |Capabilities| + bool SupportsDeviceTransientTextures() const override; + + // |Capabilities| + bool SupportsTriangleFan() const override; + + // |Capabilities| + bool SupportsPrimitiveRestart() const override; + + // |Capabilities| + bool SupportsExtendedRangeFormats() const override; + + // |Capabilities| + PixelFormat GetDefaultColorFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultStencilFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultDepthStencilFormat() const override; + + // |Capabilities| + PixelFormat GetDefaultGlyphAtlasFormat() const override; + + // |Capabilities| + ISize GetMaximumRenderPassAttachmentSize() const override; + + //---------------------------------------------------------------------------- + /// @return If fixed-rate compression for non-onscreen surfaces is + /// supported. + /// + bool SupportsTextureFixedRateCompression() const; + + /// Whether the external fence and semaphore extensions used for AHB support + /// are available. + bool SupportsExternalSemaphoreExtensions() const; + + //---------------------------------------------------------------------------- + /// @brief Get the fixed compression rate supported by the context for + /// the given format and usage. + /// + /// @param[in] compression_type The compression type. + /// @param[in] desc The format and usage of the image. + /// + /// @return The supported fixed compression rate. + /// + std::optional GetSupportedFRCRate( + CompressionType compression_type, + const FRCFormatDescriptor& desc) const; + + //---------------------------------------------------------------------------- + /// @brief Update capabilities for the given set of workarounds. + void ApplyWorkarounds(const WorkaroundsVK& workarounds); + + private: + bool validations_enabled_ = false; + std::map> exts_; + std::set required_common_device_extensions_; + std::set + required_android_device_extensions_; + std::set + optional_android_device_extensions_; + std::set optional_device_extensions_; + mutable PixelFormat default_color_format_ = PixelFormat::kUnknown; + PixelFormat default_stencil_format_ = PixelFormat::kUnknown; + PixelFormat default_depth_stencil_format_ = PixelFormat::kUnknown; + vk::PhysicalDevice physical_device_; + vk::PhysicalDeviceProperties device_properties_; + bool supports_compute_subgroups_ = false; + bool supports_device_transient_textures_ = false; + bool supports_texture_fixed_rate_compression_ = false; + ISize max_render_pass_attachment_size_ = ISize{0, 0}; + bool has_triangle_fans_ = true; + bool has_primitive_restart_ = true; + bool has_framebuffer_fetch_ = true; + bool supports_external_fence_and_semaphore_ = false; + bool is_valid_ = false; + + // The embedder.h API is responsible for providing the instance and device + // extensions. + bool use_embedder_extensions_ = false; + std::vector embedder_instance_extensions_; + std::vector embedder_device_extensions_; + + bool HasExtension(const std::string& ext) const; + + bool HasLayer(const std::string& layer) const; + + CapabilitiesVK(const CapabilitiesVK&) = delete; + + CapabilitiesVK& operator=(const CapabilitiesVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CAPABILITIES_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca1b94da4697d4a03b276ca500d0f2615e0d6cae --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.cc @@ -0,0 +1,209 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" + +#include +#include + +#include "fml/logging.h" +#include "impeller/renderer/backend/vulkan/blit_pass_vk.h" +#include "impeller/renderer/backend/vulkan/compute_pass_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/render_pass_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +CommandBufferVK::CommandBufferVK( + std::weak_ptr context, + std::weak_ptr device_holder, + std::shared_ptr tracked_objects) + : CommandBuffer(std::move(context)), + device_holder_(std::move(device_holder)), + tracked_objects_(std::move(tracked_objects)) {} + +CommandBufferVK::~CommandBufferVK() = default; + +void CommandBufferVK::SetLabel(std::string_view label) const { +#ifdef IMPELLER_DEBUG + auto context = context_.lock(); + if (!context) { + return; + } + ContextVK::Cast(*context).SetDebugName(GetCommandBuffer(), label); +#endif // IMPELLER_DEBUG +} + +bool CommandBufferVK::IsValid() const { + return true; +} + +bool CommandBufferVK::OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) { + FML_UNREACHABLE() +} + +void CommandBufferVK::OnWaitUntilCompleted() {} + +void CommandBufferVK::OnWaitUntilScheduled() {} + +std::shared_ptr CommandBufferVK::OnCreateRenderPass( + RenderTarget target) { + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto pass = + std::shared_ptr(new RenderPassVK(context, // + target, // + shared_from_this() // + )); + if (!pass->IsValid()) { + return nullptr; + } + return pass; +} + +std::shared_ptr CommandBufferVK::OnCreateBlitPass() { + if (!IsValid()) { + return nullptr; + } + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto pass = std::shared_ptr(new BlitPassVK( + shared_from_this(), ContextVK::Cast(*context).GetWorkarounds())); + if (!pass->IsValid()) { + return nullptr; + } + return pass; +} + +std::shared_ptr CommandBufferVK::OnCreateComputePass() { + if (!IsValid()) { + return nullptr; + } + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto pass = + std::shared_ptr(new ComputePassVK(context, // + shared_from_this() // + )); + if (!pass->IsValid()) { + return nullptr; + } + return pass; +} + +bool CommandBufferVK::EndCommandBuffer() const { + InsertDebugMarker("QueueSubmit"); + + auto command_buffer = GetCommandBuffer(); + tracked_objects_->GetGPUProbe().RecordCmdBufferEnd(command_buffer); + + auto status = command_buffer.end(); + if (status != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to end command buffer: " << vk::to_string(status); + return false; + } + return true; +} + +vk::CommandBuffer CommandBufferVK::GetCommandBuffer() const { + if (tracked_objects_) { + return tracked_objects_->GetCommandBuffer(); + } + return {}; +} + +bool CommandBufferVK::Track(const std::shared_ptr& object) { + if (!IsValid()) { + return false; + } + tracked_objects_->Track(object); + return true; +} + +bool CommandBufferVK::Track(const std::shared_ptr& buffer) { + if (!IsValid()) { + return false; + } + tracked_objects_->Track(buffer); + return true; +} + +bool CommandBufferVK::Track( + const std::shared_ptr& texture) { + if (!IsValid()) { + return false; + } + tracked_objects_->Track(texture); + return true; +} + +bool CommandBufferVK::Track(const std::shared_ptr& texture) { + if (!IsValid()) { + return false; + } + if (!texture) { + return true; + } + return Track(TextureVK::Cast(*texture).GetTextureSource()); +} + +fml::StatusOr CommandBufferVK::AllocateDescriptorSets( + const vk::DescriptorSetLayout& layout, + PipelineKey pipeline_key, + const ContextVK& context) { + if (!IsValid()) { + return fml::Status(fml::StatusCode::kUnknown, "command encoder invalid"); + } + + return tracked_objects_->GetDescriptorPool().AllocateDescriptorSets( + layout, pipeline_key, context); +} + +void CommandBufferVK::PushDebugGroup(std::string_view label) const { + if (!HasValidationLayers()) { + return; + } + vk::DebugUtilsLabelEXT label_info; + label_info.pLabelName = label.data(); + if (auto command_buffer = GetCommandBuffer()) { + command_buffer.beginDebugUtilsLabelEXT(label_info); + } +} + +void CommandBufferVK::PopDebugGroup() const { + if (!HasValidationLayers()) { + return; + } + if (auto command_buffer = GetCommandBuffer()) { + command_buffer.endDebugUtilsLabelEXT(); + } +} + +void CommandBufferVK::InsertDebugMarker(std::string_view label) const { + if (!HasValidationLayers()) { + return; + } + vk::DebugUtilsLabelEXT label_info; + label_info.pLabelName = label.data(); + if (auto command_buffer = GetCommandBuffer()) { + command_buffer.insertDebugUtilsLabelEXT(label_info); + } +} + +DescriptorPoolVK& CommandBufferVK::GetDescriptorPool() const { + return tracked_objects_->GetDescriptorPool(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..c43c4fdf63d3a396e4d1248dd051281a561f2cd7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_buffer_vk.h @@ -0,0 +1,126 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_ + +#include "fml/status_or.h" +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/vulkan/command_queue_vk.h" +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/tracked_objects_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +class ContextVK; +class CommandEncoderFactoryVK; +class CommandEncoderVK; + +class CommandBufferVK final + : public CommandBuffer, + public BackendCast, + public std::enable_shared_from_this { + public: + // |CommandBuffer| + ~CommandBufferVK() override; + + // Encoder Functionality + + /// @brief Ensure that [object] is kept alive until this command buffer + /// completes execution. + bool Track(const std::shared_ptr& object); + + /// @brief Ensure that [buffer] is kept alive until this command buffer + /// completes execution. + bool Track(const std::shared_ptr& buffer); + + /// @brief Ensure that [texture] is kept alive until this command buffer + /// completes execution. + bool Track(const std::shared_ptr& texture); + + /// @brief Ensure that [texture] is kept alive until this command buffer + /// completes execution. + bool Track(const std::shared_ptr& texture); + + /// @brief Retrieve the native command buffer from this object. + vk::CommandBuffer GetCommandBuffer() const; + + /// @brief Push a debug group. + /// + /// This label is only visible in debuggers like RenderDoc. This function is + /// ignored in release builds. + void PushDebugGroup(std::string_view label) const; + + /// @brief Pop the previous debug group. + /// + /// This label is only visible in debuggers like RenderDoc. This function is + /// ignored in release builds. + void PopDebugGroup() const; + + /// @brief Insert a new debug marker. + /// + /// This label is only visible in debuggers like RenderDoc. This function is + /// ignored in release builds. + void InsertDebugMarker(std::string_view label) const; + + /// @brief End recording of the current command buffer. + bool EndCommandBuffer() const; + + /// @brief Allocate a new descriptor set for the given [layout]. + fml::StatusOr AllocateDescriptorSets( + const vk::DescriptorSetLayout& layout, + PipelineKey pipeline_key, + const ContextVK& context); + + // Visible for testing. + DescriptorPoolVK& GetDescriptorPool() const; + + private: + friend class ContextVK; + friend class CommandQueueVK; + + std::weak_ptr device_holder_; + std::shared_ptr tracked_objects_; + + CommandBufferVK(std::weak_ptr context, + std::weak_ptr device_holder, + std::shared_ptr tracked_objects); + + // |CommandBuffer| + void SetLabel(std::string_view label) const override; + + // |CommandBuffer| + bool IsValid() const override; + + // |CommandBuffer| + bool OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) override; + + // |CommandBuffer| + void OnWaitUntilCompleted() override; + + // |CommandBuffer| + void OnWaitUntilScheduled() override; + + // |CommandBuffer| + std::shared_ptr OnCreateRenderPass(RenderTarget target) override; + + // |CommandBuffer| + std::shared_ptr OnCreateBlitPass() override; + + // |CommandBuffer| + std::shared_ptr OnCreateComputePass() override; + + CommandBufferVK(const CommandBufferVK&) = delete; + + CommandBufferVK& operator=(const CommandBufferVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_BUFFER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ea93053c32a9bddcb48c979ab89254848df82b3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_encoder_vk_unittests.cc @@ -0,0 +1,74 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "fml/synchronization/waitable_event.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { +namespace testing { + +TEST(CommandEncoderVKTest, DeleteEncoderAfterThreadDies) { + // Tests that when a CommandEncoderVK is deleted that it will clean up its + // command buffers before it cleans up its command pool. + std::shared_ptr> called_functions; + { + auto context = MockVulkanContextBuilder().Build(); + called_functions = GetMockVulkanFunctions(context->GetDevice()); + std::thread thread([&] { context->CreateCommandBuffer(); }); + thread.join(); + context->Shutdown(); + } + auto destroy_pool = + std::find(called_functions->begin(), called_functions->end(), + "vkDestroyCommandPool"); + auto free_buffers = + std::find(called_functions->begin(), called_functions->end(), + "vkFreeCommandBuffers"); + EXPECT_TRUE(destroy_pool != called_functions->end()); + EXPECT_TRUE(free_buffers != called_functions->end()); + EXPECT_TRUE(free_buffers < destroy_pool); +} + +TEST(CommandEncoderVKTest, CleanupAfterSubmit) { + // This tests deleting the TrackedObjects where the thread is killed before + // the fence waiter has disposed of them, making sure the command buffer and + // its pools are deleted in that order. + std::shared_ptr> called_functions; + { + fml::AutoResetWaitableEvent wait_for_submit; + fml::AutoResetWaitableEvent wait_for_thread_join; + auto context = MockVulkanContextBuilder().Build(); + std::thread thread([&] { + auto buffer = context->CreateCommandBuffer(); + context->GetCommandQueue()->Submit( + {buffer}, [&](CommandBuffer::Status status) { + ASSERT_EQ(status, CommandBuffer::Status::kCompleted); + wait_for_thread_join.Wait(); + wait_for_submit.Signal(); + }); + }); + thread.join(); + wait_for_thread_join.Signal(); + wait_for_submit.Wait(); + called_functions = GetMockVulkanFunctions(context->GetDevice()); + context->Shutdown(); + } + + auto destroy_pool = + std::find(called_functions->begin(), called_functions->end(), + "vkDestroyCommandPool"); + auto free_buffers = + std::find(called_functions->begin(), called_functions->end(), + "vkFreeCommandBuffers"); + EXPECT_TRUE(destroy_pool != called_functions->end()); + EXPECT_TRUE(free_buffers != called_functions->end()); + EXPECT_TRUE(free_buffers < destroy_pool); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfa80c252b4869fa1703694d6ad41a29efbadc3e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.cc @@ -0,0 +1,329 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" + +#include +#include +#include + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" + +#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep. +#include "vulkan/vulkan_enums.hpp" +#include "vulkan/vulkan_handles.hpp" +#include "vulkan/vulkan_structs.hpp" + +namespace impeller { + +// Holds the command pool in a background thread, recyling it when not in use. +class BackgroundCommandPoolVK final { + public: + BackgroundCommandPoolVK(BackgroundCommandPoolVK&&) = default; + + // The recycler also recycles command buffers that were never used, up to a + // limit of 16 per frame. This number was somewhat arbitrarily chosen. + static constexpr size_t kUnusedCommandBufferLimit = 16u; + + explicit BackgroundCommandPoolVK( + vk::UniqueCommandPool&& pool, + std::vector&& buffers, + size_t unused_count, + std::weak_ptr recycler) + : pool_(std::move(pool)), + buffers_(std::move(buffers)), + unused_count_(unused_count), + recycler_(std::move(recycler)) {} + + ~BackgroundCommandPoolVK() { + auto const recycler = recycler_.lock(); + + // Not only does this prevent recycling when the context is being destroyed, + // but it also prevents the destructor from effectively being called twice; + // once for the original BackgroundCommandPoolVK() and once for the moved + // BackgroundCommandPoolVK(). + if (!recycler) { + return; + } + // If there are many unused command buffers, release some of them and + // trim the command pool. + bool should_trim = unused_count_ > kUnusedCommandBufferLimit; + recycler->Reclaim(std::move(pool_), std::move(buffers_), + /*should_trim=*/should_trim); + } + + private: + BackgroundCommandPoolVK(const BackgroundCommandPoolVK&) = delete; + + BackgroundCommandPoolVK& operator=(const BackgroundCommandPoolVK&) = delete; + + vk::UniqueCommandPool pool_; + + // These are retained because the destructor of the C++ UniqueCommandBuffer + // wrapper type will attempt to reset the cmd buffer, and doing so may be a + // thread safety violation as this may happen on the fence waiter thread. + std::vector buffers_; + const size_t unused_count_; + std::weak_ptr recycler_; +}; + +CommandPoolVK::~CommandPoolVK() { + if (!pool_) { + return; + } + + auto const context = context_.lock(); + if (!context) { + return; + } + auto const recycler = context->GetCommandPoolRecycler(); + if (!recycler) { + return; + } + // Any unused command buffers are added to the set of used command buffers. + // both will be reset to the initial state when the pool is reset. + size_t unused_count = unused_command_buffers_.size(); + for (auto i = 0u; i < unused_command_buffers_.size(); i++) { + collected_buffers_.push_back(std::move(unused_command_buffers_[i])); + } + unused_command_buffers_.clear(); + + auto reset_pool_when_dropped = BackgroundCommandPoolVK( + std::move(pool_), std::move(collected_buffers_), unused_count, recycler); + + UniqueResourceVKT pool( + context->GetResourceManager(), std::move(reset_pool_when_dropped)); +} + +// TODO(matanlurey): Return a status_or<> instead of {} when we have one. +vk::UniqueCommandBuffer CommandPoolVK::CreateCommandBuffer() { + auto const context = context_.lock(); + if (!context) { + return {}; + } + + Lock lock(pool_mutex_); + if (!pool_) { + return {}; + } + if (!unused_command_buffers_.empty()) { + vk::UniqueCommandBuffer buffer = std::move(unused_command_buffers_.back()); + unused_command_buffers_.pop_back(); + return buffer; + } + + auto const device = context->GetDevice(); + vk::CommandBufferAllocateInfo info; + info.setCommandPool(pool_.get()); + info.setCommandBufferCount(1u); + info.setLevel(vk::CommandBufferLevel::ePrimary); + auto [result, buffers] = device.allocateCommandBuffersUnique(info); + if (result != vk::Result::eSuccess) { + return {}; + } + return std::move(buffers[0]); +} + +void CommandPoolVK::CollectCommandBuffer(vk::UniqueCommandBuffer&& buffer) { + Lock lock(pool_mutex_); + if (!pool_) { + // If the command pool has already been destroyed, then its buffers have + // already been freed. + buffer.release(); + return; + } + collected_buffers_.push_back(std::move(buffer)); +} + +void CommandPoolVK::Destroy() { + Lock lock(pool_mutex_); + pool_.reset(); + + // When the command pool is destroyed, all of its command buffers are freed. + // Handles allocated from that pool are now invalid and must be discarded. + for (auto& buffer : collected_buffers_) { + buffer.release(); + } + for (auto& buffer : unused_command_buffers_) { + buffer.release(); + } + unused_command_buffers_.clear(); + collected_buffers_.clear(); +} + +// Associates a resource with a thread and context. +using CommandPoolMap = + std::unordered_map>; + +// CommandPoolVK Lifecycle: +// 1. End of frame will reset the command pool (clearing this on a thread). +// There will still be references to the command pool from the uncompleted +// command buffers. +// 2. The last reference to the command pool will be released from the fence +// waiter thread, which will schedule a task on the resource +// manager thread, which in turn will reset the command pool and make it +// available for reuse ("recycle"). +static thread_local std::unique_ptr tls_command_pool_map; + +// Map each context to a list of all thread-local command pools associated +// with that context. +static Mutex g_all_pools_map_mutex; +static std::unordered_map< + uint64_t, + std::unordered_map>> g_all_pools_map + IPLR_GUARDED_BY(g_all_pools_map_mutex); + +CommandPoolRecyclerVK::CommandPoolRecyclerVK( + const std::shared_ptr& context) + : context_(context), context_hash_(context->GetHash()) {} + +// Visible for testing. +// Returns the number of pools in g_all_pools_map for the given context. +int CommandPoolRecyclerVK::GetGlobalPoolCount(const ContextVK& context) { + Lock all_pools_lock(g_all_pools_map_mutex); + auto it = g_all_pools_map.find(context.GetHash()); + return it != g_all_pools_map.end() ? it->second.size() : 0; +} + +// TODO(matanlurey): Return a status_or<> instead of nullptr when we have one. +std::shared_ptr CommandPoolRecyclerVK::Get() { + auto const strong_context = context_.lock(); + if (!strong_context) { + return nullptr; + } + + // If there is a resource in used for this thread and context, return it. + if (!tls_command_pool_map.get()) { + tls_command_pool_map.reset(new CommandPoolMap()); + } + CommandPoolMap& pool_map = *tls_command_pool_map.get(); + auto const it = pool_map.find(context_hash_); + if (it != pool_map.end()) { + return it->second; + } + + // Otherwise, create a new resource and return it. + auto data = Create(); + if (!data || !data->pool) { + return nullptr; + } + + auto const resource = std::make_shared( + std::move(data->pool), std::move(data->buffers), context_); + pool_map.emplace(context_hash_, resource); + + { + Lock all_pools_lock(g_all_pools_map_mutex); + g_all_pools_map[context_hash_][std::this_thread::get_id()] = resource; + } + + return resource; +} + +// TODO(matanlurey): Return a status_or<> instead of nullopt when we have one. +std::optional +CommandPoolRecyclerVK::Create() { + // If we can reuse a command pool and its buffers, do so. + if (auto data = Reuse()) { + return data; + } + + // Otherwise, create a new one. + auto context = context_.lock(); + if (!context) { + return std::nullopt; + } + vk::CommandPoolCreateInfo info; + info.setQueueFamilyIndex(context->GetGraphicsQueue()->GetIndex().family); + info.setFlags(vk::CommandPoolCreateFlagBits::eTransient); + + auto device = context->GetDevice(); + auto [result, pool] = device.createCommandPoolUnique(info); + if (result != vk::Result::eSuccess) { + return std::nullopt; + } + return CommandPoolRecyclerVK::RecycledData{.pool = std::move(pool), + .buffers = {}}; +} + +std::optional +CommandPoolRecyclerVK::Reuse() { + // If there are no recycled pools, return nullopt. + Lock recycled_lock(recycled_mutex_); + if (recycled_.empty()) { + return std::nullopt; + } + + // Otherwise, remove and return a recycled pool. + auto data = std::move(recycled_.back()); + recycled_.pop_back(); + return std::move(data); +} + +void CommandPoolRecyclerVK::Reclaim( + vk::UniqueCommandPool&& pool, + std::vector&& buffers, + bool should_trim) { + // Reset the pool on a background thread. + auto strong_context = context_.lock(); + if (!strong_context) { + return; + } + auto device = strong_context->GetDevice(); + if (should_trim) { + buffers.clear(); + device.resetCommandPool(pool.get(), + vk::CommandPoolResetFlagBits::eReleaseResources); + } else { + device.resetCommandPool(pool.get(), {}); + } + + // Move the pool to the recycled list. + Lock recycled_lock(recycled_mutex_); + recycled_.push_back( + RecycledData{.pool = std::move(pool), .buffers = std::move(buffers)}); +} + +void CommandPoolRecyclerVK::Dispose() { + CommandPoolMap* pool_map = tls_command_pool_map.get(); + if (pool_map) { + pool_map->erase(context_hash_); + } + + { + Lock all_pools_lock(g_all_pools_map_mutex); + auto found = g_all_pools_map.find(context_hash_); + if (found != g_all_pools_map.end()) { + found->second.erase(std::this_thread::get_id()); + } + } +} + +void CommandPoolRecyclerVK::DestroyThreadLocalPools() { + // Delete the context's entry in this thread's command pool map. + if (tls_command_pool_map.get()) { + tls_command_pool_map.get()->erase(context_hash_); + } + + // Destroy all other thread-local CommandPoolVK instances associated with + // this context. + Lock all_pools_lock(g_all_pools_map_mutex); + auto found = g_all_pools_map.find(context_hash_); + if (found != g_all_pools_map.end()) { + for (auto& [thread_id, weak_pool] : found->second) { + auto pool = weak_pool.lock(); + if (!pool) { + continue; + } + // Delete all objects held by this pool. The destroyed pool will still + // remain in its thread's TLS map until that thread exits. + pool->Destroy(); + } + g_all_pools_map.erase(found); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..1fc9d06b32fb486fec537e68c329424ddb165f0c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk.h @@ -0,0 +1,165 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_ + +#include +#include +#include + +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep. +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { + +class ContextVK; +class CommandPoolRecyclerVK; + +//------------------------------------------------------------------------------ +/// @brief Manages the lifecycle of a single |vk::CommandPool|. +/// +/// A |vk::CommandPool| is expensive to create and reset. This class manages +/// the lifecycle of a single |vk::CommandPool| by returning to the origin +/// (|CommandPoolRecyclerVK|) when it is destroyed to be reused. +/// +/// @warning This class is not thread-safe. +/// +/// @see |CommandPoolRecyclerVK| +class CommandPoolVK final { + public: + ~CommandPoolVK(); + + /// @brief Creates a resource that manages the life of a command pool. + /// + /// @param[in] pool The command pool to manage. + /// @param[in] buffers Zero or more command buffers in an initial state. + /// @param[in] recycler The context that will be notified on destruction. + CommandPoolVK(vk::UniqueCommandPool pool, + std::vector&& buffers, + std::weak_ptr& context) + : pool_(std::move(pool)), + unused_command_buffers_(std::move(buffers)), + context_(context) {} + + /// @brief Creates and returns a new |vk::CommandBuffer|. + /// + /// @return Always returns a new |vk::CommandBuffer|, but if for any + /// reason a valid command buffer could not be created, it will be + /// a `{}` default instance (i.e. while being torn down). + vk::UniqueCommandBuffer CreateCommandBuffer(); + + /// @brief Collects the given |vk::CommandBuffer| to be retained. + /// + /// @param[in] buffer The |vk::CommandBuffer| to collect. + /// + /// @see |GarbageCollectBuffersIfAble| + void CollectCommandBuffer(vk::UniqueCommandBuffer&& buffer); + + /// @brief Delete all Vulkan objects in this command pool. + void Destroy(); + + private: + CommandPoolVK(const CommandPoolVK&) = delete; + + CommandPoolVK& operator=(const CommandPoolVK&) = delete; + + Mutex pool_mutex_; + vk::UniqueCommandPool pool_ IPLR_GUARDED_BY(pool_mutex_); + std::vector unused_command_buffers_; + std::weak_ptr& context_; + + // Used to retain a reference on these until the pool is reset. + std::vector collected_buffers_ IPLR_GUARDED_BY( + pool_mutex_); +}; + +//------------------------------------------------------------------------------ +/// @brief Creates and manages the lifecycle of |vk::CommandPool| objects. +/// +/// A |vk::CommandPool| is expensive to create and reset. This class manages +/// the lifecycle of |vk::CommandPool| objects by creating and recycling them; +/// or in other words, a pool for command pools. +/// +/// A single instance should be created per |ContextVK|. +/// +/// Every "frame", a single |CommandPoolResourceVk| is made available for each +/// thread that calls |Get|. After calling |Dispose|, the current thread's pool +/// is moved to a background thread, reset, and made available for the next time +/// |Get| is called and needs to create a command pool. +/// +/// Commands in the command pool are not necessarily done executing when the +/// pool is recycled, when all references are dropped to the pool, they are +/// reset and returned to the pool of available pools. +/// +/// @note This class is thread-safe. +/// +/// @see |vk::CommandPoolResourceVk| +/// @see |ContextVK| +/// @see +/// https://arm-software.github.io/vulkan_best_practice_for_mobile_developers/samples/performance/command_buffer_usage/command_buffer_usage_tutorial.html +class CommandPoolRecyclerVK final + : public std::enable_shared_from_this { + public: + /// A unique command pool and zero or more recycled command buffers. + struct RecycledData { + vk::UniqueCommandPool pool; + std::vector buffers; + }; + + /// @brief Clean up resources held by all per-thread command pools + /// associated with the context. + void DestroyThreadLocalPools(); + + /// @brief Creates a recycler for the given |ContextVK|. + /// + /// @param[in] context The context to create the recycler for. + explicit CommandPoolRecyclerVK(const std::shared_ptr& context); + + /// @brief Gets a command pool for the current thread. + /// + /// @warning Returns a |nullptr| if a pool could not be created. + std::shared_ptr Get(); + + /// @brief Returns a command pool to be reset on a background thread. + /// + /// @param[in] pool The pool to recycle. + /// @param[in] should_trim whether to trim command pool memory before + /// reseting. + void Reclaim(vk::UniqueCommandPool&& pool, + std::vector&& buffers, + bool should_trim = false); + + /// @brief Clears this context's thread-local command pool. + void Dispose(); + + // Visible for testing. + static int GetGlobalPoolCount(const ContextVK& context); + + private: + std::weak_ptr context_; + uint64_t context_hash_; + + Mutex recycled_mutex_; + std::vector recycled_ IPLR_GUARDED_BY(recycled_mutex_); + + /// @brief Creates a new |vk::CommandPool|. + /// + /// @returns Returns a |std::nullopt| if a pool could not be created. + std::optional Create(); + + /// @brief Reuses a recycled |RecycledData|, if available. + /// + /// @returns Returns a |std::nullopt| if a pool was not available. + std::optional Reuse(); + + CommandPoolRecyclerVK(const CommandPoolRecyclerVK&) = delete; + + CommandPoolRecyclerVK& operator=(const CommandPoolRecyclerVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_POOL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..69b4e06c4ea6caf4607ed01e1763730ff7177489 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_pool_vk_unittests.cc @@ -0,0 +1,251 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep. +#include "fml/synchronization/waitable_event.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +namespace impeller { +namespace testing { + +TEST(CommandPoolRecyclerVKTest, GetsACommandPoolPerThread) { + auto const context = MockVulkanContextBuilder().Build(); + + { + // Record the memory location of each pointer to a command pool. + // + // These pools have to be held at this context, otherwise they will be + // dropped and recycled and potentially reused by another thread, causing + // flaky tests. + std::shared_ptr pool1; + std::shared_ptr pool2; + + // Create a command pool in two threads and record the memory location. + std::thread thread1( + [&]() { pool1 = context->GetCommandPoolRecycler()->Get(); }); + + std::thread thread2( + [&]() { pool2 = context->GetCommandPoolRecycler()->Get(); }); + + thread1.join(); + thread2.join(); + + // The two command pools should be different. + EXPECT_NE(pool1, pool2); + } + + context->Shutdown(); +} + +TEST(CommandPoolRecyclerVKTest, GetsTheSameCommandPoolOnSameThread) { + auto const context = MockVulkanContextBuilder().Build(); + + auto const pool1 = context->GetCommandPoolRecycler()->Get(); + auto const pool2 = context->GetCommandPoolRecycler()->Get(); + + // The two command pools should be the same. + EXPECT_EQ(pool1.get(), pool2.get()); + + context->Shutdown(); +} + +namespace { + +// Invokes the provided callback when the destructor is called. +// +// Can be moved, but not copied. +class DeathRattle final { + public: + explicit DeathRattle(std::function callback) + : callback_(std::move(callback)) {} + + DeathRattle(DeathRattle&&) = default; + DeathRattle& operator=(DeathRattle&&) = default; + + ~DeathRattle() { callback_(); } + + private: + std::function callback_; +}; + +} // namespace + +TEST(CommandPoolRecyclerVKTest, ReclaimMakesCommandPoolAvailable) { + auto const context = MockVulkanContextBuilder().Build(); + + { + // Fetch a pool (which will be created). + auto const recycler = context->GetCommandPoolRecycler(); + auto const pool = recycler->Get(); + + // This normally is called at the end of a frame. + recycler->Dispose(); + } + + // Add something to the resource manager and have it notify us when it's + // destroyed. That should give us a non-flaky signal that the pool has been + // reclaimed as well. + auto waiter = fml::AutoResetWaitableEvent(); + auto rattle = DeathRattle([&waiter]() { waiter.Signal(); }); + { + UniqueResourceVKT resource(context->GetResourceManager(), + std::move(rattle)); + } + waiter.Wait(); + + // On another thread explicitly, request a new pool. + std::thread thread([&]() { + auto const pool = context->GetCommandPoolRecycler()->Get(); + EXPECT_NE(pool.get(), nullptr); + }); + + thread.join(); + + // Now check that we only ever created one pool. + auto const called = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called->begin(), called->end(), "vkCreateCommandPool"), + 1u); + + context->Shutdown(); +} + +TEST(CommandPoolRecyclerVKTest, CommandBuffersAreRecycled) { + auto const context = MockVulkanContextBuilder().Build(); + + { + // Fetch a pool (which will be created). + auto const recycler = context->GetCommandPoolRecycler(); + auto pool = recycler->Get(); + + auto buffer = pool->CreateCommandBuffer(); + pool->CollectCommandBuffer(std::move(buffer)); + + // This normally is called at the end of a frame. + recycler->Dispose(); + } + + // Wait for the pool to be reclaimed. + for (auto i = 0u; i < 2u; i++) { + auto waiter = fml::AutoResetWaitableEvent(); + auto rattle = DeathRattle([&waiter]() { waiter.Signal(); }); + { + UniqueResourceVKT resource(context->GetResourceManager(), + std::move(rattle)); + } + waiter.Wait(); + } + + { + // Create a second pool and command buffer, which should reused the existing + // pool and cmd buffer. + auto const recycler = context->GetCommandPoolRecycler(); + auto pool = recycler->Get(); + + auto buffer = pool->CreateCommandBuffer(); + pool->CollectCommandBuffer(std::move(buffer)); + + // This normally is called at the end of a frame. + recycler->Dispose(); + } + + // Now check that we only ever created one pool and one command buffer. + auto const called = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called->begin(), called->end(), "vkCreateCommandPool"), + 1u); + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkAllocateCommandBuffers"), + 1u); + + context->Shutdown(); +} + +TEST(CommandPoolRecyclerVKTest, ExtraCommandBufferAllocationsTriggerTrim) { + auto const context = MockVulkanContextBuilder().Build(); + + { + // Fetch a pool (which will be created). + auto const recycler = context->GetCommandPoolRecycler(); + auto pool = recycler->Get(); + + // Allocate a large number of command buffers + for (auto i = 0; i < 64; i++) { + auto buffer = pool->CreateCommandBuffer(); + pool->CollectCommandBuffer(std::move(buffer)); + } + + // This normally is called at the end of a frame. + recycler->Dispose(); + } + + // Wait for the pool to be reclaimed. + for (auto i = 0u; i < 2u; i++) { + auto waiter = fml::AutoResetWaitableEvent(); + auto rattle = DeathRattle([&waiter]() { waiter.Signal(); }); + { + UniqueResourceVKT resource(context->GetResourceManager(), + std::move(rattle)); + } + waiter.Wait(); + } + + // Command pool is reset but does not release resources. + auto called = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called->begin(), called->end(), "vkResetCommandPool"), + 1u); + + // Create the pool a second time, but dont use any command buffers. + { + // Fetch a pool (which will be created). + auto const recycler = context->GetCommandPoolRecycler(); + auto pool = recycler->Get(); + + // This normally is called at the end of a frame. + recycler->Dispose(); + } + + // Wait for the pool to be reclaimed. + for (auto i = 0u; i < 2u; i++) { + auto waiter = fml::AutoResetWaitableEvent(); + auto rattle = DeathRattle([&waiter]() { waiter.Signal(); }); + { + UniqueResourceVKT resource(context->GetResourceManager(), + std::move(rattle)); + } + waiter.Wait(); + } + + // Verify that the cmd pool was trimmed. + + // Now check that we only ever created one pool and one command buffer. + called = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called->begin(), called->end(), + "vkResetCommandPoolReleaseResources"), + 1u); + + context->Shutdown(); +} + +TEST(CommandPoolRecyclerVKTest, RecyclerGlobalPoolMapSize) { + auto context = MockVulkanContextBuilder().Build(); + auto const recycler = context->GetCommandPoolRecycler(); + + // The global pool list for this context should initially be empty. + EXPECT_EQ(CommandPoolRecyclerVK::GetGlobalPoolCount(*context), 0); + + // Creating a pool for this thread should insert the pool into the global map. + auto pool = recycler->Get(); + EXPECT_EQ(CommandPoolRecyclerVK::GetGlobalPoolCount(*context), 1); + + // Disposing this thread's pool should remove it from the global map. + pool.reset(); + recycler->Dispose(); + EXPECT_EQ(CommandPoolRecyclerVK::GetGlobalPoolCount(*context), 0); + + context->Shutdown(); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3f42265ce0662c88b0bad515ebe7333749506bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.cc @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fml/status.h" + +#include "impeller/renderer/backend/vulkan/command_queue_vk.h" + +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" +#include "impeller/renderer/backend/vulkan/tracked_objects_vk.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +CommandQueueVK::CommandQueueVK(const std::weak_ptr& context) + : context_(context) {} + +CommandQueueVK::~CommandQueueVK() = default; + +fml::Status CommandQueueVK::Submit( + const std::vector>& buffers, + const CompletionCallback& completion_callback, + bool block_on_schedule) { + if (buffers.empty()) { + return fml::Status(fml::StatusCode::kInvalidArgument, + "No command buffers provided."); + } + // Success or failure, you only get to submit once. + fml::ScopedCleanupClosure reset([&]() { + if (completion_callback) { + completion_callback(CommandBuffer::Status::kError); + } + }); + + std::vector vk_buffers; + std::vector> tracked_objects; + vk_buffers.reserve(buffers.size()); + tracked_objects.reserve(buffers.size()); + for (const std::shared_ptr& buffer : buffers) { + CommandBufferVK& command_buffer = CommandBufferVK::Cast(*buffer); + if (!command_buffer.EndCommandBuffer()) { + return fml::Status(fml::StatusCode::kCancelled, + "Failed to end command buffer."); + } + vk_buffers.push_back(command_buffer.GetCommandBuffer()); + tracked_objects.push_back(std::move(command_buffer.tracked_objects_)); + } + + auto context = context_.lock(); + if (!context) { + VALIDATION_LOG << "Device lost."; + return fml::Status(fml::StatusCode::kCancelled, "Device lost."); + } + auto [fence_result, fence] = context->GetDevice().createFenceUnique({}); + if (fence_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create fence: " << vk::to_string(fence_result); + return fml::Status(fml::StatusCode::kCancelled, "Failed to create fence."); + } + + vk::SubmitInfo submit_info; + submit_info.setCommandBuffers(vk_buffers); + auto status = context->GetGraphicsQueue()->Submit(submit_info, *fence); + if (status != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to submit queue: " << vk::to_string(status); + return fml::Status(fml::StatusCode::kCancelled, "Failed to submit queue: "); + } + + // Submit will proceed, call callback with true when it is done and do not + // call when `reset` is collected. + auto added_fence = context->GetFenceWaiter()->AddFence( + std::move(fence), [completion_callback, tracked_objects = std::move( + tracked_objects)]() mutable { + // Ensure tracked objects are destructed before calling any final + // callbacks. + tracked_objects.clear(); + if (completion_callback) { + completion_callback(CommandBuffer::Status::kCompleted); + } + }); + if (!added_fence) { + return fml::Status(fml::StatusCode::kCancelled, "Failed to add fence."); + } + reset.Release(); + return fml::Status(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..20450c2a4b8169644ae2d8a5f286023bd332bf6a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/command_queue_vk.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_ + +#include "impeller/renderer/command_queue.h" + +namespace impeller { + +class ContextVK; + +class CommandQueueVK : public CommandQueue { + public: + explicit CommandQueueVK(const std::weak_ptr& context); + + ~CommandQueueVK() override; + + fml::Status Submit(const std::vector>& buffers, + const CompletionCallback& completion_callback = {}, + bool block_on_schedule = false) override; + + private: + std::weak_ptr context_; + + CommandQueueVK(const CommandQueueVK&) = delete; + + CommandQueueVK& operator=(const CommandQueueVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMMAND_QUEUE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..a82210c7bb88844c8d3b193a3224bdffbf119aa0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.cc @@ -0,0 +1,264 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/compute_pass_vk.h" + +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "vulkan/vulkan_structs.hpp" + +namespace impeller { + +ComputePassVK::ComputePassVK(std::shared_ptr context, + std::shared_ptr command_buffer) + : ComputePass(std::move(context)), + command_buffer_(std::move(command_buffer)) { + // TOOD(dnfield): This should be moved to caps. But for now keeping this + // in parallel with Metal. + max_wg_size_ = ContextVK::Cast(*context_) + .GetPhysicalDevice() + .getProperties() + .limits.maxComputeWorkGroupSize; + is_valid_ = true; +} + +ComputePassVK::~ComputePassVK() = default; + +bool ComputePassVK::IsValid() const { + return is_valid_; +} + +void ComputePassVK::OnSetLabel(const std::string& label) { + if (label.empty()) { + return; + } + label_ = label; +} + +// |RenderPass| +void ComputePassVK::SetCommandLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + command_buffer_->PushDebugGroup(label); + has_label_ = true; +#endif // IMPELLER_DEBUG +} + +// |ComputePass| +void ComputePassVK::SetPipeline( + const std::shared_ptr>& pipeline) { + const auto& pipeline_vk = ComputePipelineVK::Cast(*pipeline); + const vk::CommandBuffer& command_buffer_vk = + command_buffer_->GetCommandBuffer(); + command_buffer_vk.bindPipeline(vk::PipelineBindPoint::eCompute, + pipeline_vk.GetPipeline()); + pipeline_layout_ = pipeline_vk.GetPipelineLayout(); + + auto descriptor_result = command_buffer_->AllocateDescriptorSets( + pipeline_vk.GetDescriptorSetLayout(), pipeline_vk.GetPipelineKey(), + ContextVK::Cast(*context_)); + if (!descriptor_result.ok()) { + return; + } + descriptor_set_ = descriptor_result.value(); + pipeline_valid_ = true; +} + +// |ComputePass| +fml::Status ComputePassVK::Compute(const ISize& grid_size) { + if (grid_size.IsEmpty() || !pipeline_valid_) { + bound_image_offset_ = 0u; + bound_buffer_offset_ = 0u; + descriptor_write_offset_ = 0u; + has_label_ = false; + pipeline_valid_ = false; + return fml::Status(fml::StatusCode::kCancelled, + "Invalid pipeline or empty grid."); + } + + const ContextVK& context_vk = ContextVK::Cast(*context_); + for (auto i = 0u; i < descriptor_write_offset_; i++) { + write_workspace_[i].dstSet = descriptor_set_; + } + + context_vk.GetDevice().updateDescriptorSets(descriptor_write_offset_, + write_workspace_.data(), 0u, {}); + const vk::CommandBuffer& command_buffer_vk = + command_buffer_->GetCommandBuffer(); + + command_buffer_vk.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, // bind point + pipeline_layout_, // layout + 0, // first set + 1, // set count + &descriptor_set_, // sets + 0, // offset count + nullptr // offsets + ); + + int64_t width = grid_size.width; + int64_t height = grid_size.height; + + // Special case for linear processing. + if (height == 1) { + command_buffer_vk.dispatch(width, 1, 1); + } else { + while (width > max_wg_size_[0]) { + width = std::max(static_cast(1), width / 2); + } + while (height > max_wg_size_[1]) { + height = std::max(static_cast(1), height / 2); + } + command_buffer_vk.dispatch(width, height, 1); + } + +#ifdef IMPELLER_DEBUG + if (has_label_) { + command_buffer_->PopDebugGroup(); + } + has_label_ = false; +#endif // IMPELLER_DEBUG + + bound_image_offset_ = 0u; + bound_buffer_offset_ = 0u; + descriptor_write_offset_ = 0u; + has_label_ = false; + pipeline_valid_ = false; + + return fml::Status(); +} + +// |ResourceBinder| +bool ComputePassVK::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + return BindResource(slot.binding, type, view); +} + +// |ResourceBinder| +bool ComputePassVK::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (bound_image_offset_ >= kMaxBindings) { + return false; + } + if (!texture->IsValid() || !sampler) { + return false; + } + const TextureVK& texture_vk = TextureVK::Cast(*texture); + const SamplerVK& sampler_vk = SamplerVK::Cast(*sampler); + + if (!command_buffer_->Track(texture)) { + return false; + } + + vk::DescriptorImageInfo image_info; + image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + image_info.sampler = sampler_vk.GetSampler(); + image_info.imageView = texture_vk.GetImageView(); + image_workspace_[bound_image_offset_++] = image_info; + + vk::WriteDescriptorSet write_set; + write_set.dstBinding = slot.binding; + write_set.descriptorCount = 1u; + write_set.descriptorType = ToVKDescriptorType(type); + write_set.pImageInfo = &image_workspace_[bound_image_offset_ - 1]; + + write_workspace_[descriptor_write_offset_++] = write_set; + return true; +} + +bool ComputePassVK::BindResource(size_t binding, + DescriptorType type, + BufferView view) { + if (bound_buffer_offset_ >= kMaxBindings) { + return false; + } + + auto buffer = DeviceBufferVK::Cast(*view.GetBuffer()).GetBuffer(); + if (!buffer) { + return false; + } + + std::shared_ptr device_buffer = view.TakeBuffer(); + if (device_buffer && !command_buffer_->Track(device_buffer)) { + return false; + } + + uint32_t offset = view.GetRange().offset; + + vk::DescriptorBufferInfo buffer_info; + buffer_info.buffer = buffer; + buffer_info.offset = offset; + buffer_info.range = view.GetRange().length; + buffer_workspace_[bound_buffer_offset_++] = buffer_info; + + vk::WriteDescriptorSet write_set; + write_set.dstBinding = binding; + write_set.descriptorCount = 1u; + write_set.descriptorType = ToVKDescriptorType(type); + write_set.pBufferInfo = &buffer_workspace_[bound_buffer_offset_ - 1]; + + write_workspace_[descriptor_write_offset_++] = write_set; + return true; +} + +// Note: +// https://github.com/KhronosGroup/Vulkan-Docs/wiki/Synchronization-Examples +// Seems to suggest that anything more finely grained than a global memory +// barrier is likely to be weakened into a global barrier. Confirming this on +// mobile devices will require some experimentation. + +// |ComputePass| +void ComputePassVK::AddBufferMemoryBarrier() { + vk::MemoryBarrier barrier; + barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + + command_buffer_->GetCommandBuffer().pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, {}, 1, &barrier, 0, {}, 0, {}); +} + +// |ComputePass| +void ComputePassVK::AddTextureMemoryBarrier() { + vk::MemoryBarrier barrier; + barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + + command_buffer_->GetCommandBuffer().pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eComputeShader, {}, 1, &barrier, 0, {}, 0, {}); +} + +// |ComputePass| +bool ComputePassVK::EncodeCommands() const { + // Since we only use global memory barrier, we don't have to worry about + // compute to compute dependencies across cmd buffers. Instead, we pessimize + // here and assume that we wrote to a storage image or buffer and that a + // render pass will read from it. if there are ever scenarios where we end up + // with compute to compute dependencies this should be revisited. + + // This does not currently handle image barriers as we do not use them + // for anything. + vk::MemoryBarrier barrier; + barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite; + barrier.dstAccessMask = + vk::AccessFlagBits::eIndexRead | vk::AccessFlagBits::eVertexAttributeRead; + + command_buffer_->GetCommandBuffer().pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eVertexInput, {}, 1, &barrier, 0, {}, 0, {}); + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..f47941c34840f7013e7872bbda82c9d117816770 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pass_vk.h @@ -0,0 +1,89 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PASS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PASS_VK_H_ + +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/compute_pass.h" + +namespace impeller { + +class CommandBufferVK; + +class ComputePassVK final : public ComputePass { + public: + // |ComputePass| + ~ComputePassVK() override; + + private: + friend class CommandBufferVK; + + std::shared_ptr command_buffer_; + std::string label_; + std::array max_wg_size_ = {}; + bool is_valid_ = false; + + // Per-command state. + std::array image_workspace_; + std::array buffer_workspace_; + std::array + write_workspace_; + size_t bound_image_offset_ = 0u; + size_t bound_buffer_offset_ = 0u; + size_t descriptor_write_offset_ = 0u; + bool has_label_ = false; + bool pipeline_valid_ = false; + vk::DescriptorSet descriptor_set_ = {}; + vk::PipelineLayout pipeline_layout_ = {}; + + ComputePassVK(std::shared_ptr context, + std::shared_ptr command_buffer); + + // |ComputePass| + bool IsValid() const override; + + // |ComputePass| + void OnSetLabel(const std::string& label) override; + + // |ComputePass| + bool EncodeCommands() const override; + + // |ComputePass| + void SetCommandLabel(std::string_view label) override; + + // |ComputePass| + void SetPipeline(const std::shared_ptr>& + pipeline) override; + + // |ComputePass| + void AddBufferMemoryBarrier() override; + + // |ComputePass| + void AddTextureMemoryBarrier() override; + + // |ComputePass| + fml::Status Compute(const ISize& grid_size) override; + + // |ResourceBinder| + bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + // |ResourceBinder| + bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + bool BindResource(size_t binding, DescriptorType type, BufferView view); +}; + +} // namespace impeller +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PASS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..f1823abb3b721129b0a580e26726b60f7501645a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.cc @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h" + +namespace impeller { + +ComputePipelineVK::ComputePipelineVK( + std::weak_ptr device_holder, + std::weak_ptr library, + const ComputePipelineDescriptor& desc, + vk::UniquePipeline pipeline, + vk::UniquePipelineLayout layout, + vk::UniqueDescriptorSetLayout descriptor_set_layout, + PipelineKey pipeline_key) + : Pipeline(std::move(library), desc), + device_holder_(std::move(device_holder)), + pipeline_(std::move(pipeline)), + layout_(std::move(layout)), + descriptor_set_layout_(std::move(descriptor_set_layout)), + pipeline_key_(pipeline_key) { + is_valid_ = pipeline_ && layout_ && descriptor_set_layout_; +} + +ComputePipelineVK::~ComputePipelineVK() { + std::shared_ptr device_holder = device_holder_.lock(); + if (device_holder) { + descriptor_set_layout_.reset(); + layout_.reset(); + pipeline_.reset(); + } else { + descriptor_set_layout_.release(); + layout_.release(); + pipeline_.release(); + } +} + +bool ComputePipelineVK::IsValid() const { + return is_valid_; +} + +const vk::Pipeline& ComputePipelineVK::GetPipeline() const { + return *pipeline_; +} + +const vk::PipelineLayout& ComputePipelineVK::GetPipelineLayout() const { + return *layout_; +} + +const vk::DescriptorSetLayout& ComputePipelineVK::GetDescriptorSetLayout() + const { + return *descriptor_set_layout_; +} + +PipelineKey ComputePipelineVK::GetPipelineKey() const { + return pipeline_key_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..839a8ffeb9d4a3a0c5856ec230aaf81a7db51850 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/compute_pipeline_vk.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PIPELINE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PIPELINE_VK_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +class ComputePipelineVK final + : public Pipeline, + public BackendCast> { + public: + ComputePipelineVK(std::weak_ptr device_holder, + std::weak_ptr library, + const ComputePipelineDescriptor& desc, + vk::UniquePipeline pipeline, + vk::UniquePipelineLayout layout, + vk::UniqueDescriptorSetLayout descriptor_set_layout, + PipelineKey pipeline_key); + + // |Pipeline| + ~ComputePipelineVK() override; + + const vk::Pipeline& GetPipeline() const; + + const vk::PipelineLayout& GetPipelineLayout() const; + + const vk::DescriptorSetLayout& GetDescriptorSetLayout() const; + + /// @brief Retrieve the unique identifier for this pipeline's descriptor set + /// layout. + PipelineKey GetPipelineKey() const; + + private: + friend class PipelineLibraryVK; + + std::weak_ptr device_holder_; + vk::UniquePipeline pipeline_; + vk::UniquePipelineLayout layout_; + vk::UniqueDescriptorSetLayout descriptor_set_layout_; + const PipelineKey pipeline_key_; + bool is_valid_ = false; + + // |Pipeline| + bool IsValid() const override; + + ComputePipelineVK(const ComputePipelineVK&) = delete; + + ComputePipelineVK& operator=(const ComputePipelineVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_COMPUTE_PIPELINE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..d75db4942bbb71991fe9cf4ab76fa4e34209385b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc @@ -0,0 +1,753 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include +#include + +#include "fml/concurrent_message_loop.h" +#include "impeller/core/formats.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/vulkan/command_queue_vk.h" +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/render_target.h" + +#ifdef FML_OS_ANDROID +#include +#include +#include +#endif // FML_OS_ANDROID + +#include +#include +#include +#include +#include + +#include "flutter/fml/cpu_affinity.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/allocator_vk.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/command_queue_vk.h" +#include "impeller/renderer/backend/vulkan/debug_report_vk.h" +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" +#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h" +#include "impeller/renderer/capabilities.h" + +VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE + +namespace impeller { + +static bool gHasValidationLayers = false; + +bool HasValidationLayers() { + return gHasValidationLayers; +} + +static std::optional PickPhysicalDevice( + const CapabilitiesVK& caps, + const vk::Instance& instance) { + for (const auto& device : instance.enumeratePhysicalDevices().value) { + if (caps.GetEnabledDeviceFeatures(device).has_value()) { + return device; + } + } + return std::nullopt; +} + +static std::vector GetQueueCreateInfos( + std::initializer_list queues) { + std::map family_index_map; + for (const auto& queue : queues) { + family_index_map[queue.family] = 0; + } + for (const auto& queue : queues) { + auto value = family_index_map[queue.family]; + family_index_map[queue.family] = std::max(value, queue.index); + } + + static float kQueuePriority = 1.0f; + std::vector infos; + for (const auto& item : family_index_map) { + vk::DeviceQueueCreateInfo info; + info.setQueueFamilyIndex(item.first); + info.setQueueCount(item.second + 1); + info.setQueuePriorities(kQueuePriority); + infos.push_back(info); + } + return infos; +} + +static std::optional PickQueue(const vk::PhysicalDevice& device, + vk::QueueFlagBits flags) { + // This can be modified to ensure that dedicated queues are returned for each + // queue type depending on support. + const auto families = device.getQueueFamilyProperties(); + for (size_t i = 0u; i < families.size(); i++) { + if (!(families[i].queueFlags & flags)) { + continue; + } + return QueueIndexVK{.family = i, .index = 0}; + } + return std::nullopt; +} + +std::shared_ptr ContextVK::Create(Settings settings) { + auto context = std::shared_ptr(new ContextVK(settings.flags)); + context->Setup(std::move(settings)); + if (!context->IsValid()) { + return nullptr; + } + return context; +} + +// static +size_t ContextVK::ChooseThreadCountForWorkers(size_t hardware_concurrency) { + // Never create more than 4 worker threads. Attempt to use up to + // half of the available concurrency. + return std::clamp(hardware_concurrency / 2ull, /*lo=*/1ull, /*hi=*/4ull); +} + +namespace { +std::atomic_uint64_t context_count = 0; +uint64_t CalculateHash(void* ptr) { + return context_count.fetch_add(1); +} +} // namespace + +ContextVK::ContextVK(const Flags& flags) + : Context(flags), hash_(CalculateHash(this)) {} + +ContextVK::~ContextVK() { + if (device_holder_ && device_holder_->device) { + [[maybe_unused]] auto result = device_holder_->device->waitIdle(); + } + if (command_pool_recycler_) { + command_pool_recycler_->DestroyThreadLocalPools(); + } +} + +Context::BackendType ContextVK::GetBackendType() const { + return Context::BackendType::kVulkan; +} + +void ContextVK::Setup(Settings settings) { + TRACE_EVENT0("impeller", "ContextVK::Setup"); + + if (!settings.proc_address_callback) { + VALIDATION_LOG << "Missing proc address callback."; + return; + } + + raster_message_loop_ = fml::ConcurrentMessageLoop::Create( + ChooseThreadCountForWorkers(std::thread::hardware_concurrency())); + + auto& dispatcher = VULKAN_HPP_DEFAULT_DISPATCHER; + dispatcher.init(settings.proc_address_callback); + + std::vector embedder_instance_extensions; + std::vector embedder_device_extensions; + if (settings.embedder_data.has_value()) { + embedder_instance_extensions = settings.embedder_data->instance_extensions; + embedder_device_extensions = settings.embedder_data->device_extensions; + } + auto caps = std::shared_ptr(new CapabilitiesVK( + settings.enable_validation, // + settings.fatal_missing_validations, // + /*use_embedder_extensions=*/settings.embedder_data.has_value(), // + embedder_instance_extensions, // + embedder_device_extensions // + )); + + if (!caps->IsValid()) { + VALIDATION_LOG << "Could not determine device capabilities."; + return; + } + + gHasValidationLayers = caps->AreValidationsEnabled(); + + auto enabled_layers = caps->GetEnabledLayers(); + auto enabled_extensions = caps->GetEnabledInstanceExtensions(); + + if (!enabled_layers.has_value() || !enabled_extensions.has_value()) { + VALIDATION_LOG << "Device has insufficient capabilities."; + return; + } + + vk::InstanceCreateFlags instance_flags = {}; + + if (std::find(enabled_extensions.value().begin(), + enabled_extensions.value().end(), + "VK_KHR_portability_enumeration") != + enabled_extensions.value().end()) { + instance_flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR; + } + + std::vector enabled_layers_c; + std::vector enabled_extensions_c; + + for (const auto& layer : enabled_layers.value()) { + enabled_layers_c.push_back(layer.c_str()); + } + + for (const auto& ext : enabled_extensions.value()) { + enabled_extensions_c.push_back(ext.c_str()); + } + + vk::ApplicationInfo application_info; + + // Use the same encoding macro as vulkan versions, but otherwise application + // version is intended to be the version of the Impeller engine. This version + // information, along with the application name below is provided to allow + // IHVs to make optimizations and/or disable functionality based on knowledge + // of the engine version (for example, to work around bugs). We don't tie this + // to the overall Flutter version as that version is not yet defined when the + // engine is compiled. Instead we can manually bump it occassionally. + // + // variant, major, minor, patch + application_info.setApplicationVersion( + VK_MAKE_API_VERSION(0, 2, 0, 0) /*version 2.0.0*/); + application_info.setApiVersion(VK_API_VERSION_1_1); + application_info.setEngineVersion(VK_API_VERSION_1_0); + application_info.setPEngineName("Impeller"); + application_info.setPApplicationName("Impeller"); + + vk::StructureChain + instance_chain; + + if (!caps->AreValidationsEnabled()) { + instance_chain.unlink(); + } + + std::vector enabled_validations = { + vk::ValidationFeatureEnableEXT::eSynchronizationValidation, + }; + + auto validation = instance_chain.get(); + validation.setEnabledValidationFeatures(enabled_validations); + + auto instance_info = instance_chain.get(); + instance_info.setPEnabledLayerNames(enabled_layers_c); + instance_info.setPEnabledExtensionNames(enabled_extensions_c); + instance_info.setPApplicationInfo(&application_info); + instance_info.setFlags(instance_flags); + + auto device_holder = std::make_shared(); + if (!settings.embedder_data.has_value()) { + auto instance = vk::createInstanceUnique(instance_info); + if (instance.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create Vulkan instance: " + << vk::to_string(instance.result); + return; + } + device_holder->instance = std::move(instance.value); + } else { + device_holder->instance.reset(settings.embedder_data->instance); + device_holder->owned = false; + } + dispatcher.init(device_holder->instance.get()); + + //---------------------------------------------------------------------------- + /// Setup the debug report. + /// + /// Do this as early as possible since we could use the debug report from + /// initialization issues. + /// + auto debug_report = + std::make_unique(*caps, device_holder->instance.get()); + + if (!debug_report->IsValid()) { + VALIDATION_LOG << "Could not set up debug report."; + return; + } + + //---------------------------------------------------------------------------- + /// Pick the physical device. + /// + if (!settings.embedder_data.has_value()) { + auto physical_device = + PickPhysicalDevice(*caps, device_holder->instance.get()); + if (!physical_device.has_value()) { + VALIDATION_LOG << "No valid Vulkan device found."; + return; + } + device_holder->physical_device = physical_device.value(); + } else { + device_holder->physical_device = settings.embedder_data->physical_device; + } + + //---------------------------------------------------------------------------- + /// Pick device queues. + /// + auto graphics_queue = + PickQueue(device_holder->physical_device, vk::QueueFlagBits::eGraphics); + auto transfer_queue = + PickQueue(device_holder->physical_device, vk::QueueFlagBits::eTransfer); + auto compute_queue = + PickQueue(device_holder->physical_device, vk::QueueFlagBits::eCompute); + + if (!graphics_queue.has_value()) { + VALIDATION_LOG << "Could not pick graphics queue."; + return; + } + if (!transfer_queue.has_value()) { + transfer_queue = graphics_queue.value(); + } + if (!compute_queue.has_value()) { + VALIDATION_LOG << "Could not pick compute queue."; + return; + } + + //---------------------------------------------------------------------------- + /// Create the logical device. + /// + auto enabled_device_extensions = + caps->GetEnabledDeviceExtensions(device_holder->physical_device); + if (!enabled_device_extensions.has_value()) { + // This shouldn't happen since we already did device selection. But + // doesn't hurt to check again. + return; + } + + std::vector enabled_device_extensions_c; + for (const auto& ext : enabled_device_extensions.value()) { + enabled_device_extensions_c.push_back(ext.c_str()); + } + + const auto queue_create_infos = GetQueueCreateInfos( + {graphics_queue.value(), compute_queue.value(), transfer_queue.value()}); + + const auto enabled_features = + caps->GetEnabledDeviceFeatures(device_holder->physical_device); + if (!enabled_features.has_value()) { + // This shouldn't happen since the device can't be picked if this was not + // true. But doesn't hurt to check. + return; + } + + vk::DeviceCreateInfo device_info; + + device_info.setPNext(&enabled_features.value().get()); + device_info.setQueueCreateInfos(queue_create_infos); + device_info.setPEnabledExtensionNames(enabled_device_extensions_c); + // Device layers are deprecated and ignored. + + if (!settings.embedder_data.has_value()) { + auto device_result = + device_holder->physical_device.createDeviceUnique(device_info); + if (device_result.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create logical device."; + return; + } + device_holder->device = std::move(device_result.value); + } else { + device_holder->device.reset(settings.embedder_data->device); + } + + if (!caps->SetPhysicalDevice(device_holder->physical_device, + *enabled_features)) { + VALIDATION_LOG << "Capabilities could not be updated."; + return; + } + + //---------------------------------------------------------------------------- + /// Create the allocator. + /// + auto allocator = std::shared_ptr(new AllocatorVK( + weak_from_this(), // + application_info.apiVersion, // + device_holder->physical_device, // + device_holder, // + device_holder->instance.get(), // + *caps // + )); + + if (!allocator->IsValid()) { + VALIDATION_LOG << "Could not create memory allocator."; + return; + } + + //---------------------------------------------------------------------------- + /// Setup the pipeline library. + /// + auto pipeline_library = std::shared_ptr( + new PipelineLibraryVK(device_holder, // + caps, // + std::move(settings.cache_directory), // + raster_message_loop_->GetTaskRunner() // + )); + + if (!pipeline_library->IsValid()) { + VALIDATION_LOG << "Could not create pipeline library."; + return; + } + + auto sampler_library = + std::shared_ptr(new SamplerLibraryVK(device_holder)); + + auto shader_library = std::shared_ptr( + new ShaderLibraryVK(device_holder, // + settings.shader_libraries_data) // + ); + + if (!shader_library->IsValid()) { + VALIDATION_LOG << "Could not create shader library."; + return; + } + + //---------------------------------------------------------------------------- + /// Create the fence waiter. + /// + auto fence_waiter = + std::shared_ptr(new FenceWaiterVK(device_holder)); + + //---------------------------------------------------------------------------- + /// Create the resource manager and command pool recycler. + /// + auto resource_manager = ResourceManagerVK::Create(); + if (!resource_manager) { + VALIDATION_LOG << "Could not create resource manager."; + return; + } + + auto command_pool_recycler = + std::make_shared(shared_from_this()); + if (!command_pool_recycler) { + VALIDATION_LOG << "Could not create command pool recycler."; + return; + } + + auto descriptor_pool_recycler = + std::make_shared(weak_from_this()); + if (!descriptor_pool_recycler) { + VALIDATION_LOG << "Could not create descriptor pool recycler."; + return; + } + + //---------------------------------------------------------------------------- + /// Fetch the queues. + /// + QueuesVK queues; + if (!settings.embedder_data.has_value()) { + queues = QueuesVK::FromQueueIndices(device_holder->device.get(), // + graphics_queue.value(), // + compute_queue.value(), // + transfer_queue.value() // + ); + } else { + queues = + QueuesVK::FromEmbedderQueue(settings.embedder_data->queue, + settings.embedder_data->queue_family_index); + } + if (!queues.IsValid()) { + VALIDATION_LOG << "Could not fetch device queues."; + return; + } + + VkPhysicalDeviceProperties physical_device_properties; + dispatcher.vkGetPhysicalDeviceProperties(device_holder->physical_device, + &physical_device_properties); + + //---------------------------------------------------------------------------- + /// All done! + /// + + // Apply workarounds for broken drivers. + auto driver_info = + std::make_unique(device_holder->physical_device); + workarounds_ = GetWorkaroundsFromDriverInfo(*driver_info); + caps->ApplyWorkarounds(workarounds_); + sampler_library->ApplyWorkarounds(workarounds_); + + device_holder_ = std::move(device_holder); + idle_waiter_vk_ = std::make_shared(device_holder_); + driver_info_ = std::move(driver_info); + debug_report_ = std::move(debug_report); + allocator_ = std::move(allocator); + shader_library_ = std::move(shader_library); + sampler_library_ = std::move(sampler_library); + pipeline_library_ = std::move(pipeline_library); + yuv_conversion_library_ = std::shared_ptr( + new YUVConversionLibraryVK(device_holder_)); + queues_ = std::move(queues); + device_capabilities_ = std::move(caps); + fence_waiter_ = std::move(fence_waiter); + resource_manager_ = std::move(resource_manager); + command_pool_recycler_ = std::move(command_pool_recycler); + descriptor_pool_recycler_ = std::move(descriptor_pool_recycler); + device_name_ = std::string(physical_device_properties.deviceName); + command_queue_vk_ = std::make_shared(weak_from_this()); + should_enable_surface_control_ = settings.enable_surface_control; + should_batch_cmd_buffers_ = !workarounds_.batch_submit_command_buffer_timeout; + is_valid_ = true; + + // Create the GPU Tracer later because it depends on state from + // the ContextVK. + gpu_tracer_ = std::make_shared(weak_from_this(), + settings.enable_gpu_tracing); + gpu_tracer_->InitializeQueryPool(*this); + + //---------------------------------------------------------------------------- + /// Label all the relevant objects. This happens after setup so that the + /// debug messengers have had a chance to be set up. + /// + SetDebugName(GetDevice(), device_holder_->device.get(), "ImpellerDevice"); +} + +void ContextVK::SetOffscreenFormat(PixelFormat pixel_format) { + CapabilitiesVK::Cast(*device_capabilities_).SetOffscreenFormat(pixel_format); +} + +// |Context| +std::string ContextVK::DescribeGpuModel() const { + return device_name_; +} + +bool ContextVK::IsValid() const { + return is_valid_; +} + +std::shared_ptr ContextVK::GetResourceAllocator() const { + return allocator_; +} + +std::shared_ptr ContextVK::GetShaderLibrary() const { + return shader_library_; +} + +std::shared_ptr ContextVK::GetSamplerLibrary() const { + return sampler_library_; +} + +std::shared_ptr ContextVK::GetPipelineLibrary() const { + return pipeline_library_; +} + +std::shared_ptr ContextVK::CreateCommandBuffer() const { + const auto& recycler = GetCommandPoolRecycler(); + auto tls_pool = recycler->Get(); + if (!tls_pool) { + return nullptr; + } + + // look up a cached descriptor pool for the current frame and reuse it + // if it exists, otherwise create a new pool. + std::shared_ptr descriptor_pool; + { + Lock lock(desc_pool_mutex_); + DescriptorPoolMap::iterator current_pool = + cached_descriptor_pool_.find(std::this_thread::get_id()); + if (current_pool == cached_descriptor_pool_.end()) { + descriptor_pool = (cached_descriptor_pool_[std::this_thread::get_id()] = + descriptor_pool_recycler_->GetDescriptorPool()); + } else { + descriptor_pool = current_pool->second; + } + } + + auto tracked_objects = std::make_shared( + weak_from_this(), std::move(tls_pool), std::move(descriptor_pool), + GetGPUTracer()->CreateGPUProbe()); + auto queue = GetGraphicsQueue(); + + if (!tracked_objects || !tracked_objects->IsValid() || !queue) { + return nullptr; + } + + vk::CommandBufferBeginInfo begin_info; + begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; + if (tracked_objects->GetCommandBuffer().begin(begin_info) != + vk::Result::eSuccess) { + VALIDATION_LOG << "Could not begin command buffer."; + return nullptr; + } + + tracked_objects->GetGPUProbe().RecordCmdBufferStart( + tracked_objects->GetCommandBuffer()); + + return std::shared_ptr(new CommandBufferVK( + shared_from_this(), // + GetDeviceHolder(), // + std::move(tracked_objects) // + )); +} + +vk::Instance ContextVK::GetInstance() const { + return *device_holder_->instance; +} + +const vk::Device& ContextVK::GetDevice() const { + return device_holder_->device.get(); +} + +const std::shared_ptr +ContextVK::GetConcurrentWorkerTaskRunner() const { + return raster_message_loop_->GetTaskRunner(); +} + +void ContextVK::Shutdown() { + // There are multiple objects, for example |CommandPoolVK|, that in their + // destructors make a strong reference to |ContextVK|. Resetting these shared + // pointers ensures that cleanup happens in a correct order. + // + // tl;dr: Without it, we get thread::join failures on shutdown. + fence_waiter_.reset(); + resource_manager_.reset(); + + raster_message_loop_->Terminate(); +} + +std::shared_ptr ContextVK::CreateSurfaceContext() { + return std::make_shared(shared_from_this()); +} + +const std::shared_ptr& ContextVK::GetCapabilities() const { + return device_capabilities_; +} + +const std::shared_ptr& ContextVK::GetGraphicsQueue() const { + return queues_.graphics_queue; +} + +vk::PhysicalDevice ContextVK::GetPhysicalDevice() const { + return device_holder_->physical_device; +} + +std::shared_ptr ContextVK::GetFenceWaiter() const { + return fence_waiter_; +} + +std::shared_ptr ContextVK::GetResourceManager() const { + return resource_manager_; +} + +std::shared_ptr ContextVK::GetCommandPoolRecycler() + const { + return command_pool_recycler_; +} + +std::shared_ptr ContextVK::GetGPUTracer() const { + return gpu_tracer_; +} + +std::shared_ptr ContextVK::GetDescriptorPoolRecycler() + const { + return descriptor_pool_recycler_; +} + +std::shared_ptr ContextVK::GetCommandQueue() const { + return command_queue_vk_; +} + +bool ContextVK::EnqueueCommandBuffer( + std::shared_ptr command_buffer) { + if (should_batch_cmd_buffers_) { + pending_command_buffers_.push_back(std::move(command_buffer)); + return true; + } else { + return GetCommandQueue()->Submit({command_buffer}).ok(); + } +} + +bool ContextVK::FlushCommandBuffers() { + if (pending_command_buffers_.empty()) { + return true; + } + + if (should_batch_cmd_buffers_) { + bool result = GetCommandQueue()->Submit(pending_command_buffers_).ok(); + pending_command_buffers_.clear(); + return result; + } else { + return true; + } +} + +// Creating a render pass is observed to take an additional 6ms on a Pixel 7 +// device as the driver will lazily bootstrap and compile shaders to do so. +// The render pass does not need to be begun or executed. +void ContextVK::InitializeCommonlyUsedShadersIfNeeded() const { + RenderTargetAllocator rt_allocator(GetResourceAllocator()); + RenderTarget render_target = + rt_allocator.CreateOffscreenMSAA(*this, {1, 1}, 1); + + RenderPassBuilderVK builder; + + render_target.IterateAllColorAttachments( + [&builder](size_t index, const ColorAttachment& attachment) -> bool { + builder.SetColorAttachment( + index, // + attachment.texture->GetTextureDescriptor().format, // + attachment.texture->GetTextureDescriptor().sample_count, // + attachment.load_action, // + attachment.store_action // + ); + return true; + }); + + if (auto depth = render_target.GetDepthAttachment(); depth.has_value()) { + builder.SetDepthStencilAttachment( + depth->texture->GetTextureDescriptor().format, // + depth->texture->GetTextureDescriptor().sample_count, // + depth->load_action, // + depth->store_action // + ); + } else if (auto stencil = render_target.GetStencilAttachment(); + stencil.has_value()) { + builder.SetStencilAttachment( + stencil->texture->GetTextureDescriptor().format, // + stencil->texture->GetTextureDescriptor().sample_count, // + stencil->load_action, // + stencil->store_action // + ); + } + + auto pass = builder.Build(GetDevice()); +} + +void ContextVK::DisposeThreadLocalCachedResources() { + { + Lock lock(desc_pool_mutex_); + cached_descriptor_pool_.erase(std::this_thread::get_id()); + } + command_pool_recycler_->Dispose(); +} + +const std::shared_ptr& +ContextVK::GetYUVConversionLibrary() const { + return yuv_conversion_library_; +} + +const std::unique_ptr& ContextVK::GetDriverInfo() const { + return driver_info_; +} + +bool ContextVK::GetShouldEnableSurfaceControlSwapchain() const { + return should_enable_surface_control_ && + CapabilitiesVK::Cast(*device_capabilities_) + .SupportsExternalSemaphoreExtensions(); +} + +RuntimeStageBackend ContextVK::GetRuntimeStageBackend() const { + return RuntimeStageBackend::kVulkan; +} + +bool ContextVK::SubmitOnscreen(std::shared_ptr cmd_buffer) { + return EnqueueCommandBuffer(std::move(cmd_buffer)); +} + +const WorkaroundsVK& ContextVK::GetWorkarounds() const { + return workarounds_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..39dae91aea4cf84612614c6aa58de1db67ff9d89 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h @@ -0,0 +1,315 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CONTEXT_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CONTEXT_VK_H_ + +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/mapping.h" +#include "flutter/fml/unique_fd.h" +#include "impeller/base/backend_cast.h" +#include "impeller/base/strings.h" +#include "impeller/core/formats.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/driver_info_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h" +#include "impeller/renderer/backend/vulkan/queue_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_library_vk.h" +#include "impeller/renderer/backend/vulkan/shader_library_vk.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +bool HasValidationLayers(); + +class CommandEncoderFactoryVK; +class CommandEncoderVK; +class CommandPoolRecyclerVK; +class DebugReportVK; +class FenceWaiterVK; +class ResourceManagerVK; +class SurfaceContextVK; +class GPUTracerVK; +class DescriptorPoolRecyclerVK; +class CommandQueueVK; +class DescriptorPoolVK; + +class IdleWaiterVK : public IdleWaiter { + public: + explicit IdleWaiterVK(std::weak_ptr device_holder) + : device_holder_(std::move(device_holder)) {} + + void WaitIdle() const override { + std::shared_ptr strong_device_holder_ = + device_holder_.lock(); + if (strong_device_holder_ && strong_device_holder_->GetDevice()) { + [[maybe_unused]] auto result = + strong_device_holder_->GetDevice().waitIdle(); + } + } + + private: + std::weak_ptr device_holder_; +}; + +class ContextVK final : public Context, + public BackendCast, + public std::enable_shared_from_this { + public: + /// Embedder Stuff + struct EmbedderData { + VkInstance instance; + VkPhysicalDevice physical_device; + VkDevice device; + uint32_t queue_family_index; + VkQueue queue; + std::vector instance_extensions; + std::vector device_extensions; + }; + + struct Settings { + PFN_vkGetInstanceProcAddr proc_address_callback = nullptr; + std::vector> shader_libraries_data; + fml::UniqueFD cache_directory; + bool enable_validation = false; + bool enable_gpu_tracing = false; + bool enable_surface_control = false; + /// If validations are requested but cannot be enabled, log a fatal error. + bool fatal_missing_validations = false; + Flags flags; + + std::optional embedder_data; + + Settings() = default; + + Settings(Settings&&) = default; + }; + + /// Choose the number of worker threads the context_vk will create. + /// + /// Visible for testing. + static size_t ChooseThreadCountForWorkers(size_t hardware_concurrency); + + static std::shared_ptr Create(Settings settings); + + uint64_t GetHash() const { return hash_; } + + // |Context| + ~ContextVK() override; + + // |Context| + BackendType GetBackendType() const override; + + // |Context| + std::string DescribeGpuModel() const override; + + // |Context| + bool IsValid() const override; + + // |Context| + std::shared_ptr GetResourceAllocator() const override; + + // |Context| + std::shared_ptr GetShaderLibrary() const override; + + // |Context| + std::shared_ptr GetSamplerLibrary() const override; + + // |Context| + std::shared_ptr GetPipelineLibrary() const override; + + // |Context| + std::shared_ptr CreateCommandBuffer() const override; + + // |Context| + const std::shared_ptr& GetCapabilities() const override; + + // |Context| + virtual bool SubmitOnscreen( + std::shared_ptr cmd_buffer) override; + + const std::shared_ptr& GetYUVConversionLibrary() + const; + + // |Context| + void Shutdown() override; + + const WorkaroundsVK& GetWorkarounds() const; + + void SetOffscreenFormat(PixelFormat pixel_format); + + template + bool SetDebugName(T handle, std::string_view label) const { + return SetDebugName(GetDevice(), handle, label); + } + + template + bool SetDebugName(T handle, + std::string_view label, + std::string_view trailing) const { + if (!HasValidationLayers()) { + // No-op if validation layers are not enabled. + return true; + } + std::string combined = SPrintF("%s %s", label.data(), trailing.data()); + return SetDebugName(GetDevice(), handle, combined); + } + + template + static bool SetDebugName(const vk::Device& device, + T handle, + std::string_view label) { + if (!HasValidationLayers()) { + // No-op if validation layers are not enabled. + return true; + } + + auto c_handle = static_cast(handle); + + vk::DebugUtilsObjectNameInfoEXT info; + info.objectType = T::objectType; + info.pObjectName = label.data(); + info.objectHandle = reinterpret_cast(c_handle); + + if (device.setDebugUtilsObjectNameEXT(info) != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to set debug name: " << label; + return false; + } + + return true; + } + + std::shared_ptr GetDeviceHolder() const { + return device_holder_; + } + + vk::Instance GetInstance() const; + + const vk::Device& GetDevice() const; + + const std::unique_ptr& GetDriverInfo() const; + + const std::shared_ptr + GetConcurrentWorkerTaskRunner() const; + + std::shared_ptr CreateSurfaceContext(); + + const std::shared_ptr& GetGraphicsQueue() const; + + vk::PhysicalDevice GetPhysicalDevice() const; + + std::shared_ptr GetFenceWaiter() const; + + std::shared_ptr GetResourceManager() const; + + std::shared_ptr GetCommandPoolRecycler() const; + + std::shared_ptr GetDescriptorPoolRecycler() const; + + std::shared_ptr GetCommandQueue() const override; + + std::shared_ptr GetGPUTracer() const; + + void RecordFrameEndTime() const; + + // |Context| + void InitializeCommonlyUsedShadersIfNeeded() const override; + + // |Context| + void DisposeThreadLocalCachedResources() override; + + /// @brief Whether the Android Surface control based swapchain should be + /// enabled + bool GetShouldEnableSurfaceControlSwapchain() const; + + // | Context | + bool EnqueueCommandBuffer( + std::shared_ptr command_buffer) override; + + // | Context | + bool FlushCommandBuffers() override; + + RuntimeStageBackend GetRuntimeStageBackend() const override; + + std::shared_ptr GetIdleWaiter() const override { + return idle_waiter_vk_; + } + + private: + struct DeviceHolderImpl : public DeviceHolderVK { + // |DeviceHolder| + const vk::Device& GetDevice() const override { return device.get(); } + // |DeviceHolder| + const vk::PhysicalDevice& GetPhysicalDevice() const override { + return physical_device; + } + + ~DeviceHolderImpl() { + if (!owned) { + instance.release(); + device.release(); + } + } + + vk::UniqueInstance instance; + vk::PhysicalDevice physical_device; + vk::UniqueDevice device; + bool owned = true; + }; + + std::shared_ptr device_holder_; + std::unique_ptr driver_info_; + std::unique_ptr debug_report_; + std::shared_ptr allocator_; + std::shared_ptr shader_library_; + std::shared_ptr sampler_library_; + std::shared_ptr pipeline_library_; + std::shared_ptr yuv_conversion_library_; + QueuesVK queues_; + std::shared_ptr device_capabilities_; + std::shared_ptr fence_waiter_; + std::shared_ptr resource_manager_; + std::shared_ptr descriptor_pool_recycler_; + std::shared_ptr command_pool_recycler_; + std::string device_name_; + std::shared_ptr raster_message_loop_; + std::shared_ptr gpu_tracer_; + std::shared_ptr command_queue_vk_; + std::shared_ptr idle_waiter_vk_; + WorkaroundsVK workarounds_; + + using DescriptorPoolMap = + std::unordered_map>; + + mutable Mutex desc_pool_mutex_; + mutable DescriptorPoolMap IPLR_GUARDED_BY(desc_pool_mutex_) + cached_descriptor_pool_; + bool should_enable_surface_control_ = false; + bool should_batch_cmd_buffers_ = false; + std::vector> pending_command_buffers_; + + const uint64_t hash_; + + bool is_valid_ = false; + + explicit ContextVK(const Flags& flags); + + void Setup(Settings settings); + + ContextVK(const ContextVK&) = delete; + + ContextVK& operator=(const ContextVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_CONTEXT_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..61c0d2bee16d549bf8cd6adb6c6af24bdfd8e77f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/context_vk_unittests.cc @@ -0,0 +1,412 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "vulkan/vulkan_core.h" + +namespace impeller { +namespace testing { + +TEST(ContextVKTest, CommonHardwareConcurrencyConfigurations) { + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(100u), 4u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(9u), 4u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(8u), 4u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(7u), 3u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(6u), 3u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(5u), 2u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(4u), 2u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(3u), 1u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(2u), 1u); + EXPECT_EQ(ContextVK::ChooseThreadCountForWorkers(1u), 1u); +} + +TEST(ContextVKTest, DeletesCommandPools) { + std::weak_ptr weak_context; + std::weak_ptr weak_pool; + { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + auto const pool = context->GetCommandPoolRecycler()->Get(); + weak_pool = pool; + weak_context = context; + ASSERT_TRUE(weak_pool.lock()); + ASSERT_TRUE(weak_context.lock()); + } + ASSERT_FALSE(weak_pool.lock()); + ASSERT_FALSE(weak_context.lock()); +} + +TEST(ContextVKTest, DeletesCommandPoolsOnAllThreads) { + std::weak_ptr weak_context; + std::weak_ptr weak_pool_main; + + std::shared_ptr context = MockVulkanContextBuilder().Build(); + weak_pool_main = context->GetCommandPoolRecycler()->Get(); + weak_context = context; + ASSERT_TRUE(weak_pool_main.lock()); + ASSERT_TRUE(weak_context.lock()); + + // Start a second thread that obtains a command pool. + fml::AutoResetWaitableEvent latch1, latch2; + std::weak_ptr weak_pool_thread; + std::thread thread([&]() { + weak_pool_thread = context->GetCommandPoolRecycler()->Get(); + latch1.Signal(); + latch2.Wait(); + }); + + // Delete the ContextVK on the main thread. + latch1.Wait(); + context.reset(); + ASSERT_FALSE(weak_pool_main.lock()); + ASSERT_FALSE(weak_context.lock()); + + // Stop the second thread and check that its command pool has been deleted. + latch2.Signal(); + thread.join(); + ASSERT_FALSE(weak_pool_thread.lock()); +} + +TEST(ContextVKTest, ThreadLocalCleanupDeletesCommandPool) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + fml::AutoResetWaitableEvent latch1, latch2; + std::weak_ptr weak_pool; + std::thread thread([&]() { + weak_pool = context->GetCommandPoolRecycler()->Get(); + context->DisposeThreadLocalCachedResources(); + latch1.Signal(); + latch2.Wait(); + }); + + latch1.Wait(); + ASSERT_FALSE(weak_pool.lock()); + + latch2.Signal(); + thread.join(); +} + +TEST(ContextVKTest, DeletePipelineAfterContext) { + std::shared_ptr> pipeline; + std::shared_ptr> functions; + { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + PipelineDescriptor pipeline_desc; + pipeline_desc.SetVertexDescriptor(std::make_shared()); + PipelineFuture pipeline_future = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc); + pipeline = pipeline_future.Get(); + ASSERT_TRUE(pipeline); + functions = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreateGraphicsPipelines") != functions->end()); + } + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkDestroyDevice") != functions->end()); +} + +TEST(ContextVKTest, DeleteShaderFunctionAfterContext) { + std::shared_ptr shader_function; + std::shared_ptr> functions; + { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + PipelineDescriptor pipeline_desc; + pipeline_desc.SetVertexDescriptor(std::make_shared()); + std::vector data = {0x03, 0x02, 0x23, 0x07}; + context->GetShaderLibrary()->RegisterFunction( + "foobar_fragment_main", ShaderStage::kFragment, + std::make_shared(data), [](bool) {}); + shader_function = context->GetShaderLibrary()->GetFunction( + "foobar_fragment_main", ShaderStage::kFragment); + ASSERT_TRUE(shader_function); + functions = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreateShaderModule") != functions->end()); + } + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkDestroyDevice") != functions->end()); +} + +TEST(ContextVKTest, DeletePipelineLibraryAfterContext) { + std::shared_ptr pipeline_library; + std::shared_ptr> functions; + { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + PipelineDescriptor pipeline_desc; + pipeline_desc.SetVertexDescriptor(std::make_shared()); + pipeline_library = context->GetPipelineLibrary(); + functions = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreatePipelineCache") != functions->end()); + } + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkDestroyDevice") != functions->end()); +} + +TEST(ContextVKTest, CanCreateContextInAbsenceOfValidationLayers) { + // The mocked methods don't report the presence of a validation layer but we + // explicitly ask for validation. Context creation should continue anyway. + auto context = MockVulkanContextBuilder() + .SetSettingsCallback([](auto& settings) { + settings.enable_validation = true; + }) + .Build(); + ASSERT_NE(context, nullptr); + const CapabilitiesVK* capabilites_vk = + reinterpret_cast(context->GetCapabilities().get()); + ASSERT_FALSE(capabilites_vk->AreValidationsEnabled()); +} + +TEST(ContextVKTest, CanCreateContextWithValidationLayers) { + auto context = + MockVulkanContextBuilder() + .SetSettingsCallback( + [](auto& settings) { settings.enable_validation = true; }) + .SetInstanceExtensions( + {"VK_KHR_surface", "VK_MVK_macos_surface", "VK_EXT_debug_utils"}) + .SetInstanceLayers({"VK_LAYER_KHRONOS_validation"}) + .Build(); + ASSERT_NE(context, nullptr); + const CapabilitiesVK* capabilites_vk = + reinterpret_cast(context->GetCapabilities().get()); + ASSERT_TRUE(capabilites_vk->AreValidationsEnabled()); +} + +// In Impeller's 2D renderer, we no longer use stencil-only formats. They're +// less widely supported than combined depth-stencil formats, so make sure we +// don't fail initialization if we can't find a suitable stencil format. +TEST(CapabilitiesVKTest, ContextInitializesWithNoStencilFormat) { + const std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalDeviceFormatPropertiesCallback( + [](VkPhysicalDevice physicalDevice, VkFormat format, + VkFormatProperties* pFormatProperties) { + if (format == VK_FORMAT_R8G8B8A8_UNORM) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eColorAttachment); + } else if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eDepthStencilAttachment); + } + // Ignore just the stencil format. + }) + .Build(); + ASSERT_NE(context, nullptr); + const CapabilitiesVK* capabilites_vk = + reinterpret_cast(context->GetCapabilities().get()); + ASSERT_EQ(capabilites_vk->GetDefaultDepthStencilFormat(), + PixelFormat::kD32FloatS8UInt); + ASSERT_EQ(capabilites_vk->GetDefaultStencilFormat(), + PixelFormat::kD32FloatS8UInt); +} + +// Impeller's 2D renderer relies on hardware support for a combined +// depth-stencil format (widely supported). So fail initialization if a suitable +// one couldn't be found. That way we have an opportunity to fallback to +// OpenGLES. +TEST(CapabilitiesVKTest, + ContextFailsInitializationForNoCombinedDepthStencilFormat) { + ScopedValidationDisable disable_validation; + const std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalDeviceFormatPropertiesCallback( + [](VkPhysicalDevice physicalDevice, VkFormat format, + VkFormatProperties* pFormatProperties) { + if (format == VK_FORMAT_R8G8B8A8_UNORM) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eColorAttachment); + } + // Ignore combined depth-stencil formats. + }) + .Build(); + ASSERT_EQ(context, nullptr); +} + +TEST(ContextVKTest, WarmUpFunctionCreatesRenderPass) { + const std::shared_ptr context = MockVulkanContextBuilder().Build(); + + context->SetOffscreenFormat(PixelFormat::kR8G8B8A8UNormInt); + context->InitializeCommonlyUsedShadersIfNeeded(); + + auto functions = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreateRenderPass") != functions->end()); +} + +TEST(ContextVKTest, FatalMissingValidations) { + EXPECT_DEATH(const std::shared_ptr context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_validation = true; + settings.fatal_missing_validations = true; + }) + .Build(), + ""); +} + +TEST(ContextVKTest, HasDefaultColorFormat) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + const CapabilitiesVK* capabilites_vk = + reinterpret_cast(context->GetCapabilities().get()); + ASSERT_NE(capabilites_vk->GetDefaultColorFormat(), PixelFormat::kUnknown); +} + +TEST(ContextVKTest, EmbedderOverridesUsesInstanceExtensions) { + ContextVK::EmbedderData data; + auto other_context = MockVulkanContextBuilder().Build(); + + data.instance = other_context->GetInstance(); + data.device = other_context->GetDevice(); + data.physical_device = other_context->GetPhysicalDevice(); + data.queue = VkQueue{}; + data.queue_family_index = 0; + // Missing surface extension. + data.instance_extensions = {}; + data.device_extensions = {"VK_KHR_swapchain"}; + + ScopedValidationDisable scoped; + auto context = MockVulkanContextBuilder().SetEmbedderData(data).Build(); + + EXPECT_EQ(context, nullptr); +} + +TEST(ContextVKTest, EmbedderOverrides) { + ContextVK::EmbedderData data; + auto other_context = MockVulkanContextBuilder().Build(); + + data.instance = other_context->GetInstance(); + data.device = other_context->GetDevice(); + data.physical_device = other_context->GetPhysicalDevice(); + data.queue = VkQueue{}; + data.queue_family_index = 0; + data.instance_extensions = {"VK_KHR_surface", + "VK_KHR_portability_enumeration"}; + data.device_extensions = {"VK_KHR_swapchain"}; + + auto context = MockVulkanContextBuilder().SetEmbedderData(data).Build(); + + EXPECT_TRUE(context->IsValid()); + EXPECT_EQ(context->GetInstance(), other_context->GetInstance()); + EXPECT_EQ(context->GetDevice(), other_context->GetDevice()); + EXPECT_EQ(context->GetPhysicalDevice(), other_context->GetPhysicalDevice()); + EXPECT_EQ(context->GetGraphicsQueue()->GetIndex().index, 0u); + EXPECT_EQ(context->GetGraphicsQueue()->GetIndex().family, 0u); +} + +TEST(ContextVKTest, BatchSubmitCommandBuffersOnArm) { + std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x13B5; // ARM + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + + EXPECT_TRUE(context->EnqueueCommandBuffer(context->CreateCommandBuffer())); + EXPECT_TRUE(context->EnqueueCommandBuffer(context->CreateCommandBuffer())); + + // If command buffers are batch submitted, we should have created them but not + // created the fence to track them after enqueing. + auto functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_TRUE(std::find(functions->begin(), functions->end(), + "vkAllocateCommandBuffers") != functions->end()); + EXPECT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreateFence") == functions->end()); + + context->FlushCommandBuffers(); + + // After flushing, the fence should be created. + functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_TRUE(std::find(functions->begin(), functions->end(), + "vkCreateFence") != functions->end()); +} + +TEST(ContextVKTest, BatchSubmitCommandBuffersOnNonArm) { + std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x8686; // Made up ID + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + + EXPECT_TRUE(context->EnqueueCommandBuffer(context->CreateCommandBuffer())); + EXPECT_TRUE(context->EnqueueCommandBuffer(context->CreateCommandBuffer())); + + // If command buffers are batched and not submitted, we should have created + // them and a corresponding fence immediately. + auto functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_TRUE(std::find(functions->begin(), functions->end(), + "vkAllocateCommandBuffers") != functions->end()); + EXPECT_FALSE(std::find(functions->begin(), functions->end(), + "vkCreateFence") != functions->end()); +} + +TEST(ContextVKTest, AHBSwapchainCapabilitiesCanBeMissing) { + { + std::shared_ptr context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_surface_control = true; + }) + .Build(); + + EXPECT_FALSE(context->GetShouldEnableSurfaceControlSwapchain()); + } + + ContextVK::EmbedderData data; + auto other_context = MockVulkanContextBuilder().Build(); + + data.instance = other_context->GetInstance(); + data.device = other_context->GetDevice(); + data.physical_device = other_context->GetPhysicalDevice(); + data.queue = VkQueue{}; + data.queue_family_index = 0; + data.instance_extensions = {"VK_KHR_surface", "VK_KHR_android_surface"}; + data.device_extensions = {"VK_KHR_swapchain", + VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME, + VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME, + VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, + VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME}; + + auto context = MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_surface_control = true; + }) + .SetEmbedderData(data) + .Build(); + + EXPECT_TRUE(context->GetShouldEnableSurfaceControlSwapchain()); + +} // namespace impeller + +TEST(ContextVKTest, HashIsUniqueAcrossThreads) { + uint64_t hash1, hash2; + std::thread thread1([&]() { + auto context = MockVulkanContextBuilder().Build(); + hash1 = context->GetHash(); + }); + std::thread thread2([&]() { + auto context = MockVulkanContextBuilder().Build(); + hash2 = context->GetHash(); + }); + thread1.join(); + thread2.join(); + + EXPECT_NE(hash1, hash2); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..118bb30674103138e787c17a9bc2f83fc0286714 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.cc @@ -0,0 +1,197 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/debug_report_vk.h" + +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" + +namespace impeller { + +DebugReportVK::DebugReportVK(const CapabilitiesVK& caps, + const vk::Instance& instance) { + if (!caps.AreValidationsEnabled()) { + is_valid_ = true; + return; + } + + vk::DebugUtilsMessengerCreateInfoEXT messenger_info; + messenger_info.messageSeverity = + vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | + vk::DebugUtilsMessageSeverityFlagBitsEXT::eError; + messenger_info.messageType = + vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | + vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance | + vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation; + messenger_info.pUserData = this; + messenger_info.pfnUserCallback = DebugUtilsMessengerCallback; + + auto messenger = instance.createDebugUtilsMessengerEXTUnique(messenger_info); + + if (messenger.result != vk::Result::eSuccess) { + FML_LOG(ERROR) << "Could not create debug messenger: " + << vk::to_string(messenger.result); + return; + } + + messenger_ = std::move(messenger.value); + is_valid_ = true; +} + +DebugReportVK::~DebugReportVK() = default; + +bool DebugReportVK::IsValid() const { + return is_valid_; +} + +static std::string JoinLabels(const vk::DebugUtilsLabelEXT* labels, + size_t count) { + std::stringstream stream; + for (size_t i = 0u; i < count; i++) { + stream << labels[i].pLabelName; + if (i != count - 1u) { + stream << ", "; + } + } + return stream.str(); +} + +static std::string JoinVKDebugUtilsObjectNameInfoEXT( + const vk::DebugUtilsObjectNameInfoEXT* names, + size_t count) { + std::stringstream stream; + for (size_t i = 0u; i < count; i++) { + stream << vk::to_string(static_cast(names[i].objectType)) + << " [" << names[i].objectHandle << "] ["; + if (names[i].pObjectName != nullptr) { + stream << names[i].pObjectName; + } else { + stream << "UNNAMED"; + } + stream << "]"; + if (i != count - 1u) { + stream << ", "; + } + } + return stream.str(); +} + +VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportVK::DebugUtilsMessengerCallback( + vk::DebugUtilsMessageSeverityFlagBitsEXT severity, + vk::DebugUtilsMessageTypeFlagsEXT type, + const vk::DebugUtilsMessengerCallbackDataEXT* callback_data, + void* debug_report) { + auto result = + reinterpret_cast(debug_report) + ->OnDebugCallback( + static_cast( + severity), // + static_cast(type), // + callback_data // + ); + switch (result) { + case Result::kContinue: + return VK_FALSE; + case Result::kAbort: + return VK_TRUE; + } + return VK_FALSE; +} + +DebugReportVK::Result DebugReportVK::OnDebugCallback( + vk::DebugUtilsMessageSeverityFlagBitsEXT severity, + vk::DebugUtilsMessageTypeFlagsEXT type, + const vk::DebugUtilsMessengerCallbackDataEXT* data) { + // This is a real issue caused by INPUT_ATTACHMENT_BIT not being a supported + // `VkSurfaceCapabilitiesKHR::supportedUsageFlags` on any platform other than + // Android. This is necessary for all the framebuffer fetch related tests. We + // can get away with suppressing this on macOS but this must be fixed. + if (data->messageIdNumber == 0x2c36905d) { + return Result::kContinue; + } + // This is a performance warning when a fragment stage does not consume all + // varyings from the vertex stage. We ignore this as we want to use a single + // vertex stage for the runtime effect shader without trying to determine if + // the fragment consumes it or not. + if (data->messageIdNumber == 0x609A13B) { + return Result::kContinue; + } + + // This warning happens when running tests that use SwiftShader. + // Some SPIR-V shaders request the UniformAndStorageBuffer16BitAccess + // capability, but SwiftShader does not support it. + if (data->pMessageIdName != nullptr && + strcmp(data->pMessageIdName, + "VUID-VkShaderModuleCreateInfo-pCode-08740") == 0) { + return Result::kContinue; + } + + std::vector> items; + + items.emplace_back("Severity", vk::to_string(severity)); + items.emplace_back("Type", vk::to_string(type)); + + if (data->pMessageIdName) { + items.emplace_back("ID Name", data->pMessageIdName); + } + + items.emplace_back("ID Number", std::to_string(data->messageIdNumber)); + + if (auto queues = JoinLabels(data->pQueueLabels, data->queueLabelCount); + !queues.empty()) { + items.emplace_back("Queue Breadcrumbs", std::move(queues)); + } else { + items.emplace_back("Queue Breadcrumbs", "[NONE]"); + } + + if (auto cmd_bufs = JoinLabels(data->pCmdBufLabels, data->cmdBufLabelCount); + !cmd_bufs.empty()) { + items.emplace_back("CMD Buffer Breadcrumbs", std::move(cmd_bufs)); + } else { + items.emplace_back("CMD Buffer Breadcrumbs", "[NONE]"); + } + + if (auto related = + JoinVKDebugUtilsObjectNameInfoEXT(data->pObjects, data->objectCount); + !related.empty()) { + items.emplace_back("Related Objects", std::move(related)); + } + + if (data->pMessage) { + items.emplace_back("Trigger", data->pMessage); + } + + size_t padding = 0; + + for (const auto& item : items) { + padding = std::max(padding, item.first.size()); + } + + padding += 1; + + std::stringstream stream; + + stream << std::endl; + + stream << "--- Vulkan Debug Report ----------------------------------------"; + + stream << std::endl; + + for (const auto& item : items) { + stream << "| " << std::setw(static_cast(padding)) << item.first + << std::setw(0) << ": " << item.second << std::endl; + } + + stream << "-----------------------------------------------------------------"; + + if (type == vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance) { + FML_LOG(INFO) << stream.str(); + } else { + VALIDATION_LOG << stream.str(); + } + + return Result::kContinue; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..e3a247bb6008dab2284516291060a108c7365272 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/debug_report_vk.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEBUG_REPORT_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEBUG_REPORT_VK_H_ + +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class CapabilitiesVK; + +class DebugReportVK { + public: + DebugReportVK(const CapabilitiesVK& caps, const vk::Instance& instance); + + ~DebugReportVK(); + + bool IsValid() const; + + private: + vk::UniqueDebugUtilsMessengerEXT messenger_; + bool is_valid_ = false; + + enum class Result { + kContinue, + kAbort, + }; + + Result OnDebugCallback(vk::DebugUtilsMessageSeverityFlagBitsEXT severity, + vk::DebugUtilsMessageTypeFlagsEXT type, + const vk::DebugUtilsMessengerCallbackDataEXT* data); + + static VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback( + vk::DebugUtilsMessageSeverityFlagBitsEXT severity, + vk::DebugUtilsMessageTypeFlagsEXT type, + const vk::DebugUtilsMessengerCallbackDataEXT* callback_data, + void* user_data); + + DebugReportVK(const DebugReportVK&) = delete; + + DebugReportVK& operator=(const DebugReportVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEBUG_REPORT_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..44178962076895a902d8b0005a1eadb7049b5805 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.cc @@ -0,0 +1,186 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" + +#include + +#include "impeller/base/validation.h" + +namespace impeller { + +struct DescriptorPoolSize { + size_t buffer_bindings; + size_t texture_bindings; + size_t storage_bindings; + size_t subpass_bindings; +}; + +/// Descriptor pools are always allocated with the following sizes. +static const constexpr DescriptorPoolSize kDefaultBindingSize = + DescriptorPoolSize{ + .buffer_bindings = 512u, // Buffer Bindings + .texture_bindings = 256u, // Texture Bindings + .storage_bindings = 32, + .subpass_bindings = 4u // Subpass Bindings + }; + +DescriptorPoolVK::DescriptorPoolVK(std::weak_ptr context) + : context_(std::move(context)) {} + +void DescriptorPoolVK::Destroy() { + pools_.clear(); +} + +DescriptorPoolVK::DescriptorPoolVK(std::weak_ptr context, + DescriptorCacheMap descriptor_sets, + std::vector pools) + : context_(std::move(context)), + descriptor_sets_(std::move(descriptor_sets)), + pools_(std::move(pools)) {} + +DescriptorPoolVK::~DescriptorPoolVK() { + if (pools_.empty()) { + return; + } + + auto const context = context_.lock(); + if (!context) { + return; + } + auto const recycler = context->GetDescriptorPoolRecycler(); + if (!recycler) { + return; + } + + recycler->Reclaim(std::move(descriptor_sets_), std::move(pools_)); +} + +fml::StatusOr DescriptorPoolVK::AllocateDescriptorSets( + const vk::DescriptorSetLayout& layout, + PipelineKey pipeline_key, + const ContextVK& context_vk) { + DescriptorCacheMap::iterator existing = descriptor_sets_.find(pipeline_key); + if (existing != descriptor_sets_.end() && !existing->second.unused.empty()) { + auto descriptor_set = existing->second.unused.back(); + existing->second.unused.pop_back(); + existing->second.used.push_back(descriptor_set); + return descriptor_set; + } + + if (pools_.empty()) { + CreateNewPool(context_vk); + } + + vk::DescriptorSetAllocateInfo set_info; + set_info.setDescriptorPool(pools_.back().get()); + set_info.setPSetLayouts(&layout); + set_info.setDescriptorSetCount(1); + + vk::DescriptorSet set; + auto result = context_vk.GetDevice().allocateDescriptorSets(&set_info, &set); + if (result == vk::Result::eErrorOutOfPoolMemory) { + // If the pool ran out of memory, we need to create a new pool. + CreateNewPool(context_vk); + set_info.setDescriptorPool(pools_.back().get()); + result = context_vk.GetDevice().allocateDescriptorSets(&set_info, &set); + } + auto lookup_result = + descriptor_sets_.try_emplace(pipeline_key, DescriptorCache{}); + lookup_result.first->second.used.push_back(set); + + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not allocate descriptor sets: " + << vk::to_string(result); + return fml::Status(fml::StatusCode::kUnknown, ""); + } + return set; +} + +fml::Status DescriptorPoolVK::CreateNewPool(const ContextVK& context_vk) { + auto new_pool = context_vk.GetDescriptorPoolRecycler()->Get(); + if (!new_pool) { + return fml::Status(fml::StatusCode::kUnknown, + "Failed to create descriptor pool"); + } + pools_.emplace_back(std::move(new_pool)); + return fml::Status(); +} + +void DescriptorPoolRecyclerVK::Reclaim( + DescriptorCacheMap descriptor_sets, + std::vector pools) { + // Reset the pool on a background thread. + auto strong_context = context_.lock(); + if (!strong_context) { + return; + } + + for (auto& [_, cache] : descriptor_sets) { + cache.unused.insert(cache.unused.end(), cache.used.begin(), + cache.used.end()); + cache.used.clear(); + } + + // Move the pool to the recycled list. If more than 32 pool are + // cached then delete the newest entry. + Lock recycled_lock(recycled_mutex_); + while (recycled_.size() >= kMaxRecycledPools) { + auto& back_entry = recycled_.back(); + back_entry->Destroy(); + recycled_.pop_back(); + } + recycled_.push_back(std::make_shared( + context_, std::move(descriptor_sets), std::move(pools))); +} + +vk::UniqueDescriptorPool DescriptorPoolRecyclerVK::Get() { + // Recycle a pool with a matching minumum capcity if it is available. + return Create(); +} + +vk::UniqueDescriptorPool DescriptorPoolRecyclerVK::Create() { + auto strong_context = context_.lock(); + if (!strong_context) { + VALIDATION_LOG << "Unable to create a descriptor pool"; + return {}; + } + + std::vector pools = { + vk::DescriptorPoolSize{vk::DescriptorType::eCombinedImageSampler, + kDefaultBindingSize.texture_bindings}, + vk::DescriptorPoolSize{vk::DescriptorType::eUniformBuffer, + kDefaultBindingSize.buffer_bindings}, + vk::DescriptorPoolSize{vk::DescriptorType::eStorageBuffer, + kDefaultBindingSize.storage_bindings}, + vk::DescriptorPoolSize{vk::DescriptorType::eInputAttachment, + kDefaultBindingSize.subpass_bindings}}; + vk::DescriptorPoolCreateInfo pool_info; + pool_info.setMaxSets(kDefaultBindingSize.texture_bindings + + kDefaultBindingSize.buffer_bindings + + kDefaultBindingSize.storage_bindings + + kDefaultBindingSize.subpass_bindings); + pool_info.setPoolSizes(pools); + auto [result, pool] = + strong_context->GetDevice().createDescriptorPoolUnique(pool_info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Unable to create a descriptor pool"; + } + return std::move(pool); +} + +std::shared_ptr +DescriptorPoolRecyclerVK::GetDescriptorPool() { + { + Lock recycled_lock(recycled_mutex_); + if (!recycled_.empty()) { + auto result = recycled_.back(); + recycled_.pop_back(); + return result; + } + } + return std::make_shared(context_); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..88a911ffc54bc9b6db84d32f26475c27cc1e8100 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk.h @@ -0,0 +1,114 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_ + +#include +#include + +#include "fml/status_or.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +/// Used and un-used descriptor sets. +struct DescriptorCache { + std::vector unused; + std::vector used; +}; + +using DescriptorCacheMap = std::unordered_map; + +//------------------------------------------------------------------------------ +/// @brief A per-frame descriptor pool. Descriptors +/// from this pool don't need to be freed individually. Instead, the +/// pool must be collected after all the descriptors allocated from +/// it are done being used. +/// +/// The pool or it's descriptors may not be accessed from multiple +/// threads. +/// +/// Encoders create pools as necessary as they have the same +/// threading and lifecycle restrictions. +class DescriptorPoolVK { + public: + explicit DescriptorPoolVK(std::weak_ptr context); + + DescriptorPoolVK(std::weak_ptr context, + DescriptorCacheMap descriptor_sets, + std::vector pools); + + ~DescriptorPoolVK(); + + fml::StatusOr AllocateDescriptorSets( + const vk::DescriptorSetLayout& layout, + PipelineKey pipeline_key, + const ContextVK& context_vk); + + private: + friend class DescriptorPoolRecyclerVK; + + std::weak_ptr context_; + DescriptorCacheMap descriptor_sets_; + std::vector pools_; + + void Destroy(); + + fml::Status CreateNewPool(const ContextVK& context_vk); + + DescriptorPoolVK(const DescriptorPoolVK&) = delete; + + DescriptorPoolVK& operator=(const DescriptorPoolVK&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief Creates and manages the lifecycle of |vk::DescriptorPoolVK| +/// objects. +class DescriptorPoolRecyclerVK final + : public std::enable_shared_from_this { + public: + ~DescriptorPoolRecyclerVK() = default; + + /// The maximum number of descriptor pools this recycler will hold onto. + static constexpr size_t kMaxRecycledPools = 32u; + + /// @brief Creates a recycler for the given |ContextVK|. + /// + /// @param[in] context The context to create the recycler for. + explicit DescriptorPoolRecyclerVK(std::weak_ptr context) + : context_(std::move(context)) {} + + /// @brief Gets a descriptor pool. + /// + /// This may create a new descriptor pool if no existing pools had + /// the necessary capacity. + vk::UniqueDescriptorPool Get(); + + std::shared_ptr GetDescriptorPool(); + + void Reclaim(DescriptorCacheMap descriptor_sets, + std::vector pools); + + private: + std::weak_ptr context_; + + Mutex recycled_mutex_; + std::vector> recycled_ IPLR_GUARDED_BY( + recycled_mutex_); + + /// @brief Creates a new |vk::CommandPool|. + /// + /// @returns Returns a |std::nullopt| if a pool could not be created. + vk::UniqueDescriptorPool Create(); + + DescriptorPoolRecyclerVK(const DescriptorPoolRecyclerVK&) = delete; + + DescriptorPoolRecyclerVK& operator=(const DescriptorPoolRecyclerVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DESCRIPTOR_POOL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..843c2a68749b6984567aca475ad404a554d326e7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/descriptor_pool_vk_unittests.cc @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep. +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +namespace impeller { +namespace testing { + +TEST(DescriptorPoolRecyclerVKTest, GetDescriptorPoolRecyclerCreatesNewPools) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + vk::UniqueDescriptorPool pool1 = context->GetDescriptorPoolRecycler()->Get(); + vk::UniqueDescriptorPool pool2 = context->GetDescriptorPoolRecycler()->Get(); + + // The two descriptor pools should be different. + EXPECT_NE(pool1.get(), pool2.get()); + + context->Shutdown(); +} + +TEST(DescriptorPoolRecyclerVKTest, ReclaimMakesDescriptorPoolAvailable) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + { + // Fetch a pool (which will be created). + DescriptorPoolVK pool = DescriptorPoolVK(context); + pool.AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + } + + std::shared_ptr pool = + context->GetDescriptorPoolRecycler()->GetDescriptorPool(); + + // Now check that we only ever created one pool. + std::shared_ptr> called = + GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkCreateDescriptorPool"), 1u); + + context->Shutdown(); +} + +TEST(DescriptorPoolRecyclerVKTest, ReclaimDropsDescriptorPoolIfSizeIsExceeded) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + // Create 33 pools + { + std::vector> pools; + for (size_t i = 0u; i < 33; i++) { + std::unique_ptr pool = + std::make_unique(context); + pool->AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + pools.push_back(std::move(pool)); + } + } + + std::shared_ptr> called = + GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkCreateDescriptorPool"), + 33u); + + // Now create 33 more descriptor pools and observe that only one more is + // allocated. + { + std::vector> pools; + for (size_t i = 0u; i < 33; i++) { + std::shared_ptr pool = + context->GetDescriptorPoolRecycler()->GetDescriptorPool(); + pool->AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + pools.push_back(std::move(pool)); + } + } + + std::shared_ptr> called_twice = + GetMockVulkanFunctions(context->GetDevice()); + // 32 of the descriptor pools were recycled, so only one more is created. + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkCreateDescriptorPool"), + 34u); + + context->Shutdown(); +} + +TEST(DescriptorPoolRecyclerVKTest, MultipleCommandBuffersShareDescriptorPool) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + std::shared_ptr cmd_buffer_1 = context->CreateCommandBuffer(); + std::shared_ptr cmd_buffer_2 = context->CreateCommandBuffer(); + + CommandBufferVK& vk_1 = CommandBufferVK::Cast(*cmd_buffer_1); + CommandBufferVK& vk_2 = CommandBufferVK::Cast(*cmd_buffer_2); + + EXPECT_EQ(&vk_1.GetDescriptorPool(), &vk_2.GetDescriptorPool()); + + // Resetting resources creates a new pool. + context->DisposeThreadLocalCachedResources(); + + std::shared_ptr cmd_buffer_3 = context->CreateCommandBuffer(); + CommandBufferVK& vk_3 = CommandBufferVK::Cast(*cmd_buffer_3); + + EXPECT_NE(&vk_1.GetDescriptorPool(), &vk_3.GetDescriptorPool()); + + context->Shutdown(); +} + +TEST(DescriptorPoolRecyclerVKTest, DescriptorsAreRecycled) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + { + DescriptorPoolVK pool = DescriptorPoolVK(context); + pool.AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + } + + // Should reuse the same descriptor set allocated above. + std::shared_ptr pool = + context->GetDescriptorPoolRecycler()->GetDescriptorPool(); + pool->AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + + std::shared_ptr> called = + GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkAllocateDescriptorSets"), + 1); + + // Should allocate a new descriptor set. + pool->AllocateDescriptorSets({}, /*pipeline_key=*/0, *context); + EXPECT_EQ( + std::count(called->begin(), called->end(), "vkAllocateDescriptorSets"), + 2); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..f713d9198d57e8cad56309a6481fcaec05ff0e9e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" + +#include "flutter/flutter_vma/flutter_vma.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" + +namespace impeller { + +DeviceBufferVK::DeviceBufferVK(DeviceBufferDescriptor desc, + std::weak_ptr context, + UniqueBufferVMA buffer, + VmaAllocationInfo info, + bool is_host_coherent) + : DeviceBuffer(desc), + context_(std::move(context)), + resource_(ContextVK::Cast(*context_.lock().get()).GetResourceManager(), + BufferResource{ + std::move(buffer), // + info // + }), + is_host_coherent_(is_host_coherent) {} + +DeviceBufferVK::~DeviceBufferVK() = default; + +uint8_t* DeviceBufferVK::OnGetContents() const { + return static_cast(resource_->info.pMappedData); +} + +bool DeviceBufferVK::OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) { + uint8_t* dest = OnGetContents(); + + if (!dest) { + return false; + } + + if (source) { + ::memmove(dest + offset, source + source_range.offset, source_range.length); + } + ::vmaFlushAllocation(resource_->buffer.get().allocator, + resource_->buffer.get().allocation, offset, + source_range.length); + + return true; +} + +bool DeviceBufferVK::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + auto context = context_.lock(); + if (!context || !resource_->buffer.is_valid()) { + // The context could have died at this point. + return false; + } + + ::vmaSetAllocationName(resource_->buffer.get().allocator, // + resource_->buffer.get().allocation, // + label.data() // + ); + + return ContextVK::Cast(*context).SetDebugName(resource_->buffer.get().buffer, + label); +#else + return true; +#endif // IMPELLER_DEBUG +} + +void DeviceBufferVK::Flush(std::optional range) const { + if (is_host_coherent_) { + return; + } + auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size}); + ::vmaFlushAllocation(resource_->buffer.get().allocator, + resource_->buffer.get().allocation, flush_range.offset, + flush_range.length); +} + +// Visible for testing. +bool DeviceBufferVK::IsHostCoherent() const { + return is_host_coherent_; +} + +void DeviceBufferVK::Invalidate(std::optional range) const { + auto flush_range = range.value_or(Range{0, GetDeviceBufferDescriptor().size}); + ::vmaInvalidateAllocation(resource_->buffer.get().allocator, + resource_->buffer.get().allocation, + flush_range.offset, flush_range.length); +} + +bool DeviceBufferVK::SetLabel(std::string_view label, Range range) { + // We do not have the ability to name ranges. Just name the whole thing. + return SetLabel(label); +} + +vk::Buffer DeviceBufferVK::GetBuffer() const { + return resource_->buffer.get().buffer; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..8ec31cae8ce0ad8175d836b86cae2ff5d6fb516c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_buffer_vk.h @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/device_buffer.h" +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" +#include "impeller/renderer/backend/vulkan/vma.h" + +namespace impeller { + +class DeviceBufferVK final : public DeviceBuffer, + public BackendCast { + public: + DeviceBufferVK(DeviceBufferDescriptor desc, + std::weak_ptr context, + UniqueBufferVMA buffer, + VmaAllocationInfo info, + bool is_host_coherent); + + // |DeviceBuffer| + ~DeviceBufferVK() override; + + vk::Buffer GetBuffer() const; + + // Visible for testing. + bool IsHostCoherent() const; + + private: + friend class AllocatorVK; + + struct BufferResource { + UniqueBufferVMA buffer; + VmaAllocationInfo info = {}; + + BufferResource() = default; + + BufferResource(UniqueBufferVMA p_buffer, VmaAllocationInfo p_info) + : buffer(std::move(p_buffer)), info(p_info) {} + + BufferResource(BufferResource&& o) { + std::swap(o.buffer, buffer); + std::swap(o.info, info); + } + + BufferResource(const BufferResource&) = delete; + + BufferResource& operator=(const BufferResource&) = delete; + }; + + std::weak_ptr context_; + UniqueResourceVKT resource_; + bool is_host_coherent_ = false; + + // |DeviceBuffer| + uint8_t* OnGetContents() const override; + + // |DeviceBuffer| + bool OnCopyHostBuffer(const uint8_t* source, + Range source_range, + size_t offset) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label) override; + + // |DeviceBuffer| + bool SetLabel(std::string_view label, Range range) override; + + // |DeviceBuffer| + void Flush(std::optional range) const override; + + // |DeviceBuffer| + void Invalidate(std::optional range) const override; + + DeviceBufferVK(const DeviceBufferVK&) = delete; + + DeviceBufferVK& operator=(const DeviceBufferVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_BUFFER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_holder_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_holder_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..f85ae846fdbf5abd52d855a6b587323e8e22595f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/device_holder_vk.h @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_ + +#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep. + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Holds a strong reference to the underlying logical Vulkan +/// device. This comes in handy when the context is being torn down +/// and the various components on different threads may need to +/// orchestrate safe shutdown. +/// +class DeviceHolderVK { + public: + virtual ~DeviceHolderVK() = default; + + virtual const vk::Device& GetDevice() const = 0; + + virtual const vk::PhysicalDevice& GetPhysicalDevice() const = 0; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DEVICE_HOLDER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..5e2a6d5dcac0f86cf31f1148ac9d199dca5ccfbf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.cc @@ -0,0 +1,391 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/driver_info_vk.h" + +#include +#include +#include +#include + +#include "flutter/fml/build_config.h" + +namespace impeller { + +const std::unordered_map kAdrenoVersions = { + // X + // Note: I don't know if these strings actually match as there don't seem to + // be any android devices that use these GPUs. + {"X185", AdrenoGPU::kAdrenoX185}, + {"X145", AdrenoGPU::kAdrenoX145}, + // 700 + {"750", AdrenoGPU::kAdreno750}, + {"740", AdrenoGPU::kAdreno740}, + {"735", AdrenoGPU::kAdreno735}, + {"721", AdrenoGPU::kAdreno732}, + {"730", AdrenoGPU::kAdreno730}, + {"725", AdrenoGPU::kAdreno725}, + {"720", AdrenoGPU::kAdreno720}, + {"710", AdrenoGPU::kAdreno710}, + {"702", AdrenoGPU::kAdreno702}, + + // 600 + {"695", AdrenoGPU::kAdreno695}, + {"690", AdrenoGPU::kAdreno690}, + {"685", AdrenoGPU::kAdreno685}, + {"680", AdrenoGPU::kAdreno680}, + {"675", AdrenoGPU::kAdreno675}, + {"663", AdrenoGPU::kAdreno663}, + {"660", AdrenoGPU::kAdreno660}, + {"650", AdrenoGPU::kAdreno650}, + {"644", AdrenoGPU::kAdreno644}, + {"643L", AdrenoGPU::kAdreno643L}, + {"642", AdrenoGPU::kAdreno642}, + {"642L", AdrenoGPU::kAdreno642L}, + {"640", AdrenoGPU::kAdreno640}, + {"630", AdrenoGPU::kAdreno630}, + {"620", AdrenoGPU::kAdreno620}, + {"619", AdrenoGPU::kAdreno619}, + {"619L", AdrenoGPU::kAdreno619L}, + {"618", AdrenoGPU::kAdreno618}, + {"616", AdrenoGPU::kAdreno616}, + {"615", AdrenoGPU::kAdreno615}, + {"613", AdrenoGPU::kAdreno613}, + {"612", AdrenoGPU::kAdreno612}, + {"610", AdrenoGPU::kAdreno610}, + {"608", AdrenoGPU::kAdreno608}, + {"605", AdrenoGPU::kAdreno605}, + // 500 + {"540", AdrenoGPU::kAdreno540}, + {"530", AdrenoGPU::kAdreno530}, + {"512", AdrenoGPU::kAdreno512}, + {"510", AdrenoGPU::kAdreno510}, + {"509", AdrenoGPU::kAdreno509}, + {"508", AdrenoGPU::kAdreno508}, + {"506", AdrenoGPU::kAdreno506}, + {"505", AdrenoGPU::kAdreno505}, + {"504", AdrenoGPU::kAdreno504}, +}; + +const std::unordered_map kMaliVersions = { + // 5th Gen. + {"G925", MaliGPU::kG925}, + {"G725", MaliGPU::kG725}, + {"G625", MaliGPU::kG625}, + {"G720", MaliGPU::kG720}, + {"G620", MaliGPU::kG620}, + + // Valhall + // Note: there is an Immortalis-G715 a Mali-G715 + {"G715", MaliGPU::kG715}, + {"G615", MaliGPU::kG615}, + {"G710", MaliGPU::kG710}, + {"G610", MaliGPU::kG610}, + {"G510", MaliGPU::kG510}, + {"G310", MaliGPU::kG310}, + {"G78", MaliGPU::kG78}, + {"G68", MaliGPU::kG68}, + {"G77", MaliGPU::kG77}, + {"G57", MaliGPU::kG57}, + + // Bifrost + {"G76", MaliGPU::kG76}, + {"G72", MaliGPU::kG72}, + {"G52", MaliGPU::kG52}, + {"G71", MaliGPU::kG71}, + {"G51", MaliGPU::kG51}, + {"G31", MaliGPU::kG31}, + + // These might be Vulkan 1.0 Only. + {"T880", MaliGPU::kT880}, + {"T860", MaliGPU::kT860}, + {"T830", MaliGPU::kT830}, + {"T820", MaliGPU::kT820}, + {"T760", MaliGPU::kT760}, +}; + +AdrenoGPU GetAdrenoVersion(std::string_view version) { + /// The format that Adreno names follow is "Adreno (TM) VERSION". + auto paren_pos = version.find("Adreno (TM) "); + if (paren_pos == std::string::npos) { + return AdrenoGPU::kUnknown; + } + auto version_string = version.substr(paren_pos + 12); + const auto& result = kAdrenoVersions.find(version_string); + if (result == kAdrenoVersions.end()) { + return AdrenoGPU::kUnknown; + } + return result->second; +} + +PowerVRGPU GetPowerVRVersion(std::string_view version) { + // We don't really care about the specific model, just the series. + if (version.find("DXT") != std::string::npos) { + return PowerVRGPU::kDXT; + } + if (version.find("CXT") != std::string::npos) { + return PowerVRGPU::kCXT; + } + return PowerVRGPU::kUnknown; +} + +MaliGPU GetMaliVersion(std::string_view version) { + // These names are usually Mali-VERSION or Mali-Version-EXTRA_CRAP. + auto dash_pos = version.find("Mali-"); + if (dash_pos == std::string::npos) { + return MaliGPU::kUnknown; + } + auto version_string_with_trailing = version.substr(dash_pos + 5); + // Remove any trailing crap if present. + auto more_dash_pos = version_string_with_trailing.find("-"); + if (more_dash_pos != std::string::npos) { + version_string_with_trailing = + version_string_with_trailing.substr(0, more_dash_pos); + } + + const auto& result = kMaliVersions.find(version_string_with_trailing); + if (result == kMaliVersions.end()) { + return MaliGPU::kUnknown; + } + return result->second; +} + +constexpr VendorVK IdentifyVendor(uint32_t vendor) { + // Check if the vendor has a PCI ID: + // https://pcisig.com/membership/member-companies + switch (vendor) { + case 0x1AE0: + return VendorVK::kGoogle; + case 0x168C: + case 0x17CB: + case 0x1969: + case 0x5143: + return VendorVK::kQualcomm; + case 0x13B5: + return VendorVK::kARM; + case 0x1010: + return VendorVK::kImgTec; + case 0x1002: + case 0x1022: + return VendorVK::kAMD; + case 0x10DE: + return VendorVK::kNvidia; + case 0x8086: // :) + return VendorVK::kIntel; + case 0x106B: + return VendorVK::kApple; + case 0x19E5: + return VendorVK::kHuawei; + case 0x144D: + return VendorVK::kSamsung; + } + // Check if the ID is a known Khronos vendor. + switch (vendor) { + case VK_VENDOR_ID_MESA: + return VendorVK::kMesa; + // There are others but have never been observed. These can be added as + // needed. + } + return VendorVK::kUnknown; +} + +constexpr const char* VendorToString(VendorVK vendor) { + switch (vendor) { + case VendorVK::kUnknown: + return "Unknown"; + case VendorVK::kGoogle: + return "Google"; + case VendorVK::kQualcomm: + return "Qualcomm"; + case VendorVK::kARM: + return "ARM"; + case VendorVK::kImgTec: + return "ImgTec PowerVR"; + case VendorVK::kAMD: + return "AMD"; + case VendorVK::kNvidia: + return "Nvidia"; + case VendorVK::kIntel: + return "Intel"; + case VendorVK::kMesa: + return "Mesa"; + case VendorVK::kApple: + return "Apple"; + case VendorVK::kHuawei: + return "Huawei"; + case VendorVK::kSamsung: + return "Samsung"; + } + FML_UNREACHABLE(); +} + +constexpr const char* DeviceTypeToString(DeviceTypeVK type) { + switch (type) { + case DeviceTypeVK::kUnknown: + return "Unknown"; + case DeviceTypeVK::kIntegratedGPU: + return "Integrated GPU"; + case DeviceTypeVK::kDiscreteGPU: + return "Discrete GPU"; + case DeviceTypeVK::kVirtualGPU: + return "Virtual GPU"; + case DeviceTypeVK::kCPU: + return "CPU"; + } + FML_UNREACHABLE(); +} + +constexpr DeviceTypeVK ToDeviceType(const vk::PhysicalDeviceType& type) { + switch (type) { + case vk::PhysicalDeviceType::eOther: + return DeviceTypeVK::kUnknown; + case vk::PhysicalDeviceType::eIntegratedGpu: + return DeviceTypeVK::kIntegratedGPU; + case vk::PhysicalDeviceType::eDiscreteGpu: + return DeviceTypeVK::kDiscreteGPU; + case vk::PhysicalDeviceType::eVirtualGpu: + return DeviceTypeVK::kVirtualGPU; + case vk::PhysicalDeviceType::eCpu: + return DeviceTypeVK::kCPU; + break; + } + return DeviceTypeVK::kUnknown; +} + +DriverInfoVK::DriverInfoVK(const vk::PhysicalDevice& device) { + auto props = device.getProperties(); + api_version_ = Version{VK_API_VERSION_MAJOR(props.apiVersion), + VK_API_VERSION_MINOR(props.apiVersion), + VK_API_VERSION_PATCH(props.apiVersion)}; + vendor_ = IdentifyVendor(props.vendorID); + if (vendor_ == VendorVK::kUnknown) { + FML_LOG(WARNING) << "Unknown GPU Driver Vendor: " << props.vendorID + << ". This is not an error."; + } + type_ = ToDeviceType(props.deviceType); + if (props.deviceName.data() != nullptr) { + driver_name_ = props.deviceName.data(); + } + + switch (vendor_) { + case VendorVK::kQualcomm: + adreno_gpu_ = GetAdrenoVersion(driver_name_); + break; + case VendorVK::kARM: + mali_gpu_ = GetMaliVersion(driver_name_); + break; + case VendorVK::kPowerVR: + powervr_gpu_ = GetPowerVRVersion(driver_name_); + break; + default: + break; + } +} + +DriverInfoVK::~DriverInfoVK() = default; + +const Version& DriverInfoVK::GetAPIVersion() const { + return api_version_; +} + +const VendorVK& DriverInfoVK::GetVendor() const { + return vendor_; +} + +const DeviceTypeVK& DriverInfoVK::GetDeviceType() const { + return type_; +} + +const std::string& DriverInfoVK::GetDriverName() const { + return driver_name_; +} + +void DriverInfoVK::DumpToLog() const { + std::vector> items; + items.emplace_back("Name", driver_name_); + items.emplace_back("API Version", api_version_.ToString()); + items.emplace_back("Vendor", VendorToString(vendor_)); + items.emplace_back("Device Type", DeviceTypeToString(type_)); + items.emplace_back("Is Emulator", std::to_string(IsEmulator())); + + size_t padding = 0; + + for (const auto& item : items) { + padding = std::max(padding, item.first.size()); + } + + padding += 1; + + std::stringstream stream; + + stream << std::endl; + + stream << "--- Driver Information ------------------------------------------"; + + stream << std::endl; + + for (const auto& item : items) { + stream << "| " << std::setw(static_cast(padding)) << item.first + << std::setw(0) << ": " << item.second << std::endl; + } + + stream << "-----------------------------------------------------------------"; + + FML_LOG(IMPORTANT) << stream.str(); +} + +bool DriverInfoVK::IsEmulator() const { +#if FML_OS_ANDROID + // Google SwiftShader on Android. + if (type_ == DeviceTypeVK::kCPU && vendor_ == VendorVK::kGoogle && + driver_name_.find("SwiftShader") != std::string::npos) { + return true; + } +#endif // FML_OS_ANDROID + return false; +} + +bool DriverInfoVK::IsKnownBadDriver() const { + // Disable Maleoon series GPUs, see: + // https://github.com/flutter/flutter/issues/156623 + if (vendor_ == VendorVK::kHuawei) { + return true; + } + + if (vendor_ == VendorVK::kSamsung) { + // The first version of the Xclipse series GPU has reported + // bugs, unfortunately all versions of this GPU report the + // same driver version. Instead we use the Vulkan version + // as a proxy, assuming that any newer devices would not + // lower the supported Vulkan API level. + // See + // https://vulkan.gpuinfo.org/listreports.php?devicename=samsung+SM-S906B&platform=android + // https://github.com/flutter/flutter/issues/161334 + return !api_version_.IsAtLeast(Version{1, 3, 0}); + } + + // https://github.com/flutter/flutter/issues/161122 + // https://github.com/flutter/flutter/issues/160960 + // https://github.com/flutter/flutter/issues/160866 + // https://github.com/flutter/flutter/issues/160804 + // https://github.com/flutter/flutter/issues/160406 + if (powervr_gpu_.has_value() && powervr_gpu_.value() < PowerVRGPU::kCXT) { + return true; + } + return false; +} + +std::optional DriverInfoVK::GetMaliGPUInfo() const { + return mali_gpu_; +} + +std::optional DriverInfoVK::GetAdrenoGPUInfo() const { + return adreno_gpu_; +} + +std::optional DriverInfoVK::GetPowerVRGPUInfo() const { + return powervr_gpu_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..e40acae4d8c4102c24f5ba8b2e90c560ce0d7693 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk.h @@ -0,0 +1,295 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_ + +#include "impeller/base/version.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +// https://en.wikipedia.org/wiki/Adreno +enum class AdrenoGPU { + // I don't think the 400 series will ever run Vulkan, but if some show up we + // can add them here. + // 500s + kAdreno504, + kAdreno505, + kAdreno506, + kAdreno508, + kAdreno509, + kAdreno510, + kAdreno512, + kAdreno530, + kAdreno540, + // 600s + kAdreno605, + kAdreno608, + kAdreno610, + kAdreno612, + kAdreno613, + kAdreno615, + kAdreno616, + kAdreno618, + kAdreno619L, + kAdreno619, + kAdreno620, + kAdreno630, + // The 640 is the first GPU inside an Android device with upgradable drivers. + // Anything before this point exhibiting broken behavior is broken forever. + kAdreno640, + kAdreno642L, + kAdreno642, + kAdreno643L, + kAdreno644, + kAdreno650, + kAdreno660, + kAdreno663, + kAdreno675, + kAdreno680, + kAdreno685, + kAdreno690, + kAdreno695, + // 700s + kAdreno702, + kAdreno710, + kAdreno720, + kAdreno725, + kAdreno730, + kAdreno732, + kAdreno735, + kAdreno740, + kAdreno750, + // X + kAdrenoX145, + kAdrenoX185, + // Unknown GPU, likely newer model. + kUnknown, +}; + +// https://en.wikipedia.org/wiki/Mali_(processor) +enum class MaliGPU { + // These might be Vulkan 1.0 Only. + kT760, + kT820, + kT830, + kT860, + kT880, + + // Bifrost + kG31, + kG51, + kG71, + kG52, + kG72, + kG76, + + // Valhall + // Note: there is an Immortalis-G715 a Mali-G715 + kG57, + kG77, + kG68, + kG78, + kG310, + kG510, + kG610, + kG710, + kG615, + kG715, + + // 5th Gen + kG620, + kG720, + kG625, + kG725, + kG925, + kUnknown, +}; + +// Ordered by approximate release date. We currently don't attempt to +// parse the exact power VR GPU variant so newer names will fall back +// to OpenGL. This is acceptable for now. +enum class PowerVRGPU { + kUnknown, + // Not good. + kRogue, + // Vulkan may work, but not tested. + kAXE, + kAXM, + kAXT, + kBXE, + kBXM, + kBXS, + kBXT, + // First good vulkan drivers. + kCXT, + kDXT, +}; + +enum class VendorVK { + kUnknown, + //---------------------------------------------------------------------------- + /// Includes the SwiftShader CPU implementation. + /// + kGoogle, + kQualcomm, + kARM, + kImgTec, + kPowerVR = kImgTec, + kAMD, + kNvidia, + kIntel, + kHuawei, + kSamsung, + //---------------------------------------------------------------------------- + /// Includes the LLVM Pipe CPU implementation. + /// + kMesa, + //---------------------------------------------------------------------------- + /// Includes Vulkan on Metal via MoltenVK. + /// + kApple, +}; + +enum class DeviceTypeVK { + kUnknown, + //---------------------------------------------------------------------------- + /// The device is an integrated GPU. Typically mobile GPUs. + /// + kIntegratedGPU, + //---------------------------------------------------------------------------- + /// The device is a discrete GPU. Typically desktop GPUs. + /// + kDiscreteGPU, + //---------------------------------------------------------------------------- + /// The device is a GPU in a virtualized environment. + /// + kVirtualGPU, + //---------------------------------------------------------------------------- + /// There is no GPU. Vulkan is implemented on the CPU. This is typically + /// emulators like SwiftShader and LLVMPipe. + /// + kCPU, +}; + +// visible for testing. +AdrenoGPU GetAdrenoVersion(std::string_view version); + +// visible for testing. +MaliGPU GetMaliVersion(std::string_view version); + +//------------------------------------------------------------------------------ +/// @brief Get information about the Vulkan driver. +/// +/// @warning Be extremely cautious about the information reported here. This +/// is self-reported information (by the driver) and may be +/// inaccurate and or inconsistent. +/// +/// Before gating features behind any of the information reported by +/// the driver, consider alternatives (extensions checks perhaps) +/// and try to get a reviewer buddy to convince you to avoid using +/// this. +/// +class DriverInfoVK { + public: + explicit DriverInfoVK(const vk::PhysicalDevice& device); + + ~DriverInfoVK(); + + DriverInfoVK(const DriverInfoVK&) = delete; + + DriverInfoVK& operator=(const DriverInfoVK&) = delete; + + //---------------------------------------------------------------------------- + /// @brief Gets the Vulkan API version. Should be at or above Vulkan 1.1 + /// which is the Impeller baseline. + /// + /// @return The Vulkan API version. + /// + const Version& GetAPIVersion() const; + + //---------------------------------------------------------------------------- + /// @brief Get the vendor of the Vulkan implementation. This is a broad + /// check and includes multiple drivers and platforms. + /// + /// @return The vendor. + /// + const VendorVK& GetVendor() const; + + //---------------------------------------------------------------------------- + /// @brief Get the device type. Typical use might be to check if the + /// device is a CPU implementation. + /// + /// @return The device type. + /// + const DeviceTypeVK& GetDeviceType() const; + + //---------------------------------------------------------------------------- + /// @brief Get the self-reported name of the graphics driver. + /// + /// @return The driver name. + /// + const std::string& GetDriverName() const; + + //---------------------------------------------------------------------------- + /// @brief Dumps the current driver info to the log. + /// + void DumpToLog() const; + + //---------------------------------------------------------------------------- + /// @brief Determines if the driver represents an emulator. There is no + /// definitive way to tell if a driver is an emulator and drivers + /// don't self identify as emulators. So take this information + /// with a pinch of salt. + /// + /// @return True if emulator, False otherwise. + /// + bool IsEmulator() const; + + //---------------------------------------------------------------------------- + /// @brief Determines if the driver has been tested and determined to be + /// non-functional. + /// + /// If true, context setup should fail such that the device falls + /// back to OpenGLES. + /// + /// @return True if non-functional device, False otherwise. + /// + bool IsKnownBadDriver() const; + + //---------------------------------------------------------------------------- + /// @brief Returns Mali GPU info if this is a Mali GPU, otherwise + /// std::nullopt. + /// + std::optional GetMaliGPUInfo() const; + + //---------------------------------------------------------------------------- + /// @brief Returns Adreno GPU info if this is a Adreno GPU, otherwise + /// std::nullopt. + /// + std::optional GetAdrenoGPUInfo() const; + + //---------------------------------------------------------------------------- + /// @brief Returns PowerVR GPU info if this is a PowerVR GPU, otherwise + /// std::nullopt. + /// + std::optional GetPowerVRGPUInfo() const; + + private: + bool is_valid_ = false; + Version api_version_; + VendorVK vendor_ = VendorVK::kUnknown; + DeviceTypeVK type_ = DeviceTypeVK::kUnknown; + // If the VendorVK is VendorVK::kQualcomm, this will be populated with the + // identified Adreno GPU. + std::optional adreno_gpu_ = std::nullopt; + std::optional mali_gpu_ = std::nullopt; + std::optional powervr_gpu_ = std::nullopt; + std::string driver_name_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_DRIVER_INFO_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a4db67885fd8dc6bb6f76d61eab49a3abb82ef20 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/driver_info_vk_unittests.cc @@ -0,0 +1,290 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/driver_info_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" + +namespace impeller::testing { + +using DriverInfoVKTest = PlaygroundTest; +INSTANTIATE_VULKAN_PLAYGROUND_SUITE(DriverInfoVKTest); + +TEST_P(DriverInfoVKTest, CanQueryDriverInfo) { + ASSERT_TRUE(GetContext()); + const auto& driver_info = + SurfaceContextVK::Cast(*GetContext()).GetParent()->GetDriverInfo(); + ASSERT_NE(driver_info, nullptr); + // 1.1 is the base Impeller version. The driver can't be lower than that. + ASSERT_TRUE(driver_info->GetAPIVersion().IsAtLeast(Version{1, 1, 0})); + ASSERT_NE(driver_info->GetVendor(), VendorVK::kUnknown); + ASSERT_NE(driver_info->GetDeviceType(), DeviceTypeVK::kUnknown); + ASSERT_NE(driver_info->GetDriverName(), ""); + EXPECT_FALSE(driver_info->IsKnownBadDriver()); +} + +TEST_P(DriverInfoVKTest, CanDumpToLog) { + ASSERT_TRUE(GetContext()); + const auto& driver_info = + SurfaceContextVK::Cast(*GetContext()).GetParent()->GetDriverInfo(); + ASSERT_NE(driver_info, nullptr); + fml::testing::LogCapture log; + driver_info->DumpToLog(); + EXPECT_TRUE(log.str().find("Driver Information") != std::string::npos); +} + +TEST(DriverInfoVKTest, CanIdentifyBadMaleoonDriver) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x19E5; // Huawei + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + + EXPECT_TRUE(context->GetDriverInfo()->IsKnownBadDriver()); +} + +bool IsBadVersionTest(std::string_view driver_name, bool qc = true) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [&driver_name, qc](VkPhysicalDevice device, + VkPhysicalDeviceProperties* prop) { + if (qc) { + prop->vendorID = 0x168C; // Qualcomm + } else { + prop->vendorID = 0x13B5; // ARM + } + driver_name.copy(prop->deviceName, driver_name.size()); + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + return context->GetDriverInfo()->IsKnownBadDriver(); +} + +bool CanBatchSubmitTest(std::string_view driver_name, bool qc = true) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [&driver_name, qc](VkPhysicalDevice device, + VkPhysicalDeviceProperties* prop) { + if (qc) { + prop->vendorID = 0x168C; // Qualcomm + } else { + prop->vendorID = 0x13B5; // ARM + } + driver_name.copy(prop->deviceName, driver_name.size()); + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + return !GetWorkaroundsFromDriverInfo(*context->GetDriverInfo()) + .batch_submit_command_buffer_timeout; +} + +TEST(DriverInfoVKTest, CanBatchSubmitCommandBuffers) { + // Old Adreno no batch submit! + EXPECT_FALSE(CanBatchSubmitTest("Adreno (TM) 540", true)); + + EXPECT_TRUE(CanBatchSubmitTest("Mali-G51", false)); + EXPECT_TRUE(CanBatchSubmitTest("Adreno (TM) 750", true)); +} + +bool CanUsePrimitiveRestartSubmitTest(std::string_view driver_name, + bool qc = true) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [&driver_name, qc](VkPhysicalDevice device, + VkPhysicalDeviceProperties* prop) { + if (qc) { + prop->vendorID = 0x168C; // Qualcomm + } else { + prop->vendorID = 0x13B5; // ARM + } + driver_name.copy(prop->deviceName, driver_name.size()); + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + return !GetWorkaroundsFromDriverInfo(*context->GetDriverInfo()) + .slow_primitive_restart_performance; +} + +TEST(DriverInfoVKTest, CanUsePrimitiveRestart) { + // Adreno no primitive restart + EXPECT_FALSE(CanUsePrimitiveRestartSubmitTest("Adreno (TM) 540", true)); + EXPECT_FALSE(CanUsePrimitiveRestartSubmitTest("Adreno (TM) 750", true)); + + // Mali A-OK + EXPECT_TRUE(CanUsePrimitiveRestartSubmitTest("Mali-G51", false)); +} + +bool CanUseMipgeneration(std::string_view driver_name, bool qc = true) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [&driver_name, qc](VkPhysicalDevice device, + VkPhysicalDeviceProperties* prop) { + if (qc) { + prop->vendorID = 0x168C; // Qualcomm + } else { + prop->vendorID = 0x13B5; // ARM + } + driver_name.copy(prop->deviceName, driver_name.size()); + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + return !GetWorkaroundsFromDriverInfo(*context->GetDriverInfo()) + .broken_mipmap_generation; +} + +TEST(DriverInfoVKTest, CanGenerateMipMaps) { + // Adreno no mips + EXPECT_FALSE(CanUseMipgeneration("Adreno (TM) 540", true)); + EXPECT_FALSE(CanUseMipgeneration("Adreno (TM) 750", true)); + + // Mali A-OK + EXPECT_TRUE(CanUseMipgeneration("Mali-G51", false)); +} + +TEST(DriverInfoVKTest, DriverParsingMali) { + EXPECT_EQ(GetMaliVersion("Mali-G51-MORE STUFF"), MaliGPU::kG51); + EXPECT_EQ(GetMaliVersion("Mali-G51"), MaliGPU::kG51); + EXPECT_EQ(GetMaliVersion("Mali-111111"), MaliGPU::kUnknown); +} + +TEST(DriverInfoVKTest, DriverParsingAdreno) { + EXPECT_EQ(GetAdrenoVersion("Adreno (TM) 540"), AdrenoGPU::kAdreno540); + EXPECT_EQ(GetAdrenoVersion("Foo Bar"), AdrenoGPU::kUnknown); +} + +TEST(DriverInfoVKTest, DisabledDevices) { + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 620")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 610")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 530")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 512")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 509")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 508")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 506")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 505")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 504")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 630")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 640")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 650")); +} + +TEST(DriverInfoVKTest, EnabledDevicesMali) { + EXPECT_FALSE(IsBadVersionTest("Mali-G52", /*qc=*/false)); + EXPECT_FALSE(IsBadVersionTest("Mali-G54-MORE STUFF", /*qc=*/false)); +} + +TEST(DriverInfoVKTest, EnabledDevicesAdreno) { + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 750")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 740")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 732")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 730")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 725")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 720")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 710")); + EXPECT_FALSE(IsBadVersionTest("Adreno (TM) 702")); +} + +bool CanUseFramebufferFetch(std::string_view driver_name, bool qc = true) { + auto const context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [&driver_name, qc](VkPhysicalDevice device, + VkPhysicalDeviceProperties* prop) { + if (qc) { + prop->vendorID = 0x168C; // Qualcomm + } else { + prop->vendorID = 0x13B5; // ARM + } + driver_name.copy(prop->deviceName, driver_name.size()); + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + }) + .Build(); + return !GetWorkaroundsFromDriverInfo(*context->GetDriverInfo()) + .input_attachment_self_dependency_broken; +} + +TEST(DriverInfoVKTest, CanUseFramebufferFetch) { + // Adreno no primitive restart on models as or older than 630. + EXPECT_FALSE(CanUseFramebufferFetch("Adreno (TM) 540", true)); + EXPECT_FALSE(CanUseFramebufferFetch("Adreno (TM) 630", true)); + + EXPECT_TRUE(CanUseFramebufferFetch("Adreno (TM) 640", true)); + EXPECT_TRUE(CanUseFramebufferFetch("Adreno (TM) 750", true)); + EXPECT_TRUE(CanUseFramebufferFetch("Mali-G51", false)); +} + +TEST(DriverInfoVKTest, DisableOldXclipseDriver) { + auto context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x144D; // Samsung + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + // Version 1.1.0 + prop->apiVersion = (1 << 22) | (1 << 12); + }) + .Build(); + + EXPECT_TRUE(context->GetDriverInfo()->IsKnownBadDriver()); + + context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x144D; // Samsung + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + // Version 1.3.0 + prop->apiVersion = (1 << 22) | (3 << 12); + }) + .Build(); + + EXPECT_FALSE(context->GetDriverInfo()->IsKnownBadDriver()); +} + +TEST(DriverInfoVKTest, OldPowerVRDisabled) { + std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x1010; + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + std::string name = "PowerVR Rogue GE8320"; + name.copy(prop->deviceName, name.size()); + }) + .Build(); + + EXPECT_TRUE(context->GetDriverInfo()->IsKnownBadDriver()); + EXPECT_EQ(context->GetDriverInfo()->GetPowerVRGPUInfo(), + std::optional(PowerVRGPU::kUnknown)); +} + +TEST(DriverInfoVKTest, NewPowerVREnabled) { + std::shared_ptr context = + MockVulkanContextBuilder() + .SetPhysicalPropertiesCallback( + [](VkPhysicalDevice device, VkPhysicalDeviceProperties* prop) { + prop->vendorID = 0x1010; + prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; + std::string name = "PowerVR DXT 123"; + name.copy(prop->deviceName, name.size()); + }) + .Build(); + + EXPECT_FALSE(context->GetDriverInfo()->IsKnownBadDriver()); + EXPECT_EQ(context->GetDriverInfo()->GetPowerVRGPUInfo(), + std::optional(PowerVRGPU::kDXT)); + EXPECT_TRUE(GetWorkaroundsFromDriverInfo(*context->GetDriverInfo()) + .input_attachment_self_dependency_broken); +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..ddd617a58033e5bf9cf810f4f47b2d38b75d621f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.cc @@ -0,0 +1,215 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" + +#include +#include +#include + +#include "flutter/fml/cpu_affinity.h" +#include "flutter/fml/thread.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/validation.h" + +namespace impeller { + +class WaitSetEntry { + public: + static std::shared_ptr Create(vk::UniqueFence p_fence, + const fml::closure& p_callback) { + return std::shared_ptr( + new WaitSetEntry(std::move(p_fence), p_callback)); + } + + void UpdateSignalledStatus(const vk::Device& device) { + if (is_signalled_) { + return; + } + is_signalled_ = device.getFenceStatus(fence_.get()) == vk::Result::eSuccess; + } + + const vk::Fence& GetFence() const { return fence_.get(); } + + bool IsSignalled() const { return is_signalled_; } + + private: + vk::UniqueFence fence_; + fml::ScopedCleanupClosure callback_; + bool is_signalled_ = false; + + WaitSetEntry(vk::UniqueFence p_fence, const fml::closure& p_callback) + : fence_(std::move(p_fence)), + callback_(fml::ScopedCleanupClosure{p_callback}) {} + + WaitSetEntry(const WaitSetEntry&) = delete; + + WaitSetEntry(WaitSetEntry&&) = delete; + + WaitSetEntry& operator=(const WaitSetEntry&) = delete; + + WaitSetEntry& operator=(WaitSetEntry&&) = delete; +}; + +FenceWaiterVK::FenceWaiterVK(std::weak_ptr device_holder) + : device_holder_(std::move(device_holder)) { + waiter_thread_ = std::make_unique([&]() { Main(); }); +} + +FenceWaiterVK::~FenceWaiterVK() { + Terminate(); + waiter_thread_->join(); +} + +bool FenceWaiterVK::AddFence(vk::UniqueFence fence, + const fml::closure& callback) { + if (!fence || !callback) { + return false; + } + { + // Maintain the invariant that terminate_ is accessed only under the lock. + std::scoped_lock lock(wait_set_mutex_); + if (terminate_) { + return false; + } + wait_set_.emplace_back(WaitSetEntry::Create(std::move(fence), callback)); + } + wait_set_cv_.notify_one(); + return true; +} + +static std::vector GetFencesForWaitSet(const WaitSet& set) { + std::vector fences; + for (const auto& entry : set) { + if (!entry->IsSignalled()) { + fences.emplace_back(entry->GetFence()); + } + } + return fences; +} + +void FenceWaiterVK::Main() { + fml::Thread::SetCurrentThreadName( + fml::Thread::ThreadConfig{"IplrVkFenceWait"}); + // Since this thread mostly waits on fences, it doesn't need to be fast. + fml::RequestAffinity(fml::CpuAffinity::kEfficiency); + + while (true) { + // We'll read the terminate_ flag within the lock below. + bool terminate = false; + + { + std::unique_lock lock(wait_set_mutex_); + + // If there are no fences to wait on, wait on the condition variable. + wait_set_cv_.wait(lock, + [&]() { return !wait_set_.empty() || terminate_; }); + + // Still under the lock, check if the waiter has been terminated. + terminate = terminate_; + } + + if (terminate) { + WaitUntilEmpty(); + break; + } + + if (!Wait()) { + break; + } + } +} + +void FenceWaiterVK::WaitUntilEmpty() { + // Note, there is no lock because once terminate_ is set to true, no other + // fence can be added to the wait set. Just in case, here's a FML_DCHECK: + FML_DCHECK(terminate_) << "Fence waiter must be terminated."; + while (!wait_set_.empty() && Wait()) { + // Intentionally empty. + } +} + +bool FenceWaiterVK::Wait() { + // Snapshot the wait set and wait on the fences. + WaitSet wait_set; + { + std::scoped_lock lock(wait_set_mutex_); + wait_set = wait_set_; + } + + using namespace std::literals::chrono_literals; + + // Check if the context had died in the meantime. + auto device_holder = device_holder_.lock(); + if (!device_holder) { + return false; + } + + const auto& device = device_holder->GetDevice(); + // Wait for one or more fences to be signaled. Any additional fences added + // to the waiter will be serviced in the next pass. If a fence that is going + // to be signaled at an abnormally long deadline is the only one in the set, + // a timeout will bail out the wait. + auto fences = GetFencesForWaitSet(wait_set); + if (fences.empty()) { + return true; + } + + auto result = device.waitForFences( + /*fenceCount=*/fences.size(), + /*pFences=*/fences.data(), + /*waitAll=*/false, + /*timeout=*/std::chrono::nanoseconds{100ms}.count()); + if (!(result == vk::Result::eSuccess || result == vk::Result::eTimeout)) { + VALIDATION_LOG << "Fence waiter encountered an unexpected error. Tearing " + "down the waiter thread."; + return false; + } + + // One or more fences have been signaled. Find out which ones and update + // their signaled statuses. + { + TRACE_EVENT0("impeller", "CheckFenceStatus"); + for (auto& entry : wait_set) { + entry->UpdateSignalledStatus(device); + } + wait_set.clear(); + } + + // Quickly acquire the wait set lock and erase signaled entries. Make sure + // the mutex is unlocked before calling the destructors of the erased + // entries. These might touch allocators. + WaitSet erased_entries; + { + static constexpr auto is_signalled = [](const auto& entry) { + return entry->IsSignalled(); + }; + std::scoped_lock lock(wait_set_mutex_); + + // TODO(matanlurey): Iterate the list 1x by copying is_signaled into erased. + std::copy_if(wait_set_.begin(), wait_set_.end(), + std::back_inserter(erased_entries), is_signalled); + wait_set_.erase( + std::remove_if(wait_set_.begin(), wait_set_.end(), is_signalled), + wait_set_.end()); + } + + { + TRACE_EVENT0("impeller", "ClearSignaledFences"); + // Erase the erased entries which will invoke callbacks. + erased_entries.clear(); // Bit redundant because of scope but hey. + } + + return true; +} + +void FenceWaiterVK::Terminate() { + { + std::scoped_lock lock(wait_set_mutex_); + terminate_ = true; + } + wait_set_cv_.notify_one(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..229218694ba27f0006711ef8069b9ad5b97da5f5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FENCE_WAITER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FENCE_WAITER_VK_H_ + +#include +#include +#include +#include + +#include "flutter/fml/closure.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" + +namespace impeller { + +class ContextVK; +class WaitSetEntry; + +using WaitSet = std::vector>; + +class FenceWaiterVK { + public: + ~FenceWaiterVK(); + + bool IsValid() const; + + void Terminate(); + + bool AddFence(vk::UniqueFence fence, const fml::closure& callback); + + private: + friend class ContextVK; + + std::weak_ptr device_holder_; + std::unique_ptr waiter_thread_; + std::mutex wait_set_mutex_; + std::condition_variable wait_set_cv_; + WaitSet wait_set_; + bool terminate_ = false; + + explicit FenceWaiterVK(std::weak_ptr device_holder); + + void Main(); + + bool Wait(); + void WaitUntilEmpty(); + + FenceWaiterVK(const FenceWaiterVK&) = delete; + + FenceWaiterVK& operator=(const FenceWaiterVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FENCE_WAITER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef2ff5d40cbb950a5fde469d8e0972ef7b4d254d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/fence_waiter_vk_unittests.cc @@ -0,0 +1,130 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "fml/synchronization/waitable_event.h" +#include "gtest/gtest.h" // IWYU pragma: keep +#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h" // IWYU pragma: keep +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +namespace impeller { +namespace testing { + +TEST(FenceWaiterVKTest, IgnoresNullFence) { + auto const context = MockVulkanContextBuilder().Build(); + auto const waiter = context->GetFenceWaiter(); + EXPECT_FALSE(waiter->AddFence(vk::UniqueFence(), []() {})); +} + +TEST(FenceWaiterVKTest, IgnoresNullCallback) { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + + auto fence = device.createFenceUnique({}).value; + EXPECT_FALSE(waiter->AddFence(std::move(fence), nullptr)); +} + +TEST(FenceWaiterVKTest, ExecutesFenceCallback) { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + + auto signal = fml::ManualResetWaitableEvent(); + auto fence = device.createFenceUnique({}).value; + waiter->AddFence(std::move(fence), [&signal]() { signal.Signal(); }); + + signal.Wait(); +} + +TEST(FenceWaiterVKTest, ExecutesFenceCallbackX2) { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + + auto signal = fml::ManualResetWaitableEvent(); + auto fence = device.createFenceUnique({}).value; + waiter->AddFence(std::move(fence), [&signal]() { signal.Signal(); }); + + auto signal2 = fml::ManualResetWaitableEvent(); + auto fence2 = device.createFenceUnique({}).value; + waiter->AddFence(std::move(fence2), [&signal2]() { signal2.Signal(); }); + + signal.Wait(); + signal2.Wait(); +} + +TEST(FenceWaiterVKTest, ExecutesNewFenceThenOldFence) { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + + auto signal = fml::ManualResetWaitableEvent(); + auto fence = device.createFenceUnique({}).value; + MockFence::SetStatus(fence, vk::Result::eNotReady); + auto raw_fence = MockFence::GetRawPointer(fence); + waiter->AddFence(std::move(fence), [&signal]() { signal.Signal(); }); + + // The easiest way to verify that the callback was _not_ called is to wait + // for a timeout, but that could introduce flakiness. Instead, we'll add a + // second fence that will signal immediately, and wait for that one instead. + { + auto signal2 = fml::ManualResetWaitableEvent(); + auto fence2 = device.createFenceUnique({}).value; + MockFence::SetStatus(fence2, vk::Result::eSuccess); + waiter->AddFence(std::move(fence2), [&signal2]() { signal2.Signal(); }); + signal2.Wait(); + } + + // Now, we'll signal the first fence, and wait for the callback to be called. + raw_fence->SetStatus(vk::Result::eSuccess); + + // Now, we'll signal the first fence, and wait for the callback to be called. + signal.Wait(); +} + +TEST(FenceWaiterVKTest, AddFenceDoesNothingIfTerminating) { + auto signal = fml::ManualResetWaitableEvent(); + + { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + waiter->Terminate(); + + auto fence = device.createFenceUnique({}).value; + waiter->AddFence(std::move(fence), [&signal]() { signal.Signal(); }); + } + + // Ensure the fence did _not_ signal. + EXPECT_TRUE(signal.WaitWithTimeout(fml::TimeDelta::FromMilliseconds(100))); +} + +TEST(FenceWaiterVKTest, InProgressFencesStillWaitIfTerminated) { + MockFence* raw_fence = nullptr; + auto signal = fml::ManualResetWaitableEvent(); + + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + auto const waiter = context->GetFenceWaiter(); + + // Add a fence that isn't signalled yet. + auto fence = device.createFenceUnique({}).value; + + // Even if the fence is eSuccess, it's not guaranteed to be called in time. + MockFence::SetStatus(fence, vk::Result::eNotReady); + raw_fence = MockFence::GetRawPointer(fence); + waiter->AddFence(std::move(fence), [&signal]() { signal.Signal(); }); + + // Terminate the waiter. + waiter->Terminate(); + + // Signal the fence. + raw_fence->SetStatus(vk::Result::eSuccess); + + // This will hang if the fence was not signalled. + signal.Wait(); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..f27452ccdbfed748d7e28cd1e9d2ecd0481eab14 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/formats_vk.h" + +namespace impeller { + +vk::PipelineDepthStencilStateCreateInfo ToVKPipelineDepthStencilStateCreateInfo( + std::optional depth, + std::optional front, + std::optional back) { + vk::PipelineDepthStencilStateCreateInfo info; + + if (depth.has_value()) { + info.depthTestEnable = true; + info.depthWriteEnable = depth->depth_write_enabled; + info.depthCompareOp = ToVKCompareOp(depth->depth_compare); + info.minDepthBounds = 0.0f; + info.maxDepthBounds = 1.0f; + } + + if (front.has_value()) { + info.stencilTestEnable = true; + info.front = ToVKStencilOpState(*front); + } + + if (back.has_value()) { + info.stencilTestEnable = true; + info.back = ToVKStencilOpState(*back); + } + + return info; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..2dbb21c5af08e58481ffac50c7c332fd8e7e08f3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk.h @@ -0,0 +1,615 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_ + +#include +#include + +#include "fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { + +constexpr std::optional VkFormatToImpellerFormat( + vk::Format format) { + switch (format) { + case vk::Format::eR8G8B8A8Unorm: + return PixelFormat::kR8G8B8A8UNormInt; + case vk::Format::eB8G8R8A8Unorm: + return PixelFormat::kB8G8R8A8UNormInt; + default: + return std::nullopt; + } +} + +constexpr vk::SampleCountFlagBits ToVKSampleCountFlagBits(SampleCount count) { + switch (count) { + case SampleCount::kCount1: + return vk::SampleCountFlagBits::e1; + case SampleCount::kCount4: + return vk::SampleCountFlagBits::e4; + } + FML_UNREACHABLE(); +} + +constexpr vk::BlendFactor ToVKBlendFactor(BlendFactor factor) { + switch (factor) { + case BlendFactor::kZero: + return vk::BlendFactor::eZero; + case BlendFactor::kOne: + return vk::BlendFactor::eOne; + case BlendFactor::kSourceColor: + return vk::BlendFactor::eSrcColor; + case BlendFactor::kOneMinusSourceColor: + return vk::BlendFactor::eOneMinusSrcColor; + case BlendFactor::kSourceAlpha: + return vk::BlendFactor::eSrcAlpha; + case BlendFactor::kOneMinusSourceAlpha: + return vk::BlendFactor::eOneMinusSrcAlpha; + case BlendFactor::kDestinationColor: + return vk::BlendFactor::eDstColor; + case BlendFactor::kOneMinusDestinationColor: + return vk::BlendFactor::eOneMinusDstColor; + case BlendFactor::kDestinationAlpha: + return vk::BlendFactor::eDstAlpha; + case BlendFactor::kOneMinusDestinationAlpha: + return vk::BlendFactor::eOneMinusDstAlpha; + case BlendFactor::kSourceAlphaSaturated: + return vk::BlendFactor::eSrcAlphaSaturate; + case BlendFactor::kBlendColor: + return vk::BlendFactor::eConstantColor; + case BlendFactor::kOneMinusBlendColor: + return vk::BlendFactor::eOneMinusConstantColor; + case BlendFactor::kBlendAlpha: + return vk::BlendFactor::eConstantAlpha; + case BlendFactor::kOneMinusBlendAlpha: + return vk::BlendFactor::eOneMinusConstantAlpha; + } + FML_UNREACHABLE(); +} + +constexpr vk::BlendOp ToVKBlendOp(BlendOperation op) { + switch (op) { + case BlendOperation::kAdd: + return vk::BlendOp::eAdd; + case BlendOperation::kSubtract: + return vk::BlendOp::eSubtract; + case BlendOperation::kReverseSubtract: + return vk::BlendOp::eReverseSubtract; + } + FML_UNREACHABLE(); +} + +constexpr vk::ColorComponentFlags ToVKColorComponentFlags(ColorWriteMask type) { + vk::ColorComponentFlags mask; + + if (type & ColorWriteMaskBits::kRed) { + mask |= vk::ColorComponentFlagBits::eR; + } + + if (type & ColorWriteMaskBits::kGreen) { + mask |= vk::ColorComponentFlagBits::eG; + } + + if (type & ColorWriteMaskBits::kBlue) { + mask |= vk::ColorComponentFlagBits::eB; + } + + if (type & ColorWriteMaskBits::kAlpha) { + mask |= vk::ColorComponentFlagBits::eA; + } + + return mask; +} + +constexpr vk::PipelineColorBlendAttachmentState +ToVKPipelineColorBlendAttachmentState(const ColorAttachmentDescriptor& desc) { + vk::PipelineColorBlendAttachmentState res; + + res.setBlendEnable(desc.blending_enabled); + + res.setSrcColorBlendFactor(ToVKBlendFactor(desc.src_color_blend_factor)); + res.setColorBlendOp(ToVKBlendOp(desc.color_blend_op)); + res.setDstColorBlendFactor(ToVKBlendFactor(desc.dst_color_blend_factor)); + + res.setSrcAlphaBlendFactor(ToVKBlendFactor(desc.src_alpha_blend_factor)); + res.setAlphaBlendOp(ToVKBlendOp(desc.alpha_blend_op)); + res.setDstAlphaBlendFactor(ToVKBlendFactor(desc.dst_alpha_blend_factor)); + + res.setColorWriteMask(ToVKColorComponentFlags(desc.write_mask)); + + return res; +} + +constexpr std::optional ToVKShaderStageFlagBits( + ShaderStage stage) { + switch (stage) { + case ShaderStage::kUnknown: + return std::nullopt; + case ShaderStage::kVertex: + return vk::ShaderStageFlagBits::eVertex; + case ShaderStage::kFragment: + return vk::ShaderStageFlagBits::eFragment; + case ShaderStage::kCompute: + return vk::ShaderStageFlagBits::eCompute; + } + FML_UNREACHABLE(); +} + +constexpr vk::Format ToVKImageFormat(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10A10XR: + case PixelFormat::kB10G10R10XRSRGB: + return vk::Format::eUndefined; + case PixelFormat::kA8UNormInt: + // TODO(csg): This is incorrect. Don't depend on swizzle support for GLES. + return vk::Format::eR8Unorm; + case PixelFormat::kR8G8B8A8UNormInt: + return vk::Format::eR8G8B8A8Unorm; + case PixelFormat::kR8G8B8A8UNormIntSRGB: + return vk::Format::eR8G8B8A8Srgb; + case PixelFormat::kB8G8R8A8UNormInt: + return vk::Format::eB8G8R8A8Unorm; + case PixelFormat::kB8G8R8A8UNormIntSRGB: + return vk::Format::eB8G8R8A8Srgb; + case PixelFormat::kR32G32B32A32Float: + return vk::Format::eR32G32B32A32Sfloat; + case PixelFormat::kR16G16B16A16Float: + return vk::Format::eR16G16B16A16Sfloat; + case PixelFormat::kS8UInt: + return vk::Format::eS8Uint; + case PixelFormat::kD24UnormS8Uint: + return vk::Format::eD24UnormS8Uint; + case PixelFormat::kD32FloatS8UInt: + return vk::Format::eD32SfloatS8Uint; + case PixelFormat::kR8UNormInt: + return vk::Format::eR8Unorm; + case PixelFormat::kR8G8UNormInt: + return vk::Format::eR8G8Unorm; + } + + FML_UNREACHABLE(); +} + +constexpr PixelFormat ToPixelFormat(vk::Format format) { + switch (format) { + case vk::Format::eUndefined: + return PixelFormat::kUnknown; + case vk::Format::eR8G8B8A8Unorm: + return PixelFormat::kR8G8B8A8UNormInt; + case vk::Format::eR8G8B8A8Srgb: + return PixelFormat::kR8G8B8A8UNormIntSRGB; + case vk::Format::eB8G8R8A8Unorm: + return PixelFormat::kB8G8R8A8UNormInt; + case vk::Format::eB8G8R8A8Srgb: + return PixelFormat::kB8G8R8A8UNormIntSRGB; + case vk::Format::eR32G32B32A32Sfloat: + return PixelFormat::kR32G32B32A32Float; + case vk::Format::eR16G16B16A16Sfloat: + return PixelFormat::kR16G16B16A16Float; + case vk::Format::eS8Uint: + return PixelFormat::kS8UInt; + case vk::Format::eD24UnormS8Uint: + return PixelFormat::kD24UnormS8Uint; + case vk::Format::eD32SfloatS8Uint: + return PixelFormat::kD32FloatS8UInt; + case vk::Format::eR8Unorm: + return PixelFormat::kR8UNormInt; + case vk::Format::eR8G8Unorm: + return PixelFormat::kR8G8UNormInt; + default: + return PixelFormat::kUnknown; + } +} + +constexpr vk::SampleCountFlagBits ToVKSampleCount(SampleCount sample_count) { + switch (sample_count) { + case SampleCount::kCount1: + return vk::SampleCountFlagBits::e1; + case SampleCount::kCount4: + return vk::SampleCountFlagBits::e4; + } + + FML_UNREACHABLE(); +} + +constexpr vk::Filter ToVKSamplerMinMagFilter(MinMagFilter filter) { + switch (filter) { + case MinMagFilter::kNearest: + return vk::Filter::eNearest; + case MinMagFilter::kLinear: + return vk::Filter::eLinear; + } + + FML_UNREACHABLE(); +} + +constexpr vk::SamplerMipmapMode ToVKSamplerMipmapMode(MipFilter filter) { + switch (filter) { + case MipFilter::kBase: + case MipFilter::kNearest: + return vk::SamplerMipmapMode::eNearest; + case MipFilter::kLinear: + return vk::SamplerMipmapMode::eLinear; + } + + FML_UNREACHABLE(); +} + +constexpr vk::SamplerAddressMode ToVKSamplerAddressMode( + SamplerAddressMode mode) { + switch (mode) { + case SamplerAddressMode::kRepeat: + return vk::SamplerAddressMode::eRepeat; + case SamplerAddressMode::kMirror: + return vk::SamplerAddressMode::eMirroredRepeat; + case SamplerAddressMode::kClampToEdge: + return vk::SamplerAddressMode::eClampToEdge; + case SamplerAddressMode::kDecal: + return vk::SamplerAddressMode::eClampToBorder; + } + + FML_UNREACHABLE(); +} + +constexpr vk::ShaderStageFlags ToVkShaderStage(ShaderStage stage) { + switch (stage) { + case ShaderStage::kUnknown: + return vk::ShaderStageFlagBits::eAll; + case ShaderStage::kFragment: + return vk::ShaderStageFlagBits::eFragment; + case ShaderStage::kCompute: + return vk::ShaderStageFlagBits::eCompute; + case ShaderStage::kVertex: + return vk::ShaderStageFlagBits::eVertex; + } + + FML_UNREACHABLE(); +} + +static_assert(static_cast(DescriptorType::kSampledImage) == + static_cast(vk::DescriptorType::eCombinedImageSampler)); +static_assert(static_cast(DescriptorType::kUniformBuffer) == + static_cast(vk::DescriptorType::eUniformBuffer)); +static_assert(static_cast(DescriptorType::kStorageBuffer) == + static_cast(vk::DescriptorType::eStorageBuffer)); +static_assert(static_cast(DescriptorType::kImage) == + static_cast(vk::DescriptorType::eSampledImage)); +static_assert(static_cast(DescriptorType::kSampler) == + static_cast(vk::DescriptorType::eSampler)); +static_assert(static_cast(DescriptorType::kInputAttachment) == + static_cast(vk::DescriptorType::eInputAttachment)); + +constexpr vk::DescriptorType ToVKDescriptorType(DescriptorType type) { + return static_cast(type); +} + +constexpr vk::DescriptorSetLayoutBinding ToVKDescriptorSetLayoutBinding( + const DescriptorSetLayout& layout) { + vk::DescriptorSetLayoutBinding binding; + binding.binding = layout.binding; + binding.descriptorCount = 1u; + binding.descriptorType = ToVKDescriptorType(layout.descriptor_type); + binding.stageFlags = ToVkShaderStage(layout.shader_stage); + return binding; +} + +constexpr vk::AttachmentLoadOp ToVKAttachmentLoadOp(LoadAction load_action) { + switch (load_action) { + case LoadAction::kLoad: + return vk::AttachmentLoadOp::eLoad; + case LoadAction::kClear: + return vk::AttachmentLoadOp::eClear; + case LoadAction::kDontCare: + return vk::AttachmentLoadOp::eDontCare; + } + + FML_UNREACHABLE(); +} + +constexpr vk::AttachmentStoreOp ToVKAttachmentStoreOp(StoreAction store_action, + bool is_resolve_texture) { + switch (store_action) { + case StoreAction::kStore: + // Both MSAA and resolve textures need to be stored. A resolve is NOT + // performed. + return vk::AttachmentStoreOp::eStore; + case StoreAction::kDontCare: + // Both MSAA and resolve textures can be discarded. A resolve is NOT + // performed. + return vk::AttachmentStoreOp::eDontCare; + case StoreAction::kMultisampleResolve: + // The resolve texture is stored but the MSAA texture can be discarded. A + // resolve IS performed. + return is_resolve_texture ? vk::AttachmentStoreOp::eStore + : vk::AttachmentStoreOp::eDontCare; + case StoreAction::kStoreAndMultisampleResolve: + // Both MSAA and resolve textures need to be stored. A resolve IS + // performed. + return vk::AttachmentStoreOp::eStore; + } + FML_UNREACHABLE(); +} + +constexpr bool StoreActionPerformsResolve(StoreAction store_action) { + switch (store_action) { + case StoreAction::kDontCare: + case StoreAction::kStore: + return false; + case StoreAction::kMultisampleResolve: + case StoreAction::kStoreAndMultisampleResolve: + return true; + } + FML_UNREACHABLE(); +} + +constexpr vk::IndexType ToVKIndexType(IndexType index_type) { + switch (index_type) { + case IndexType::k16bit: + return vk::IndexType::eUint16; + case IndexType::k32bit: + return vk::IndexType::eUint32; + case IndexType::kUnknown: + return vk::IndexType::eUint32; + case IndexType::kNone: + FML_UNREACHABLE(); + } + + FML_UNREACHABLE(); +} + +constexpr vk::PolygonMode ToVKPolygonMode(PolygonMode mode) { + switch (mode) { + case PolygonMode::kFill: + return vk::PolygonMode::eFill; + case PolygonMode::kLine: + return vk::PolygonMode::eLine; + } + FML_UNREACHABLE(); +} + +constexpr bool PrimitiveTopologySupportsPrimitiveRestart( + PrimitiveType primitive) { + switch (primitive) { + case PrimitiveType::kTriangleStrip: + case PrimitiveType::kLine: + case PrimitiveType::kPoint: + case PrimitiveType::kTriangleFan: + return true; + case PrimitiveType::kTriangle: + case PrimitiveType::kLineStrip: + return false; + } + FML_UNREACHABLE(); +} + +constexpr vk::PrimitiveTopology ToVKPrimitiveTopology(PrimitiveType primitive) { + switch (primitive) { + case PrimitiveType::kTriangle: + return vk::PrimitiveTopology::eTriangleList; + case PrimitiveType::kTriangleStrip: + return vk::PrimitiveTopology::eTriangleStrip; + case PrimitiveType::kLine: + return vk::PrimitiveTopology::eLineList; + case PrimitiveType::kLineStrip: + return vk::PrimitiveTopology::eLineStrip; + case PrimitiveType::kPoint: + return vk::PrimitiveTopology::ePointList; + case PrimitiveType::kTriangleFan: + return vk::PrimitiveTopology::eTriangleFan; + } + + FML_UNREACHABLE(); +} + +constexpr bool PixelFormatIsDepthStencil(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return false; + case PixelFormat::kS8UInt: + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return true; + } + return false; +} + +static constexpr vk::AttachmentReference kUnusedAttachmentReference = { + VK_ATTACHMENT_UNUSED, vk::ImageLayout::eUndefined}; + +constexpr vk::CullModeFlags ToVKCullModeFlags(CullMode mode) { + switch (mode) { + case CullMode::kNone: + return vk::CullModeFlagBits::eNone; + case CullMode::kFrontFace: + return vk::CullModeFlagBits::eFront; + case CullMode::kBackFace: + return vk::CullModeFlagBits::eBack; + } + FML_UNREACHABLE(); +} + +constexpr vk::CompareOp ToVKCompareOp(CompareFunction op) { + switch (op) { + case CompareFunction::kNever: + return vk::CompareOp::eNever; + case CompareFunction::kAlways: + return vk::CompareOp::eAlways; + case CompareFunction::kLess: + return vk::CompareOp::eLess; + case CompareFunction::kEqual: + return vk::CompareOp::eEqual; + case CompareFunction::kLessEqual: + return vk::CompareOp::eLessOrEqual; + case CompareFunction::kGreater: + return vk::CompareOp::eGreater; + case CompareFunction::kNotEqual: + return vk::CompareOp::eNotEqual; + case CompareFunction::kGreaterEqual: + return vk::CompareOp::eGreaterOrEqual; + } + FML_UNREACHABLE(); +} + +constexpr vk::StencilOp ToVKStencilOp(StencilOperation op) { + switch (op) { + case StencilOperation::kKeep: + return vk::StencilOp::eKeep; + case StencilOperation::kZero: + return vk::StencilOp::eZero; + case StencilOperation::kSetToReferenceValue: + return vk::StencilOp::eReplace; + case StencilOperation::kIncrementClamp: + return vk::StencilOp::eIncrementAndClamp; + case StencilOperation::kDecrementClamp: + return vk::StencilOp::eDecrementAndClamp; + case StencilOperation::kInvert: + return vk::StencilOp::eInvert; + case StencilOperation::kIncrementWrap: + return vk::StencilOp::eIncrementAndWrap; + case StencilOperation::kDecrementWrap: + return vk::StencilOp::eDecrementAndWrap; + break; + } + FML_UNREACHABLE(); +} + +constexpr vk::StencilOpState ToVKStencilOpState( + const StencilAttachmentDescriptor& desc) { + vk::StencilOpState state; + state.failOp = ToVKStencilOp(desc.stencil_failure); + state.passOp = ToVKStencilOp(desc.depth_stencil_pass); + state.depthFailOp = ToVKStencilOp(desc.depth_failure); + state.compareOp = ToVKCompareOp(desc.stencil_compare); + state.compareMask = desc.read_mask; + state.writeMask = desc.write_mask; + // This is irrelevant as the stencil references are always dynamic state and + // will be set in the render pass. + state.reference = 1988; + return state; +} + +constexpr vk::ImageAspectFlags ToVKImageAspectFlags(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return vk::ImageAspectFlagBits::eColor; + case PixelFormat::kS8UInt: + return vk::ImageAspectFlagBits::eStencil; + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return vk::ImageAspectFlagBits::eDepth | + vk::ImageAspectFlagBits::eStencil; + } + FML_UNREACHABLE(); +} + +constexpr uint32_t ToArrayLayerCount(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + case TextureType::kTexture2DMultisample: + return 1u; + case TextureType::kTextureCube: + return 6u; + case TextureType::kTextureExternalOES: + VALIDATION_LOG + << "kTextureExternalOES can not be used with the Vulkan backend."; + } + FML_UNREACHABLE(); +} + +constexpr vk::ImageViewType ToVKImageViewType(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + case TextureType::kTexture2DMultisample: + return vk::ImageViewType::e2D; + case TextureType::kTextureCube: + return vk::ImageViewType::eCube; + case TextureType::kTextureExternalOES: + VALIDATION_LOG + << "kTextureExternalOES can not be used with the Vulkan backend."; + } + FML_UNREACHABLE(); +} + +constexpr vk::ImageCreateFlags ToVKImageCreateFlags(TextureType type) { + switch (type) { + case TextureType::kTexture2D: + case TextureType::kTexture2DMultisample: + return {}; + case TextureType::kTextureCube: + return vk::ImageCreateFlagBits::eCubeCompatible; + case TextureType::kTextureExternalOES: + VALIDATION_LOG + << "kTextureExternalOES can not be used with the Vulkan backend."; + } + FML_UNREACHABLE(); +} + +vk::PipelineDepthStencilStateCreateInfo ToVKPipelineDepthStencilStateCreateInfo( + std::optional depth, + std::optional front, + std::optional back); + +constexpr vk::ImageAspectFlags ToImageAspectFlags(PixelFormat format) { + switch (format) { + case PixelFormat::kUnknown: + return {}; + case PixelFormat::kA8UNormInt: + case PixelFormat::kR8UNormInt: + case PixelFormat::kR8G8UNormInt: + case PixelFormat::kR8G8B8A8UNormInt: + case PixelFormat::kR8G8B8A8UNormIntSRGB: + case PixelFormat::kB8G8R8A8UNormInt: + case PixelFormat::kB8G8R8A8UNormIntSRGB: + case PixelFormat::kR32G32B32A32Float: + case PixelFormat::kR16G16B16A16Float: + case PixelFormat::kB10G10R10XR: + case PixelFormat::kB10G10R10XRSRGB: + case PixelFormat::kB10G10R10A10XR: + return vk::ImageAspectFlagBits::eColor; + case PixelFormat::kS8UInt: + return vk::ImageAspectFlagBits::eStencil; + case PixelFormat::kD24UnormS8Uint: + case PixelFormat::kD32FloatS8UInt: + return vk::ImageAspectFlagBits::eDepth | + vk::ImageAspectFlagBits::eStencil; + } + FML_UNREACHABLE(); +} + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_FORMATS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c0ecbfdd393a728519245664ea2cebc07500da8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/formats_vk_unittests.cc @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" // IWYU pragma: keep +#include "impeller/renderer/backend/vulkan/formats_vk.h" + +namespace impeller { +namespace testing { + +TEST(FormatsVKTest, DescriptorMapping) { + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kSampledImage), + vk::DescriptorType::eCombinedImageSampler); + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kUniformBuffer), + vk::DescriptorType::eUniformBuffer); + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kStorageBuffer), + vk::DescriptorType::eStorageBuffer); + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kImage), + vk::DescriptorType::eSampledImage); + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kSampler), + vk::DescriptorType::eSampler); + EXPECT_EQ(ToVKDescriptorType(DescriptorType::kInputAttachment), + vk::DescriptorType::eInputAttachment); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..4213c932355501641a17fcbcc089eb7a410ef57f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.cc @@ -0,0 +1,249 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" + +#include +#include +#include +#include + +#include "fml/logging.h" +#include "fml/trace_event.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" + +namespace impeller { + +static constexpr uint32_t kPoolSize = 128u; + +GPUTracerVK::GPUTracerVK(std::weak_ptr context, + bool enable_gpu_tracing) + : context_(std::move(context)) { + if (!enable_gpu_tracing) { + return; + } + timestamp_period_ = context_.lock() + ->GetDeviceHolder() + ->GetPhysicalDevice() + .getProperties() + .limits.timestampPeriod; + if (timestamp_period_ <= 0) { + // The device does not support timestamp queries. + return; + } +// Disable tracing in release mode. +#ifdef IMPELLER_DEBUG + enabled_ = true; +#endif // IMPELLER_DEBUG +} + +void GPUTracerVK::InitializeQueryPool(const ContextVK& context) { + if (!enabled_) { + return; + } + Lock lock(trace_state_mutex_); + std::shared_ptr buffer = context.CreateCommandBuffer(); + CommandBufferVK& buffer_vk = CommandBufferVK::Cast(*buffer); + + for (auto i = 0u; i < kTraceStatesSize; i++) { + vk::QueryPoolCreateInfo info; + info.queryCount = kPoolSize; + info.queryType = vk::QueryType::eTimestamp; + + auto [status, pool] = context.GetDevice().createQueryPoolUnique(info); + if (status != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create query pool."; + return; + } + trace_states_[i].query_pool = std::move(pool); + buffer_vk.GetCommandBuffer().resetQueryPool( + trace_states_[i].query_pool.get(), 0, kPoolSize); + } + if (!context.GetCommandQueue()->Submit({buffer}).ok()) { + VALIDATION_LOG << "Failed to reset query pool for trace events."; + enabled_ = false; + } +} + +bool GPUTracerVK::IsEnabled() const { + return enabled_; +} + +void GPUTracerVK::MarkFrameStart() { + if (!enabled_) { + return; + } + FML_DCHECK(!in_frame_); + in_frame_ = true; + raster_thread_id_ = std::this_thread::get_id(); +} + +void GPUTracerVK::MarkFrameEnd() { + in_frame_ = false; + + if (!enabled_) { + return; + } + + Lock lock(trace_state_mutex_); + current_state_ = (current_state_ + 1) % kTraceStatesSize; + + auto& state = trace_states_[current_state_]; + // If there are still pending buffers on the trace state we're switching to, + // that means that a cmd buffer we were relying on to signal this likely + // never finished. This shouldn't happen unless there is a bug in the + // encoder logic. We set it to zero anyway to prevent a validation error + // from becoming a memory leak. + FML_DCHECK(state.pending_buffers == 0u); + state.pending_buffers = 0; + state.current_index = 0; +} + +std::unique_ptr GPUTracerVK::CreateGPUProbe() { + return std::make_unique(weak_from_this()); +} + +void GPUTracerVK::RecordCmdBufferStart(const vk::CommandBuffer& buffer, + GPUProbe& probe) { + if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || + !in_frame_) { + return; + } + Lock lock(trace_state_mutex_); + auto& state = trace_states_[current_state_]; + + // Reset previously completed queries. + if (!states_to_reset_.empty()) { + for (auto i = 0u; i < states_to_reset_.size(); i++) { + buffer.resetQueryPool(trace_states_[states_to_reset_[i]].query_pool.get(), + 0, kPoolSize); + } + states_to_reset_.clear(); + } + + // We size the query pool to kPoolSize, but Flutter applications can create an + // unbounded amount of work per frame. If we encounter this, stop recording + // cmds. + if (state.current_index >= kPoolSize) { + return; + } + + buffer.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, + trace_states_[current_state_].query_pool.get(), + state.current_index); + state.current_index += 1; + probe.index_ = current_state_; + state.pending_buffers += 1; +} + +void GPUTracerVK::RecordCmdBufferEnd(const vk::CommandBuffer& buffer, + GPUProbe& probe) { + if (!enabled_ || std::this_thread::get_id() != raster_thread_id_ || + !in_frame_ || !probe.index_.has_value()) { + return; + } + Lock lock(trace_state_mutex_); + GPUTraceState& state = trace_states_[current_state_]; + + if (state.current_index >= kPoolSize) { + return; + } + + buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, + state.query_pool.get(), state.current_index); + + state.current_index += 1; +} + +void GPUTracerVK::OnFenceComplete(size_t frame_index) { + if (!enabled_) { + return; + } + + size_t pending = 0; + size_t query_count = 0; + vk::QueryPool pool; + { + Lock lock(trace_state_mutex_); + GPUTraceState& state = trace_states_[frame_index]; + + FML_DCHECK(state.pending_buffers > 0); + state.pending_buffers -= 1; + pending = state.pending_buffers; + query_count = state.current_index; + pool = state.query_pool.get(); + } + + if (pending == 0) { + std::vector bits(query_count); + std::shared_ptr context = context_.lock(); + if (!context) { + return; + } + + auto result = context->GetDevice().getQueryPoolResults( + pool, 0, query_count, query_count * sizeof(uint64_t), bits.data(), + sizeof(uint64_t), vk::QueryResultFlagBits::e64); + // This may return VK_NOT_READY if the query couldn't be completed, or if + // there are queries still pending. From local testing, this happens + // occassionally on very expensive frames. Its unclear if we can do anything + // about this, because by design this should only signal after all cmd + // buffers have signaled. Adding VK_QUERY_RESULT_WAIT_BIT to the flags + // passed to getQueryPoolResults seems like it would fix this, but actually + // seems to result in more stuck query errors. Better to just drop them and + // move on. + if (result == vk::Result::eSuccess) { + uint64_t smallest_timestamp = std::numeric_limits::max(); + uint64_t largest_timestamp = 0; + for (auto i = 0u; i < bits.size(); i++) { + smallest_timestamp = std::min(smallest_timestamp, bits[i]); + largest_timestamp = std::max(largest_timestamp, bits[i]); + } + auto gpu_ms = + (((largest_timestamp - smallest_timestamp) * timestamp_period_) / + 1000000); + FML_TRACE_COUNTER("flutter", "GPUTracer", + reinterpret_cast(this), // Trace Counter ID + "FrameTimeMS", gpu_ms); + } + + // Record this query to be reset the next time a command is recorded. + Lock lock(trace_state_mutex_); + states_to_reset_.push_back(frame_index); + } +} + +GPUProbe::GPUProbe(const std::weak_ptr& tracer) + : tracer_(tracer) {} + +GPUProbe::~GPUProbe() { + if (!index_.has_value()) { + return; + } + auto tracer = tracer_.lock(); + if (!tracer) { + return; + } + tracer->OnFenceComplete(index_.value()); +} + +void GPUProbe::RecordCmdBufferStart(const vk::CommandBuffer& buffer) { + auto tracer = tracer_.lock(); + if (!tracer) { + return; + } + tracer->RecordCmdBufferStart(buffer, *this); +} + +void GPUProbe::RecordCmdBufferEnd(const vk::CommandBuffer& buffer) { + auto tracer = tracer_.lock(); + if (!tracer) { + return; + } + tracer->RecordCmdBufferEnd(buffer, *this); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..ee6c0e4c34601ac8e5d70615e9f6a1a1d49103c6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/gpu_tracer_vk.h @@ -0,0 +1,127 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_GPU_TRACER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_GPU_TRACER_VK_H_ + +#include +#include + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { + +class GPUProbe; + +/// @brief A class that uses timestamp queries to record the approximate GPU +/// execution time. +/// +/// To enable, add the following metadata to the application's Android manifest: +/// +class GPUTracerVK : public std::enable_shared_from_this { + public: + GPUTracerVK(std::weak_ptr context, bool enable_gpu_tracing); + + ~GPUTracerVK() = default; + + /// @brief Create a GPUProbe to trace the execution of a command buffer on the + /// GPU. + std::unique_ptr CreateGPUProbe(); + + /// @brief Signal the start of a frame workload. + /// + /// Any cmd buffers that are created after this call and before + /// [MarkFrameEnd] will be attributed to the current frame. + void MarkFrameStart(); + + /// @brief Signal the end of a frame workload. + void MarkFrameEnd(); + + // visible for testing. + bool IsEnabled() const; + + /// Initialize the set of query pools. + void InitializeQueryPool(const ContextVK& context); + + private: + friend class GPUProbe; + + static const constexpr size_t kTraceStatesSize = 16u; + + /// @brief Signal that the cmd buffer is completed. + /// + /// If [frame_index] is std::nullopt, this frame recording is ignored. + void OnFenceComplete(size_t frame); + + /// @brief Record a timestamp query into the provided cmd buffer to record + /// start time. + void RecordCmdBufferStart(const vk::CommandBuffer& buffer, GPUProbe& probe); + + /// @brief Record a timestamp query into the provided cmd buffer to record end + /// time. + void RecordCmdBufferEnd(const vk::CommandBuffer& buffer, GPUProbe& probe); + + std::weak_ptr context_; + + struct GPUTraceState { + size_t current_index = 0; + size_t pending_buffers = 0; + vk::UniqueQueryPool query_pool; + }; + + mutable Mutex trace_state_mutex_; + GPUTraceState trace_states_[kTraceStatesSize] IPLR_GUARDED_BY( + trace_state_mutex_); + size_t current_state_ IPLR_GUARDED_BY(trace_state_mutex_) = 0u; + std::vector IPLR_GUARDED_BY(trace_state_mutex_) states_to_reset_ = {}; + + // The number of nanoseconds for each timestamp unit. + float timestamp_period_ = 1; + + // If in_frame_ is not true, then this cmd buffer was started as a part of + // some non-frame workload like image decoding. We should not record this as + // part of the frame workload, as the gap between this non-frame and a + // frameworkload may be substantial. For example, support the engine creates a + // cmd buffer to perform an image upload at timestamp 0 and then 30 ms later + // actually renders a frame. Without the in_frame_ guard, the GPU frame time + // would include this 30ms gap during which the engine was idle. + bool in_frame_ = false; + + // Track the raster thread id to avoid recording mipmap/image cmd buffers + // that are not guaranteed to start/end according to frame boundaries. + std::thread::id raster_thread_id_; + bool enabled_ = false; +}; + +class GPUProbe { + public: + explicit GPUProbe(const std::weak_ptr& tracer); + + GPUProbe(GPUProbe&&) = delete; + GPUProbe& operator=(GPUProbe&&) = delete; + + ~GPUProbe(); + + /// @brief Record a timestamp query into the provided cmd buffer to record + /// start time. + void RecordCmdBufferStart(const vk::CommandBuffer& buffer); + + /// @brief Record a timestamp query into the provided cmd buffer to record end + /// time. + void RecordCmdBufferEnd(const vk::CommandBuffer& buffer); + + private: + friend class GPUTracerVK; + + std::weak_ptr tracer_; + std::optional index_ = std::nullopt; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_GPU_TRACER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/limits_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/limits_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..4303d7d94db60877e0226dc9ae9135fd7e41eac0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/limits_vk.h @@ -0,0 +1,17 @@ +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_LIMITS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_LIMITS_VK_H_ + +#include + +namespace impeller { + +// Maximum size to use VMA image suballocation. Any allocation greater than or +// equal to this value will use a dedicated VkDeviceMemory. +// +// This value was taken from ANGLE. +constexpr size_t kImageSizeThresholdForDedicatedMemoryAllocation = + 4 * 1024 * 1024; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_LIMITS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..ecb46b7831642aa43a8402b37d91d646246c311e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.cc @@ -0,0 +1,121 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h" + +#include "flutter/fml/file.h" +#include "impeller/base/allocation.h" +#include "impeller/base/validation.h" + +namespace impeller { + +static constexpr const char* kPipelineCacheFileName = + "flutter.impeller.vkcache"; + +bool PipelineCacheDataPersist(const fml::UniqueFD& cache_directory, + const VkPhysicalDeviceProperties& props, + const vk::UniquePipelineCache& cache) { + if (!cache_directory.is_valid()) { + return false; + } + size_t data_size = 0u; + if (cache.getOwner().getPipelineCacheData(*cache, &data_size, nullptr) != + vk::Result::eSuccess) { + VALIDATION_LOG << "Could not fetch pipeline cache size."; + return false; + } + if (data_size == 0u) { + return true; + } + auto allocation = std::make_shared(); + if (!allocation->Truncate(Bytes{sizeof(PipelineCacheHeaderVK) + data_size}, + false)) { + VALIDATION_LOG << "Could not allocate pipeline cache data staging buffer."; + return false; + } + const auto header = PipelineCacheHeaderVK{props, data_size}; + std::memcpy(allocation->GetBuffer(), &header, sizeof(header)); + vk::Result lookup_result = cache.getOwner().getPipelineCacheData( + *cache, &data_size, allocation->GetBuffer() + sizeof(header)); + + // Some drivers may return incomplete erroneously, but this is not an + // error condition as some/all data was still written. + if (lookup_result != vk::Result::eSuccess && + lookup_result != vk::Result::eIncomplete) { + VALIDATION_LOG << "Could not copy pipeline cache data."; + return false; + } + + auto allocation_mapping = CreateMappingFromAllocation(allocation); + if (!allocation_mapping) { + return false; + } + if (!fml::WriteAtomically(cache_directory, kPipelineCacheFileName, + *allocation_mapping)) { + VALIDATION_LOG << "Could not write cache file to disk."; + return false; + } + return true; +} + +std::unique_ptr PipelineCacheDataRetrieve( + const fml::UniqueFD& cache_directory, + const VkPhysicalDeviceProperties& props) { + if (!cache_directory.is_valid()) { + return nullptr; + } + std::shared_ptr on_disk_data = + fml::FileMapping::CreateReadOnly(cache_directory, kPipelineCacheFileName); + if (!on_disk_data) { + return nullptr; + } + if (on_disk_data->GetSize() < sizeof(PipelineCacheHeaderVK)) { + VALIDATION_LOG << "Pipeline cache data size is too small."; + return nullptr; + } + auto on_disk_header = PipelineCacheHeaderVK{}; + std::memcpy(&on_disk_header, // + on_disk_data->GetMapping(), // + sizeof(on_disk_header) // + ); + const auto current_header = PipelineCacheHeaderVK{props, 0u}; + if (!on_disk_header.IsCompatibleWith(current_header)) { + FML_LOG(WARNING) + << "Persisted pipeline cache is not compatible with current " + "Vulkan context. Ignoring."; + return nullptr; + } + // Zero sized data is known to cause issues. + if (on_disk_header.data_size == 0u) { + return nullptr; + } + return std::make_unique( + on_disk_data->GetMapping() + sizeof(on_disk_header), + on_disk_header.data_size, [on_disk_data](auto, auto) {}); +} + +PipelineCacheHeaderVK::PipelineCacheHeaderVK() = default; + +PipelineCacheHeaderVK::PipelineCacheHeaderVK( + const VkPhysicalDeviceProperties& props, + uint64_t p_data_size) + : driver_version(props.driverVersion), + vendor_id(props.vendorID), + device_id(props.deviceID), + data_size(p_data_size) { + std::memcpy(uuid, props.pipelineCacheUUID, VK_UUID_SIZE); +} + +bool PipelineCacheHeaderVK::IsCompatibleWith( + const PipelineCacheHeaderVK& o) const { + // Check for everything but the data size. + return magic == o.magic && // + driver_version == o.driver_version && // + vendor_id == o.vendor_id && // + device_id == o.device_id && // + abi == o.abi && // + std::memcmp(uuid, o.uuid, VK_UUID_SIZE) == 0; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..fa39062d7fe2582581958ae698e4d40b520144c8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_DATA_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_DATA_VK_H_ + +#include "flutter/fml/mapping.h" +#include "flutter/fml/unique_fd.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief An Impeller specific header prepended to all pipeline cache +/// information that is persisted on disk. This information is used +/// to perform additional integrity checks that may have been missed +/// by the Vulkan driver. +/// +/// Inspired by +/// https://medium.com/@zeuxcg/creating-a-robust-pipeline-cache-with-vulkan-961d09416cda. +/// +struct PipelineCacheHeaderVK { + // This can be used by Impeller to manually invalidate all old caches. + uint32_t magic = 0xC0DEF00D; + // Notably, this field is missing from checks the Vulkan driver performs. For + // drivers that don't correctly check the UUID, explicitly disregarding caches + // generated by previous driver versions sidesteps some landmines. + uint32_t driver_version = 0; + uint32_t vendor_id = 0; + uint32_t device_id = 0; + // If applications are published as 32-bit and updated via the app store to be + // 64-bits, this check comes in handy to disregard previous caches. + uint32_t abi = sizeof(void*); + uint8_t uuid[VK_UUID_SIZE] = {}; + uint64_t data_size = 0; + + //---------------------------------------------------------------------------- + /// @brief Constructs a new empty instance. + /// + PipelineCacheHeaderVK(); + + //---------------------------------------------------------------------------- + /// @brief Constructs a new instance that will be compatible with the + /// given physical device properties. + /// + /// @param[in] props The properties. + /// @param[in] p_data_size The data size. + /// + explicit PipelineCacheHeaderVK(const VkPhysicalDeviceProperties& props, + uint64_t p_data_size); + + //---------------------------------------------------------------------------- + /// @brief Determines whether the specified o is compatible with. + /// + /// The size of the data following the header may be different and + /// is not part of compatibility checks. + /// + /// @param[in] other The other header. + /// + /// @return True if the specified header is compatible with this one, + /// False otherwise. The size of the data following the header may + /// be different. + /// + bool IsCompatibleWith(const PipelineCacheHeaderVK& other) const; +}; + +//------------------------------------------------------------------------------ +/// @brief Persist the pipeline cache to a file in the given cache +/// directory. This function performs integrity checks the Vulkan +/// driver may have missed. +/// +/// @warning The pipeline cache must be externally synchronized for most +/// complete results. If additional pipelines are being created +/// while this function is executing, this function may fail to +/// persist data. +/// +/// @param[in] cache_directory The cache directory +/// @param[in] props The physical device properties +/// @param[in] cache The cache +/// +/// @return If the cache data could be persisted to disk. +/// +bool PipelineCacheDataPersist(const fml::UniqueFD& cache_directory, + const VkPhysicalDeviceProperties& props, + const vk::UniquePipelineCache& cache); + +//------------------------------------------------------------------------------ +/// @brief Retrieve the previously persisted pipeline cache data. This +/// function provides integrity checks the Vulkan driver may have +/// missed. +/// +/// The data is stripped of any additional headers that perform +/// integrity checks. It can be used directly to construct a +/// pre-initialized Vulkan pipeline cache. +/// +/// @param[in] cache_directory The cache directory +/// @param[in] props The properties +/// +/// @return The cache data if it was found and checked to have passed +/// additional integrity checks. +/// +std::unique_ptr PipelineCacheDataRetrieve( + const fml::UniqueFD& cache_directory, + const VkPhysicalDeviceProperties& props); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_DATA_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a5f4ee41b41a238d19a7d3b076df3dcdab9a254 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_data_vk_unittests.cc @@ -0,0 +1,148 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/build_config.h" +#include "flutter/fml/file.h" +#include "flutter/testing/testing.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" + +namespace impeller::testing { + +TEST(PipelineCacheDataVKTest, CanTestHeaderCompatibility) { + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + EXPECT_EQ(a.abi, sizeof(void*)); +#ifdef FML_ARCH_CPU_64_BITS + EXPECT_EQ(a.abi, 8u); +#elif FML_ARCH_CPU_32_BITS + EXPECT_EQ(a.abi, 4u); +#endif + EXPECT_TRUE(a.IsCompatibleWith(b)); + } + // Different data sizes don't matter. + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + a.data_size = b.data_size + 100u; + EXPECT_TRUE(a.IsCompatibleWith(b)); + } + // Magic, Driver, vendor, ABI, and UUID matter. + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + b.magic = 100; + EXPECT_FALSE(a.IsCompatibleWith(b)); + } + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + b.driver_version = 100; + EXPECT_FALSE(a.IsCompatibleWith(b)); + } + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + b.vendor_id = 100; + EXPECT_FALSE(a.IsCompatibleWith(b)); + } + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + b.device_id = 100; + EXPECT_FALSE(a.IsCompatibleWith(b)); + } + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + b.abi = a.abi / 2u; + EXPECT_FALSE(a.IsCompatibleWith(b)); + } + { + PipelineCacheHeaderVK a; + PipelineCacheHeaderVK b; + for (size_t i = 0; i < VK_UUID_SIZE; i++) { + b.uuid[i] = a.uuid[i] + 1; + } + EXPECT_FALSE(a.IsCompatibleWith(b)); + } +} + +TEST(PipelineCacheDataVKTest, CanCreateFromDeviceProperties) { + vk::PhysicalDeviceProperties props; + std::array uuid{ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + }; + props.pipelineCacheUUID = uuid; + props.deviceID = 10; + props.vendorID = 11; + props.driverVersion = 12; + PipelineCacheHeaderVK header(props, 99); + EXPECT_EQ(uuid.size(), std::size(header.uuid)); + EXPECT_EQ(props.deviceID, header.device_id); + EXPECT_EQ(props.vendorID, header.vendor_id); + EXPECT_EQ(props.driverVersion, header.driver_version); + for (size_t i = 0; i < uuid.size(); i++) { + EXPECT_EQ(header.uuid[i], uuid.at(i)); + } +} + +using PipelineCacheDataVKPlaygroundTest = PlaygroundTest; +INSTANTIATE_VULKAN_PLAYGROUND_SUITE(PipelineCacheDataVKPlaygroundTest); + +TEST_P(PipelineCacheDataVKPlaygroundTest, CanPersistAndRetrievePipelineCache) { + fml::ScopedTemporaryDirectory temp_dir; + const auto& surface_context = SurfaceContextVK::Cast(*GetContext()); + const auto& context_vk = ContextVK::Cast(*surface_context.GetParent()); + const auto& caps = CapabilitiesVK::Cast(*context_vk.GetCapabilities()); + + { + auto cache = context_vk.GetDevice().createPipelineCacheUnique({}); + ASSERT_EQ(cache.result, vk::Result::eSuccess); + ASSERT_FALSE(fml::FileExists(temp_dir.fd(), "flutter.impeller.vkcache")); + ASSERT_TRUE(PipelineCacheDataPersist( + temp_dir.fd(), caps.GetPhysicalDeviceProperties(), cache.value)); + } + ASSERT_TRUE(fml::FileExists(temp_dir.fd(), "flutter.impeller.vkcache")); + + auto mapping = PipelineCacheDataRetrieve(temp_dir.fd(), + caps.GetPhysicalDeviceProperties()); + ASSERT_NE(mapping, nullptr); + // Assert that the utility has stripped away the cache header giving us clean + // pipeline cache bootstrap information. + vk::PipelineCacheHeaderVersionOne vk_cache_header; + ASSERT_GE(mapping->GetSize(), sizeof(vk_cache_header)); + std::memcpy(&vk_cache_header, mapping->GetMapping(), sizeof(vk_cache_header)); + ASSERT_EQ(vk_cache_header.headerVersion, + vk::PipelineCacheHeaderVersion::eOne); +} + +TEST_P(PipelineCacheDataVKPlaygroundTest, + IntegrityChecksArePerformedOnPersistedData) { + fml::ScopedTemporaryDirectory temp_dir; + const auto& surface_context = SurfaceContextVK::Cast(*GetContext()); + const auto& context_vk = ContextVK::Cast(*surface_context.GetParent()); + const auto& caps = CapabilitiesVK::Cast(*context_vk.GetCapabilities()); + + { + auto cache = context_vk.GetDevice().createPipelineCacheUnique({}); + ASSERT_EQ(cache.result, vk::Result::eSuccess); + ASSERT_FALSE(fml::FileExists(temp_dir.fd(), "flutter.impeller.vkcache")); + ASSERT_TRUE(PipelineCacheDataPersist( + temp_dir.fd(), caps.GetPhysicalDeviceProperties(), cache.value)); + } + ASSERT_TRUE(fml::FileExists(temp_dir.fd(), "flutter.impeller.vkcache")); + auto incompatible_caps = caps.GetPhysicalDeviceProperties(); + // Simulate a driver version bump. + incompatible_caps.driverVersion = + caps.GetPhysicalDeviceProperties().driverVersion + 1u; + auto mapping = PipelineCacheDataRetrieve(temp_dir.fd(), incompatible_caps); + ASSERT_EQ(mapping, nullptr); +} + +} // namespace impeller::testing diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c7818f834805d4666d19acdabfff7940af234c0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.cc @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/123467 + +#include "impeller/renderer/backend/vulkan/pipeline_cache_vk.h" + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/allocation_size.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/pipeline_cache_data_vk.h" + +namespace impeller { + +PipelineCacheVK::PipelineCacheVK(std::shared_ptr caps, + std::shared_ptr device_holder, + fml::UniqueFD cache_directory) + : caps_(std::move(caps)), + device_holder_(device_holder), + cache_directory_(std::move(cache_directory)) { + if (!caps_ || !device_holder->GetDevice()) { + return; + } + + const auto& vk_caps = CapabilitiesVK::Cast(*caps_); + + auto existing_cache_data = PipelineCacheDataRetrieve( + cache_directory_, vk_caps.GetPhysicalDeviceProperties()); + + vk::PipelineCacheCreateInfo cache_info; + if (existing_cache_data) { + cache_info.initialDataSize = existing_cache_data->GetSize(); + cache_info.pInitialData = existing_cache_data->GetMapping(); + } + + auto [result, existing_cache] = + device_holder->GetDevice().createPipelineCacheUnique(cache_info); + + if (result == vk::Result::eSuccess) { + cache_ = std::move(existing_cache); + } else { + // Even though we perform consistency checks because we don't trust the + // driver, the driver may have additional information that may cause it to + // reject the cache too. + FML_LOG(INFO) << "Existing pipeline cache was invalid: " + << vk::to_string(result) << ". Starting with a fresh cache."; + cache_info.pInitialData = nullptr; + cache_info.initialDataSize = 0u; + auto [result2, new_cache] = + device_holder->GetDevice().createPipelineCacheUnique(cache_info); + if (result2 == vk::Result::eSuccess) { + cache_ = std::move(new_cache); + } else { + VALIDATION_LOG << "Could not create new pipeline cache: " + << vk::to_string(result2); + } + } + + is_valid_ = !!cache_; +} + +PipelineCacheVK::~PipelineCacheVK() { + std::shared_ptr device_holder = device_holder_.lock(); + if (device_holder) { + cache_.reset(); + } else { + cache_.release(); + } +} + +bool PipelineCacheVK::IsValid() const { + return is_valid_; +} + +vk::UniquePipeline PipelineCacheVK::CreatePipeline( + const vk::GraphicsPipelineCreateInfo& info) { + std::shared_ptr strong_device = device_holder_.lock(); + if (!strong_device) { + return {}; + } + + auto [result, pipeline] = + strong_device->GetDevice().createGraphicsPipelineUnique(*cache_, info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create graphics pipeline: " + << vk::to_string(result); + } + return std::move(pipeline); +} + +vk::UniquePipeline PipelineCacheVK::CreatePipeline( + const vk::ComputePipelineCreateInfo& info) { + std::shared_ptr strong_device = device_holder_.lock(); + if (!strong_device) { + return {}; + } + + auto [result, pipeline] = + strong_device->GetDevice().createComputePipelineUnique(*cache_, info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create compute pipeline: " + << vk::to_string(result); + } + return std::move(pipeline); +} + +void PipelineCacheVK::PersistCacheToDisk() const { + if (!is_valid_) { + return; + } + const auto& vk_caps = CapabilitiesVK::Cast(*caps_); + PipelineCacheDataPersist(cache_directory_, // + vk_caps.GetPhysicalDeviceProperties(), // + cache_ // + ); +} + +const CapabilitiesVK* PipelineCacheVK::GetCapabilities() const { + return CapabilitiesVK::Cast(caps_.get()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..216cf9d32e39727c252dc2eed7950a43116cf2f5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_cache_vk.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_VK_H_ + +#include "flutter/fml/file.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" + +namespace impeller { + +class PipelineCacheVK { + public: + // The [device] is passed in directly so that it can be used in the + // constructor directly. The [device_holder] isn't guaranteed to be valid + // at the time of executing `PipelineCacheVK` because of how `ContextVK` does + // initialization. + explicit PipelineCacheVK(std::shared_ptr caps, + std::shared_ptr device_holder, + fml::UniqueFD cache_directory); + + ~PipelineCacheVK(); + + bool IsValid() const; + + vk::UniquePipeline CreatePipeline(const vk::GraphicsPipelineCreateInfo& info); + + vk::UniquePipeline CreatePipeline(const vk::ComputePipelineCreateInfo& info); + + const CapabilitiesVK* GetCapabilities() const; + + void PersistCacheToDisk() const; + + private: + const std::shared_ptr caps_; + std::weak_ptr device_holder_; + const fml::UniqueFD cache_directory_; + vk::UniquePipelineCache cache_; + bool is_valid_ = false; + + PipelineCacheVK(const PipelineCacheVK&) = delete; + + PipelineCacheVK& operator=(const PipelineCacheVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_CACHE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..109b406467566c89a4b341be9f4e4931d8e409f1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.cc @@ -0,0 +1,306 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h" + +#include + +#include "flutter/fml/container.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/promise.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/shader_function_vk.h" + +namespace impeller { + +PipelineLibraryVK::PipelineLibraryVK( + const std::shared_ptr& device_holder, + std::shared_ptr caps, + fml::UniqueFD cache_directory, + std::shared_ptr worker_task_runner) + : device_holder_(device_holder), + pso_cache_(std::make_shared(std::move(caps), + device_holder, + std::move(cache_directory))), + worker_task_runner_(std::move(worker_task_runner)) { + FML_DCHECK(worker_task_runner_); + if (!pso_cache_->IsValid() || !worker_task_runner_) { + return; + } + + is_valid_ = true; +} + +PipelineLibraryVK::~PipelineLibraryVK() = default; + +// |PipelineLibrary| +bool PipelineLibraryVK::IsValid() const { + return is_valid_; +} + +std::unique_ptr PipelineLibraryVK::CreateComputePipeline( + const ComputePipelineDescriptor& desc, + PipelineKey pipeline_key) { + TRACE_EVENT0("flutter", __FUNCTION__); + vk::ComputePipelineCreateInfo pipeline_info; + + //---------------------------------------------------------------------------- + /// Shader Stage + /// + const auto entrypoint = desc.GetStageEntrypoint(); + if (!entrypoint) { + VALIDATION_LOG << "Compute shader is missing an entrypoint."; + return nullptr; + } + + std::shared_ptr strong_device = device_holder_.lock(); + if (!strong_device) { + return nullptr; + } + auto device_properties = strong_device->GetPhysicalDevice().getProperties(); + auto max_wg_size = device_properties.limits.maxComputeWorkGroupSize; + + // Give all compute shaders a specialization constant entry for the + // workgroup/threadgroup size. + vk::SpecializationMapEntry specialization_map_entry[1]; + + uint32_t workgroup_size_x = max_wg_size[0]; + specialization_map_entry[0].constantID = 0; + specialization_map_entry[0].offset = 0; + specialization_map_entry[0].size = sizeof(uint32_t); + + vk::SpecializationInfo specialization_info; + specialization_info.mapEntryCount = 1; + specialization_info.pMapEntries = &specialization_map_entry[0]; + specialization_info.dataSize = sizeof(uint32_t); + specialization_info.pData = &workgroup_size_x; + + vk::PipelineShaderStageCreateInfo info; + info.setStage(vk::ShaderStageFlagBits::eCompute); + info.setPName("main"); + info.setModule(ShaderFunctionVK::Cast(entrypoint.get())->GetModule()); + info.setPSpecializationInfo(&specialization_info); + pipeline_info.setStage(info); + + //---------------------------------------------------------------------------- + /// Pipeline Layout a.k.a the descriptor sets and uniforms. + /// + std::vector desc_bindings; + + for (auto layout : desc.GetDescriptorSetLayouts()) { + auto vk_desc_layout = ToVKDescriptorSetLayoutBinding(layout); + desc_bindings.push_back(vk_desc_layout); + } + + vk::DescriptorSetLayoutCreateInfo descs_layout_info; + descs_layout_info.setBindings(desc_bindings); + + auto [descs_result, descs_layout] = + strong_device->GetDevice().createDescriptorSetLayoutUnique( + descs_layout_info); + if (descs_result != vk::Result::eSuccess) { + VALIDATION_LOG << "unable to create uniform descriptors"; + return nullptr; + } + + ContextVK::SetDebugName(strong_device->GetDevice(), descs_layout.get(), + "Descriptor Set Layout " + desc.GetLabel()); + + //---------------------------------------------------------------------------- + /// Create the pipeline layout. + /// + vk::PipelineLayoutCreateInfo pipeline_layout_info; + pipeline_layout_info.setSetLayouts(descs_layout.get()); + auto pipeline_layout = strong_device->GetDevice().createPipelineLayoutUnique( + pipeline_layout_info); + if (pipeline_layout.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create pipeline layout for pipeline " + << desc.GetLabel() << ": " + << vk::to_string(pipeline_layout.result); + return nullptr; + } + pipeline_info.setLayout(pipeline_layout.value.get()); + + //---------------------------------------------------------------------------- + /// Finally, all done with the setup info. Create the pipeline itself. + /// + auto pipeline = pso_cache_->CreatePipeline(pipeline_info); + if (!pipeline) { + VALIDATION_LOG << "Could not create graphics pipeline: " << desc.GetLabel(); + return nullptr; + } + + ContextVK::SetDebugName(strong_device->GetDevice(), *pipeline_layout.value, + "Pipeline Layout " + desc.GetLabel()); + ContextVK::SetDebugName(strong_device->GetDevice(), *pipeline, + "Pipeline " + desc.GetLabel()); + + return std::make_unique( + device_holder_, + weak_from_this(), // + desc, // + std::move(pipeline), // + std::move(pipeline_layout.value), // + std::move(descs_layout), // + pipeline_key); +} + +// |PipelineLibrary| +PipelineFuture PipelineLibraryVK::GetPipeline( + PipelineDescriptor descriptor, + bool async) { + Lock lock(pipelines_mutex_); + if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) { + return found->second; + } + + cache_dirty_ = true; + if (!IsValid()) { + return { + descriptor, + RealizedFuture>>(nullptr)}; + } + + auto promise = std::make_shared< + NoExceptionPromise>>>(); + auto pipeline_future = + PipelineFuture{descriptor, promise->get_future()}; + pipelines_[descriptor] = pipeline_future; + + auto weak_this = weak_from_this(); + + PipelineKey next_key = pipeline_key_++; + auto generation_task = [descriptor, weak_this, promise, next_key]() { + auto thiz = weak_this.lock(); + if (!thiz) { + promise->set_value(nullptr); + VALIDATION_LOG << "Pipeline library was collected before the pipeline " + "could be created."; + return; + } + + promise->set_value(PipelineVK::Create( + descriptor, // + PipelineLibraryVK::Cast(*thiz).device_holder_.lock(), // + weak_this, // + next_key // + )); + }; + + if (async) { + worker_task_runner_->PostTask(generation_task); + } else { + generation_task(); + } + + return pipeline_future; +} + +// |PipelineLibrary| +PipelineFuture PipelineLibraryVK::GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) { + Lock lock(pipelines_mutex_); + if (auto found = compute_pipelines_.find(descriptor); + found != compute_pipelines_.end()) { + return found->second; + } + + cache_dirty_ = true; + if (!IsValid()) { + return { + descriptor, + RealizedFuture>>( + nullptr)}; + } + + auto promise = std::make_shared< + std::promise>>>(); + auto pipeline_future = PipelineFuture{ + descriptor, promise->get_future()}; + compute_pipelines_[descriptor] = pipeline_future; + + auto weak_this = weak_from_this(); + + PipelineKey next_key = pipeline_key_++; + auto generation_task = [descriptor, weak_this, promise, next_key]() { + auto self = weak_this.lock(); + if (!self) { + promise->set_value(nullptr); + VALIDATION_LOG << "Pipeline library was collected before the pipeline " + "could be created."; + return; + } + + auto pipeline = PipelineLibraryVK::Cast(*self).CreateComputePipeline( + descriptor, next_key); + if (!pipeline) { + promise->set_value(nullptr); + VALIDATION_LOG << "Could not create pipeline: " << descriptor.GetLabel(); + return; + } + + promise->set_value(std::move(pipeline)); + }; + + if (async) { + worker_task_runner_->PostTask(generation_task); + } else { + generation_task(); + } + + return pipeline_future; +} + +// |PipelineLibrary| +bool PipelineLibraryVK::HasPipeline(const PipelineDescriptor& descriptor) { + Lock lock(pipelines_mutex_); + return pipelines_.find(descriptor) != pipelines_.end(); +} + +// |PipelineLibrary| +void PipelineLibraryVK::RemovePipelinesWithEntryPoint( + std::shared_ptr function) { + Lock lock(pipelines_mutex_); + + fml::erase_if(pipelines_, [&](auto item) { + return item->first.GetEntrypointForStage(function->GetStage()) + ->IsEqual(*function); + }); +} + +void PipelineLibraryVK::DidAcquireSurfaceFrame() { + if (++frames_acquired_ == 50u) { + if (cache_dirty_) { + cache_dirty_ = false; + PersistPipelineCacheToDisk(); + } + frames_acquired_ = 0; + } +} + +void PipelineLibraryVK::PersistPipelineCacheToDisk() { + worker_task_runner_->PostTask( + [weak_cache = decltype(pso_cache_)::weak_type(pso_cache_)]() { + auto cache = weak_cache.lock(); + if (!cache) { + return; + } + cache->PersistCacheToDisk(); + }); +} + +const std::shared_ptr& PipelineLibraryVK::GetPSOCache() const { + return pso_cache_; +} + +const std::shared_ptr& +PipelineLibraryVK::GetWorkerTaskRunner() const { + return worker_task_runner_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..2c2eac667b9e15d375e4fdfd5539524117689144 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_library_vk.h @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_ + +#include + +#include "flutter/fml/concurrent_message_loop.h" +#include "flutter/fml/unique_fd.h" +#include "impeller/base/backend_cast.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/compute_pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_cache_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/pipeline.h" +#include "impeller/renderer/pipeline_library.h" + +namespace impeller { + +class ContextVK; + +class PipelineLibraryVK final + : public PipelineLibrary, + public BackendCast { + public: + // |PipelineLibrary| + ~PipelineLibraryVK() override; + + void DidAcquireSurfaceFrame(); + + const std::shared_ptr& GetPSOCache() const; + + const std::shared_ptr& GetWorkerTaskRunner() const; + + private: + friend ContextVK; + + std::weak_ptr device_holder_; + std::shared_ptr pso_cache_; + std::shared_ptr worker_task_runner_; + Mutex pipelines_mutex_; + PipelineMap pipelines_ IPLR_GUARDED_BY(pipelines_mutex_); + ComputePipelineMap compute_pipelines_ IPLR_GUARDED_BY(pipelines_mutex_); + std::atomic_size_t frames_acquired_ = 0u; + PipelineKey pipeline_key_ IPLR_GUARDED_BY(pipelines_mutex_) = 1; + bool is_valid_ = false; + bool cache_dirty_ = false; + + PipelineLibraryVK( + const std::shared_ptr& device_holder, + std::shared_ptr caps, + fml::UniqueFD cache_directory, + std::shared_ptr worker_task_runner); + + // |PipelineLibrary| + bool IsValid() const override; + + // |PipelineLibrary| + PipelineFuture GetPipeline(PipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + PipelineFuture GetPipeline( + ComputePipelineDescriptor descriptor, + bool async) override; + + // |PipelineLibrary| + bool HasPipeline(const PipelineDescriptor& descriptor) override; + + // |PipelineLibrary| + void RemovePipelinesWithEntryPoint( + std::shared_ptr function) override; + + std::unique_ptr CreateComputePipeline( + const ComputePipelineDescriptor& desc, + PipelineKey pipeline_key); + + void PersistPipelineCacheToDisk(); + + PipelineLibraryVK(const PipelineLibraryVK&) = delete; + + PipelineLibraryVK& operator=(const PipelineLibraryVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_LIBRARY_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..72ba5b99be8cd9d0900c7cf2232fad3404b6eace --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.cc @@ -0,0 +1,592 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" + +#include "flutter/fml/make_copyable.h" +#include "flutter/fml/status_or.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/strings.h" +#include "impeller/base/timing.h" +#include "impeller/renderer/backend/vulkan/capabilities_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/shader_function_vk.h" +#include "impeller/renderer/backend/vulkan/vertex_descriptor_vk.h" + +namespace impeller { + +static vk::PipelineCreationFeedbackEXT EmptyFeedback() { + vk::PipelineCreationFeedbackEXT feedback; + // If the VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT is not set in flags, an + // implementation must not set any other bits in flags, and the values of all + // other VkPipelineCreationFeedback data members are undefined. + feedback.flags = vk::PipelineCreationFeedbackFlagBits::eValid; + return feedback; +} + +constexpr vk::FrontFace ToVKFrontFace(WindingOrder order) { + switch (order) { + case WindingOrder::kClockwise: + return vk::FrontFace::eClockwise; + case WindingOrder::kCounterClockwise: + return vk::FrontFace::eCounterClockwise; + } + FML_UNREACHABLE(); +} + +static void ReportPipelineCreationFeedbackToLog( + std::stringstream& stream, + const vk::PipelineCreationFeedbackEXT& feedback) { + const auto pipeline_cache_hit = + feedback.flags & + vk::PipelineCreationFeedbackFlagBits::eApplicationPipelineCacheHit; + const auto base_pipeline_accl = + feedback.flags & + vk::PipelineCreationFeedbackFlagBits::eBasePipelineAcceleration; + auto duration = std::chrono::duration_cast( + std::chrono::nanoseconds{feedback.duration}); + stream << "Time: " << duration.count() << "ms" + << " Cache Hit: " << static_cast(pipeline_cache_hit) + << " Base Accel: " << static_cast(base_pipeline_accl) + << " Thread: " << std::this_thread::get_id(); +} + +static void ReportPipelineCreationFeedbackToLog( + const PipelineDescriptor& desc, + const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) { + std::stringstream stream; + stream << std::fixed << std::showpoint << std::setprecision(2); + stream << std::endl << ">>>>>>" << std::endl; + stream << "Pipeline '" << desc.GetLabel() << "' "; + ReportPipelineCreationFeedbackToLog(stream, + *feedback.pPipelineCreationFeedback); + if (feedback.pipelineStageCreationFeedbackCount != 0) { + stream << std::endl; + } + for (size_t i = 0, count = feedback.pipelineStageCreationFeedbackCount; + i < count; i++) { + stream << "\tStage " << i + 1 << ": "; + ReportPipelineCreationFeedbackToLog( + stream, feedback.pPipelineStageCreationFeedbacks[i]); + if (i != count - 1) { + stream << std::endl; + } + } + stream << std::endl << "<<<<<<" << std::endl; + FML_LOG(ERROR) << stream.str(); +} + +static void ReportPipelineCreationFeedbackToTrace( + const PipelineDescriptor& desc, + const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) { + static int64_t gPipelineCacheHits = 0; + static int64_t gPipelineCacheMisses = 0; + static int64_t gPipelines = 0; + if (feedback.pPipelineCreationFeedback->flags & + vk::PipelineCreationFeedbackFlagBits::eApplicationPipelineCacheHit) { + gPipelineCacheHits++; + } else { + gPipelineCacheMisses++; + } + gPipelines++; + static constexpr int64_t kImpellerPipelineTraceID = 1988; + FML_TRACE_COUNTER("impeller", // + "PipelineCache", // series name + kImpellerPipelineTraceID, // series ID + "PipelineCacheHits", gPipelineCacheHits, // + "PipelineCacheMisses", gPipelineCacheMisses, // + "TotalPipelines", gPipelines // + ); +} + +static void ReportPipelineCreationFeedback( + const PipelineDescriptor& desc, + const vk::PipelineCreationFeedbackCreateInfoEXT& feedback) { + constexpr bool kReportPipelineCreationFeedbackToLogs = false; + constexpr bool kReportPipelineCreationFeedbackToTraces = true; + if (kReportPipelineCreationFeedbackToLogs) { + ReportPipelineCreationFeedbackToLog(desc, feedback); + } + if (kReportPipelineCreationFeedbackToTraces) { + ReportPipelineCreationFeedbackToTrace(desc, feedback); + } +} + +//---------------------------------------------------------------------------- +/// Render Pass +/// We are NOT going to use the same render pass with the framebuffer (later) +/// and the graphics pipeline (here). Instead, we are going to ensure that the +/// sub-passes are compatible. To see the compatibility rules, see the Vulkan +/// spec: +/// https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/chap8.html#renderpass-compatibility +/// +static vk::UniqueRenderPass CreateCompatRenderPassForPipeline( + const vk::Device& device, + const PipelineDescriptor& desc) { + RenderPassBuilderVK builder; + + for (const auto& [bind_point, color] : desc.GetColorAttachmentDescriptors()) { + builder.SetColorAttachment(bind_point, // + color.format, // + desc.GetSampleCount(), // + LoadAction::kDontCare, // + StoreAction::kDontCare // + ); + } + + if (auto depth = desc.GetDepthStencilAttachmentDescriptor(); + depth.has_value()) { + builder.SetDepthStencilAttachment(desc.GetDepthPixelFormat(), // + desc.GetSampleCount(), // + LoadAction::kDontCare, // + StoreAction::kDontCare // + ); + } else if (desc.HasStencilAttachmentDescriptors()) { + builder.SetStencilAttachment(desc.GetStencilPixelFormat(), // + desc.GetSampleCount(), // + LoadAction::kDontCare, // + StoreAction::kDontCare // + ); + } + + auto pass = builder.Build(device); + if (!pass) { + VALIDATION_LOG << "Failed to create render pass for pipeline: " + << desc.GetLabel(); + return {}; + } + +#ifdef IMPELLER_DEBUG + ContextVK::SetDebugName( + device, pass.get(), + SPrintF("Compat Render Pass: %s", desc.GetLabel().data())); +#endif // IMPELLER_DEBUG + + return pass; +} + +namespace { +fml::StatusOr MakeDescriptorSetLayout( + const PipelineDescriptor& desc, + const std::shared_ptr& device_holder, + const std::shared_ptr& immutable_sampler) { + std::vector set_bindings; + + vk::Sampler vk_immutable_sampler = + immutable_sampler ? immutable_sampler->GetSampler() + : static_cast(VK_NULL_HANDLE); + + for (auto layout : desc.GetVertexDescriptor()->GetDescriptorSetLayouts()) { + vk::DescriptorSetLayoutBinding set_binding; + set_binding.binding = layout.binding; + set_binding.descriptorCount = 1u; + set_binding.descriptorType = ToVKDescriptorType(layout.descriptor_type); + set_binding.stageFlags = ToVkShaderStage(layout.shader_stage); + // TODO(143719): This specifies the immutable sampler for all sampled + // images. This is incorrect. In cases where the shader samples from the + // multiple images, there is currently no way to tell which sampler needs to + // be immutable and which one needs a binding set in the render pass. Expect + // errors if the shader has more than on sampled image. The sampling from + // the one that is expected to be non-immutable will be incorrect. + if (vk_immutable_sampler && + layout.descriptor_type == DescriptorType::kSampledImage) { + set_binding.setImmutableSamplers(vk_immutable_sampler); + } + set_bindings.push_back(set_binding); + } + + vk::DescriptorSetLayoutCreateInfo desc_set_layout_info; + desc_set_layout_info.setBindings(set_bindings); + + auto [descs_result, descs_layout] = + device_holder->GetDevice().createDescriptorSetLayoutUnique( + desc_set_layout_info); + if (descs_result != vk::Result::eSuccess) { + VALIDATION_LOG << "unable to create uniform descriptors"; + return {fml::Status(fml::StatusCode::kUnknown, + "unable to create uniform descriptors")}; + } + +#ifdef IMPELLER_DEBUG + ContextVK::SetDebugName( + device_holder->GetDevice(), descs_layout.get(), + SPrintF("Descriptor Set Layout: %s", desc.GetLabel().data())); +#endif // IMPELLER_DEBUG + + return fml::StatusOr(std::move(descs_layout)); +} + +fml::StatusOr MakePipelineLayout( + const PipelineDescriptor& desc, + const std::shared_ptr& device_holder, + const vk::DescriptorSetLayout& descs_layout) { + vk::PipelineLayoutCreateInfo pipeline_layout_info; + pipeline_layout_info.setSetLayouts(descs_layout); + auto pipeline_layout = device_holder->GetDevice().createPipelineLayoutUnique( + pipeline_layout_info); + if (pipeline_layout.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create pipeline layout for pipeline " + << desc.GetLabel() << ": " + << vk::to_string(pipeline_layout.result); + return {fml::Status(fml::StatusCode::kUnknown, + "Could not create pipeline layout for pipeline.")}; + } + +#ifdef IMPELLER_DEBUG + ContextVK::SetDebugName( + device_holder->GetDevice(), *pipeline_layout.value, + SPrintF("Pipeline Layout %s", desc.GetLabel().data())); +#endif // IMPELLER_DEBUG + + return std::move(pipeline_layout.value); +} + +fml::StatusOr MakePipeline( + const PipelineDescriptor& desc, + const std::shared_ptr& device_holder, + const std::shared_ptr& pso_cache, + const vk::PipelineLayout& pipeline_layout, + const vk::RenderPass& render_pass) { + vk::StructureChain + chain; + + const auto* caps = pso_cache->GetCapabilities(); + + const auto supports_pipeline_creation_feedback = caps->HasExtension( + OptionalDeviceExtensionVK::kEXTPipelineCreationFeedback); + if (!supports_pipeline_creation_feedback) { + chain.unlink(); + } + + auto& pipeline_info = chain.get(); + pipeline_info.setLayout(pipeline_layout); + + //---------------------------------------------------------------------------- + /// Dynamic States + /// + vk::PipelineDynamicStateCreateInfo dynamic_create_state_info; + std::vector dynamic_states = { + vk::DynamicState::eViewport, + vk::DynamicState::eScissor, + vk::DynamicState::eStencilReference, + }; + dynamic_create_state_info.setDynamicStates(dynamic_states); + pipeline_info.setPDynamicState(&dynamic_create_state_info); + + //---------------------------------------------------------------------------- + /// Viewport State + /// + vk::PipelineViewportStateCreateInfo viewport_state; + viewport_state.setViewportCount(1u); + viewport_state.setScissorCount(1u); + // The actual viewport and scissor rects are not set here since they are + // dynamic as mentioned above in the dynamic state info. + pipeline_info.setPViewportState(&viewport_state); + + //---------------------------------------------------------------------------- + /// Shader Stages + /// + const auto& constants = desc.GetSpecializationConstants(); + + std::vector> map_entries( + desc.GetStageEntrypoints().size()); + std::vector specialization_infos( + desc.GetStageEntrypoints().size()); + std::vector shader_stages; + + size_t entrypoint_count = 0; + for (const auto& entrypoint : desc.GetStageEntrypoints()) { + auto stage = ToVKShaderStageFlagBits(entrypoint.first); + if (!stage.has_value()) { + VALIDATION_LOG << "Unsupported shader type in pipeline: " + << desc.GetLabel(); + return {fml::Status(fml::StatusCode::kUnknown, + "Unsupported shader type in pipeline.")}; + } + + std::vector& entries = + map_entries[entrypoint_count]; + for (auto i = 0u; i < constants.size(); i++) { + vk::SpecializationMapEntry entry; + entry.offset = (i * sizeof(Scalar)); + entry.size = sizeof(Scalar); + entry.constantID = i; + entries.emplace_back(entry); + } + + vk::SpecializationInfo& specialization_info = + specialization_infos[entrypoint_count]; + specialization_info.setMapEntries(map_entries[entrypoint_count]); + specialization_info.setPData(constants.data()); + specialization_info.setDataSize(sizeof(Scalar) * constants.size()); + + vk::PipelineShaderStageCreateInfo info; + info.setStage(stage.value()); + info.setPName("main"); + info.setModule( + ShaderFunctionVK::Cast(entrypoint.second.get())->GetModule()); + info.setPSpecializationInfo(&specialization_info); + shader_stages.push_back(info); + entrypoint_count++; + } + pipeline_info.setStages(shader_stages); + + //---------------------------------------------------------------------------- + /// Rasterization State + /// + vk::PipelineRasterizationStateCreateInfo rasterization_state; + rasterization_state.setFrontFace(ToVKFrontFace(desc.GetWindingOrder())); + rasterization_state.setCullMode(ToVKCullModeFlags(desc.GetCullMode())); + rasterization_state.setPolygonMode(ToVKPolygonMode(desc.GetPolygonMode())); + rasterization_state.setLineWidth(1.0f); + rasterization_state.setDepthClampEnable(false); + rasterization_state.setRasterizerDiscardEnable(false); + pipeline_info.setPRasterizationState(&rasterization_state); + + //---------------------------------------------------------------------------- + /// Multi-sample State + /// + vk::PipelineMultisampleStateCreateInfo multisample_state; + multisample_state.setRasterizationSamples( + ToVKSampleCountFlagBits(desc.GetSampleCount())); + pipeline_info.setPMultisampleState(&multisample_state); + + //---------------------------------------------------------------------------- + /// Primitive Input Assembly State + vk::PipelineInputAssemblyStateCreateInfo input_assembly; + const auto topology = ToVKPrimitiveTopology(desc.GetPrimitiveType()); + input_assembly.setTopology(topology); + input_assembly.setPrimitiveRestartEnable( + caps->SupportsPrimitiveRestart() && + PrimitiveTopologySupportsPrimitiveRestart(desc.GetPrimitiveType())); + pipeline_info.setPInputAssemblyState(&input_assembly); + + //---------------------------------------------------------------------------- + /// Color Blend State + std::vector attachment_blend_state; + for (const auto& color_desc : desc.GetColorAttachmentDescriptors()) { + // TODO(csg): The blend states are per color attachment. But it isn't clear + // how the color attachment indices are specified in the pipeline create + // info. But, this should always work for one color attachment. + attachment_blend_state.push_back( + ToVKPipelineColorBlendAttachmentState(color_desc.second)); + } + vk::PipelineColorBlendStateCreateInfo blend_state; + blend_state.setAttachments(attachment_blend_state); + pipeline_info.setPColorBlendState(&blend_state); + + // Convention wisdom says that the base acceleration pipelines are never used + // by drivers for cache hits. Instead, the PSO cache is the preferred + // mechanism. + pipeline_info.setBasePipelineHandle(VK_NULL_HANDLE); + pipeline_info.setSubpass(0u); + pipeline_info.setRenderPass(render_pass); + + //---------------------------------------------------------------------------- + /// Vertex Input Setup + /// + std::vector attr_descs; + std::vector buffer_descs; + + const auto& stage_inputs = desc.GetVertexDescriptor()->GetStageInputs(); + const auto& stage_buffer_layouts = + desc.GetVertexDescriptor()->GetStageLayouts(); + for (const ShaderStageIOSlot& stage_in : stage_inputs) { + vk::VertexInputAttributeDescription attr_desc; + attr_desc.setBinding(stage_in.binding); + attr_desc.setLocation(stage_in.location); + attr_desc.setFormat(ToVertexDescriptorFormat(stage_in)); + attr_desc.setOffset(stage_in.offset); + attr_descs.push_back(attr_desc); + } + for (const ShaderStageBufferLayout& layout : stage_buffer_layouts) { + vk::VertexInputBindingDescription binding_description; + binding_description.setBinding(layout.binding); + binding_description.setInputRate(vk::VertexInputRate::eVertex); + binding_description.setStride(layout.stride); + buffer_descs.push_back(binding_description); + } + + vk::PipelineVertexInputStateCreateInfo vertex_input_state; + vertex_input_state.setVertexAttributeDescriptions(attr_descs); + vertex_input_state.setVertexBindingDescriptions(buffer_descs); + + pipeline_info.setPVertexInputState(&vertex_input_state); + + //---------------------------------------------------------------------------- + /// Create the depth stencil state. + /// + auto depth_stencil_state = ToVKPipelineDepthStencilStateCreateInfo( + desc.GetDepthStencilAttachmentDescriptor(), + desc.GetFrontStencilAttachmentDescriptor(), + desc.GetBackStencilAttachmentDescriptor()); + pipeline_info.setPDepthStencilState(&depth_stencil_state); + + //---------------------------------------------------------------------------- + /// Setup the optional pipeline creation feedback struct so we can understand + /// how Vulkan created the PSO. + /// + auto& feedback = chain.get(); + auto pipeline_feedback = EmptyFeedback(); + std::vector stage_feedbacks( + pipeline_info.stageCount, EmptyFeedback()); + feedback.setPPipelineCreationFeedback(&pipeline_feedback); + feedback.setPipelineStageCreationFeedbacks(stage_feedbacks); + + //---------------------------------------------------------------------------- + /// Finally, all done with the setup info. Create the pipeline itself. + /// + auto pipeline = pso_cache->CreatePipeline(pipeline_info); + if (!pipeline) { + VALIDATION_LOG << "Could not create graphics pipeline: " << desc.GetLabel(); + return {fml::Status(fml::StatusCode::kUnknown, + "Could not create graphics pipeline.")}; + } + + if (supports_pipeline_creation_feedback) { + ReportPipelineCreationFeedback(desc, feedback); + } + +#ifdef IMPELLER_DEBUG + ContextVK::SetDebugName(device_holder->GetDevice(), *pipeline, + SPrintF("Pipeline %s", desc.GetLabel().data())); +#endif // IMPELLER_DEBUG + + return std::move(pipeline); +} +} // namespace + +std::unique_ptr PipelineVK::Create( + const PipelineDescriptor& desc, + const std::shared_ptr& device_holder, + const std::weak_ptr& weak_library, + PipelineKey pipeline_key, + std::shared_ptr immutable_sampler) { + TRACE_EVENT1("flutter", "PipelineVK::Create", "Name", desc.GetLabel().data()); + + auto library = weak_library.lock(); + + if (!device_holder || !library) { + return nullptr; + } + + const auto& pso_cache = PipelineLibraryVK::Cast(*library).GetPSOCache(); + + fml::StatusOr descs_layout = + MakeDescriptorSetLayout(desc, device_holder, immutable_sampler); + if (!descs_layout.ok()) { + return nullptr; + } + + fml::StatusOr pipeline_layout = + MakePipelineLayout(desc, device_holder, descs_layout.value().get()); + if (!pipeline_layout.ok()) { + return nullptr; + } + + vk::UniqueRenderPass render_pass = + CreateCompatRenderPassForPipeline(device_holder->GetDevice(), desc); + if (!render_pass) { + VALIDATION_LOG << "Could not create render pass for pipeline."; + return nullptr; + } + + fml::StatusOr pipeline = + MakePipeline(desc, device_holder, pso_cache, + pipeline_layout.value().get(), render_pass.get()); + if (!pipeline.ok()) { + return nullptr; + } + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + auto pipeline_vk = std::unique_ptr(new PipelineVK( + device_holder, // + library, // + desc, // + std::move(pipeline.value()), // + std::move(render_pass), // + std::move(pipeline_layout.value()), // + std::move(descs_layout.value()), // + pipeline_key, // + std::move(immutable_sampler) // + )); + if (!pipeline_vk->IsValid()) { + VALIDATION_LOG << "Could not create a valid pipeline."; + return nullptr; + } + return pipeline_vk; +} + +PipelineVK::PipelineVK(std::weak_ptr device_holder, + std::weak_ptr library, + const PipelineDescriptor& desc, + vk::UniquePipeline pipeline, + vk::UniqueRenderPass render_pass, + vk::UniquePipelineLayout layout, + vk::UniqueDescriptorSetLayout descriptor_set_layout, + PipelineKey pipeline_key, + std::shared_ptr immutable_sampler) + : Pipeline(std::move(library), desc), + device_holder_(std::move(device_holder)), + pipeline_(std::move(pipeline)), + render_pass_(std::move(render_pass)), + layout_(std::move(layout)), + descriptor_set_layout_(std::move(descriptor_set_layout)), + immutable_sampler_(std::move(immutable_sampler)), + pipeline_key_(pipeline_key) { + is_valid_ = pipeline_ && render_pass_ && layout_ && descriptor_set_layout_; +} + +PipelineVK::~PipelineVK() { + if (auto device = device_holder_.lock(); !device) { + descriptor_set_layout_.release(); + layout_.release(); + render_pass_.release(); + pipeline_.release(); + } +} + +bool PipelineVK::IsValid() const { + return is_valid_; +} + +vk::Pipeline PipelineVK::GetPipeline() const { + return *pipeline_; +} + +const vk::PipelineLayout& PipelineVK::GetPipelineLayout() const { + return *layout_; +} + +const vk::DescriptorSetLayout& PipelineVK::GetDescriptorSetLayout() const { + return *descriptor_set_layout_; +} + +std::shared_ptr PipelineVK::CreateVariantForImmutableSamplers( + const std::shared_ptr& immutable_sampler) const { + if (!immutable_sampler) { + return nullptr; + } + auto cache_key = ImmutableSamplerKeyVK{*immutable_sampler}; + Lock lock(immutable_sampler_variants_mutex_); + auto found = immutable_sampler_variants_.find(cache_key); + if (found != immutable_sampler_variants_.end()) { + return found->second; + } + auto device_holder = device_holder_.lock(); + if (!device_holder) { + return nullptr; + } + // Note: immutable sampler variant of a pipeline is the negation of the + // existing pipeline key. This keeps the descriptors separate. + return (immutable_sampler_variants_[cache_key] = + Create(desc_, device_holder, library_, -1 * pipeline_key_, + immutable_sampler)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..8ef19546f943ab8b37a0f987b68c1e7bf058ee61 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/pipeline_vk.h @@ -0,0 +1,91 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_ + +#include +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +// Limit on the total number of buffer and image bindings that allow the Vulkan +// backend to avoid dynamic heap allocations. +static constexpr size_t kMaxBindings = 32; + +class PipelineVK final + : public Pipeline, + public BackendCast> { + public: + static std::unique_ptr Create( + const PipelineDescriptor& desc, + const std::shared_ptr& device_holder, + const std::weak_ptr& weak_library, + PipelineKey pipeline_key, + std::shared_ptr immutable_sampler = {}); + + // |Pipeline| + ~PipelineVK() override; + + vk::Pipeline GetPipeline() const; + + const vk::PipelineLayout& GetPipelineLayout() const; + + const vk::DescriptorSetLayout& GetDescriptorSetLayout() const; + + std::shared_ptr CreateVariantForImmutableSamplers( + const std::shared_ptr& immutable_sampler) const; + + PipelineKey GetPipelineKey() const { return pipeline_key_; } + + private: + friend class PipelineLibraryVK; + + using ImmutableSamplerVariants = + std::unordered_map, + ComparableHash, + ComparableEqual>; + + std::weak_ptr device_holder_; + vk::UniquePipeline pipeline_; + vk::UniqueRenderPass render_pass_; + vk::UniquePipelineLayout layout_; + vk::UniqueDescriptorSetLayout descriptor_set_layout_; + std::shared_ptr immutable_sampler_; + const PipelineKey pipeline_key_; + mutable Mutex immutable_sampler_variants_mutex_; + mutable ImmutableSamplerVariants immutable_sampler_variants_ IPLR_GUARDED_BY( + immutable_sampler_variants_mutex_); + bool is_valid_ = false; + + PipelineVK(std::weak_ptr device_holder, + std::weak_ptr library, + const PipelineDescriptor& desc, + vk::UniquePipeline pipeline, + vk::UniqueRenderPass render_pass, + vk::UniquePipelineLayout layout, + vk::UniqueDescriptorSetLayout descriptor_set_layout, + PipelineKey pipeline_key, + std::shared_ptr immutable_sampler); + + // |Pipeline| + bool IsValid() const override; + + PipelineVK(const PipelineVK&) = delete; + + PipelineVK& operator=(const PipelineVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_PIPELINE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..a96e2b0882b459ab437f65f49386d6ddd932c080 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.cc @@ -0,0 +1,108 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/queue_vk.h" + +#include + +#include "impeller/renderer/backend/vulkan/context_vk.h" + +namespace impeller { + +QueueVK::QueueVK(QueueIndexVK index, vk::Queue queue) + : index_(index), queue_(queue) {} + +QueueVK::~QueueVK() = default; + +const QueueIndexVK& QueueVK::GetIndex() const { + return index_; +} + +vk::Result QueueVK::Submit(const vk::SubmitInfo& submit_info, + const vk::Fence& fence) const { + Lock lock(queue_mutex_); + return queue_.submit(submit_info, fence); +} + +vk::Result QueueVK::Submit(const vk::Fence& fence) const { + Lock lock(queue_mutex_); + return queue_.submit({}, fence); +} + +vk::Result QueueVK::Present(const vk::PresentInfoKHR& present_info) { + Lock lock(queue_mutex_); + return queue_.presentKHR(present_info); +} + +void QueueVK::InsertDebugMarker(std::string_view label) const { + if (!HasValidationLayers()) { + return; + } + vk::DebugUtilsLabelEXT label_info; + label_info.pLabelName = label.data(); + Lock lock(queue_mutex_); + queue_.insertDebugUtilsLabelEXT(label_info); +} + +QueuesVK::QueuesVK() = default; + +QueuesVK::QueuesVK(std::shared_ptr graphics_queue, + std::shared_ptr compute_queue, + std::shared_ptr transfer_queue) + : graphics_queue(std::move(graphics_queue)), + compute_queue(std::move(compute_queue)), + transfer_queue(std::move(transfer_queue)) {} + +// static +QueuesVK QueuesVK::FromEmbedderQueue(vk::Queue queue, + uint32_t queue_family_index) { + auto graphics_queue = std::make_shared( + QueueIndexVK{.family = queue_family_index, .index = 0}, queue); + + return QueuesVK(graphics_queue, graphics_queue, graphics_queue); +} + +// static +QueuesVK QueuesVK::FromQueueIndices(const vk::Device& device, + QueueIndexVK graphics, + QueueIndexVK compute, + QueueIndexVK transfer) { + auto vk_graphics = device.getQueue(graphics.family, graphics.index); + auto vk_compute = device.getQueue(compute.family, compute.index); + auto vk_transfer = device.getQueue(transfer.family, transfer.index); + + // Always set up the graphics queue. + auto graphics_queue = std::make_shared(graphics, vk_graphics); + ContextVK::SetDebugName(device, vk_graphics, "ImpellerGraphicsQ"); + + // Setup the compute queue if its different from the graphics queue. + std::shared_ptr compute_queue; + if (compute == graphics) { + compute_queue = graphics_queue; + } else { + compute_queue = std::make_shared(compute, vk_compute); + ContextVK::SetDebugName(device, vk_compute, "ImpellerComputeQ"); + } + + // Setup the transfer queue if its different from the graphics or compute + // queues. + std::shared_ptr transfer_queue; + if (transfer == graphics) { + transfer_queue = graphics_queue; + } else if (transfer == compute) { + transfer_queue = compute_queue; + } else { + transfer_queue = std::make_shared(transfer, vk_transfer); + ContextVK::SetDebugName(device, vk_transfer, "ImpellerTransferQ"); + } + + return QueuesVK(std::move(graphics_queue), std::move(compute_queue), + std::move(transfer_queue)); +} + +bool QueuesVK::IsValid() const { + return graphics_queue && compute_queue && transfer_queue; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..2fcf7fba09d7da801fc298b34af899170f858623 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/queue_vk.h @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_QUEUE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_QUEUE_VK_H_ + +#include + +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +struct QueueIndexVK { + size_t family = 0; + size_t index = 0; + + constexpr bool operator==(const QueueIndexVK& other) const { + return family == other.family && index == other.index; + } +}; + +//------------------------------------------------------------------------------ +/// @brief A thread safe object that can be used to access device queues. +/// If multiple objects are created with the same underlying queue, +/// then the external synchronization guarantees of Vulkan queues +/// cannot be met. So care must be taken the same device queue +/// doesn't form the basis of multiple `QueueVK`s. +/// +class QueueVK { + public: + QueueVK(QueueIndexVK index, vk::Queue queue); + + ~QueueVK(); + + const QueueIndexVK& GetIndex() const; + + vk::Result Submit(const vk::SubmitInfo& submit_info, + const vk::Fence& fence) const; + + vk::Result Submit(const vk::Fence& fence) const; + + vk::Result Present(const vk::PresentInfoKHR& present_info); + + void InsertDebugMarker(std::string_view label) const; + + private: + mutable Mutex queue_mutex_; + + const QueueIndexVK index_; + const vk::Queue queue_ IPLR_GUARDED_BY(queue_mutex_); + + QueueVK(const QueueVK&) = delete; + + QueueVK& operator=(const QueueVK&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief The collection of queues used by the context. The queues may all +/// be the same. +/// +struct QueuesVK { + std::shared_ptr graphics_queue; + std::shared_ptr compute_queue; + std::shared_ptr transfer_queue; + + QueuesVK(); + + QueuesVK(std::shared_ptr graphics_queue, + std::shared_ptr compute_queue, + std::shared_ptr transfer_queue); + + static QueuesVK FromEmbedderQueue(vk::Queue queue, + uint32_t queue_family_index); + + static QueuesVK FromQueueIndices(const vk::Device& device, + QueueIndexVK graphics, + QueueIndexVK compute, + QueueIndexVK transfer); + + bool IsValid() const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_QUEUE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..d55cedfe488864cffa53dfcf54f8b1c62f0d1d88 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.cc @@ -0,0 +1,301 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" + +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" + +namespace impeller { + +namespace { +// Compute the final layout for a given image state. +vk::ImageLayout ComputeFinalLayout(bool is_swapchain, SampleCount count) { + if (is_swapchain || count != SampleCount::kCount1) { + return vk::ImageLayout::eGeneral; + } + return vk::ImageLayout::eShaderReadOnlyOptimal; +} +} // namespace + +constexpr auto kSelfDependencySrcStageMask = + vk::PipelineStageFlagBits::eColorAttachmentOutput; +constexpr auto kSelfDependencySrcAccessMask = + vk::AccessFlagBits::eColorAttachmentWrite; + +constexpr auto kSelfDependencyDstStageMask = + vk::PipelineStageFlagBits::eFragmentShader; +constexpr auto kSelfDependencyDstAccessMask = + vk::AccessFlagBits::eInputAttachmentRead; + +constexpr auto kSelfDependencyFlags = vk::DependencyFlagBits::eByRegion; + +RenderPassBuilderVK::RenderPassBuilderVK() = default; + +RenderPassBuilderVK::~RenderPassBuilderVK() = default; + +RenderPassBuilderVK& RenderPassBuilderVK::SetColorAttachment( + size_t index, + PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action, + vk::ImageLayout current_layout, + bool is_swapchain) { + vk::AttachmentDescription desc; + desc.format = ToVKImageFormat(format); + desc.samples = ToVKSampleCount(sample_count); + desc.loadOp = ToVKAttachmentLoadOp(load_action); + desc.storeOp = ToVKAttachmentStoreOp(store_action, false); + desc.stencilLoadOp = vk::AttachmentLoadOp::eDontCare; + desc.stencilStoreOp = vk::AttachmentStoreOp::eDontCare; + if (load_action == LoadAction::kLoad) { + desc.initialLayout = current_layout; + } else { + desc.initialLayout = vk::ImageLayout::eUndefined; + } + desc.finalLayout = ComputeFinalLayout(is_swapchain, sample_count); + + const bool performs_resolves = StoreActionPerformsResolve(store_action); + if (index == 0u) { + color0_ = desc; + + if (performs_resolves) { + desc.storeOp = ToVKAttachmentStoreOp(store_action, true); + desc.samples = vk::SampleCountFlagBits::e1; + desc.finalLayout = ComputeFinalLayout(is_swapchain, SampleCount::kCount1); + color0_resolve_ = desc; + } else { + color0_resolve_ = std::nullopt; + } + } else { + colors_[index] = desc; + if (performs_resolves) { + desc.storeOp = ToVKAttachmentStoreOp(store_action, true); + desc.samples = vk::SampleCountFlagBits::e1; + desc.finalLayout = ComputeFinalLayout(is_swapchain, SampleCount::kCount1); + resolves_[index] = desc; + } else { + resolves_.erase(index); + } + } + return *this; +} + +RenderPassBuilderVK& RenderPassBuilderVK::SetDepthStencilAttachment( + PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action) { + vk::AttachmentDescription desc; + desc.format = ToVKImageFormat(format); + desc.samples = ToVKSampleCount(sample_count); + desc.loadOp = ToVKAttachmentLoadOp(load_action); + desc.storeOp = ToVKAttachmentStoreOp(store_action, false); + desc.stencilLoadOp = desc.loadOp; // Not separable in Impeller. + desc.stencilStoreOp = desc.storeOp; // Not separable in Impeller. + desc.initialLayout = vk::ImageLayout::eUndefined; + desc.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; + depth_stencil_ = desc; + return *this; +} + +RenderPassBuilderVK& RenderPassBuilderVK::SetStencilAttachment( + PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action) { + vk::AttachmentDescription desc; + desc.format = ToVKImageFormat(format); + desc.samples = ToVKSampleCount(sample_count); + desc.loadOp = vk::AttachmentLoadOp::eDontCare; + desc.storeOp = vk::AttachmentStoreOp::eDontCare; + desc.stencilLoadOp = ToVKAttachmentLoadOp(load_action); + desc.stencilStoreOp = ToVKAttachmentStoreOp(store_action, false); + desc.initialLayout = vk::ImageLayout::eUndefined; + desc.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal; + depth_stencil_ = desc; + return *this; +} + +vk::UniqueRenderPass RenderPassBuilderVK::Build( + const vk::Device& device) const { + // This must be less than `VkPhysicalDeviceLimits::maxColorAttachments` but we + // are not checking. + auto color_attachments_count = + colors_.empty() ? 0u : colors_.rbegin()->first + 1u; + if (color0_.has_value()) { + color_attachments_count++; + } + + std::array attachments; + std::array color_refs; + std::array resolve_refs; + vk::AttachmentReference depth_stencil_ref = kUnusedAttachmentReference; + size_t attachments_index = 0; + size_t color_index = 0; + size_t resolve_index = 0; + + if (color0_.has_value()) { + vk::AttachmentReference color_ref; + color_ref.attachment = attachments_index; + color_ref.layout = vk::ImageLayout::eGeneral; + color_refs.at(color_index++) = color_ref; + attachments.at(attachments_index++) = color0_.value(); + + if (color0_resolve_.has_value()) { + vk::AttachmentReference resolve_ref; + resolve_ref.attachment = attachments_index; + resolve_ref.layout = vk::ImageLayout::eGeneral; + resolve_refs.at(resolve_index++) = resolve_ref; + attachments.at(attachments_index++) = color0_resolve_.value(); + } else { + resolve_refs.at(resolve_index++) = kUnusedAttachmentReference; + } + } + + for (const auto& color : colors_) { + vk::AttachmentReference color_ref; + color_ref.attachment = attachments_index; + color_ref.layout = vk::ImageLayout::eGeneral; + color_refs.at(color_index++) = color_ref; + attachments.at(attachments_index++) = color.second; + + if (auto found = resolves_.find(color.first); found != resolves_.end()) { + vk::AttachmentReference resolve_ref; + resolve_ref.attachment = attachments_index; + resolve_ref.layout = vk::ImageLayout::eGeneral; + resolve_refs.at(resolve_index++) = resolve_ref; + attachments.at(attachments_index++) = found->second; + } else { + resolve_refs.at(resolve_index++) = kUnusedAttachmentReference; + } + } + + if (depth_stencil_.has_value()) { + depth_stencil_ref.attachment = attachments_index; + depth_stencil_ref.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal; + attachments.at(attachments_index++) = depth_stencil_.value(); + } + + vk::SubpassDescription subpass0; + subpass0.pipelineBindPoint = vk::PipelineBindPoint::eGraphics; + subpass0.setPInputAttachments(color_refs.data()); + subpass0.setInputAttachmentCount(color_index); + subpass0.setPColorAttachments(color_refs.data()); + subpass0.setColorAttachmentCount(color_index); + subpass0.setPResolveAttachments(resolve_refs.data()); + + subpass0.setPDepthStencilAttachment(&depth_stencil_ref); + + vk::SubpassDependency deps[3]; + // Incoming dependency. If the attachments were previously used + // as attachments for a render pass, or sampled from/transfered to, + // then these operations must complete before we resolve anything + // to the onscreen. + deps[0].srcSubpass = VK_SUBPASS_EXTERNAL; + deps[0].dstSubpass = 0u; + deps[0].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | + vk::PipelineStageFlagBits::eFragmentShader; + deps[0].srcAccessMask = vk::AccessFlagBits::eShaderRead | + vk::AccessFlagBits::eColorAttachmentWrite; + deps[0].dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; + deps[0].dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; + deps[0].dependencyFlags = kSelfDependencyFlags; + + // Self dependency for reading back the framebuffer, necessary for + // programmable blend support / framebuffer fetch. + deps[1].srcSubpass = 0u; // first subpass + deps[1].dstSubpass = 0u; // to itself + deps[1].srcStageMask = kSelfDependencySrcStageMask; + deps[1].srcAccessMask = kSelfDependencySrcAccessMask; + deps[1].dstStageMask = kSelfDependencyDstStageMask; + deps[1].dstAccessMask = kSelfDependencyDstAccessMask; + deps[1].dependencyFlags = kSelfDependencyFlags; + + // Outgoing dependency. The resolve step or color attachment must complete + // before we can sample from the image. This dependency is ignored for the + // onscreen as we will already insert a barrier before presenting the + // swapchain. + deps[2].srcSubpass = 0u; // first subpass + deps[2].dstSubpass = VK_SUBPASS_EXTERNAL; + deps[2].srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput; + deps[2].srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite; + deps[2].dstStageMask = vk::PipelineStageFlagBits::eFragmentShader; + deps[2].dstAccessMask = vk::AccessFlagBits::eShaderRead; + deps[2].dependencyFlags = kSelfDependencyFlags; + + vk::RenderPassCreateInfo render_pass_desc; + render_pass_desc.setPAttachments(attachments.data()); + render_pass_desc.setAttachmentCount(attachments_index); + render_pass_desc.setSubpasses(subpass0); + render_pass_desc.setPDependencies(deps); + render_pass_desc.setDependencyCount(3); + + auto [result, pass] = device.createRenderPassUnique(render_pass_desc); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Failed to create render pass: " << vk::to_string(result); + return {}; + } + return std::move(pass); +} + +void InsertBarrierForInputAttachmentRead(const vk::CommandBuffer& buffer, + const vk::Image& image) { + // This barrier must be a subset of the masks specified in the subpass + // dependency setup. + vk::ImageMemoryBarrier barrier; + barrier.srcAccessMask = kSelfDependencySrcAccessMask; + barrier.dstAccessMask = kSelfDependencyDstAccessMask; + barrier.oldLayout = vk::ImageLayout::eGeneral; + barrier.newLayout = vk::ImageLayout::eGeneral; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.image = image; + + vk::ImageSubresourceRange image_levels; + image_levels.aspectMask = vk::ImageAspectFlagBits::eColor; + image_levels.baseArrayLayer = 0u; + image_levels.baseMipLevel = 0u; + image_levels.layerCount = VK_REMAINING_ARRAY_LAYERS; + image_levels.levelCount = VK_REMAINING_MIP_LEVELS; + barrier.subresourceRange = image_levels; + + buffer.pipelineBarrier(kSelfDependencySrcStageMask, // + kSelfDependencyDstStageMask, // + kSelfDependencyFlags, // + {}, // + {}, // + barrier // + ); +} + +const std::map& +RenderPassBuilderVK::GetColorAttachments() const { + return colors_; +} + +const std::map& +RenderPassBuilderVK::GetResolves() const { + return resolves_; +} + +const std::optional& +RenderPassBuilderVK::GetDepthStencil() const { + return depth_stencil_; +} + +// Visible for testing. +std::optional RenderPassBuilderVK::GetColor0() + const { + return color0_; +} + +// Visible for testing. +std::optional RenderPassBuilderVK::GetColor0Resolve() + const { + return color0_resolve_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..6021f32a2ba38060d6f49a217cff0eabe5b84f8e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk.h @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_BUILDER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_BUILDER_VK_H_ + +#include +#include + +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +static constexpr size_t kMaxColorAttachments = 16; +static constexpr size_t kMaxAttachments = + (kMaxColorAttachments * 2) + 1; // MSAA + resolve plus depth/stencil + +class RenderPassBuilderVK { + public: + RenderPassBuilderVK(); + + ~RenderPassBuilderVK(); + + RenderPassBuilderVK(const RenderPassBuilderVK&) = delete; + + RenderPassBuilderVK& operator=(const RenderPassBuilderVK&) = delete; + + RenderPassBuilderVK& SetColorAttachment( + size_t index, + PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action, + vk::ImageLayout current_layout = vk::ImageLayout::eUndefined, + bool is_swapchain = false); + + RenderPassBuilderVK& SetDepthStencilAttachment(PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action); + + RenderPassBuilderVK& SetStencilAttachment(PixelFormat format, + SampleCount sample_count, + LoadAction load_action, + StoreAction store_action); + + vk::UniqueRenderPass Build(const vk::Device& device) const; + + // Visible for testing. + const std::map& GetColorAttachments() + const; + + // Visible for testing. + const std::map& GetResolves() const; + + // Visible for testing. + const std::optional& GetDepthStencil() const; + + // Visible for testing. + std::optional GetColor0() const; + + // Visible for testing. + std::optional GetColor0Resolve() const; + + private: + std::optional color0_; + std::optional color0_resolve_; + std::optional depth_stencil_; + + // Color attachment 0 is stored in the field above and not in these maps. + std::map colors_; + std::map resolves_; +}; + +//------------------------------------------------------------------------------ +/// @brief Inserts the appropriate barriers to ensure that subsequent +/// commands can read from the specified image (itself a framebuffer +/// attachment) as an input attachment. +/// +/// Unlike most barriers, this barrier may only be inserted within a +/// Vulkan render-pass. +/// +/// The type of barrier inserted depends on the subpass setup and +/// self-dependencies. Only use this utility method for inserting +/// barriers in render passes created by `RenderPassBuilderVK`. +/// +/// @param[in] buffer The buffer +/// @param[in] image The image +/// +void InsertBarrierForInputAttachmentRead(const vk::CommandBuffer& buffer, + const vk::Image& image); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_BUILDER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff248a8886e19d331e09e944c44cc759ce15f3ce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_builder_vk_unittests.cc @@ -0,0 +1,174 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { +namespace testing { + +TEST(RenderPassBuilder, CreatesRenderPassWithNoDepthStencil) { + RenderPassBuilderVK builder = RenderPassBuilderVK(); + auto const context = MockVulkanContextBuilder().Build(); + + // Create a single color attachment with a transient depth stencil. + builder.SetColorAttachment(0, PixelFormat::kR8G8B8A8UNormInt, + SampleCount::kCount1, LoadAction::kClear, + StoreAction::kStore); + + auto render_pass = builder.Build(context->GetDevice()); + + EXPECT_TRUE(!!render_pass); + EXPECT_FALSE(builder.GetDepthStencil().has_value()); +} + +TEST(RenderPassBuilder, RenderPassWithLoadOpUsesCurrentLayout) { + RenderPassBuilderVK builder = RenderPassBuilderVK(); + auto const context = MockVulkanContextBuilder().Build(); + + builder.SetColorAttachment(0, PixelFormat::kR8G8B8A8UNormInt, + SampleCount::kCount1, LoadAction::kLoad, + StoreAction::kStore, + vk::ImageLayout::eColorAttachmentOptimal); + + auto render_pass = builder.Build(context->GetDevice()); + + EXPECT_TRUE(!!render_pass); + + std::optional maybe_color = builder.GetColor0(); + ASSERT_TRUE(maybe_color.has_value()); + if (!maybe_color.has_value()) { + return; + } + vk::AttachmentDescription color = maybe_color.value(); + + EXPECT_EQ(color.initialLayout, vk::ImageLayout::eColorAttachmentOptimal); + EXPECT_EQ(color.finalLayout, vk::ImageLayout::eShaderReadOnlyOptimal); + EXPECT_EQ(color.loadOp, vk::AttachmentLoadOp::eLoad); + EXPECT_EQ(color.storeOp, vk::AttachmentStoreOp::eStore); +} + +TEST(RenderPassBuilder, CreatesRenderPassWithCombinedDepthStencil) { + RenderPassBuilderVK builder = RenderPassBuilderVK(); + auto const context = MockVulkanContextBuilder().Build(); + + // Create a single color attachment with a transient depth stencil. + builder.SetColorAttachment(0, PixelFormat::kR8G8B8A8UNormInt, + SampleCount::kCount1, LoadAction::kClear, + StoreAction::kStore, vk::ImageLayout::eGeneral); + builder.SetDepthStencilAttachment(PixelFormat::kD24UnormS8Uint, + SampleCount::kCount1, LoadAction::kDontCare, + StoreAction::kDontCare); + + auto render_pass = builder.Build(context->GetDevice()); + + EXPECT_TRUE(!!render_pass); + + std::optional maybe_color = builder.GetColor0(); + ASSERT_TRUE(maybe_color.has_value()); + if (!maybe_color.has_value()) { + return; + } + vk::AttachmentDescription color = maybe_color.value(); + + EXPECT_EQ(color.initialLayout, vk::ImageLayout::eUndefined); + EXPECT_EQ(color.finalLayout, vk::ImageLayout::eShaderReadOnlyOptimal); + EXPECT_EQ(color.loadOp, vk::AttachmentLoadOp::eClear); + EXPECT_EQ(color.storeOp, vk::AttachmentStoreOp::eStore); + + std::optional maybe_depth_stencil = + builder.GetDepthStencil(); + ASSERT_TRUE(maybe_depth_stencil.has_value()); + if (!maybe_depth_stencil.has_value()) { + return; + } + vk::AttachmentDescription depth_stencil = maybe_depth_stencil.value(); + + EXPECT_EQ(depth_stencil.initialLayout, vk::ImageLayout::eUndefined); + EXPECT_EQ(depth_stencil.finalLayout, + vk::ImageLayout::eDepthStencilAttachmentOptimal); + EXPECT_EQ(depth_stencil.loadOp, vk::AttachmentLoadOp::eDontCare); + EXPECT_EQ(depth_stencil.storeOp, vk::AttachmentStoreOp::eDontCare); + EXPECT_EQ(depth_stencil.stencilLoadOp, vk::AttachmentLoadOp::eDontCare); + EXPECT_EQ(depth_stencil.stencilStoreOp, vk::AttachmentStoreOp::eDontCare); +} + +TEST(RenderPassBuilder, CreatesRenderPassWithOnlyStencil) { + RenderPassBuilderVK builder = RenderPassBuilderVK(); + auto const context = MockVulkanContextBuilder().Build(); + + // Create a single color attachment with a transient depth stencil. + builder.SetColorAttachment(0, PixelFormat::kR8G8B8A8UNormInt, + SampleCount::kCount1, LoadAction::kClear, + StoreAction::kStore); + builder.SetStencilAttachment(PixelFormat::kS8UInt, SampleCount::kCount1, + LoadAction::kDontCare, StoreAction::kDontCare); + + auto render_pass = builder.Build(context->GetDevice()); + + EXPECT_TRUE(!!render_pass); + + std::optional maybe_depth_stencil = + builder.GetDepthStencil(); + ASSERT_TRUE(maybe_depth_stencil.has_value()); + if (!maybe_depth_stencil.has_value()) { + return; + } + vk::AttachmentDescription depth_stencil = maybe_depth_stencil.value(); + + EXPECT_EQ(depth_stencil.initialLayout, vk::ImageLayout::eUndefined); + EXPECT_EQ(depth_stencil.finalLayout, + vk::ImageLayout::eDepthStencilAttachmentOptimal); + EXPECT_EQ(depth_stencil.loadOp, vk::AttachmentLoadOp::eDontCare); + EXPECT_EQ(depth_stencil.storeOp, vk::AttachmentStoreOp::eDontCare); + EXPECT_EQ(depth_stencil.stencilLoadOp, vk::AttachmentLoadOp::eDontCare); + EXPECT_EQ(depth_stencil.stencilStoreOp, vk::AttachmentStoreOp::eDontCare); +} + +TEST(RenderPassBuilder, CreatesMSAAResolveWithCorrectStore) { + RenderPassBuilderVK builder = RenderPassBuilderVK(); + auto const context = MockVulkanContextBuilder().Build(); + + // Create an MSAA color attachment. + builder.SetColorAttachment(0, PixelFormat::kR8G8B8A8UNormInt, + SampleCount::kCount4, LoadAction::kClear, + StoreAction::kMultisampleResolve); + + auto render_pass = builder.Build(context->GetDevice()); + + EXPECT_TRUE(!!render_pass); + + auto maybe_color = builder.GetColor0(); + ASSERT_TRUE(maybe_color.has_value()); + if (!maybe_color.has_value()) { + return; + } + vk::AttachmentDescription color = maybe_color.value(); + + // MSAA Texture. + EXPECT_EQ(color.initialLayout, vk::ImageLayout::eUndefined); + EXPECT_EQ(color.finalLayout, vk::ImageLayout::eGeneral); + EXPECT_EQ(color.loadOp, vk::AttachmentLoadOp::eClear); + EXPECT_EQ(color.storeOp, vk::AttachmentStoreOp::eDontCare); + + auto maybe_resolve = builder.GetColor0Resolve(); + ASSERT_TRUE(maybe_resolve.has_value()); + if (!maybe_resolve.has_value()) { + return; + } + vk::AttachmentDescription resolve = maybe_resolve.value(); + + // MSAA Resolve Texture. + EXPECT_EQ(resolve.initialLayout, vk::ImageLayout::eUndefined); + EXPECT_EQ(resolve.finalLayout, vk::ImageLayout::eShaderReadOnlyOptimal); + EXPECT_EQ(resolve.loadOp, vk::AttachmentLoadOp::eClear); + EXPECT_EQ(resolve.storeOp, vk::AttachmentStoreOp::eStore); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_cache_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_cache_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f0684adae66d86b4d1a10b45ab7181f4989d338 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_cache_unittests.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { +namespace testing { + +using RendererTest = PlaygroundTest; + +TEST_P(RendererTest, CachesRenderPassAndFramebuffer) { + if (GetBackend() != PlaygroundBackend::kVulkan) { + GTEST_SKIP() << "Test only applies to Vulkan"; + } + + auto allocator = std::make_shared( + GetContext()->GetResourceAllocator()); + + RenderTarget render_target = + allocator->CreateOffscreenMSAA(*GetContext(), {100, 100}, 1); + std::shared_ptr resolve_texture = + render_target.GetColorAttachment(0).resolve_texture; + TextureVK& texture_vk = TextureVK::Cast(*resolve_texture); + + EXPECT_EQ(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_EQ(texture_vk.GetCachedRenderPass(), nullptr); + + auto buffer = GetContext()->CreateCommandBuffer(); + auto render_pass = buffer->CreateRenderPass(render_target); + + EXPECT_NE(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_NE(texture_vk.GetCachedRenderPass(), nullptr); + + render_pass->EncodeCommands(); + EXPECT_TRUE(GetContext()->GetCommandQueue()->Submit({buffer}).ok()); + + // Can be reused without error. + auto buffer_2 = GetContext()->CreateCommandBuffer(); + auto render_pass_2 = buffer_2->CreateRenderPass(render_target); + + EXPECT_TRUE(render_pass_2->EncodeCommands()); + EXPECT_TRUE(GetContext()->GetCommandQueue()->Submit({buffer_2}).ok()); +} + +TEST_P(RendererTest, CachesRenderPassAndFramebufferNonMSAA) { + if (GetBackend() != PlaygroundBackend::kVulkan) { + GTEST_SKIP() << "Test only applies to Vulkan"; + } + + auto allocator = std::make_shared( + GetContext()->GetResourceAllocator()); + + RenderTarget render_target = + allocator->CreateOffscreen(*GetContext(), {100, 100}, 1); + std::shared_ptr color_texture = + render_target.GetColorAttachment(0).texture; + TextureVK& texture_vk = TextureVK::Cast(*color_texture); + + EXPECT_EQ(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_EQ(texture_vk.GetCachedRenderPass(), nullptr); + + auto buffer = GetContext()->CreateCommandBuffer(); + auto render_pass = buffer->CreateRenderPass(render_target); + + EXPECT_NE(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_NE(texture_vk.GetCachedRenderPass(), nullptr); + + render_pass->EncodeCommands(); + EXPECT_TRUE(GetContext()->GetCommandQueue()->Submit({buffer}).ok()); + + // Can be reused without error. + auto buffer_2 = GetContext()->CreateCommandBuffer(); + auto render_pass_2 = buffer_2->CreateRenderPass(render_target); + + EXPECT_TRUE(render_pass_2->EncodeCommands()); + EXPECT_TRUE(GetContext()->GetCommandQueue()->Submit({buffer_2}).ok()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..29a78abdc183fdb721174df5ad1f3f3a2c2dfe2a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.cc @@ -0,0 +1,681 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/render_pass_vk.h" + +#include +#include + +#include "fml/status.h" +#include "impeller/base/validation.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" + +namespace impeller { + +// Warning: if any of the constant values or layouts are changed in the +// framebuffer fetch shader, then this input binding may need to be +// manually changed. +// +// See: impeller/entity/shaders/blending/framebuffer_blend.frag +static constexpr size_t kMagicSubpassInputBinding = 64u; + +static vk::ClearColorValue VKClearValueFromColor(Color color) { + vk::ClearColorValue value; + value.setFloat32( + std::array{color.red, color.green, color.blue, color.alpha}); + return value; +} + +static vk::ClearDepthStencilValue VKClearValueFromDepthStencil(uint32_t stencil, + Scalar depth) { + vk::ClearDepthStencilValue value; + value.depth = depth; + value.stencil = stencil; + return value; +} + +static size_t GetVKClearValues( + const RenderTarget& target, + std::array& values) { + size_t offset = 0u; + target.IterateAllColorAttachments( + [&values, &offset](size_t index, + const ColorAttachment& attachment) -> bool { + values.at(offset++) = VKClearValueFromColor(attachment.clear_color); + if (attachment.resolve_texture) { + values.at(offset++) = VKClearValueFromColor(attachment.clear_color); + } + return true; + }); + + const auto& depth = target.GetDepthAttachment(); + const auto& stencil = target.GetStencilAttachment(); + + if (depth.has_value()) { + values.at(offset++) = VKClearValueFromDepthStencil( + stencil ? stencil->clear_stencil : 0u, depth->clear_depth); + } else if (stencil.has_value()) { + values.at(offset++) = VKClearValueFromDepthStencil( + stencil->clear_stencil, depth ? depth->clear_depth : 0.0f); + } + return offset; +} + +SharedHandleVK RenderPassVK::CreateVKRenderPass( + const ContextVK& context, + const SharedHandleVK& recycled_renderpass, + const std::shared_ptr& command_buffer, + bool is_swapchain) const { + RenderPassBuilderVK builder; + + render_target_.IterateAllColorAttachments([&](size_t bind_point, + const ColorAttachment& + attachment) -> bool { + builder.SetColorAttachment( + bind_point, // + attachment.texture->GetTextureDescriptor().format, // + attachment.texture->GetTextureDescriptor().sample_count, // + attachment.load_action, // + attachment.store_action, // + /*current_layout=*/TextureVK::Cast(*attachment.texture).GetLayout(), // + /*is_swapchain=*/is_swapchain); + return true; + }); + + if (auto depth = render_target_.GetDepthAttachment(); depth.has_value()) { + builder.SetDepthStencilAttachment( + depth->texture->GetTextureDescriptor().format, // + depth->texture->GetTextureDescriptor().sample_count, // + depth->load_action, // + depth->store_action // + ); + } else if (auto stencil = render_target_.GetStencilAttachment(); + stencil.has_value()) { + builder.SetStencilAttachment( + stencil->texture->GetTextureDescriptor().format, // + stencil->texture->GetTextureDescriptor().sample_count, // + stencil->load_action, // + stencil->store_action // + ); + } + + if (recycled_renderpass != nullptr) { + return recycled_renderpass; + } + + auto pass = builder.Build(context.GetDevice()); + + if (!pass) { + VALIDATION_LOG << "Failed to create render pass for framebuffer."; + return {}; + } + + context.SetDebugName(pass.get(), debug_label_.c_str()); + + return MakeSharedVK(std::move(pass)); +} + +RenderPassVK::RenderPassVK(const std::shared_ptr& context, + const RenderTarget& target, + std::shared_ptr command_buffer) + : RenderPass(context, target), command_buffer_(std::move(command_buffer)) { + const ColorAttachment& color0 = render_target_.GetColorAttachment(0); + color_image_vk_ = color0.texture; + resolve_image_vk_ = color0.resolve_texture; + + const auto& vk_context = ContextVK::Cast(*context); + command_buffer_vk_ = command_buffer_->GetCommandBuffer(); + render_target_.IterateAllAttachments([&](const auto& attachment) -> bool { + command_buffer_->Track(attachment.texture); + command_buffer_->Track(attachment.resolve_texture); + return true; + }); + + SharedHandleVK recycled_render_pass; + SharedHandleVK recycled_framebuffer; + if (resolve_image_vk_) { + recycled_render_pass = + TextureVK::Cast(*resolve_image_vk_).GetCachedRenderPass(); + recycled_framebuffer = + TextureVK::Cast(*resolve_image_vk_).GetCachedFramebuffer(); + } else { + recycled_render_pass = + TextureVK::Cast(*color_image_vk_).GetCachedRenderPass(); + recycled_framebuffer = + TextureVK::Cast(*color_image_vk_).GetCachedFramebuffer(); + } + + const auto& target_size = render_target_.GetRenderTargetSize(); + + bool is_swapchain = false; + if (resolve_image_vk_) { + is_swapchain = TextureVK::Cast(*resolve_image_vk_).IsSwapchainImage(); + } else { + is_swapchain = TextureVK::Cast(*color_image_vk_).IsSwapchainImage(); + } + + render_pass_ = CreateVKRenderPass(vk_context, recycled_render_pass, + command_buffer_, is_swapchain); + if (!render_pass_) { + VALIDATION_LOG << "Could not create renderpass."; + is_valid_ = false; + return; + } + + auto framebuffer = (recycled_framebuffer == nullptr) + ? CreateVKFramebuffer(vk_context, *render_pass_) + : recycled_framebuffer; + if (!framebuffer) { + VALIDATION_LOG << "Could not create framebuffer."; + is_valid_ = false; + return; + } + + if (!command_buffer_->Track(framebuffer) || + !command_buffer_->Track(render_pass_)) { + is_valid_ = false; + return; + } + if (resolve_image_vk_) { + TextureVK::Cast(*resolve_image_vk_).SetCachedFramebuffer(framebuffer); + TextureVK::Cast(*resolve_image_vk_).SetCachedRenderPass(render_pass_); + } else { + TextureVK::Cast(*color_image_vk_).SetCachedFramebuffer(framebuffer); + TextureVK::Cast(*color_image_vk_).SetCachedRenderPass(render_pass_); + } + + std::array clears; + size_t clear_count = GetVKClearValues(render_target_, clears); + + vk::RenderPassBeginInfo pass_info; + pass_info.renderPass = *render_pass_; + pass_info.framebuffer = *framebuffer; + pass_info.renderArea.extent.width = static_cast(target_size.width); + pass_info.renderArea.extent.height = + static_cast(target_size.height); + pass_info.setPClearValues(clears.data()); + pass_info.setClearValueCount(clear_count); + + command_buffer_vk_.beginRenderPass(pass_info, vk::SubpassContents::eInline); + + if (resolve_image_vk_) { + TextureVK::Cast(*resolve_image_vk_) + .SetLayoutWithoutEncoding( + is_swapchain ? vk::ImageLayout::eGeneral + : vk::ImageLayout::eShaderReadOnlyOptimal); + } + if (color_image_vk_) { + TextureVK::Cast(*color_image_vk_) + .SetLayoutWithoutEncoding(vk::ImageLayout::eGeneral); + } + + // Set the initial viewport. + const auto vp = Viewport{.rect = Rect::MakeSize(target_size)}; + vk::Viewport viewport = vk::Viewport() + .setWidth(vp.rect.GetWidth()) + .setHeight(-vp.rect.GetHeight()) + .setY(vp.rect.GetHeight()) + .setMinDepth(0.0f) + .setMaxDepth(1.0f); + command_buffer_vk_.setViewport(0, 1, &viewport); + + // Set the initial scissor. + const auto sc = IRect::MakeSize(target_size); + vk::Rect2D scissor = + vk::Rect2D() + .setOffset(vk::Offset2D(sc.GetX(), sc.GetY())) + .setExtent(vk::Extent2D(sc.GetWidth(), sc.GetHeight())); + command_buffer_vk_.setScissor(0, 1, &scissor); + + // Set the initial stencil reference. + command_buffer_vk_.setStencilReference( + vk::StencilFaceFlagBits::eVkStencilFrontAndBack, 0u); + + is_valid_ = true; +} + +RenderPassVK::~RenderPassVK() = default; + +bool RenderPassVK::IsValid() const { + return is_valid_; +} + +void RenderPassVK::OnSetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + ContextVK::Cast(*context_).SetDebugName(render_pass_->Get(), label.data()); +#endif // IMPELLER_DEBUG +} + +SharedHandleVK RenderPassVK::CreateVKFramebuffer( + const ContextVK& context, + const vk::RenderPass& pass) const { + vk::FramebufferCreateInfo fb_info; + + fb_info.renderPass = pass; + + const auto target_size = render_target_.GetRenderTargetSize(); + fb_info.width = target_size.width; + fb_info.height = target_size.height; + fb_info.layers = 1u; + + std::array attachments; + size_t count = 0; + + // This bit must be consistent to ensure compatibility with the pass created + // earlier. Follow this order: Color attachments, then depth-stencil, then + // stencil. + render_target_.IterateAllColorAttachments( + [&attachments, &count](size_t index, + const ColorAttachment& attachment) -> bool { + // The bind point doesn't matter here since that information is present + // in the render pass. + attachments[count++] = + TextureVK::Cast(*attachment.texture).GetRenderTargetView(); + if (attachment.resolve_texture) { + attachments[count++] = TextureVK::Cast(*attachment.resolve_texture) + .GetRenderTargetView(); + } + return true; + }); + + if (auto depth = render_target_.GetDepthAttachment(); depth.has_value()) { + attachments[count++] = + TextureVK::Cast(*depth->texture).GetRenderTargetView(); + } else if (auto stencil = render_target_.GetStencilAttachment(); + stencil.has_value()) { + attachments[count++] = + TextureVK::Cast(*stencil->texture).GetRenderTargetView(); + } + + fb_info.setPAttachments(attachments.data()); + fb_info.setAttachmentCount(count); + + auto [result, framebuffer] = + context.GetDevice().createFramebufferUnique(fb_info); + + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create framebuffer: " << vk::to_string(result); + return {}; + } + + return MakeSharedVK(std::move(framebuffer)); +} + +// |RenderPass| +void RenderPassVK::SetPipeline(PipelineRef pipeline) { + pipeline_ = pipeline; + if (!pipeline_) { + return; + } + + pipeline_uses_input_attachments_ = + pipeline_->GetDescriptor().GetVertexDescriptor()->UsesInputAttacments(); + + if (pipeline_uses_input_attachments_) { + if (bound_image_offset_ >= kMaxBindings) { + pipeline_ = PipelineRef(nullptr); + return; + } + vk::DescriptorImageInfo image_info; + image_info.imageLayout = vk::ImageLayout::eGeneral; + image_info.sampler = VK_NULL_HANDLE; + image_info.imageView = TextureVK::Cast(*color_image_vk_).GetImageView(); + image_workspace_[bound_image_offset_++] = image_info; + + vk::WriteDescriptorSet write_set; + write_set.dstBinding = kMagicSubpassInputBinding; + write_set.descriptorCount = 1u; + write_set.descriptorType = vk::DescriptorType::eInputAttachment; + write_set.pImageInfo = &image_workspace_[bound_image_offset_ - 1]; + + write_workspace_[descriptor_write_offset_++] = write_set; + } +} + +// |RenderPass| +void RenderPassVK::SetCommandLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + command_buffer_->PushDebugGroup(label); + has_label_ = true; +#endif // IMPELLER_DEBUG +} + +// |RenderPass| +void RenderPassVK::SetStencilReference(uint32_t value) { + if (current_stencil_ == value) { + return; + } + current_stencil_ = value; + command_buffer_vk_.setStencilReference( + vk::StencilFaceFlagBits::eVkStencilFrontAndBack, value); +} + +// |RenderPass| +void RenderPassVK::SetBaseVertex(uint64_t value) { + base_vertex_ = value; +} + +// |RenderPass| +void RenderPassVK::SetViewport(Viewport viewport) { + vk::Viewport viewport_vk = vk::Viewport() + .setWidth(viewport.rect.GetWidth()) + .setHeight(-viewport.rect.GetHeight()) + .setY(viewport.rect.GetHeight()) + .setMinDepth(0.0f) + .setMaxDepth(1.0f); + command_buffer_vk_.setViewport(0, 1, &viewport_vk); +} + +// |RenderPass| +void RenderPassVK::SetScissor(IRect scissor) { + vk::Rect2D scissor_vk = + vk::Rect2D() + .setOffset(vk::Offset2D(scissor.GetX(), scissor.GetY())) + .setExtent(vk::Extent2D(scissor.GetWidth(), scissor.GetHeight())); + command_buffer_vk_.setScissor(0, 1, &scissor_vk); +} + +// |RenderPass| +void RenderPassVK::SetElementCount(size_t count) { + element_count_ = count; +} + +// |RenderPass| +void RenderPassVK::SetInstanceCount(size_t count) { + instance_count_ = count; +} + +// |RenderPass| +bool RenderPassVK::SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count) { + if (!ValidateVertexBuffers(vertex_buffers, vertex_buffer_count)) { + return false; + } + + vk::Buffer buffers[kMaxVertexBuffers]; + vk::DeviceSize vertex_buffer_offsets[kMaxVertexBuffers]; + for (size_t i = 0; i < vertex_buffer_count; i++) { + buffers[i] = + DeviceBufferVK::Cast(*vertex_buffers[i].GetBuffer()).GetBuffer(); + vertex_buffer_offsets[i] = vertex_buffers[i].GetRange().offset; + std::shared_ptr device_buffer = + vertex_buffers[i].TakeBuffer(); + if (device_buffer) { + command_buffer_->Track(device_buffer); + } + } + + // Bind the vertex buffers. + command_buffer_vk_.bindVertexBuffers(0u, vertex_buffer_count, buffers, + vertex_buffer_offsets); + + return true; +} + +// |RenderPass| +bool RenderPassVK::SetIndexBuffer(BufferView index_buffer, + IndexType index_type) { + if (!ValidateIndexBuffer(index_buffer, index_type)) { + return false; + } + + if (index_type != IndexType::kNone) { + has_index_buffer_ = true; + + BufferView index_buffer_view = std::move(index_buffer); + if (!index_buffer_view) { + return false; + } + + if (!index_buffer_view.GetBuffer()) { + VALIDATION_LOG << "Failed to acquire device buffer" + << " for index buffer view"; + return false; + } + + std::shared_ptr index_buffer = + index_buffer_view.TakeBuffer(); + if (index_buffer && !command_buffer_->Track(index_buffer)) { + return false; + } + + vk::Buffer index_buffer_handle = + DeviceBufferVK::Cast(*index_buffer_view.GetBuffer()).GetBuffer(); + command_buffer_vk_.bindIndexBuffer(index_buffer_handle, + index_buffer_view.GetRange().offset, + ToVKIndexType(index_type)); + } else { + has_index_buffer_ = false; + } + + return true; +} + +// |RenderPass| +fml::Status RenderPassVK::Draw() { + if (!pipeline_) { + return fml::Status(fml::StatusCode::kCancelled, + "No valid pipeline is bound to the RenderPass."); + } + + //---------------------------------------------------------------------------- + /// If there are immutable samplers referenced in the render pass, the base + /// pipeline variant is no longer valid and needs to be re-constructed to + /// reference the samplers. + /// + /// This is an instance of JIT creation of PSOs that can cause jank. It is + /// unavoidable because it isn't possible to know all possible combinations of + /// target YUV conversions. Fortunately, this will only ever happen when + /// rendering to external textures. Like Android Hardware Buffers on Android. + /// + /// Even when JIT creation is unavoidable, pipelines will cache their variants + /// when able and all pipeline creation will happen via a base pipeline cache + /// anyway. So the jank can be mostly entirely ameliorated and it should only + /// ever happen when the first unknown YUV conversion is encountered. + /// + /// Jank can be completely eliminated by pre-populating known YUV conversion + /// pipelines. + if (immutable_sampler_) { + std::shared_ptr> pipeline_variant = + PipelineVK::Cast(*pipeline_) + .CreateVariantForImmutableSamplers(immutable_sampler_); + if (!pipeline_variant) { + return fml::Status( + fml::StatusCode::kAborted, + "Could not create pipeline variant with immutable sampler."); + } + pipeline_ = raw_ptr(pipeline_variant); + } + + const auto& context_vk = ContextVK::Cast(*context_); + const auto& pipeline_vk = PipelineVK::Cast(*pipeline_); + + auto descriptor_result = command_buffer_->AllocateDescriptorSets( + pipeline_vk.GetDescriptorSetLayout(), pipeline_vk.GetPipelineKey(), + context_vk); + if (!descriptor_result.ok()) { + return fml::Status(fml::StatusCode::kAborted, + "Could not allocate descriptor sets."); + } + const auto descriptor_set = descriptor_result.value(); + const auto pipeline_layout = pipeline_vk.GetPipelineLayout(); + command_buffer_vk_.bindPipeline(vk::PipelineBindPoint::eGraphics, + pipeline_vk.GetPipeline()); + + for (auto i = 0u; i < descriptor_write_offset_; i++) { + write_workspace_[i].dstSet = descriptor_set; + } + + context_vk.GetDevice().updateDescriptorSets(descriptor_write_offset_, + write_workspace_.data(), 0u, {}); + + command_buffer_vk_.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, // bind point + pipeline_layout, // layout + 0, // first set + 1, // set count + &descriptor_set, // sets + 0, // offset count + nullptr // offsets + ); + + if (pipeline_uses_input_attachments_) { + InsertBarrierForInputAttachmentRead( + command_buffer_vk_, TextureVK::Cast(*color_image_vk_).GetImage()); + } + + if (has_index_buffer_) { + command_buffer_vk_.drawIndexed(element_count_, // index count + instance_count_, // instance count + 0u, // first index + base_vertex_, // vertex offset + 0u // first instance + ); + } else { + command_buffer_vk_.draw(element_count_, // vertex count + instance_count_, // instance count + base_vertex_, // vertex offset + 0u // first instance + ); + } + +#ifdef IMPELLER_DEBUG + if (has_label_) { + command_buffer_->PopDebugGroup(); + } +#endif // IMPELLER_DEBUG + has_label_ = false; + has_index_buffer_ = false; + bound_image_offset_ = 0u; + bound_buffer_offset_ = 0u; + descriptor_write_offset_ = 0u; + instance_count_ = 1u; + base_vertex_ = 0u; + element_count_ = 0u; + pipeline_ = PipelineRef(nullptr); + pipeline_uses_input_attachments_ = false; + immutable_sampler_ = nullptr; + return fml::Status(); +} + +// The RenderPassVK binding methods only need the binding, set, and buffer type +// information. +bool RenderPassVK::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + return BindResource(slot.binding, type, view); +} + +bool RenderPassVK::BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) { + return BindResource(slot.binding, type, view); +} + +bool RenderPassVK::BindResource(size_t binding, + DescriptorType type, + BufferView view) { + if (bound_buffer_offset_ >= kMaxBindings) { + return false; + } + + auto buffer = DeviceBufferVK::Cast(*view.GetBuffer()).GetBuffer(); + if (!buffer) { + return false; + } + + std::shared_ptr device_buffer = view.TakeBuffer(); + if (device_buffer && !command_buffer_->Track(device_buffer)) { + return false; + } + + uint32_t offset = view.GetRange().offset; + + vk::DescriptorBufferInfo buffer_info; + buffer_info.buffer = buffer; + buffer_info.offset = offset; + buffer_info.range = view.GetRange().length; + buffer_workspace_[bound_buffer_offset_++] = buffer_info; + + vk::WriteDescriptorSet write_set; + write_set.dstBinding = binding; + write_set.descriptorCount = 1u; + write_set.descriptorType = ToVKDescriptorType(type); + write_set.pBufferInfo = &buffer_workspace_[bound_buffer_offset_ - 1]; + + write_workspace_[descriptor_write_offset_++] = write_set; + return true; +} + +bool RenderPassVK::BindDynamicResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) { + return BindResource(stage, type, slot, nullptr, texture, sampler); +} + +bool RenderPassVK::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (bound_buffer_offset_ >= kMaxBindings) { + return false; + } + if (!texture || !texture->IsValid() || !sampler) { + return false; + } + const TextureVK& texture_vk = TextureVK::Cast(*texture); + const SamplerVK& sampler_vk = SamplerVK::Cast(*sampler); + + if (!command_buffer_->Track(texture)) { + return false; + } + + if (!immutable_sampler_) { + immutable_sampler_ = texture_vk.GetImmutableSamplerVariant(sampler_vk); + } + + vk::DescriptorImageInfo image_info; + image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + image_info.sampler = sampler_vk.GetSampler(); + image_info.imageView = texture_vk.GetImageView(); + image_workspace_[bound_image_offset_++] = image_info; + + vk::WriteDescriptorSet write_set; + write_set.dstBinding = slot.binding; + write_set.descriptorCount = 1u; + write_set.descriptorType = vk::DescriptorType::eCombinedImageSampler; + write_set.pImageInfo = &image_workspace_[bound_image_offset_ - 1]; + + write_workspace_[descriptor_write_offset_++] = write_set; + return true; +} + +bool RenderPassVK::OnEncodeCommands(const Context& context) const { + command_buffer_->GetCommandBuffer().endRenderPass(); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..b8361bcd3dfc1fc11e0f0814862d320e9cc21b81 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk.h @@ -0,0 +1,152 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_ + +#include "impeller/core/buffer_view.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/pipeline_vk.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +class CommandBufferVK; +class SamplerVK; + +class RenderPassVK final : public RenderPass { + public: + // |RenderPass| + ~RenderPassVK() override; + + private: + friend class CommandBufferVK; + + std::shared_ptr command_buffer_; + std::string debug_label_; + SharedHandleVK render_pass_; + bool is_valid_ = false; + + vk::CommandBuffer command_buffer_vk_; + std::shared_ptr color_image_vk_; + std::shared_ptr resolve_image_vk_; + uint32_t current_stencil_ = 0; + + // Per-command state. + std::array image_workspace_; + std::array buffer_workspace_; + std::array + write_workspace_; + size_t bound_image_offset_ = 0u; + size_t bound_buffer_offset_ = 0u; + size_t descriptor_write_offset_ = 0u; + size_t instance_count_ = 1u; + size_t base_vertex_ = 0u; + size_t element_count_ = 0u; + bool has_index_buffer_ = false; + bool has_label_ = false; + PipelineRef pipeline_ = PipelineRef(nullptr); + bool pipeline_uses_input_attachments_ = false; + std::shared_ptr immutable_sampler_; + + RenderPassVK(const std::shared_ptr& context, + const RenderTarget& target, + std::shared_ptr command_buffer); + + // |RenderPass| + void SetPipeline(PipelineRef pipeline) override; + + // |RenderPass| + void SetCommandLabel(std::string_view label) override; + + // |RenderPass| + void SetStencilReference(uint32_t value) override; + + // |RenderPass| + void SetBaseVertex(uint64_t value) override; + + // |RenderPass| + void SetViewport(Viewport viewport) override; + + // |RenderPass| + void SetScissor(IRect scissor) override; + + // |RenderPass| + void SetElementCount(size_t count) override; + + // |RenderPass| + void SetInstanceCount(size_t count) override; + + // |RenderPass| + bool SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count) override; + + // |RenderPass| + bool SetIndexBuffer(BufferView index_buffer, IndexType index_type) override; + + // |RenderPass| + fml::Status Draw() override; + + // |ResourceBinder| + bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + // |ResourceBinder| + bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) override; + + // |RenderPass| + bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr sampler) override; + + bool BindResource(size_t binding, DescriptorType type, BufferView view); + + // |RenderPass| + bool IsValid() const override; + + // |RenderPass| + void OnSetLabel(std::string_view label) override; + + // |RenderPass| + bool OnEncodeCommands(const Context& context) const override; + + SharedHandleVK CreateVKRenderPass( + const ContextVK& context, + const SharedHandleVK& recycled_renderpass, + const std::shared_ptr& command_buffer, + bool is_swapchain) const; + + SharedHandleVK CreateVKFramebuffer( + const ContextVK& context, + const vk::RenderPass& pass) const; + + RenderPassVK(const RenderPassVK&) = delete; + + RenderPassVK& operator=(const RenderPassVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RENDER_PASS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e692f51beb8c1ebbaeb780027b34873d6d09ad5a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/render_pass_vk_unittests.cc @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/render_pass_builder_vk.h" +#include "impeller/renderer/backend/vulkan/render_pass_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/render_target.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { +namespace testing { + +TEST(RenderPassVK, DoesNotRedundantlySetStencil) { + std::shared_ptr context = MockVulkanContextBuilder().Build(); + std::shared_ptr copy = context; + auto cmd_buffer = context->CreateCommandBuffer(); + + RenderTargetAllocator allocator(context->GetResourceAllocator()); + RenderTarget target = allocator.CreateOffscreenMSAA(*copy.get(), {1, 1}, 1); + + std::shared_ptr render_pass = + cmd_buffer->CreateRenderPass(target); + + // Stencil reference set once at buffer start. + auto called_functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called_functions->begin(), called_functions->end(), + "vkCmdSetStencilReference"), + 1); + + // Duplicate stencil ref is not replaced. + render_pass->SetStencilReference(0); + render_pass->SetStencilReference(0); + render_pass->SetStencilReference(0); + + called_functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called_functions->begin(), called_functions->end(), + "vkCmdSetStencilReference"), + 1); + + // Different stencil value is updated. + render_pass->SetStencilReference(1); + called_functions = GetMockVulkanFunctions(context->GetDevice()); + EXPECT_EQ(std::count(called_functions->begin(), called_functions->end(), + "vkCmdSetStencilReference"), + 2); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..8b55801047ec9e3d659dded3d095a290b4476587 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.cc @@ -0,0 +1,97 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" + +#include "flutter/fml/cpu_affinity.h" +#include "flutter/fml/thread.h" +#include "flutter/fml/trace_event.h" +#include "fml/logging.h" + +namespace impeller { + +std::shared_ptr ResourceManagerVK::Create() { + // It will be tempting to refactor this to create the waiter thread in the + // static method instead of the constructor. However, that causes the + // destructor never to be called, and the thread never terminates! + // + // See https://github.com/flutter/flutter/issues/134482. + return std::shared_ptr(new ResourceManagerVK()); +} + +ResourceManagerVK::ResourceManagerVK() : waiter_([&]() { Start(); }) {} + +ResourceManagerVK::~ResourceManagerVK() { + FML_DCHECK(waiter_.get_id() != std::this_thread::get_id()) + << "The ResourceManager being destructed on its own spawned thread is a " + << "sign that ContextVK was not properly destroyed. A usual fix for this " + << "is to ensure that ContextVK is shutdown (i.e. context->Shutdown()) " + "before the ResourceManager is destroyed (i.e. at the end of a test)."; + Terminate(); + waiter_.join(); +} + +void ResourceManagerVK::Start() { + // It's possible for Start() to be called when terminating: + // { ResourceManagerVK::Create(); } + // + // ... so no FML_DCHECK here. + + fml::Thread::SetCurrentThreadName(fml::Thread::ThreadConfig{"IplrVkResMgr"}); + // While this code calls destructors it doesn't need to be particularly fast + // with them, as long as it doesn't interrupt raster thread. + fml::RequestAffinity(fml::CpuAffinity::kEfficiency); + + bool should_exit = false; + while (!should_exit) { + std::unique_lock lock(reclaimables_mutex_); + + // Wait until there are reclaimable resource or if the manager should be + // torn down. + reclaimables_cv_.wait( + lock, [&]() { return !reclaimables_.empty() || should_exit_; }); + + // Don't reclaim resources when the lock is being held as this may gate + // further reclaimables from being registered. + Reclaimables resources_to_collect; + std::swap(resources_to_collect, reclaimables_); + + // We can't read the ivar outside the lock. Read it here instead. + should_exit = should_exit_; + + // We know what to collect. Unlock before doing anything else. + lock.unlock(); + + // Claim all resources while tracing. + { + TRACE_EVENT0("Impeller", "ReclaimResources"); + resources_to_collect.clear(); // Redundant because of scope but here so + // we can add a trace around it. + } + } +} + +void ResourceManagerVK::Reclaim(std::unique_ptr resource) { + if (!resource) { + return; + } + { + std::scoped_lock lock(reclaimables_mutex_); + reclaimables_.emplace_back(std::move(resource)); + } + reclaimables_cv_.notify_one(); +} + +void ResourceManagerVK::Terminate() { + // The thread should not be terminated more than once. + FML_DCHECK(!should_exit_); + + { + std::scoped_lock lock(reclaimables_mutex_); + should_exit_ = true; + } + reclaimables_cv_.notify_one(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..205fa203e14857351af861e119bba8ec1881bf4d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk.h @@ -0,0 +1,211 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RESOURCE_MANAGER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RESOURCE_MANAGER_VK_H_ + +#include +#include +#include +#include +#include + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A resource that may be reclaimed by a |ResourceManagerVK|. +/// +/// To create a resource, use `UniqueResourceVKT` to create a unique handle: +/// +/// auto resource = UniqueResourceVKT(resource_manager); +/// +/// @see |ResourceManagerVK::Reclaim|. +class ResourceVK { + public: + virtual ~ResourceVK() = default; +}; + +//------------------------------------------------------------------------------ +/// @brief A resource manager controls how resources are allocated and +/// reclaimed. +/// +/// Reclaimed resources are collected in a batch on a separate +/// thread. In the future, the resource manager may allow resource +/// pooling/reuse, delaying reclamation past frame workloads, etc... +/// +class ResourceManagerVK final + : public std::enable_shared_from_this { + public: + //---------------------------------------------------------------------------- + /// @brief Creates a shared resource manager (a dedicated thread). + /// + /// Upon creation, a thread is spawned which will collect resources as they + /// are reclaimed (passed to `Reclaim`). The thread will exit when the + /// resource manager is destroyed. + /// + /// @note Only one |ResourceManagerVK| should be created per Vulkan + /// context, but that contract is not enforced by this method. + /// + /// @return A resource manager if one could be created. + /// + static std::shared_ptr Create(); + + //---------------------------------------------------------------------------- + /// @brief Mark a resource as being reclaimable. + /// + /// The resource will be reset at some point in the future. + /// + /// @param[in] resource The resource to reclaim. + /// + /// @note Despite being a public API, this method cannot be invoked + /// directly. Instead, use `UniqueResourceVKT` to create a unique + /// handle to a resource, which will call this method. + void Reclaim(std::unique_ptr resource); + + //---------------------------------------------------------------------------- + /// @brief Destroys the resource manager. + /// + /// The resource manager will stop collecting resources and will be destroyed + /// when all references to it are dropped. + ~ResourceManagerVK(); + + private: + using Reclaimables = std::vector>; + + ResourceManagerVK(); + std::mutex reclaimables_mutex_; + std::condition_variable reclaimables_cv_; + Reclaimables reclaimables_; + bool should_exit_ = false; + // This should be initialized last since it references the other instance + // variables. + std::thread waiter_; + + //---------------------------------------------------------------------------- + /// @brief Starts the resource manager thread. + /// + /// This method is called implicitly by `Create`. + void Start(); + + //---------------------------------------------------------------------------- + /// @brief Terminates the resource manager thread. + /// + /// Any resources given to the resource manager post termination will be + /// collected when the resource manager is collected. + void Terminate(); + + ResourceManagerVK(const ResourceManagerVK&) = delete; + + ResourceManagerVK& operator=(const ResourceManagerVK&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief An internal type that is used to move a resource reference. +/// +/// Do not use directly, use `UniqueResourceVKT` instead. +/// +/// @tparam ResourceType_ The type of the resource. +/// +/// @see |UniqueResourceVKT|. +template +class ResourceVKT : public ResourceVK { + public: + using ResourceType = ResourceType_; + + /// @brief Construct a resource from a move-constructible resource. + /// + /// @param[in] resource The resource to move. + explicit ResourceVKT(ResourceType&& resource) + : resource_(std::move(resource)) {} + + /// @brief Returns a pointer to the resource. + const ResourceType* Get() const { return &resource_; } + + private: + // Prevents subclassing, use `UniqueResourceVKT`. + ResourceVKT() = default; + + ResourceType resource_; + + ResourceVKT(const ResourceVKT&) = delete; + + ResourceVKT& operator=(const ResourceVKT&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief A unique handle to a resource which will be reclaimed by the +/// specified resource manager. +/// +/// @tparam ResourceType_ A move-constructible resource type. +/// +template +class UniqueResourceVKT final { + public: + using ResourceType = ResourceType_; + + /// @brief Construct a unique resource handle belonging to a manager. + /// + /// Initially the handle is empty, and can be populated by calling `Swap`. + /// + /// @param[in] resource_manager The resource manager. + explicit UniqueResourceVKT(std::weak_ptr resource_manager) + : resource_manager_(std::move(resource_manager)) {} + + /// @brief Construct a unique resource handle belonging to a manager. + /// + /// Initially the handle is populated with the specified resource, but can + /// be replaced (reclaiming the old resource) by calling `Swap`. + /// + /// @param[in] resource_manager The resource manager. + /// @param[in] resource The resource to move. + explicit UniqueResourceVKT(std::weak_ptr resource_manager, + ResourceType&& resource) + : resource_manager_(std::move(resource_manager)), + resource_( + std::make_unique>(std::move(resource))) {} + + ~UniqueResourceVKT() { Reset(); } + + /// @brief Returns a pointer to the resource. + const ResourceType* operator->() const { + // If this would segfault, fail with a nicer error message. + FML_CHECK(resource_) << "UniqueResourceVKT was reclaimed."; + + return resource_.get()->Get(); + } + + /// @brief Reclaims the existing resource, if any, and replaces it. + /// + /// @param[in] other The (new) resource to move. + void Swap(ResourceType&& other) { + Reset(); + resource_ = std::make_unique>(std::move(other)); + } + + /// @brief Reclaims the existing resource, if any. + void Reset() { + if (!resource_) { + return; + } + // If there is a manager, ask it to reclaim the resource. If there isn't a + // manager (because the manager has been destroyed), just drop it on the + // floor here. + if (auto manager = resource_manager_.lock()) { + manager->Reclaim(std::move(resource_)); + } + resource_.reset(); + } + + private: + std::weak_ptr resource_manager_; + std::unique_ptr> resource_; + + UniqueResourceVKT(const UniqueResourceVKT&) = delete; + + UniqueResourceVKT& operator=(const UniqueResourceVKT&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RESOURCE_MANAGER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..78f653a37eefa90b2bee18679f6a97aa59dbee35 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/resource_manager_vk_unittests.cc @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include +#include +#include "fml/closure.h" +#include "fml/synchronization/waitable_event.h" +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/resource_manager_vk.h" + +namespace impeller { +namespace testing { + +// While expected to be a singleton per context, the class does not enforce it. +TEST(ResourceManagerVKTest, CreatesANewInstance) { + auto const a = ResourceManagerVK::Create(); + auto const b = ResourceManagerVK::Create(); + EXPECT_NE(a, b); +} + +TEST(ResourceManagerVKTest, ReclaimMovesAResourceAndDestroysIt) { + auto const manager = ResourceManagerVK::Create(); + + auto waiter = fml::AutoResetWaitableEvent(); + auto dead = false; + auto rattle = fml::ScopedCleanupClosure([&waiter]() { waiter.Signal(); }); + + // Not killed immediately. + EXPECT_FALSE(waiter.IsSignaledForTest()); + + { + auto resource = UniqueResourceVKT( + manager, std::move(rattle)); + } + + waiter.Wait(); +} + +// Regression test for https://github.com/flutter/flutter/issues/134482. +TEST(ResourceManagerVKTest, TerminatesWhenOutOfScope) { + // Originally, this shared_ptr was never destroyed, and the thread never + // terminated. This test ensures that the thread terminates when the + // ResourceManagerVK is out of scope. + std::weak_ptr manager; + + { + auto shared = ResourceManagerVK::Create(); + manager = shared; + } + + // The thread should have terminated. + EXPECT_EQ(manager.lock(), nullptr); +} + +TEST(ResourceManagerVKTest, IsThreadSafe) { + // In a typical app, there is a single ResourceManagerVK per app, shared b/w + // threads. + // + // This test ensures that the ResourceManagerVK is thread-safe. + std::weak_ptr manager; + + { + auto const manager = ResourceManagerVK::Create(); + + // Spawn two threads, and have them both put resources into the manager. + struct MockResource {}; + + std::thread thread1([&manager]() { + UniqueResourceVKT(manager, MockResource{}); + }); + + std::thread thread2([&manager]() { + UniqueResourceVKT(manager, MockResource{}); + }); + + thread1.join(); + thread2.join(); + } + + // The thread should have terminated. + EXPECT_EQ(manager.lock(), nullptr); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..38331af7e9911d0831a49850aa7f81220d26512f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.cc @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/sampler_library_vk.h" + +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" + +namespace impeller { + +SamplerLibraryVK::SamplerLibraryVK( + const std::weak_ptr& device_holder) + : device_holder_(device_holder) {} + +SamplerLibraryVK::~SamplerLibraryVK() = default; + +void SamplerLibraryVK::ApplyWorkarounds(const WorkaroundsVK& workarounds) { + mips_disabled_workaround_ = workarounds.broken_mipmap_generation; +} + +raw_ptr SamplerLibraryVK::GetSampler( + const SamplerDescriptor& desc) { + SamplerDescriptor desc_copy = desc; + if (mips_disabled_workaround_) { + desc_copy.mip_filter = MipFilter::kBase; + } + + uint64_t p_key = SamplerDescriptor::ToKey(desc_copy); + for (const auto& [key, value] : samplers_) { + if (key == p_key) { + return raw_ptr(value); + } + } + auto device_holder = device_holder_.lock(); + if (!device_holder || !device_holder->GetDevice()) { + return raw_ptr(nullptr); + } + samplers_.push_back(std::make_pair( + p_key, + std::make_shared(device_holder->GetDevice(), desc_copy))); + return raw_ptr(samplers_.back().second); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..402b76b2f67622eeb17d93293a619f4a277c76fc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_library_vk.h @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_LIBRARY_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_LIBRARY_VK_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/core/sampler.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/sampler_library.h" + +namespace impeller { + +class SamplerLibraryVK final + : public SamplerLibrary, + public BackendCast { + public: + // |SamplerLibrary| + ~SamplerLibraryVK() override; + + explicit SamplerLibraryVK(const std::weak_ptr& device_holder); + + void ApplyWorkarounds(const WorkaroundsVK& workarounds); + + private: + friend class ContextVK; + + std::weak_ptr device_holder_; + std::vector>> samplers_; + bool mips_disabled_workaround_ = false; + + // |SamplerLibrary| + raw_ptr GetSampler( + const SamplerDescriptor& descriptor) override; + + SamplerLibraryVK(const SamplerLibraryVK&) = delete; + + SamplerLibraryVK& operator=(const SamplerLibraryVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_LIBRARY_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..5231d3054e56e2ad83feb09110aa86651ae06d49 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.cc @@ -0,0 +1,130 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/sampler_vk.h" + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" +#include "vulkan/vulkan_core.h" + +namespace impeller { + +static vk::UniqueSampler CreateSampler( + const vk::Device& device, + const SamplerDescriptor& desc, + const std::shared_ptr& yuv_conversion) { + const auto min_filter = ToVKSamplerMinMagFilter(desc.min_filter); + const auto mag_filter = ToVKSamplerMinMagFilter(desc.mag_filter); + + const auto address_mode_u = ToVKSamplerAddressMode(desc.width_address_mode); + const auto address_mode_v = ToVKSamplerAddressMode(desc.height_address_mode); + const auto address_mode_w = ToVKSamplerAddressMode(desc.depth_address_mode); + + vk::StructureChain + sampler_chain; + + auto& sampler_info = sampler_chain.get(); + + sampler_info.magFilter = mag_filter; + sampler_info.minFilter = min_filter; + sampler_info.addressModeU = address_mode_u; + sampler_info.addressModeV = address_mode_v; + sampler_info.addressModeW = address_mode_w; + sampler_info.borderColor = vk::BorderColor::eFloatTransparentBlack; + sampler_info.maxLod = VK_LOD_CLAMP_NONE; + + // https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSamplerCreateInfo.html#_description + switch (desc.mip_filter) { + case MipFilter::kBase: + sampler_info.mipmapMode = vk::SamplerMipmapMode::eNearest; + sampler_info.minLod = sampler_info.maxLod = 0.0f; + break; + case MipFilter::kNearest: + sampler_info.mipmapMode = vk::SamplerMipmapMode::eNearest; + break; + case MipFilter::kLinear: + sampler_info.mipmapMode = vk::SamplerMipmapMode::eLinear; + break; + } + + if (yuv_conversion && yuv_conversion->IsValid()) { + sampler_chain.get().conversion = + yuv_conversion->GetConversion(); + + // Spec: If sampler Y'CBCR conversion is enabled and the potential format + // features of the sampler Y'CBCR conversion do not support or enable + // separate reconstruction filters, minFilter and magFilter must be equal to + // the sampler Y'CBCR conversion's chromaFilter. + // + // We don't enable separate reconstruction filters. So, just do what the + // spec. says and use the conversions chromaFilter. + // + // See the validation VUID-VkSamplerCreateInfo-minFilter-01645 for more. + // + sampler_info.minFilter = sampler_info.magFilter = + yuv_conversion->GetDescriptor().get().chromaFilter; + + // Spec: If sampler Y′CBCR conversion is enabled, addressModeU, + // addressModeV, and addressModeW must be + // VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, anisotropyEnable must be VK_FALSE, + // and unnormalizedCoordinates must be VK_FALSE. + // + // See the validation VUID-VkSamplerCreateInfo-addressModeU-01646 for more. + // + sampler_info.addressModeU = vk::SamplerAddressMode::eClampToEdge; + sampler_info.addressModeV = vk::SamplerAddressMode::eClampToEdge; + sampler_info.addressModeW = vk::SamplerAddressMode::eClampToEdge; + sampler_info.anisotropyEnable = false; + sampler_info.unnormalizedCoordinates = false; + } else { + sampler_chain.unlink(); + } + + auto sampler = device.createSamplerUnique(sampler_chain.get()); + if (sampler.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create sampler: " + << vk::to_string(sampler.result); + return {}; + } + + if (!desc.label.empty()) { + ContextVK::SetDebugName(device, sampler.value.get(), desc.label.data()); + } + + return std::move(sampler.value); +} + +SamplerVK::SamplerVK(const vk::Device& device, + const SamplerDescriptor& desc, + std::shared_ptr yuv_conversion) + : Sampler(desc), + device_(device), + sampler_(MakeSharedVK( + CreateSampler(device, desc_, yuv_conversion))), + yuv_conversion_(std::move(yuv_conversion)) { + is_valid_ = sampler_ && !!sampler_->Get(); +} + +SamplerVK::~SamplerVK() = default; + +vk::Sampler SamplerVK::GetSampler() const { + return *sampler_; +} + +std::shared_ptr SamplerVK::CreateVariantForConversion( + std::shared_ptr conversion) const { + if (!conversion || !is_valid_) { + return nullptr; + } + return std::make_shared(device_, desc_, std::move(conversion)); +} + +const std::shared_ptr& SamplerVK::GetYUVConversion() const { + return yuv_conversion_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..70519c9ab4e79d26348c9cf02592035307ece6b2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/sampler_vk.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/core/sampler.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class SamplerLibraryVK; +class YUVConversionVK; + +class SamplerVK final : public Sampler, public BackendCast { + public: + SamplerVK(const vk::Device& device, + const SamplerDescriptor&, + std::shared_ptr yuv_conversion = {}); + + // |Sampler| + ~SamplerVK() override; + + vk::Sampler GetSampler() const; + + std::shared_ptr CreateVariantForConversion( + std::shared_ptr conversion) const; + + const std::shared_ptr& GetYUVConversion() const; + + private: + friend SamplerLibraryVK; + + const vk::Device device_; + SharedHandleVK sampler_; + std::shared_ptr yuv_conversion_; + bool mips_disabled_workaround_ = false; + bool is_valid_ = false; + + SamplerVK(const SamplerVK&) = delete; + + SamplerVK& operator=(const SamplerVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SAMPLER_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a2a12c8354ea456c26e07737765ce8eb07af393 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.cc @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/shader_function_vk.h" + +namespace impeller { + +ShaderFunctionVK::ShaderFunctionVK( + const std::weak_ptr& device_holder, + UniqueID parent_library_id, + std::string name, + ShaderStage stage, + vk::UniqueShaderModule module) + : ShaderFunction(parent_library_id, std::move(name), stage), + module_(std::move(module)), + device_holder_(device_holder) {} + +ShaderFunctionVK::~ShaderFunctionVK() { + std::shared_ptr device_holder = device_holder_.lock(); + if (device_holder) { + module_.reset(); + } else { + module_.release(); + } +} + +const vk::ShaderModule& ShaderFunctionVK::GetModule() const { + return module_.get(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..7286fd4fa27dfaac19c376dfc25f07c2a391ab23 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_function_vk.h @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/shader_function_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/shader_function.h" + +namespace impeller { + +class ShaderFunctionVK final + : public ShaderFunction, + public BackendCast { + public: + // |ShaderFunction| + ~ShaderFunctionVK() override; + + const vk::ShaderModule& GetModule() const; + + private: + friend class ShaderLibraryVK; + + vk::UniqueShaderModule module_; + std::weak_ptr device_holder_; + + ShaderFunctionVK(const std::weak_ptr& device_holder, + UniqueID parent_library_id, + std::string name, + ShaderStage stage, + vk::UniqueShaderModule module); + + ShaderFunctionVK(const ShaderFunctionVK&) = delete; + + ShaderFunctionVK& operator=(const ShaderFunctionVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_FUNCTION_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..3748328b3eaeaed609b8996dc7036491f42f55de --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.cc @@ -0,0 +1,194 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/shader_library_vk.h" + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/shader_function_vk.h" +#include "impeller/shader_archive/shader_archive.h" + +namespace impeller { + +static ShaderStage ToShaderStage(ArchiveShaderType type) { + switch (type) { + case ArchiveShaderType::kVertex: + return ShaderStage::kVertex; + case ArchiveShaderType::kFragment: + return ShaderStage::kFragment; + case ArchiveShaderType::kCompute: + return ShaderStage::kCompute; + } + FML_UNREACHABLE(); +} + +static std::string VKShaderNameToShaderKeyName(const std::string& name, + ShaderStage stage) { + std::stringstream stream; + stream << name; + switch (stage) { + case ShaderStage::kUnknown: + stream << "_unknown_"; + break; + case ShaderStage::kVertex: + stream << "_vertex_"; + break; + case ShaderStage::kFragment: + stream << "_fragment_"; + break; + case ShaderStage::kCompute: + stream << "_compute_"; + break; + } + stream << "main"; + return stream.str(); +} + +ShaderLibraryVK::ShaderLibraryVK( + std::weak_ptr device_holder, + const std::vector>& shader_libraries_data) + : device_holder_(std::move(device_holder)) { + TRACE_EVENT0("impeller", "CreateShaderLibrary"); + bool success = true; + auto iterator = [&](auto type, // + const auto& name, // + const auto& code // + ) -> bool { + const auto stage = ToShaderStage(type); + if (!RegisterFunction(VKShaderNameToShaderKeyName(name, stage), stage, + code)) { + success = false; + return false; + } + return true; + }; + for (const auto& library_data : shader_libraries_data) { + auto blob_library = ShaderArchive{library_data}; + if (!blob_library.IsValid()) { + VALIDATION_LOG << "Could not construct shader blob library."; + return; + } + blob_library.IterateAllShaders(iterator); + } + + if (!success) { + VALIDATION_LOG << "Could not create shader modules for all shader blobs."; + return; + } + is_valid_ = true; +} + +ShaderLibraryVK::~ShaderLibraryVK() = default; + +bool ShaderLibraryVK::IsValid() const { + return is_valid_; +} + +// |ShaderLibrary| +std::shared_ptr ShaderLibraryVK::GetFunction( + std::string_view name, + ShaderStage stage) { + ReaderLock lock(functions_mutex_); + + const auto key = ShaderKey{{name.data(), name.size()}, stage}; + auto found = functions_.find(key); + if (found != functions_.end()) { + return found->second; + } + return nullptr; +} + +// |ShaderLibrary| +void ShaderLibraryVK::RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback) { + const auto result = RegisterFunction(name, stage, code); + if (callback) { + callback(result); + } +} + +static bool IsMappingSPIRV(const fml::Mapping& mapping) { + // https://registry.khronos.org/SPIR-V/specs/1.0/SPIRV.html#Magic + const uint32_t kSPIRVMagic = 0x07230203; + if (mapping.GetSize() < sizeof(kSPIRVMagic)) { + return false; + } + uint32_t magic = 0u; + ::memcpy(&magic, mapping.GetMapping(), sizeof(magic)); + return magic == kSPIRVMagic; +} + +bool ShaderLibraryVK::RegisterFunction( + const std::string& name, + ShaderStage stage, + const std::shared_ptr& code) { + if (!code) { + return false; + } + + if (!IsMappingSPIRV(*code)) { + VALIDATION_LOG << "Shader is not valid SPIRV."; + return false; + } + + vk::ShaderModuleCreateInfo shader_module_info; + + shader_module_info.setPCode( + reinterpret_cast(code->GetMapping())); + shader_module_info.setCodeSize(code->GetSize()); + + auto device_holder = device_holder_.lock(); + if (!device_holder) { + return false; + } + FML_DCHECK(device_holder->GetDevice()); + auto module = + device_holder->GetDevice().createShaderModuleUnique(shader_module_info); + + if (module.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create shader module: " + << vk::to_string(module.result); + return false; + } + + vk::UniqueShaderModule shader_module = std::move(module.value); + ContextVK::SetDebugName(device_holder->GetDevice(), *shader_module, + "Shader " + name); + + WriterLock lock(functions_mutex_); + functions_[ShaderKey{name, stage}] = std::shared_ptr( + new ShaderFunctionVK(device_holder_, + library_id_, // + name, // + stage, // + std::move(shader_module) // + )); + + return true; +} + +// |ShaderLibrary| +void ShaderLibraryVK::UnregisterFunction(std::string name, ShaderStage stage) { + WriterLock lock(functions_mutex_); + + const auto key = ShaderKey{name, stage}; + + auto found = functions_.find(key); + if (found == functions_.end()) { + VALIDATION_LOG << "Library function named " << name + << " was not found, so it couldn't be unregistered."; + return; + } + + functions_.erase(found); + + return; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..1ab2a7285d42c20fc9bc0ec94199082c87f331c2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shader_library_vk.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_LIBRARY_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_LIBRARY_VK_H_ + +#include "impeller/base/comparable.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/shader_key.h" +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +class ShaderLibraryVK final : public ShaderLibrary { + public: + // |ShaderLibrary| + ~ShaderLibraryVK() override; + + // |ShaderLibrary| + bool IsValid() const override; + + private: + friend class ContextVK; + std::weak_ptr device_holder_; + const UniqueID library_id_; + mutable RWMutex functions_mutex_; + ShaderFunctionMap functions_ IPLR_GUARDED_BY(functions_mutex_); + bool is_valid_ = false; + + ShaderLibraryVK( + std::weak_ptr device_holder, + const std::vector>& shader_libraries_data); + + // |ShaderLibrary| + std::shared_ptr GetFunction(std::string_view name, + ShaderStage stage) override; + + // |ShaderLibrary| + void RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback) override; + + bool RegisterFunction(const std::string& name, + ShaderStage stage, + const std::shared_ptr& code); + + // |ShaderLibrary| + void UnregisterFunction(std::string name, ShaderStage stage) override; + + ShaderLibraryVK(const ShaderLibraryVK&) = delete; + + ShaderLibraryVK& operator=(const ShaderLibraryVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHADER_LIBRARY_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..ddfcdf545e3fc99061dd5e82759b5e17bae39429 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..103a52cecd7addd1bf574f4650f3118587859644 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/shared_object_vk.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHARED_OBJECT_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHARED_OBJECT_VK_H_ + +#include + +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class SharedObjectVK { + public: + virtual ~SharedObjectVK() = default; +}; + +template +class SharedObjectVKT : public SharedObjectVK { + public: + using Resource = T; + using UniqueResource = + vk::UniqueHandle; + + explicit SharedObjectVKT(UniqueResource res) : resource_(std::move(res)) {} + + // NOLINTNEXTLINE(google-explicit-constructor) + operator Resource() const { return Get(); } + + const Resource& Get() const { return *resource_; } + + const UniqueResource& GetUniqueWrapper() const { return resource_; } + + private: + UniqueResource resource_; + + SharedObjectVKT(const SharedObjectVKT&) = delete; + + SharedObjectVKT& operator=(const SharedObjectVKT&) = delete; +}; + +template +auto MakeSharedVK( + vk::UniqueHandle handle) { + if (!handle) { + return std::shared_ptr>{nullptr}; + } + return std::make_shared>(std::move(handle)); +} + +template +using SharedHandleVK = std::shared_ptr>; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SHARED_OBJECT_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..e14320f134d5f016f9864d4b167d75f7611ff7c5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.cc @@ -0,0 +1,149 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" + +#include "flutter/fml/trace_event.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +SurfaceContextVK::SurfaceContextVK(const std::shared_ptr& parent) + : Context(parent->GetFlags()), parent_(parent) {} + +SurfaceContextVK::~SurfaceContextVK() = default; + +Context::BackendType SurfaceContextVK::GetBackendType() const { + return parent_->GetBackendType(); +} + +std::string SurfaceContextVK::DescribeGpuModel() const { + return parent_->DescribeGpuModel(); +} + +bool SurfaceContextVK::IsValid() const { + return parent_->IsValid(); +} + +std::shared_ptr SurfaceContextVK::GetResourceAllocator() const { + return parent_->GetResourceAllocator(); +} + +std::shared_ptr SurfaceContextVK::GetShaderLibrary() const { + return parent_->GetShaderLibrary(); +} + +std::shared_ptr SurfaceContextVK::GetSamplerLibrary() const { + return parent_->GetSamplerLibrary(); +} + +std::shared_ptr SurfaceContextVK::GetPipelineLibrary() const { + return parent_->GetPipelineLibrary(); +} + +std::shared_ptr SurfaceContextVK::CreateCommandBuffer() const { + return parent_->CreateCommandBuffer(); +} + +std::shared_ptr SurfaceContextVK::GetCommandQueue() const { + return parent_->GetCommandQueue(); +} + +const std::shared_ptr& SurfaceContextVK::GetCapabilities() + const { + return parent_->GetCapabilities(); +} + +std::shared_ptr SurfaceContextVK::GetIdleWaiter() const { + return parent_->GetIdleWaiter(); +} + +void SurfaceContextVK::Shutdown() { + parent_->Shutdown(); +} + +bool SurfaceContextVK::SetWindowSurface(vk::UniqueSurfaceKHR surface, + const ISize& size) { + return SetSwapchain(SwapchainVK::Create(parent_, std::move(surface), size)); +} + +void SurfaceContextVK::TeardownSwapchain() { + // When background the application, tear down the swapchain to release memory + // from the images. When returning to the foreground, SetWindowSurface will be + // called which will re-create the swapchain. + swapchain_.reset(); +} + +bool SurfaceContextVK::SetSwapchain(std::shared_ptr swapchain) { + if (!swapchain || !swapchain->IsValid()) { + VALIDATION_LOG << "Invalid swapchain."; + return false; + } + swapchain_ = std::move(swapchain); + return true; +} + +std::unique_ptr SurfaceContextVK::AcquireNextSurface() { + TRACE_EVENT0("impeller", __FUNCTION__); + auto surface = swapchain_ ? swapchain_->AcquireNextDrawable() : nullptr; + if (!surface) { + return nullptr; + } + MarkFrameEnd(); + return surface; +} + +void SurfaceContextVK::MarkFrameEnd() { + if (auto pipeline_library = parent_->GetPipelineLibrary()) { + impeller::PipelineLibraryVK::Cast(*pipeline_library) + .DidAcquireSurfaceFrame(); + } + parent_->DisposeThreadLocalCachedResources(); + parent_->GetResourceAllocator()->DebugTraceMemoryStatistics(); +} + +void SurfaceContextVK::UpdateSurfaceSize(const ISize& size) const { + swapchain_->UpdateSurfaceSize(size); +} + +const vk::Device& SurfaceContextVK::GetDevice() const { + return parent_->GetDevice(); +} + +void SurfaceContextVK::InitializeCommonlyUsedShadersIfNeeded() const { + parent_->InitializeCommonlyUsedShadersIfNeeded(); +} + +void SurfaceContextVK::DisposeThreadLocalCachedResources() { + parent_->DisposeThreadLocalCachedResources(); +} + +const std::shared_ptr& SurfaceContextVK::GetParent() const { + return parent_; +} + +bool SurfaceContextVK::EnqueueCommandBuffer( + std::shared_ptr command_buffer) { + return parent_->EnqueueCommandBuffer(std::move(command_buffer)); +} + +bool SurfaceContextVK::FlushCommandBuffers() { + return parent_->FlushCommandBuffers(); +} + +bool SurfaceContextVK::SubmitOnscreen( + std::shared_ptr cmd_buffer) { + swapchain_->AddFinalCommandBuffer(std::move(cmd_buffer)); + return true; +} + +RuntimeStageBackend SurfaceContextVK::GetRuntimeStageBackend() const { + return parent_->GetRuntimeStageBackend(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..9f0b08855d7f9e65fe2f70b3c1fd3b50e156b9cc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk.h @@ -0,0 +1,124 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SURFACE_CONTEXT_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SURFACE_CONTEXT_VK_H_ + +#include + +#include "impeller/base/backend_cast.h" +#include "impeller/core/runtime_types.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +class ContextVK; +class Surface; +class SwapchainVK; + +/// For Vulkan, there is both a ContextVK that implements Context and a +/// SurfaceContextVK that also implements Context and takes a ContextVK as its +/// parent. There is a one to many relationship between ContextVK and +/// SurfaceContextVK. +/// +/// Most operations in this class are delegated to the parent ContextVK. +/// This class specifically manages swapchains and creation of VkSurfaces on +/// Android. By maintaining the swapchain this way, it is possible to have +/// multiple surfaces sharing the same ContextVK without stepping on each +/// other's swapchains. +class SurfaceContextVK : public Context, + public BackendCast { + public: + explicit SurfaceContextVK(const std::shared_ptr& parent); + + // |Context| + ~SurfaceContextVK() override; + + // |Context| + BackendType GetBackendType() const override; + + // |Context| + std::string DescribeGpuModel() const override; + + // |Context| + bool IsValid() const override; + + // |Context| + std::shared_ptr GetResourceAllocator() const override; + + // |Context| + std::shared_ptr GetShaderLibrary() const override; + + // |Context| + std::shared_ptr GetSamplerLibrary() const override; + + // |Context| + std::shared_ptr GetPipelineLibrary() const override; + + // |Context| + std::shared_ptr CreateCommandBuffer() const override; + + // |Context| + const std::shared_ptr& GetCapabilities() const override; + + // |Context| + std::shared_ptr GetCommandQueue() const override; + + // |Context| + std::shared_ptr GetIdleWaiter() const override; + + // |Context| + RuntimeStageBackend GetRuntimeStageBackend() const override; + + // |Context| + bool SubmitOnscreen(std::shared_ptr cmd_buffer) override; + + // |Context| + void Shutdown() override; + + [[nodiscard]] bool SetWindowSurface(vk::UniqueSurfaceKHR surface, + const ISize& size); + + [[nodiscard]] bool SetSwapchain(std::shared_ptr swapchain); + + std::unique_ptr AcquireNextSurface(); + + /// @brief Performs frame incrementing processes like AcquireNextSurface but + /// without the surface. + /// + /// Used by the embedder.h implementations. + void MarkFrameEnd(); + + /// @brief Mark the current swapchain configuration as dirty, forcing it to be + /// recreated on the next frame. + void UpdateSurfaceSize(const ISize& size) const; + + /// @brief Can be called when the surface is destroyed to reduce memory usage. + void TeardownSwapchain(); + + // |Context| + void InitializeCommonlyUsedShadersIfNeeded() const override; + + // |Context| + void DisposeThreadLocalCachedResources() override; + + const vk::Device& GetDevice() const; + + const std::shared_ptr& GetParent() const; + + bool EnqueueCommandBuffer( + std::shared_ptr command_buffer) override; + + bool FlushCommandBuffers() override; + + private: + std::shared_ptr parent_; + std::shared_ptr swapchain_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SURFACE_CONTEXT_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..5cb2c7e83dfa25528936034a15ad8e7c0b894709 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/surface_context_vk_unittests.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/surface_context_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/surface.h" + +namespace impeller { +namespace testing { + +namespace { +vk::UniqueSurfaceKHR CreateSurface(const ContextVK& context) { +#if FML_OS_DARWIN + impeller::vk::MetalSurfaceCreateInfoEXT createInfo = {}; + auto [result, surface] = + context.GetInstance().createMetalSurfaceEXTUnique(createInfo); + FML_DCHECK(result == vk::Result::eSuccess); + return std::move(surface); +#else + return {}; +#endif // FML_OS_DARWIN +} +} // namespace + +TEST(SurfaceContextVK, TearsDownSwapchain) { + SetSwapchainImageSize({100, 100}); + std::shared_ptr context = MockVulkanContextBuilder().Build(); + + vk::UniqueSurfaceKHR surface = CreateSurface(*context); + SurfaceContextVK surface_context(context); + + EXPECT_TRUE(surface_context.SetWindowSurface(std::move(surface), {100, 100})); + EXPECT_NE(surface_context.AcquireNextSurface(), nullptr); + + surface_context.TeardownSwapchain(); + + EXPECT_EQ(surface_context.AcquireNextSurface(), nullptr); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/README.md b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1d08d7e680bf55d50889e2576a98675d3577d085 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/README.md @@ -0,0 +1,4 @@ +Vulkan Swapchains +================= + +Contains implementations of swapchains for Window System Integration (WSI) on different platforms. diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_formats.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_formats.h new file mode 100644 index 0000000000000000000000000000000000000000..4575716ad954cccbea8e0cc389c4570a8285749b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_formats.h @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_FORMATS_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_FORMATS_H_ + +#include "impeller/core/formats.h" +#include "impeller/toolkit/android/hardware_buffer.h" + +namespace impeller { + +constexpr PixelFormat ToPixelFormat(android::HardwareBufferFormat format) { + switch (format) { + case android::HardwareBufferFormat::kR8G8B8A8UNormInt: + return PixelFormat::kR8G8B8A8UNormInt; + } + FML_UNREACHABLE(); +} + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_FORMATS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..cab587ba1dc5a89a12e15c377fb82e2bd25c2394 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.cc @@ -0,0 +1,367 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.h" + +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_formats.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/surface_vk.h" +#include "impeller/toolkit/android/surface_transaction.h" +#include "impeller/toolkit/android/surface_transaction_stats.h" + +namespace impeller { + +static TextureDescriptor ToSwapchainTextureDescriptor( + const android::HardwareBufferDescriptor& ahb_desc) { + TextureDescriptor desc; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.type = TextureType::kTexture2D; + desc.format = ToPixelFormat(ahb_desc.format); + desc.size = ahb_desc.size; + desc.mip_count = 1u; + desc.usage = TextureUsage::kRenderTarget; + desc.sample_count = SampleCount::kCount1; + desc.compression_type = CompressionType::kLossless; + return desc; +} + +AHBFrameSynchronizerVK::AHBFrameSynchronizerVK(const vk::Device& device) { + auto acquire_res = device.createFenceUnique( + vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled}); + if (acquire_res.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create synchronizer."; + return; + } + acquire = std::move(acquire_res.value); + is_valid = true; +} + +AHBFrameSynchronizerVK::~AHBFrameSynchronizerVK() = default; + +bool AHBFrameSynchronizerVK::IsValid() const { + return is_valid; +} + +bool AHBFrameSynchronizerVK::WaitForFence(const vk::Device& device) { + if (auto result = device.waitForFences( + *acquire, // fence + true, // wait all + std::numeric_limits::max() // timeout (ns) + ); + result != vk::Result::eSuccess) { + VALIDATION_LOG << "Fence wait failed: " << vk::to_string(result); + return false; + } + if (auto result = device.resetFences(*acquire); + result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not reset fence: " << vk::to_string(result); + return false; + } + return true; +} + +std::shared_ptr AHBSwapchainImplVK::Create( + const std::weak_ptr& context, + std::weak_ptr surface_control, + const CreateTransactionCB& cb, + const ISize& size, + bool enable_msaa, + size_t swapchain_image_count) { + auto impl = std::shared_ptr( + new AHBSwapchainImplVK(context, std::move(surface_control), cb, size, + enable_msaa, swapchain_image_count)); + return impl->IsValid() ? impl : nullptr; +} + +AHBSwapchainImplVK::AHBSwapchainImplVK( + const std::weak_ptr& context, + std::weak_ptr surface_control, + const CreateTransactionCB& cb, + const ISize& size, + bool enable_msaa, + size_t swapchain_image_count) + : surface_control_(std::move(surface_control)), cb_(cb) { + desc_ = android::HardwareBufferDescriptor::MakeForSwapchainImage(size); + pool_ = + std::make_shared(context, desc_, swapchain_image_count); + if (!pool_->IsValid()) { + return; + } + transients_ = std::make_shared( + context, ToSwapchainTextureDescriptor(desc_), enable_msaa); + + for (auto i = 0u; i < kMaxPendingPresents; i++) { + auto sync = std::make_unique( + ContextVK::Cast(*context.lock()).GetDeviceHolder()->GetDevice()); + if (!sync->IsValid()) { + return; + } + frame_data_.push_back(std::move(sync)); + } + + auto control = surface_control_.lock(); + is_valid_ = control && control->IsValid(); +} + +AHBSwapchainImplVK::~AHBSwapchainImplVK() = default; + +const ISize& AHBSwapchainImplVK::GetSize() const { + return desc_.size; +} + +bool AHBSwapchainImplVK::IsValid() const { + return is_valid_; +} + +const android::HardwareBufferDescriptor& AHBSwapchainImplVK::GetDescriptor() + const { + return desc_; +} + +std::unique_ptr AHBSwapchainImplVK::AcquireNextDrawable() { + auto context = transients_->GetContext().lock(); + if (!context) { + return nullptr; + } + + frame_index_ = (frame_index_ + 1) % kMaxPendingPresents; + + if (!frame_data_[frame_index_]->WaitForFence( + ContextVK::Cast(*context).GetDevice())) { + return nullptr; + } + + if (!is_valid_) { + return nullptr; + } + + auto pool_entry = pool_->Pop(); + + if (!pool_entry.IsValid()) { + VALIDATION_LOG << "Could not create AHB texture source."; + return nullptr; + } + + // Import the render ready semaphore that will block onscreen rendering until + // it is ready. + if (!ImportRenderReady(pool_entry.render_ready_fence, pool_entry.texture)) { + VALIDATION_LOG << "Could wait on render ready fence."; + return nullptr; + } + +#if IMPELLER_DEBUG + if (context) { + ContextVK::Cast(*context).GetGPUTracer()->MarkFrameStart(); + } +#endif // IMPELLER_DEBUG + + auto surface = SurfaceVK::WrapSwapchainImage( + transients_, pool_entry.texture, + [weak = weak_from_this(), texture = pool_entry.texture]() { + auto thiz = weak.lock(); + if (!thiz) { + VALIDATION_LOG << "Swapchain died before image could be presented."; + return false; + } + return thiz->Present(texture); + }); + + if (!surface) { + return nullptr; + } + + return surface; +} + +bool AHBSwapchainImplVK::Present( + const std::shared_ptr& texture) { + auto control = surface_control_.lock(); + if (!control || !control->IsValid()) { + VALIDATION_LOG << "Surface control died before swapchain image could be " + "presented."; + return false; + } + +#if IMPELLER_DEBUG + auto context = transients_->GetContext().lock(); + if (context) { + ContextVK::Cast(*context).GetGPUTracer()->MarkFrameEnd(); + } +#endif // IMPELLER_DEBUG + + if (!texture) { + return false; + } + + auto present_ready = SubmitSignalForPresentReady(texture); + + if (!present_ready) { + VALIDATION_LOG << "Could not submit completion signal."; + return false; + } + + android::SurfaceTransaction transaction = cb_(); + if (!transaction.SetContents(control.get(), // + texture->GetBackingStore(), // + present_ready->CreateFD() // + )) { + VALIDATION_LOG << "Could not set swapchain image contents on the surface " + "control."; + return false; + } + return transaction.Apply( + [texture, weak = weak_from_this()](ASurfaceTransactionStats* stats) { + auto thiz = weak.lock(); + if (!thiz) { + return; + } + thiz->OnTextureUpdatedOnSurfaceControl(texture, stats); + }); +} + +void AHBSwapchainImplVK::AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) { + frame_data_[frame_index_]->final_cmd_buffer = std::move(cmd_buffer); +} + +std::shared_ptr +AHBSwapchainImplVK::SubmitSignalForPresentReady( + const std::shared_ptr& texture) const { + auto context = transients_->GetContext().lock(); + if (!context) { + return nullptr; + } + + auto present_ready = std::make_shared(context); + if (!present_ready || !present_ready->IsValid()) { + return nullptr; + } + + auto& sync = frame_data_[frame_index_]; + auto command_buffer = sync->final_cmd_buffer; + if (!command_buffer) { + return nullptr; + } + CommandBufferVK& command_buffer_vk = CommandBufferVK::Cast(*command_buffer); + const auto command_encoder_vk = command_buffer_vk.GetCommandBuffer(); + if (!command_buffer_vk.EndCommandBuffer()) { + return nullptr; + } + sync->present_ready = present_ready; + + vk::SubmitInfo submit_info; + vk::PipelineStageFlags wait_stage = + vk::PipelineStageFlagBits::eColorAttachmentOutput; + if (sync->render_ready) { + submit_info.setPWaitSemaphores(&sync->render_ready.get()); + submit_info.setWaitSemaphoreCount(1); + submit_info.setWaitDstStageMask(wait_stage); + } + submit_info.setCommandBuffers(command_encoder_vk); + submit_info.setPSignalSemaphores(&sync->present_ready->GetHandle()); + submit_info.setSignalSemaphoreCount(1); + + auto result = ContextVK::Cast(*context).GetGraphicsQueue()->Submit( + submit_info, *sync->acquire); + if (result != vk::Result::eSuccess) { + return nullptr; + } + return present_ready; +} + +vk::UniqueSemaphore AHBSwapchainImplVK::CreateRenderReadySemaphore( + const std::shared_ptr& fd) const { + if (!fd->is_valid()) { + return {}; + } + + auto context = transients_->GetContext().lock(); + if (!context) { + return {}; + } + + const auto& context_vk = ContextVK::Cast(*context); + const auto& device = context_vk.GetDevice(); + + auto signal_wait = device.createSemaphoreUnique({}); + if (signal_wait.result != vk::Result::eSuccess) { + return {}; + } + + context_vk.SetDebugName(*signal_wait.value, "AHBRenderReadySemaphore"); + + vk::ImportSemaphoreFdInfoKHR import_info; + import_info.semaphore = *signal_wait.value; + import_info.fd = fd->get(); + import_info.handleType = vk::ExternalSemaphoreHandleTypeFlagBits::eSyncFd; + // From the spec: Sync FDs can only be imported temporarily. + import_info.flags = vk::SemaphoreImportFlagBitsKHR::eTemporary; + + const auto import_result = device.importSemaphoreFdKHR(import_info); + + if (import_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not import semaphore FD: " + << vk::to_string(import_result); + return {}; + } + + // From the spec: Importing a semaphore payload from a file descriptor + // transfers ownership of the file descriptor from the application to the + // Vulkan implementation. The application must not perform any operations on + // the file descriptor after a successful import. + [[maybe_unused]] auto released = fd->release(); + + return std::move(signal_wait.value); +} + +bool AHBSwapchainImplVK::ImportRenderReady( + const std::shared_ptr& render_ready_fence, + const std::shared_ptr& texture) { + auto context = transients_->GetContext().lock(); + if (!context) { + return false; + } + + // If there is no render ready fence, we are already ready to render into + // the texture. There is nothing more to do. + if (!render_ready_fence || !render_ready_fence->is_valid()) { + frame_data_[frame_index_]->render_ready = {}; + return true; + } + + auto semaphore = CreateRenderReadySemaphore(render_ready_fence); + if (!semaphore) { + return false; + } + // This semaphore will be later used to block the onscreen render pass + // from starting until the system is done reading the onscreen. + frame_data_[frame_index_]->render_ready = std::move(semaphore); + return true; +} + +void AHBSwapchainImplVK::OnTextureUpdatedOnSurfaceControl( + std::shared_ptr texture, + ASurfaceTransactionStats* stats) { + auto control = surface_control_.lock(); + if (!control) { + return; + } + + // Ask for an FD that gets signaled when the previous buffer is released. This + // can be invalid if there is no wait necessary. + auto render_ready_fence = + android::CreatePreviousReleaseFence(*control, stats); + + // The transaction completion indicates that the surface control now + // references the hardware buffer. We can recycle the previous set buffer + // safely. + Lock lock(currently_displayed_texture_mutex_); + auto old_texture = currently_displayed_texture_; + currently_displayed_texture_ = std::move(texture); + pool_->Push(std::move(old_texture), std::move(render_ready_fence)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..aedc6f5d8815fd013d45f445f1f618dabf30e7fa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.h @@ -0,0 +1,162 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_IMPL_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_IMPL_VK_H_ + +#include + +#include "flutter/fml/closure.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h" +#include "impeller/renderer/surface.h" +#include "impeller/toolkit/android/hardware_buffer.h" +#include "impeller/toolkit/android/surface_control.h" +#include "impeller/toolkit/android/surface_transaction.h" +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { + +using CreateTransactionCB = std::function; + +static constexpr const size_t kMaxPendingPresents = 2u; + +struct AHBFrameSynchronizerVK { + vk::UniqueFence acquire; + vk::UniqueSemaphore render_ready = {}; + std::shared_ptr present_ready; + std::shared_ptr final_cmd_buffer; + bool is_valid = false; + + explicit AHBFrameSynchronizerVK(const vk::Device& device); + + ~AHBFrameSynchronizerVK(); + + bool IsValid() const; + + bool WaitForFence(const vk::Device& device); +}; + +//------------------------------------------------------------------------------ +/// @brief The implementation of a swapchain at a specific size. Resizes to +/// the surface will cause the instance of the swapchain impl at +/// that size to be discarded along with all its caches and +/// transients. +/// +class AHBSwapchainImplVK final + : public std::enable_shared_from_this { + public: + //---------------------------------------------------------------------------- + /// @brief Create a swapchain of a specific size whose images will be + /// presented to the provided surface control. + /// + /// @param[in] context The context whose allocators will be used to + /// create swapchain image resources. + /// @param[in] surface_control The surface control to which the swapchain + /// images will be presented. + /// @param[in] size The size of the swapchain images. This is + /// constant for the lifecycle of the swapchain + /// impl. + /// @param[in] enable_msaa If the swapchain images will be presented + /// using a render target that enables MSAA. This + /// allows for additional caching of transients. + /// + /// @return A valid swapchain impl if one can be created. `nullptr` + /// otherwise. + /// + static std::shared_ptr Create( + const std::weak_ptr& context, + std::weak_ptr surface_control, + const CreateTransactionCB& cb, + const ISize& size, + bool enable_msaa, + size_t swapchain_image_count); + + ~AHBSwapchainImplVK(); + + AHBSwapchainImplVK(const AHBSwapchainImplVK&) = delete; + + AHBSwapchainImplVK& operator=(const AHBSwapchainImplVK&) = delete; + + //---------------------------------------------------------------------------- + /// @return The size of the swapchain images that will be displayed on the + /// surface control. + /// + const ISize& GetSize() const; + + //---------------------------------------------------------------------------- + /// @return If the swapchain impl is valid. If it is not, the instance + /// must be discarded. There is no error recovery. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Get the descriptor used to create the hardware buffers that + /// will be displayed on the surface control. + /// + /// @return The descriptor. + /// + const android::HardwareBufferDescriptor& GetDescriptor() const; + + //---------------------------------------------------------------------------- + /// @brief Acquire the next surface that can be used to present to the + /// swapchain. + /// + /// @return A surface if one can be created. If one cannot be created, it + /// is likely due to resource exhaustion. + /// + std::unique_ptr AcquireNextDrawable(); + + void AddFinalCommandBuffer(std::shared_ptr cmd_buffer); + + private: + using AutoSemaSignaler = std::shared_ptr; + + std::weak_ptr surface_control_; + android::HardwareBufferDescriptor desc_; + std::shared_ptr pool_; + std::shared_ptr transients_; + + // In C++20, this mutex can be replaced by the shared pointer specialization + // of std::atomic. + Mutex currently_displayed_texture_mutex_; + std::shared_ptr currently_displayed_texture_ + IPLR_GUARDED_BY(currently_displayed_texture_mutex_); + + std::vector> frame_data_; + size_t frame_index_ = 0; + CreateTransactionCB cb_; + bool is_valid_ = false; + + explicit AHBSwapchainImplVK( + const std::weak_ptr& context, + std::weak_ptr surface_control, + const CreateTransactionCB& cb, + const ISize& size, + bool enable_msaa, + size_t swapchain_image_count); + + bool Present(const std::shared_ptr& texture); + + vk::UniqueSemaphore CreateRenderReadySemaphore( + const std::shared_ptr& fd) const; + + bool ImportRenderReady( + const std::shared_ptr& render_ready_fence, + const std::shared_ptr& texture); + + std::shared_ptr SubmitSignalForPresentReady( + const std::shared_ptr& texture) const; + + void OnTextureUpdatedOnSurfaceControl( + std::shared_ptr texture, + ASurfaceTransactionStats* stats); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_IMPL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..682a37b9aa1776df45e6d0ff4435fe66cad4d54d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.cc @@ -0,0 +1,97 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h" + +#include "flutter/fml/trace_event.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_formats.h" +#include "third_party/vulkan-deps/vulkan-headers/src/include/vulkan/vulkan_enums.hpp" + +namespace impeller { + +bool AHBSwapchainVK::IsAvailableOnPlatform() { + return android::SurfaceControl::IsAvailableOnPlatform() && + android::HardwareBuffer::IsAvailableOnPlatform(); +} + +AHBSwapchainVK::AHBSwapchainVK(const std::shared_ptr& context, + ANativeWindow* window, + const CreateTransactionCB& cb, + const vk::UniqueSurfaceKHR& surface, + const ISize& size, + bool enable_msaa) + : context_(context), + surface_control_( + std::make_shared(window, "ImpellerSurface")), + enable_msaa_(enable_msaa), + cb_(cb) { + const auto [caps_result, surface_caps] = + ContextVK::Cast(*context).GetPhysicalDevice().getSurfaceCapabilitiesKHR( + *surface); + if (caps_result == vk::Result::eSuccess) { + swapchain_image_count_ = + std::clamp(surface_caps.minImageCount + 1u, // preferred image count + surface_caps.minImageCount, // min count cannot be zero + surface_caps.maxImageCount == 0u + ? surface_caps.minImageCount + 1u + : surface_caps.maxImageCount // max zero means no limit + ); + } + + UpdateSurfaceSize(size); +} + +AHBSwapchainVK::~AHBSwapchainVK() = default; + +// |SwapchainVK| +bool AHBSwapchainVK::IsValid() const { + return impl_ ? impl_->IsValid() : false; +} + +// |SwapchainVK| +std::unique_ptr AHBSwapchainVK::AcquireNextDrawable() { + if (!IsValid()) { + return nullptr; + } + + TRACE_EVENT0("impeller", __FUNCTION__); + return impl_->AcquireNextDrawable(); +} + +// |SwapchainVK| +vk::Format AHBSwapchainVK::GetSurfaceFormat() const { + return IsValid() + ? ToVKImageFormat(ToPixelFormat(impl_->GetDescriptor().format)) + : vk::Format::eUndefined; +} + +// |SwapchainVK| +void AHBSwapchainVK::AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) const { + return impl_->AddFinalCommandBuffer(cmd_buffer); +} + +// |SwapchainVK| +void AHBSwapchainVK::UpdateSurfaceSize(const ISize& size) { + if (impl_ && impl_->GetSize() == size) { + return; + } + TRACE_EVENT0("impeller", __FUNCTION__); + auto impl = AHBSwapchainImplVK::Create(context_, // + surface_control_, // + cb_, // + size, // + enable_msaa_, // + swapchain_image_count_ // + ); + if (!impl || !impl->IsValid()) { + VALIDATION_LOG << "Could not resize swapchain to size: " << size; + return; + } + impl_ = std::move(impl); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..40a700f215e499bda19673e97a47c6523e662539 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_VK_H_ + +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_impl_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h" +#include "impeller/toolkit/android/native_window.h" +#include "impeller/toolkit/android/surface_control.h" +#include "impeller/toolkit/android/surface_transaction.h" + +namespace impeller { + +using CreateTransactionCB = std::function; + +//------------------------------------------------------------------------------ +/// @brief The implementation of a swapchain that uses hardware buffers +/// presented to a given surface control on Android. +/// +/// @warning This swapchain implementation is not available on all Android +/// versions supported by Flutter. Perform the +/// `IsAvailableOnPlatform` check and fallback to KHR swapchains if +/// this type of swapchain cannot be created. The available building +/// blocks for these kinds of swapchains are only available on +/// Android API levels >= 29. +/// +class AHBSwapchainVK final : public SwapchainVK { + public: + static bool IsAvailableOnPlatform(); + + // |SwapchainVK| + ~AHBSwapchainVK() override; + + AHBSwapchainVK(const AHBSwapchainVK&) = delete; + + AHBSwapchainVK& operator=(const AHBSwapchainVK&) = delete; + + // |SwapchainVK| + bool IsValid() const override; + + // |SwapchainVK| + std::unique_ptr AcquireNextDrawable() override; + + // |SwapchainVK| + vk::Format GetSurfaceFormat() const override; + + // |SwapchainVK| + void UpdateSurfaceSize(const ISize& size) override; + + // |SwapchainVK| + void AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) const override; + + private: + friend class SwapchainVK; + + std::weak_ptr context_; + std::shared_ptr surface_control_; + const bool enable_msaa_; + size_t swapchain_image_count_ = 3u; + CreateTransactionCB cb_; + std::shared_ptr impl_; + + explicit AHBSwapchainVK(const std::shared_ptr& context, + ANativeWindow* window, + const CreateTransactionCB& cb, + const vk::UniqueSurfaceKHR& surface, + const ISize& size, + bool enable_msaa); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_SWAPCHAIN_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfeb182eeb3bb76cf61dcb990ee2f41c84101d38 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.cc @@ -0,0 +1,101 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.h" + +#include "flutter/fml/trace_event.h" + +namespace impeller { + +AHBTexturePoolVK::AHBTexturePoolVK(std::weak_ptr context, + android::HardwareBufferDescriptor desc, + size_t max_entries) + : context_(std::move(context)), desc_(desc), max_entries_(max_entries) { + if (!desc_.IsAllocatable()) { + VALIDATION_LOG << "Swapchain image is not allocatable."; + return; + } + for (auto i = 0u; i < max_entries_; i++) { + auto texture = CreateTexture(); + if (!texture->IsValid()) { + return; + } + pool_.emplace_back(std::move(texture)); + } + is_valid_ = true; +} + +AHBTexturePoolVK::~AHBTexturePoolVK() = default; + +AHBTexturePoolVK::PoolEntry AHBTexturePoolVK::Pop() { + { + Lock lock(pool_mutex_); + if (!pool_.empty()) { + // Buffers are pushed to the back of the queue. To give the ready fences + // the most time to signal, pick a buffer from the front of the queue. + auto entry = pool_.front(); + pool_.pop_front(); + return entry; + } + } + return PoolEntry{CreateTexture()}; +} + +void AHBTexturePoolVK::Push(std::shared_ptr texture, + fml::UniqueFD render_ready_fence) { + if (!texture) { + return; + } + Lock lock(pool_mutex_); + pool_.push_back(PoolEntry{std::move(texture), std::move(render_ready_fence)}); + PerformGCLocked(); +} + +std::shared_ptr AHBTexturePoolVK::CreateTexture() const { + TRACE_EVENT0("impeller", "CreateSwapchainTexture"); + auto context = context_.lock(); + if (!context) { + VALIDATION_LOG << "Context died before image could be created."; + return nullptr; + } + + auto ahb = std::make_unique(desc_); + if (!ahb->IsValid()) { + VALIDATION_LOG << "Could not create hardware buffer of size: " + << desc_.size; + return nullptr; + } + + auto ahb_texture_source = + std::make_shared(context, std::move(ahb), true); + if (!ahb_texture_source->IsValid()) { + VALIDATION_LOG << "Could not create hardware buffer texture source for " + "swapchain image of size: " + << desc_.size; + return nullptr; + } + + return ahb_texture_source; +} + +void AHBTexturePoolVK::PerformGC() { + Lock lock(pool_mutex_); + PerformGCLocked(); +} + +void AHBTexturePoolVK::PerformGCLocked() { + while (!pool_.empty() && (pool_.size() > max_entries_)) { + // Buffers are pushed to the back of the queue and popped from the front. + // The ones at the back should be given the most time for their fences to + // signal. If we are going to get rid of textures, they might as well be the + // newest ones since their fences will take the longest to signal. + pool_.pop_back(); + } +} + +bool AHBTexturePoolVK::IsValid() const { + return is_valid_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..f6d38408d4a4bd6f445056a6d6bb12ca0d467f86 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/ahb_texture_pool_vk.h @@ -0,0 +1,123 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_TEXTURE_POOL_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_TEXTURE_POOL_VK_H_ + +#include + +#include "flutter/fml/unique_fd.h" +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Maintains a bounded pool of hardware buffer backed texture +/// sources that can be used as swapchain images. +/// +/// The number of cached entries in the texture pool is capped to a +/// caller specified value. +/// +/// If a previously cached entry cannot be obtained from the pool, a +/// new entry is created. The only case where a valid texture source +/// cannot be obtained is due to resource exhaustion. +/// +/// Pools are thread-safe. +/// +class AHBTexturePoolVK { + public: + struct PoolEntry { + std::shared_ptr texture; + std::shared_ptr render_ready_fence; + + explicit PoolEntry(std::shared_ptr p_item, + fml::UniqueFD p_render_ready_fence = {}) + : texture(std::move(p_item)), + render_ready_fence(std::make_shared( + std::move(p_render_ready_fence))) {} + + constexpr bool IsValid() const { return !!texture; } + }; + + //---------------------------------------------------------------------------- + /// @brief Create a new (empty) texture pool. + /// + /// @param[in] context The context whose allocators will be used to + /// create the resources for the texture sources. + /// @param[in] desc The descriptor of the hardware buffers that + /// will be used to create the backing stores of + /// the texture sources. + /// @param[in] max_entries The maximum entries that will remain cached + /// in the pool. + /// + explicit AHBTexturePoolVK(std::weak_ptr context, + android::HardwareBufferDescriptor desc, + size_t max_entries = 3u); + + ~AHBTexturePoolVK(); + + AHBTexturePoolVK(const AHBTexturePoolVK&) = delete; + + AHBTexturePoolVK& operator=(const AHBTexturePoolVK&) = delete; + + //---------------------------------------------------------------------------- + /// @brief If the pool can create and pool hardware buffer backed texture + /// sources. The only reason valid textures cannot be obtained + /// from a valid pool is because of resource exhaustion. + /// + /// @return `true` if valid, `false` otherwise. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Pops an texture source from the pool. If the pool is empty, a + /// new texture source is created and returned. + /// + /// This operation is thread-safe. + /// + /// @return A texture source that can be used as a swapchain image. This + /// can be nullptr in case of resource exhaustion. + /// + PoolEntry Pop(); + + //---------------------------------------------------------------------------- + /// @brief Push a popped texture back into the pool. This also performs a + /// GC. + /// + /// This operation is thread-safe. + /// + /// @warning Only a texture source obtained from the same pool can be + /// returned to it. It is user error to mix and match texture + /// sources from different pools. + /// + /// @param[in] texture The texture to be returned to the pool. + /// + void Push(std::shared_ptr texture, + fml::UniqueFD render_ready_fence); + + //---------------------------------------------------------------------------- + /// @brief Perform an explicit GC of the pool items. This happens + /// implicitly when a texture source us pushed into the pool but + /// one may be necessary explicitly if there is no push back into + /// the pool for a long time. + /// + void PerformGC(); + + private: + const std::weak_ptr context_; + const android::HardwareBufferDescriptor desc_; + const size_t max_entries_; + bool is_valid_ = false; + Mutex pool_mutex_; + std::deque pool_ IPLR_GUARDED_BY(pool_mutex_); + + void PerformGCLocked() IPLR_REQUIRES(pool_mutex_); + + std::shared_ptr CreateTexture() const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_AHB_TEXTURE_POOL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..0fb9b270a23658812ab0e74b40566684d8b6c471 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.cc @@ -0,0 +1,70 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h" + +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { + +ExternalSemaphoreVK::ExternalSemaphoreVK( + const std::shared_ptr& context) { + if (!context) { + return; + } + vk::StructureChain + info; + + info.get().handleTypes = + vk::ExternalSemaphoreHandleTypeFlagBits::eSyncFd; + + const auto& context_vk = ContextVK::Cast(*context); + auto [result, semaphore] = + context_vk.GetDevice().createSemaphoreUnique(info.get()); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create external fence: " + << vk::to_string(result); + return; + } + + context_vk.SetDebugName(semaphore.get(), "ExternalSemaphoreSyncFD"); + + semaphore_ = MakeSharedVK(std::move(semaphore)); +} + +ExternalSemaphoreVK::~ExternalSemaphoreVK() = default; + +bool ExternalSemaphoreVK::IsValid() const { + return !!semaphore_; +} + +fml::UniqueFD ExternalSemaphoreVK::CreateFD() const { + if (!IsValid()) { + return {}; + } + vk::SemaphoreGetFdInfoKHR info; + info.semaphore = semaphore_->Get(); + info.handleType = vk::ExternalSemaphoreHandleTypeFlagBits::eSyncFd; + auto [result, fd] = + semaphore_->GetUniqueWrapper().getOwner().getSemaphoreFdKHR(info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not export external fence FD: " + << vk::to_string(result); + return {}; + } + return fml::UniqueFD{fd}; +} + +const vk::Semaphore& ExternalSemaphoreVK::GetHandle() const { + return semaphore_->Get(); +} + +const SharedHandleVK& ExternalSemaphoreVK::GetSharedHandle() + const { + return semaphore_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..31d87362489e6f9d3c2d36f12678c3dc49caf9f2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/ahb/external_semaphore_vk.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_EXTERNAL_SEMAPHORE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_EXTERNAL_SEMAPHORE_VK_H_ + +#include "flutter/fml/unique_fd.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/context.h" +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A Vulkan semaphore that can be exported as a platform specific +/// file descriptor. +/// +/// The semaphore are exported as sync file descriptors. +/// +/// @warning Only semaphore that have been signaled or have a single +/// operation pending can be exported. Make sure to submit a fence +/// signalling operation to a queue before attempted to obtain a +/// file descriptor for the fence. +/// +class ExternalSemaphoreVK { + public: + //---------------------------------------------------------------------------- + /// @brief Create a new un-signaled semaphore that can be exported as a + /// sync file descriptor. + /// + /// @param[in] context The device context. + /// + explicit ExternalSemaphoreVK(const std::shared_ptr& context); + + ~ExternalSemaphoreVK(); + + ExternalSemaphoreVK(const ExternalSemaphoreVK&) = delete; + + ExternalSemaphoreVK& operator=(const ExternalSemaphoreVK&) = delete; + + //---------------------------------------------------------------------------- + /// @brief If a valid fence could be created. + /// + /// @return True if valid, False otherwise. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Create a new sync file descriptor for the underlying + /// semaphore. + /// + /// The semaphore must already be signaled or have a signal + /// operation pending in a queue. There are no checks for this in + /// the implementation and only Vulkan validation will catch such + /// a misuse and undefined behavior. + /// + /// @warning Implementations are also allowed to return invalid file + /// descriptors in case a semaphore has already been signaled. So + /// it is not necessary an error to obtain an invalid descriptor + /// from this call. For APIs that are meant to consume such + /// descriptors, pass -1 as the file handle. + /// + /// Since this call can return an invalid FD even in case of + /// success, make sure to make the `IsValid` check before + /// attempting to export a FD. + /// + /// @return A (potentially invalid even in case of success) file + /// descriptor. + /// + fml::UniqueFD CreateFD() const; + + const vk::Semaphore& GetHandle() const; + + const SharedHandleVK& GetSharedHandle() const; + + private: + SharedHandleVK semaphore_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_AHB_EXTERNAL_SEMAPHORE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/README.md b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..886de7e51bc894efabe81c15908bf965dbb14883 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/README.md @@ -0,0 +1,4 @@ +KHR Swapchain +============= + +An implementation of a Vulkan swapchain that depends on [`VK_KHR_swapchain`](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_swapchain.html). This swapchain is available on most platforms but may not be ideal on all. But, it is a good fallback. diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..af71a1badf25dbf3ad3f2ee3d20c455e2176682a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.cc @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h" + +namespace impeller { + +KHRSwapchainImageVK::KHRSwapchainImageVK(TextureDescriptor desc, + const vk::Device& device, + vk::Image image) + : TextureSourceVK(desc), image_(image) { + vk::ImageViewCreateInfo view_info; + view_info.image = image_; + view_info.viewType = vk::ImageViewType::e2D; + view_info.format = ToVKImageFormat(desc.format); + view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; + view_info.subresourceRange.baseMipLevel = 0u; + view_info.subresourceRange.baseArrayLayer = 0u; + view_info.subresourceRange.levelCount = desc.mip_count; + view_info.subresourceRange.layerCount = ToArrayLayerCount(desc.type); + + auto [view_result, view] = device.createImageViewUnique(view_info); + if (view_result != vk::Result::eSuccess) { + return; + } + + image_view_ = std::move(view); + is_valid_ = true; +} + +KHRSwapchainImageVK::~KHRSwapchainImageVK() = default; + +bool KHRSwapchainImageVK::IsValid() const { + return is_valid_; +} + +// |TextureSourceVK| +vk::Image KHRSwapchainImageVK::GetImage() const { + return image_; +} + +// |TextureSourceVK| +vk::ImageView KHRSwapchainImageVK::GetImageView() const { + return image_view_.get(); +} + +// |TextureSourceVK| +vk::ImageView KHRSwapchainImageVK::GetRenderTargetView() const { + return image_view_.get(); +} + +// |TextureSourceVK| +bool KHRSwapchainImageVK::IsSwapchainImage() const { + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..92afa32eea0e2933f657ab963491f9c962368996 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMAGE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMAGE_VK_H_ + +#include "impeller/geometry/size.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class KHRSwapchainImageVK final : public TextureSourceVK { + public: + KHRSwapchainImageVK(TextureDescriptor desc, + const vk::Device& device, + vk::Image image); + + // |TextureSourceVK| + ~KHRSwapchainImageVK() override; + + bool IsValid() const; + + // |TextureSourceVK| + vk::Image GetImage() const override; + + // |TextureSourceVK| + vk::ImageView GetImageView() const override; + + // |TextureSourceVK| + vk::ImageView GetRenderTargetView() const override; + + // |TextureSourceVK| + bool IsSwapchainImage() const override; + + private: + vk::Image image_ = VK_NULL_HANDLE; + vk::UniqueImageView image_view_ = {}; + bool is_valid_ = false; + + KHRSwapchainImageVK(const KHRSwapchainImageVK&) = delete; + + KHRSwapchainImageVK& operator=(const KHRSwapchainImageVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMAGE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..84ebc9e944df9d7342c4dd1ba2f6c6e14488cda1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.cc @@ -0,0 +1,521 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h" + +#include "fml/synchronization/semaphore.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/surface_vk.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +static constexpr size_t kMaxFramesInFlight = 2u; + +struct KHRFrameSynchronizerVK { + vk::UniqueFence acquire; + vk::UniqueSemaphore render_ready; + vk::UniqueSemaphore present_ready; + std::shared_ptr final_cmd_buffer; + bool is_valid = false; + // Whether the renderer attached an onscreen command buffer to render to. + bool has_onscreen = false; + + explicit KHRFrameSynchronizerVK(const vk::Device& device) { + auto acquire_res = device.createFenceUnique( + vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled}); + auto render_res = device.createSemaphoreUnique({}); + auto present_res = device.createSemaphoreUnique({}); + if (acquire_res.result != vk::Result::eSuccess || + render_res.result != vk::Result::eSuccess || + present_res.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create synchronizer."; + return; + } + acquire = std::move(acquire_res.value); + render_ready = std::move(render_res.value); + present_ready = std::move(present_res.value); + is_valid = true; + } + + ~KHRFrameSynchronizerVK() = default; + + bool WaitForFence(const vk::Device& device) { + if (auto result = device.waitForFences( + *acquire, // fence + true, // wait all + std::numeric_limits::max() // timeout (ns) + ); + result != vk::Result::eSuccess) { + VALIDATION_LOG << "Fence wait failed: " << vk::to_string(result); + return false; + } + if (auto result = device.resetFences(*acquire); + result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not reset fence: " << vk::to_string(result); + return false; + } + return true; + } +}; + +static bool ContainsFormat(const std::vector& formats, + vk::SurfaceFormatKHR format) { + return std::find(formats.begin(), formats.end(), format) != formats.end(); +} + +static std::optional ChooseSurfaceFormat( + const std::vector& formats, + PixelFormat preference) { + const auto colorspace = vk::ColorSpaceKHR::eSrgbNonlinear; + const auto vk_preference = + vk::SurfaceFormatKHR{ToVKImageFormat(preference), colorspace}; + if (ContainsFormat(formats, vk_preference)) { + return vk_preference; + } + + std::vector options = { + {vk::Format::eB8G8R8A8Unorm, colorspace}, + {vk::Format::eR8G8B8A8Unorm, colorspace}}; + for (const auto& format : options) { + if (ContainsFormat(formats, format)) { + return format; + } + } + + return std::nullopt; +} + +static std::optional ChooseAlphaCompositionMode( + vk::CompositeAlphaFlagsKHR flags) { + if (flags & vk::CompositeAlphaFlagBitsKHR::eInherit) { + return vk::CompositeAlphaFlagBitsKHR::eInherit; + } + if (flags & vk::CompositeAlphaFlagBitsKHR::ePreMultiplied) { + return vk::CompositeAlphaFlagBitsKHR::ePreMultiplied; + } + if (flags & vk::CompositeAlphaFlagBitsKHR::ePostMultiplied) { + return vk::CompositeAlphaFlagBitsKHR::ePostMultiplied; + } + if (flags & vk::CompositeAlphaFlagBitsKHR::eOpaque) { + return vk::CompositeAlphaFlagBitsKHR::eOpaque; + } + + return std::nullopt; +} + +std::shared_ptr KHRSwapchainImplVK::Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa, + vk::SwapchainKHR old_swapchain) { + return std::shared_ptr(new KHRSwapchainImplVK( + context, std::move(surface), size, enable_msaa, old_swapchain)); +} + +KHRSwapchainImplVK::KHRSwapchainImplVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa, + vk::SwapchainKHR old_swapchain) { + if (!context) { + VALIDATION_LOG << "Cannot create a swapchain without a context."; + return; + } + + auto& vk_context = ContextVK::Cast(*context); + + const auto [caps_result, surface_caps] = + vk_context.GetPhysicalDevice().getSurfaceCapabilitiesKHR(*surface); + if (caps_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get surface capabilities: " + << vk::to_string(caps_result); + return; + } + + auto [formats_result, formats] = + vk_context.GetPhysicalDevice().getSurfaceFormatsKHR(*surface); + if (formats_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get surface formats: " + << vk::to_string(formats_result); + return; + } + + const auto format = ChooseSurfaceFormat( + formats, vk_context.GetCapabilities()->GetDefaultColorFormat()); + if (!format.has_value()) { + VALIDATION_LOG << "Swapchain has no supported formats."; + return; + } + vk_context.SetOffscreenFormat(ToPixelFormat(format.value().format)); + + const auto composite = + ChooseAlphaCompositionMode(surface_caps.supportedCompositeAlpha); + if (!composite.has_value()) { + VALIDATION_LOG << "No composition mode supported."; + return; + } + + vk::SwapchainCreateInfoKHR swapchain_info; + swapchain_info.surface = *surface; + swapchain_info.imageFormat = format.value().format; + swapchain_info.imageColorSpace = format.value().colorSpace; + swapchain_info.presentMode = vk::PresentModeKHR::eFifo; + swapchain_info.imageExtent = vk::Extent2D{ + std::clamp(static_cast(size.width), + surface_caps.minImageExtent.width, + surface_caps.maxImageExtent.width), + std::clamp(static_cast(size.height), + surface_caps.minImageExtent.height, + surface_caps.maxImageExtent.height), + }; + swapchain_info.minImageCount = + std::clamp(surface_caps.minImageCount + 1u, // preferred image count + surface_caps.minImageCount, // min count cannot be zero + surface_caps.maxImageCount == 0u + ? surface_caps.minImageCount + 1u + : surface_caps.maxImageCount // max zero means no limit + ); + swapchain_info.imageArrayLayers = 1u; + // Swapchain images are primarily used as color attachments (via resolve) or + // input attachments. + swapchain_info.imageUsage = vk::ImageUsageFlagBits::eColorAttachment | + vk::ImageUsageFlagBits::eInputAttachment; + swapchain_info.preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity; + swapchain_info.compositeAlpha = composite.value(); + // If we set the clipped value to true, Vulkan expects we will never read back + // from the buffer. This is analogous to [CAMetalLayer framebufferOnly] in + // Metal. + swapchain_info.clipped = true; + // Setting queue family indices is irrelevant since the present mode is + // exclusive. + swapchain_info.imageSharingMode = vk::SharingMode::eExclusive; + swapchain_info.oldSwapchain = old_swapchain; + + auto [swapchain_result, swapchain] = + vk_context.GetDevice().createSwapchainKHRUnique(swapchain_info); + if (swapchain_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create swapchain: " + << vk::to_string(swapchain_result); + return; + } + + auto [images_result, images] = + vk_context.GetDevice().getSwapchainImagesKHR(*swapchain); + if (images_result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not get swapchain images."; + return; + } + + TextureDescriptor texture_desc; + texture_desc.usage = TextureUsage::kRenderTarget; + texture_desc.storage_mode = StorageMode::kDevicePrivate; + texture_desc.format = ToPixelFormat(swapchain_info.imageFormat); + texture_desc.size = ISize::MakeWH(swapchain_info.imageExtent.width, + swapchain_info.imageExtent.height); + + std::vector> swapchain_images; + for (const auto& image : images) { + auto swapchain_image = std::make_shared( + texture_desc, // texture descriptor + vk_context.GetDevice(), // device + image // image + ); + if (!swapchain_image->IsValid()) { + VALIDATION_LOG << "Could not create swapchain image."; + return; + } + ContextVK::SetDebugName( + vk_context.GetDevice(), swapchain_image->GetImage(), + "SwapchainImage" + std::to_string(swapchain_images.size())); + ContextVK::SetDebugName( + vk_context.GetDevice(), swapchain_image->GetImageView(), + "SwapchainImageView" + std::to_string(swapchain_images.size())); + + swapchain_images.emplace_back(swapchain_image); + } + + std::vector> synchronizers; + for (size_t i = 0u; i < kMaxFramesInFlight; i++) { + auto sync = + std::make_unique(vk_context.GetDevice()); + if (!sync->is_valid) { + VALIDATION_LOG << "Could not create frame synchronizers."; + return; + } + synchronizers.emplace_back(std::move(sync)); + } + FML_DCHECK(!synchronizers.empty()); + + context_ = context; + surface_ = std::move(surface); + surface_format_ = swapchain_info.imageFormat; + swapchain_ = std::move(swapchain); + transients_ = std::make_shared(context, texture_desc, + enable_msaa); + images_ = std::move(swapchain_images); + synchronizers_ = std::move(synchronizers); + current_frame_ = synchronizers_.size() - 1u; + size_ = size; + enable_msaa_ = enable_msaa; + is_valid_ = true; +} + +KHRSwapchainImplVK::~KHRSwapchainImplVK() { + DestroySwapchain(); +} + +const ISize& KHRSwapchainImplVK::GetSize() const { + return size_; +} + +std::optional KHRSwapchainImplVK::GetCurrentUnderlyingSurfaceSize() + const { + if (!IsValid()) { + return std::nullopt; + } + + auto context = context_.lock(); + if (!context) { + return std::nullopt; + } + + auto& vk_context = ContextVK::Cast(*context); + const auto [result, surface_caps] = + vk_context.GetPhysicalDevice().getSurfaceCapabilitiesKHR(surface_.get()); + if (result != vk::Result::eSuccess) { + return std::nullopt; + } + + // From the spec: `currentExtent` is the current width and height of the + // surface, or the special value (0xFFFFFFFF, 0xFFFFFFFF) indicating that the + // surface size will be determined by the extent of a swapchain targeting the + // surface. + constexpr uint32_t kCurrentExtentsPlaceholder = 0xFFFFFFFF; + if (surface_caps.currentExtent.width == kCurrentExtentsPlaceholder || + surface_caps.currentExtent.height == kCurrentExtentsPlaceholder) { + return std::nullopt; + } + + return ISize::MakeWH(surface_caps.currentExtent.width, + surface_caps.currentExtent.height); +} + +bool KHRSwapchainImplVK::IsValid() const { + return is_valid_; +} + +void KHRSwapchainImplVK::WaitIdle() const { + if (auto context = context_.lock()) { + [[maybe_unused]] auto result = + ContextVK::Cast(*context).GetDevice().waitIdle(); + } +} + +std::pair +KHRSwapchainImplVK::DestroySwapchain() { + WaitIdle(); + is_valid_ = false; + synchronizers_.clear(); + images_.clear(); + context_.reset(); + return {std::move(surface_), std::move(swapchain_)}; +} + +vk::Format KHRSwapchainImplVK::GetSurfaceFormat() const { + return surface_format_; +} + +std::shared_ptr KHRSwapchainImplVK::GetContext() const { + return context_.lock(); +} + +KHRSwapchainImplVK::AcquireResult KHRSwapchainImplVK::AcquireNextDrawable() { + auto context_strong = context_.lock(); + if (!context_strong) { + return KHRSwapchainImplVK::AcquireResult{}; + } + + const auto& context = ContextVK::Cast(*context_strong); + + current_frame_ = (current_frame_ + 1u) % synchronizers_.size(); + + const auto& sync = synchronizers_[current_frame_]; + + //---------------------------------------------------------------------------- + /// Wait on the host for the synchronizer fence. + /// + if (!sync->WaitForFence(context.GetDevice())) { + VALIDATION_LOG << "Could not wait for fence."; + return KHRSwapchainImplVK::AcquireResult{}; + } + + //---------------------------------------------------------------------------- + /// Get the next image index. + /// + /// @bug Non-infinite timeouts are not supported on some older Android + /// devices and the only indication we get is log spam which serves to + /// add confusion. Just use an infinite timeout instead of being + /// defensive. + auto [acq_result, index] = context.GetDevice().acquireNextImageKHR( + *swapchain_, // swapchain + std::numeric_limits::max(), // timeout (ns) + *sync->render_ready, // signal semaphore + nullptr // fence + ); + + switch (acq_result) { + case vk::Result::eSuccess: + // Keep going. + break; + case vk::Result::eSuboptimalKHR: + case vk::Result::eErrorOutOfDateKHR: + // A recoverable error. Just say we are out of date. + return AcquireResult{true /* out of date */}; + break; + default: + // An unrecoverable error. + VALIDATION_LOG << "Could not acquire next swapchain image: " + << vk::to_string(acq_result); + return AcquireResult{false /* out of date */}; + } + + if (index >= images_.size()) { + VALIDATION_LOG << "Swapchain returned an invalid image index."; + return KHRSwapchainImplVK::AcquireResult{}; + } + + /// Record all subsequent cmd buffers as part of the current frame. + context.GetGPUTracer()->MarkFrameStart(); + + auto image = images_[index % images_.size()]; + uint32_t image_index = index; + return AcquireResult{SurfaceVK::WrapSwapchainImage( + transients_, // transients + image, // swapchain image + [weak_swapchain = weak_from_this(), image, image_index]() -> bool { + auto swapchain = weak_swapchain.lock(); + if (!swapchain) { + return false; + } + return swapchain->Present(image, image_index); + } // swap callback + )}; +} + +void KHRSwapchainImplVK::AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) { + const auto& sync = synchronizers_[current_frame_]; + sync->final_cmd_buffer = std::move(cmd_buffer); + sync->has_onscreen = true; +} + +bool KHRSwapchainImplVK::Present( + const std::shared_ptr& image, + uint32_t index) { + auto context_strong = context_.lock(); + if (!context_strong) { + return false; + } + + const auto& context = ContextVK::Cast(*context_strong); + const auto& sync = synchronizers_[current_frame_]; + context.GetGPUTracer()->MarkFrameEnd(); + + //---------------------------------------------------------------------------- + /// Transition the image to color-attachment-optimal. + /// + if (!sync->has_onscreen) { + sync->final_cmd_buffer = context.CreateCommandBuffer(); + } + sync->has_onscreen = false; + if (!sync->final_cmd_buffer) { + return false; + } + + auto vk_final_cmd_buffer = + CommandBufferVK::Cast(*sync->final_cmd_buffer).GetCommandBuffer(); + { + BarrierVK barrier; + barrier.new_layout = vk::ImageLayout::ePresentSrcKHR; + barrier.cmd_buffer = vk_final_cmd_buffer; + barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite; + barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput; + barrier.dst_access = {}; + barrier.dst_stage = vk::PipelineStageFlagBits::eBottomOfPipe; + + if (!image->SetLayout(barrier).ok()) { + return false; + } + + if (vk_final_cmd_buffer.end() != vk::Result::eSuccess) { + return false; + } + } + + //---------------------------------------------------------------------------- + /// Signal that the presentation semaphore is ready. + /// + { + vk::SubmitInfo submit_info; + vk::PipelineStageFlags wait_stage = + vk::PipelineStageFlagBits::eColorAttachmentOutput; + submit_info.setWaitDstStageMask(wait_stage); + submit_info.setWaitSemaphores(*sync->render_ready); + submit_info.setSignalSemaphores(*sync->present_ready); + submit_info.setCommandBuffers(vk_final_cmd_buffer); + auto result = + context.GetGraphicsQueue()->Submit(submit_info, *sync->acquire); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not wait on render semaphore: " + << vk::to_string(result); + return false; + } + } + + //---------------------------------------------------------------------------- + /// Present the image. + /// + uint32_t indices[] = {static_cast(index)}; + + vk::PresentInfoKHR present_info; + present_info.setSwapchains(*swapchain_); + present_info.setImageIndices(indices); + present_info.setWaitSemaphores(*sync->present_ready); + + auto result = context.GetGraphicsQueue()->Present(present_info); + + switch (result) { + case vk::Result::eErrorOutOfDateKHR: + // Caller will recreate the impl on acquisition, not submission. + [[fallthrough]]; + case vk::Result::eErrorSurfaceLostKHR: + // Vulkan guarantees that the set of queue operations will still + // complete successfully. + [[fallthrough]]; + case vk::Result::eSuboptimalKHR: + // Even though we're handling rotation changes via polling, we + // still need to handle the case where the swapchain signals that + // it's suboptimal (i.e. every frame when we are rotated given we + // aren't doing Vulkan pre-rotation). + [[fallthrough]]; + case vk::Result::eSuccess: + break; + default: + VALIDATION_LOG << "Could not present queue: " << vk::to_string(result); + break; + } + + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..14dd47775022f835cd41a7a4e4c7f4b39aa95d6b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_ + +#include +#include + +#include "impeller/geometry/size.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class Context; +class KHRSwapchainImageVK; +class Surface; +struct KHRFrameSynchronizerVK; + +//------------------------------------------------------------------------------ +/// @brief An instance of a swapchain that does NOT adapt to going out of +/// date with the underlying surface. Errors will be indicated when +/// the next drawable is acquired from this implementation of the +/// swapchain. If the error is due the swapchain going out of date, +/// the caller must recreate another instance by optionally +/// stealing this implementations guts. +/// +class KHRSwapchainImplVK final + : public std::enable_shared_from_this { + public: + static std::shared_ptr Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa = true, + vk::SwapchainKHR old_swapchain = VK_NULL_HANDLE); + + ~KHRSwapchainImplVK(); + + bool IsValid() const; + + struct AcquireResult { + std::unique_ptr surface; + bool out_of_date = false; + + explicit AcquireResult(bool p_out_of_date = false) + : out_of_date(p_out_of_date) {} + + explicit AcquireResult(std::unique_ptr p_surface) + : surface(std::move(p_surface)) {} + }; + + AcquireResult AcquireNextDrawable(); + + vk::Format GetSurfaceFormat() const; + + std::shared_ptr GetContext() const; + + std::pair DestroySwapchain(); + + const ISize& GetSize() const; + + void AddFinalCommandBuffer(std::shared_ptr cmd_buffer); + + std::optional GetCurrentUnderlyingSurfaceSize() const; + + private: + std::weak_ptr context_; + vk::UniqueSurfaceKHR surface_; + vk::Format surface_format_ = vk::Format::eUndefined; + vk::UniqueSwapchainKHR swapchain_; + std::shared_ptr transients_; + std::vector> images_; + std::vector> synchronizers_; + size_t current_frame_ = 0u; + ISize size_; + bool enable_msaa_ = true; + bool is_valid_ = false; + + KHRSwapchainImplVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa, + vk::SwapchainKHR old_swapchain); + + bool Present(const std::shared_ptr& image, + uint32_t index); + + void WaitIdle() const; + + KHRSwapchainImplVK(const KHRSwapchainImplVK&) = delete; + + KHRSwapchainImplVK& operator=(const KHRSwapchainImplVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_IMPL_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..339a01b1018fbe3a4ec3c46250a5d03156404118 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.cc @@ -0,0 +1,118 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h" + +#include "flutter/fml/build_config.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_impl_vk.h" + +namespace impeller { + +KHRSwapchainVK::KHRSwapchainVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa) + : size_(size), enable_msaa_(enable_msaa) { + auto impl = KHRSwapchainImplVK::Create(context, // + std::move(surface), // + size_, // + enable_msaa_ // + ); + if (!impl || !impl->IsValid()) { + VALIDATION_LOG << "Failed to create SwapchainVK implementation."; + return; + } + impl_ = std::move(impl); +} + +KHRSwapchainVK::~KHRSwapchainVK() = default; + +bool KHRSwapchainVK::IsValid() const { + return impl_ ? impl_->IsValid() : false; +} + +void KHRSwapchainVK::UpdateSurfaceSize(const ISize& size) { + // Update the size of the swapchain. On the next acquired drawable, + // the sizes may no longer match, forcing the swapchain to be recreated. + size_ = size; +} + +void KHRSwapchainVK::AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) const { + impl_->AddFinalCommandBuffer(std::move(cmd_buffer)); +} + +std::unique_ptr KHRSwapchainVK::AcquireNextDrawable() { + return AcquireNextDrawable(0u); +} + +std::unique_ptr KHRSwapchainVK::AcquireNextDrawable( + size_t resize_retry_count) { + if (!IsValid()) { + return nullptr; + } + + TRACE_EVENT0("impeller", __FUNCTION__); + + auto result = impl_->AcquireNextDrawable(); + if (!result.out_of_date && size_ == impl_->GetSize()) { + return std::move(result.surface); + } + +// When the swapchain says its out-of-date, we attempt to read the underlying +// surface size and re-create the swapchain at that size automatically (subject +// to a specific number of retries). However, on some platforms, the surface +// size reported by the Vulkan API may be stale for several frames. Those +// platforms must explicitly set the swapchain size using out-of-band (to +// Vulkan) APIs. +// +// TODO(163070): Expose the API to set surface size in impeller.h +#if !FML_OS_ANDROID + constexpr const size_t kMaxResizeAttempts = 3u; + if (resize_retry_count == kMaxResizeAttempts) { + VALIDATION_LOG << "Attempted to resize the swapchain" << kMaxResizeAttempts + << " time unsuccessfully. This platform likely doesn't " + "support returning the current swapchain extents and " + "must recreate the swapchain using the actual size."; + return nullptr; + } + + size_ = impl_->GetCurrentUnderlyingSurfaceSize().value_or(size_); +#endif // !FML_OS_ANDROID + + TRACE_EVENT0("impeller", "RecreateSwapchain"); + + // This swapchain implementation indicates that it is out of date. Tear it + // down and make a new one. + auto context = impl_->GetContext(); + auto [surface, old_swapchain] = impl_->DestroySwapchain(); + + auto new_impl = KHRSwapchainImplVK::Create(context, // + std::move(surface), // + size_, // + enable_msaa_, // + *old_swapchain // + ); + if (!new_impl || !new_impl->IsValid()) { + VALIDATION_LOG << "Could not update swapchain."; + // The old swapchain is dead because we took its surface. This is + // unrecoverable. + impl_.reset(); + return nullptr; + } + impl_ = std::move(new_impl); + + //---------------------------------------------------------------------------- + /// We managed to recreate the swapchain in the new configuration. Try again. + /// + return AcquireNextDrawable(resize_retry_count + 1); +} + +vk::Format KHRSwapchainVK::GetSurfaceFormat() const { + return IsValid() ? impl_->GetSurfaceFormat() : vk::Format::eUndefined; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..39648cf2ffcde57620ff1e5a395dd26d22c7e4cc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_ + +#include + +#include "impeller/geometry/size.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +class KHRSwapchainImplVK; + +//------------------------------------------------------------------------------ +/// @brief A swapchain implemented backed by VK_KHR_swapchain and +/// VK_KHR_surface. +/// +class KHRSwapchainVK final : public SwapchainVK { + public: + ~KHRSwapchainVK(); + + // |SwapchainVK| + bool IsValid() const override; + + // |SwapchainVK| + std::unique_ptr AcquireNextDrawable() override; + + // |SwapchainVK| + vk::Format GetSurfaceFormat() const override; + + // |SwapchainVK| + void UpdateSurfaceSize(const ISize& size) override; + + // |SwapchainVK| + void AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) const override; + + private: + friend class SwapchainVK; + + std::shared_ptr impl_; + ISize size_; + const bool enable_msaa_; + + KHRSwapchainVK(const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa); + + KHRSwapchainVK(const KHRSwapchainVK&) = delete; + + KHRSwapchainVK& operator=(const KHRSwapchainVK&) = delete; + + std::unique_ptr AcquireNextDrawable(size_t resize_retry_count); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_KHR_KHR_SWAPCHAIN_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..0128579601e915bdb62a9127d16dd11b4fa4ce26 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.cc @@ -0,0 +1,87 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/surface_vk.h" + +#include "impeller/core/formats.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +std::unique_ptr SurfaceVK::WrapSwapchainImage( + const std::shared_ptr& transients, + const std::shared_ptr& swapchain_image, + SwapCallback swap_callback) { + if (!transients || !swapchain_image || !swap_callback) { + return nullptr; + } + + auto context = transients->GetContext().lock(); + if (!context) { + return nullptr; + } + + const auto enable_msaa = transients->IsMSAAEnabled(); + + const auto swapchain_tex_desc = swapchain_image->GetTextureDescriptor(); + + TextureDescriptor resolve_tex_desc; + resolve_tex_desc.type = TextureType::kTexture2D; + resolve_tex_desc.format = swapchain_tex_desc.format; + resolve_tex_desc.size = swapchain_tex_desc.size; + resolve_tex_desc.usage = TextureUsage::kRenderTarget; + resolve_tex_desc.sample_count = SampleCount::kCount1; + resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; + + std::shared_ptr resolve_tex = + std::make_shared(context, // + swapchain_image // + ); + + if (!resolve_tex) { + return nullptr; + } + resolve_tex->SetLabel("ImpellerOnscreenResolve"); + + ColorAttachment color0; + color0.clear_color = Color::DarkSlateGray(); + color0.load_action = LoadAction::kClear; + if (enable_msaa) { + color0.texture = transients->GetMSAATexture(); + color0.store_action = StoreAction::kMultisampleResolve; + color0.resolve_texture = resolve_tex; + } else { + color0.texture = resolve_tex; + color0.store_action = StoreAction::kStore; + } + + RenderTarget render_target_desc; + render_target_desc.SetColorAttachment(color0, 0u); + render_target_desc.SetupDepthStencilAttachments( + /*context=*/*context, // + /*allocator=*/*context->GetResourceAllocator(), // + /*size=*/swapchain_tex_desc.size, // + /*msaa=*/enable_msaa, // + /*label=*/"Onscreen", // + /*stencil_attachment_config=*/ + RenderTarget::kDefaultStencilAttachmentConfig, // + /*depth_stencil_texture=*/transients->GetDepthStencilTexture() // + ); + + // The constructor is private. So make_unique may not be used. + return std::unique_ptr( + new SurfaceVK(render_target_desc, std::move(swap_callback))); +} + +SurfaceVK::SurfaceVK(const RenderTarget& target, SwapCallback swap_callback) + : Surface(target), swap_callback_(std::move(swap_callback)) {} + +SurfaceVK::~SurfaceVK() = default; + +bool SurfaceVK::Present() const { + return swap_callback_ ? swap_callback_() : false; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..44b069a867cea39f42de6d115721fc2fa48fd7f6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/surface_vk.h @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SURFACE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SURFACE_VK_H_ + +#include + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/surface.h" + +namespace impeller { + +class SurfaceVK final : public Surface { + public: + using SwapCallback = std::function; + + /// @brief Wrap the swapchain image in a Surface, which provides the + /// additional configuration required for usage as on onscreen render + /// target by Impeller. + /// + /// This creates the associated MSAA and depth+stencil texture. + static std::unique_ptr WrapSwapchainImage( + const std::shared_ptr& transients, + const std::shared_ptr& swapchain_image, + SwapCallback swap_callback); + + // |Surface| + ~SurfaceVK() override; + + private: + SwapCallback swap_callback_; + + SurfaceVK(const RenderTarget& target, SwapCallback swap_callback); + + // |Surface| + bool Present() const override; + + SurfaceVK(const SurfaceVK&) = delete; + + SurfaceVK& operator=(const SurfaceVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SURFACE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..d097b114143a3d6566413eaadcba707ff8f416eb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.cc @@ -0,0 +1,98 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h" + +#include "flutter/fml/trace_event.h" + +namespace impeller { + +SwapchainTransientsVK::SwapchainTransientsVK(std::weak_ptr context, + TextureDescriptor desc, + bool enable_msaa) + : context_(std::move(context)), desc_(desc), enable_msaa_(enable_msaa) {} + +SwapchainTransientsVK::~SwapchainTransientsVK() = default; + +const std::shared_ptr& SwapchainTransientsVK::GetMSAATexture() { + if (cached_msaa_texture_) { + return cached_msaa_texture_; + } + cached_msaa_texture_ = CreateMSAATexture(); + return cached_msaa_texture_; +} + +const std::shared_ptr& +SwapchainTransientsVK::GetDepthStencilTexture() { + if (cached_depth_stencil_) { + return cached_depth_stencil_; + } + cached_depth_stencil_ = CreateDepthStencilTexture(); + return cached_depth_stencil_; +} + +std::shared_ptr SwapchainTransientsVK::CreateMSAATexture() const { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!enable_msaa_) { + return nullptr; + } + TextureDescriptor msaa_desc; + msaa_desc.storage_mode = StorageMode::kDeviceTransient; + msaa_desc.type = TextureType::kTexture2DMultisample; + msaa_desc.sample_count = SampleCount::kCount4; + msaa_desc.format = desc_.format; + msaa_desc.size = desc_.size; + msaa_desc.usage = TextureUsage::kRenderTarget; + + auto context = context_.lock(); + if (!context) { + return nullptr; + } + auto texture = context->GetResourceAllocator()->CreateTexture(msaa_desc); + if (!texture) { + return nullptr; + } + texture->SetLabel("SwapchainMSAA"); + return texture; +} + +std::shared_ptr SwapchainTransientsVK::CreateDepthStencilTexture() + const { + TRACE_EVENT0("impeller", __FUNCTION__); + auto context = context_.lock(); + if (!context) { + return nullptr; + } + TextureDescriptor depth_stencil_desc; + depth_stencil_desc.storage_mode = StorageMode::kDeviceTransient; + if (enable_msaa_) { + depth_stencil_desc.type = TextureType::kTexture2DMultisample; + depth_stencil_desc.sample_count = SampleCount::kCount4; + } else { + depth_stencil_desc.type = TextureType::kTexture2D; + depth_stencil_desc.sample_count = SampleCount::kCount1; + } + depth_stencil_desc.format = + context->GetCapabilities()->GetDefaultDepthStencilFormat(); + depth_stencil_desc.size = desc_.size; + depth_stencil_desc.usage = TextureUsage::kRenderTarget; + + auto texture = + context->GetResourceAllocator()->CreateTexture(depth_stencil_desc); + if (!texture) { + return nullptr; + } + texture->SetLabel("SwapchainDepthStencil"); + return texture; +} + +bool SwapchainTransientsVK::IsMSAAEnabled() const { + return enable_msaa_; +} + +const std::weak_ptr& SwapchainTransientsVK::GetContext() const { + return context_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..1ea6f7bdb9b02b8c08fcccb66dd7833b5d7bde1c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_transients_vk.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_TRANSIENTS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_TRANSIENTS_VK_H_ + +#include "impeller/core/texture.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Resources, meant to be memoized by the texture descriptor of the +/// wrapped swapchain images, that are intuitively cheap to create +/// but have been observed to be time consuming to construct on some +/// Vulkan drivers. This includes the device-transient MSAA and +/// depth-stencil textures. +/// +/// The same textures are used for all swapchain images. +/// +class SwapchainTransientsVK { + public: + explicit SwapchainTransientsVK(std::weak_ptr context, + TextureDescriptor desc, + bool enable_msaa); + + ~SwapchainTransientsVK(); + + SwapchainTransientsVK(const SwapchainTransientsVK&) = delete; + + SwapchainTransientsVK& operator=(const SwapchainTransientsVK&) = delete; + + const std::weak_ptr& GetContext() const; + + bool IsMSAAEnabled() const; + + const std::shared_ptr& GetMSAATexture(); + + const std::shared_ptr& GetDepthStencilTexture(); + + private: + std::weak_ptr context_; + const TextureDescriptor desc_; + const bool enable_msaa_; + std::shared_ptr cached_msaa_texture_; + std::shared_ptr cached_depth_stencil_; + + std::shared_ptr CreateMSAATexture() const; + + std::shared_ptr CreateDepthStencilTexture() const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_TRANSIENTS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..07e94042de38a830930d34a87bc6615d2bc70eb0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.cc @@ -0,0 +1,90 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h" + +#include "flutter/fml/trace_event.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +#if FML_OS_ANDROID +#include "impeller/renderer/backend/vulkan/swapchain/ahb/ahb_swapchain_vk.h" +#endif // FML_OS_ANDROID + +namespace impeller { + +std::shared_ptr SwapchainVK::Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa) { + auto swapchain = std::shared_ptr( + new KHRSwapchainVK(context, std::move(surface), size, enable_msaa)); + if (!swapchain->IsValid()) { + VALIDATION_LOG << "Could not create valid swapchain."; + return nullptr; + } + return swapchain; +} + +#if FML_OS_ANDROID +std::shared_ptr SwapchainVK::Create( + const std::shared_ptr& context, + ANativeWindow* p_window, + const CreateTransactionCB& cb, + bool enable_msaa) { + TRACE_EVENT0("impeller", "CreateAndroidSwapchain"); + if (!context) { + return nullptr; + } + + android::NativeWindow window(p_window); + if (!window.IsValid()) { + return nullptr; + } + + vk::AndroidSurfaceCreateInfoKHR surface_info; + surface_info.setWindow(window.GetHandle()); + auto [result, surface] = + ContextVK::Cast(*context).GetInstance().createAndroidSurfaceKHRUnique( + surface_info); + if (result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create KHR Android Surface: " + << vk::to_string(result); + return nullptr; + } + + // Use AHB Swapchains if they are opted in. + if (ContextVK::Cast(*context).GetShouldEnableSurfaceControlSwapchain() && + AHBSwapchainVK::IsAvailableOnPlatform() && + android_get_device_api_level() >= 34) { + FML_LOG(WARNING) << "Using Android SurfaceControl Swapchain."; + auto ahb_swapchain = std::shared_ptr(new AHBSwapchainVK( + context, // + window.GetHandle(), // + cb, // + surface, // + window.GetSize(), // + enable_msaa // + )); + + if (ahb_swapchain->IsValid()) { + return ahb_swapchain; + } else { + VALIDATION_LOG + << "Could not create AHB swapchain. Falling back to KHR variant."; + } + } + + // Fallback to KHR swapchains if AHB swapchains aren't available. + return Create(context, std::move(surface), window.GetSize(), enable_msaa); +} +#endif // FML_OS_ANDROID + +SwapchainVK::SwapchainVK() = default; + +SwapchainVK::~SwapchainVK() = default; + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..795b75847be5da615fbc4553c8eb76b3cd727cfa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_VK_H_ + +#include + +#include "flutter/fml/build_config.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/surface.h" + +#if FML_OS_ANDROID +#include "impeller/toolkit/android/native_window.h" +#include "impeller/toolkit/android/surface_transaction.h" +#endif // FML_OS_ANDROID + +namespace impeller { + +#if FML_OS_ANDROID +using CreateTransactionCB = std::function; +#endif // FML_OS_ANDROID + +//------------------------------------------------------------------------------ +/// @brief A swapchain that adapts to the underlying surface going out of +/// date. If the caller cannot acquire the next drawable, it is due +/// to an unrecoverable error and the swapchain must be recreated +/// with a new surface. +/// +class SwapchainVK { + public: + static std::shared_ptr Create( + const std::shared_ptr& context, + vk::UniqueSurfaceKHR surface, + const ISize& size, + bool enable_msaa = true); + +#if FML_OS_ANDROID + static std::shared_ptr Create( + const std::shared_ptr& context, + ANativeWindow* window, + const CreateTransactionCB& cb, + bool enable_msaa = true); +#endif // FML_OS_ANDROID + + virtual ~SwapchainVK(); + + SwapchainVK(const SwapchainVK&) = delete; + + SwapchainVK& operator=(const SwapchainVK&) = delete; + + virtual bool IsValid() const = 0; + + virtual std::unique_ptr AcquireNextDrawable() = 0; + + virtual vk::Format GetSurfaceFormat() const = 0; + + virtual void AddFinalCommandBuffer( + std::shared_ptr cmd_buffer) const = 0; + + /// @brief Mark the current swapchain configuration as dirty, forcing it to be + /// recreated on the next frame. + virtual void UpdateSurfaceSize(const ISize& size) = 0; + + protected: + SwapchainVK(); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_SWAPCHAIN_SWAPCHAIN_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..d0a28a3b5d8896e0b01866fb3fa8262412a4a87f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/gpu_tracer_unittests.cc @@ -0,0 +1,156 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "fml/synchronization/count_down_latch.h" +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +namespace impeller { +namespace testing { + +#ifdef IMPELLER_DEBUG +TEST(GPUTracerVK, CanBeDisabled) { + auto const context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_gpu_tracing = false; + }) + .Build(); + auto tracer = context->GetGPUTracer(); + + ASSERT_FALSE(tracer->IsEnabled()); +} + +TEST(GPUTracerVK, DisabledFrameCycle) { + auto const context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_gpu_tracing = false; + }) + .Build(); + auto tracer = context->GetGPUTracer(); + + // Check that a repeated frame start/end cycle does not fail any assertions. + for (int i = 0; i < 2; i++) { + tracer->MarkFrameStart(); + tracer->MarkFrameEnd(); + } +} + +TEST(GPUTracerVK, CanTraceCmdBuffer) { + auto const context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_gpu_tracing = true; + }) + .Build(); + auto tracer = context->GetGPUTracer(); + + ASSERT_TRUE(tracer->IsEnabled()); + tracer->MarkFrameStart(); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + blit_pass->EncodeCommands(); + + auto latch = std::make_shared(1u); + + if (!context->GetCommandQueue() + ->Submit( + {cmd_buffer}, + [latch](CommandBuffer::Status status) { latch->CountDown(); }) + .ok()) { + GTEST_FAIL() << "Failed to submit cmd buffer"; + } + + tracer->MarkFrameEnd(); + latch->Wait(); + + auto called = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") != + called->end()); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") != called->end()); +} + +TEST(GPUTracerVK, DoesNotTraceOutsideOfFrameWorkload) { + auto const context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_gpu_tracing = true; + }) + .Build(); + auto tracer = context->GetGPUTracer(); + + ASSERT_TRUE(tracer->IsEnabled()); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + blit_pass->EncodeCommands(); + + auto latch = std::make_shared(1u); + if (!context->GetCommandQueue() + ->Submit( + {cmd_buffer}, + [latch](CommandBuffer::Status status) { latch->CountDown(); }) + .ok()) { + GTEST_FAIL() << "Failed to submit cmd buffer"; + } + + latch->Wait(); + + auto called = GetMockVulkanFunctions(context->GetDevice()); + + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") == called->end()); +} + +// This cmd buffer starts when there is a frame but finishes when there is none. +// This should result in the same recorded work. +TEST(GPUTracerVK, TracesWithPartialFrameOverlap) { + auto const context = + MockVulkanContextBuilder() + .SetSettingsCallback([](ContextVK::Settings& settings) { + settings.enable_gpu_tracing = true; + }) + .Build(); + auto tracer = context->GetGPUTracer(); + + ASSERT_TRUE(tracer->IsEnabled()); + tracer->MarkFrameStart(); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + blit_pass->EncodeCommands(); + + auto latch = std::make_shared(1u); + if (!context->GetCommandQueue() + ->Submit( + {cmd_buffer}, + [latch](CommandBuffer::Status status) { latch->CountDown(); }) + .ok()) { + GTEST_FAIL() << "Failed to submit cmd buffer"; + } + tracer->MarkFrameEnd(); + + latch->Wait(); + + auto called = GetMockVulkanFunctions(context->GetDevice()); + ASSERT_NE(called, nullptr); + ASSERT_TRUE(std::find(called->begin(), called->end(), "vkCreateQueryPool") != + called->end()); + ASSERT_TRUE(std::find(called->begin(), called->end(), + "vkGetQueryPoolResults") != called->end()); +} + +#endif // IMPELLER_DEBUG + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ea8beaec330c7a0b83d9e98c32bc541fe9f7e77 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc @@ -0,0 +1,973 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" + +#include +#include +#include +#include + +#include "impeller/base/thread_safety.h" +#include "impeller/renderer/backend/vulkan/vk.h" // IWYU pragma: keep. +#include "third_party/swiftshader/include/vulkan/vulkan_core.h" +#include "vulkan/vulkan.hpp" +#include "vulkan/vulkan_core.h" + +namespace impeller { +namespace testing { + +namespace { + +struct MockCommandBuffer { + explicit MockCommandBuffer( + std::shared_ptr> called_functions) + : called_functions_(std::move(called_functions)) {} + std::shared_ptr> called_functions_; +}; + +struct MockQueryPool {}; + +struct MockCommandPool {}; + +struct MockDescriptorPool {}; + +struct MockSurfaceKHR {}; + +struct MockImage {}; + +struct MockSwapchainKHR { + std::array images; + size_t current_image = 0; +}; + +struct MockSemaphore {}; + +struct MockFramebuffer {}; + +static ISize currentImageSize = ISize{1, 1}; + +class MockDevice final { + public: + explicit MockDevice() : called_functions_(new std::vector()) {} + + MockCommandBuffer* NewCommandBuffer() { + auto buffer = std::make_unique(called_functions_); + MockCommandBuffer* result = buffer.get(); + Lock lock(command_buffers_mutex_); + command_buffers_.emplace_back(std::move(buffer)); + return result; + } + + MockCommandPool* NewCommandPool() { + auto pool = std::make_unique(); + MockCommandPool* result = pool.get(); + Lock lock(commmand_pools_mutex_); + command_pools_.emplace_back(std::move(pool)); + return result; + } + + void DeleteCommandPool(MockCommandPool* pool) { + Lock lock(commmand_pools_mutex_); + auto it = std::find_if(command_pools_.begin(), command_pools_.end(), + [pool](const std::unique_ptr& p) { + return p.get() == pool; + }); + if (it != command_pools_.end()) { + command_pools_.erase(it); + } + } + + const std::shared_ptr>& GetCalledFunctions() { + return called_functions_; + } + + void AddCalledFunction(const std::string& function) { + Lock lock(called_functions_mutex_); + called_functions_->push_back(function); + } + + private: + MockDevice(const MockDevice&) = delete; + + MockDevice& operator=(const MockDevice&) = delete; + + Mutex called_functions_mutex_; + std::shared_ptr> called_functions_ IPLR_GUARDED_BY( + called_functions_mutex_); + + Mutex command_buffers_mutex_; + std::vector> command_buffers_ + IPLR_GUARDED_BY(command_buffers_mutex_); + + Mutex commmand_pools_mutex_; + std::vector> command_pools_ IPLR_GUARDED_BY( + commmand_pools_mutex_); +}; + +void noop() {} + +static thread_local std::vector g_instance_extensions; + +VkResult vkEnumerateInstanceExtensionProperties( + const char* pLayerName, + uint32_t* pPropertyCount, + VkExtensionProperties* pProperties) { + if (!pProperties) { + *pPropertyCount = g_instance_extensions.size(); + } else { + uint32_t count = 0; + for (const std::string& ext : g_instance_extensions) { + strncpy(pProperties[count].extensionName, ext.c_str(), + sizeof(VkExtensionProperties::extensionName)); + pProperties[count].specVersion = 0; + count++; + } + } + return VK_SUCCESS; +} + +static thread_local std::vector g_instance_layers; + +VkResult vkEnumerateInstanceLayerProperties(uint32_t* pPropertyCount, + VkLayerProperties* pProperties) { + if (!pProperties) { + *pPropertyCount = g_instance_layers.size(); + } else { + uint32_t count = 0; + for (const std::string& layer : g_instance_layers) { + strncpy(pProperties[count].layerName, layer.c_str(), + sizeof(VkLayerProperties::layerName)); + pProperties[count].specVersion = 0; + count++; + } + } + return VK_SUCCESS; +} + +VkResult vkEnumeratePhysicalDevices(VkInstance instance, + uint32_t* pPhysicalDeviceCount, + VkPhysicalDevice* pPhysicalDevices) { + if (!pPhysicalDevices) { + *pPhysicalDeviceCount = 1; + } else { + pPhysicalDevices[0] = reinterpret_cast(0xfeedface); + } + return VK_SUCCESS; +} + +static thread_local std::function + g_format_properties_callback; + +void vkGetPhysicalDeviceFormatProperties( + VkPhysicalDevice physicalDevice, + VkFormat format, + VkFormatProperties* pFormatProperties) { + g_format_properties_callback(physicalDevice, format, pFormatProperties); +} + +static thread_local std::function + g_physical_device_properties_callback; + +void vkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice, + VkPhysicalDeviceProperties* pProperties) { + pProperties->limits.framebufferColorSampleCounts = + static_cast(VK_SAMPLE_COUNT_1_BIT | + VK_SAMPLE_COUNT_4_BIT); + pProperties->limits.maxImageDimension2D = 4096; + pProperties->limits.timestampPeriod = 1; + if (g_physical_device_properties_callback) { + g_physical_device_properties_callback(physicalDevice, pProperties); + } +} + +void vkGetPhysicalDeviceQueueFamilyProperties( + VkPhysicalDevice physicalDevice, + uint32_t* pQueueFamilyPropertyCount, + VkQueueFamilyProperties* pQueueFamilyProperties) { + if (!pQueueFamilyProperties) { + *pQueueFamilyPropertyCount = 1; + } else { + pQueueFamilyProperties[0].queueCount = 3; + pQueueFamilyProperties[0].queueFlags = static_cast( + VK_QUEUE_TRANSFER_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT); + } +} + +VkResult vkEnumerateDeviceExtensionProperties( + VkPhysicalDevice physicalDevice, + const char* pLayerName, + uint32_t* pPropertyCount, + VkExtensionProperties* pProperties) { + if (!pProperties) { + *pPropertyCount = 1; + } else { + strcpy(pProperties[0].extensionName, "VK_KHR_swapchain"); + pProperties[0].specVersion = 0; + } + return VK_SUCCESS; +} + +VkResult vkCreateDevice(VkPhysicalDevice physicalDevice, + const VkDeviceCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkDevice* pDevice) { + *pDevice = reinterpret_cast(new MockDevice()); + return VK_SUCCESS; +} + +VkResult vkCreateInstance(const VkInstanceCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkInstance* pInstance) { + *pInstance = reinterpret_cast(0xbaadf00d); + return VK_SUCCESS; +} + +void vkGetPhysicalDeviceMemoryProperties( + VkPhysicalDevice physicalDevice, + VkPhysicalDeviceMemoryProperties* pMemoryProperties) { + pMemoryProperties->memoryTypeCount = 2; + pMemoryProperties->memoryHeapCount = 2; + pMemoryProperties->memoryTypes[0].heapIndex = 0; + pMemoryProperties->memoryTypes[0].propertyFlags = + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + pMemoryProperties->memoryTypes[1].heapIndex = 1; + pMemoryProperties->memoryTypes[1].propertyFlags = + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + pMemoryProperties->memoryHeaps[0].size = 1024 * 1024 * 1024; + pMemoryProperties->memoryHeaps[0].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT; + pMemoryProperties->memoryHeaps[1].size = 1024 * 1024 * 1024; + pMemoryProperties->memoryHeaps[1].flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT; +} + +VkResult vkCreatePipelineCache(VkDevice device, + const VkPipelineCacheCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkPipelineCache* pPipelineCache) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreatePipelineCache"); + *pPipelineCache = reinterpret_cast(0xb000dead); + return VK_SUCCESS; +} + +VkResult vkCreateCommandPool(VkDevice device, + const VkCommandPoolCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkCommandPool* pCommandPool) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateCommandPool"); + *pCommandPool = + reinterpret_cast(mock_device->NewCommandPool()); + return VK_SUCCESS; +} + +VkResult vkResetCommandPool(VkDevice device, + VkCommandPool commandPool, + VkCommandPoolResetFlags flags) { + MockDevice* mock_device = reinterpret_cast(device); + if (flags & VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT) { + mock_device->AddCalledFunction("vkResetCommandPoolReleaseResources"); + } else { + mock_device->AddCalledFunction("vkResetCommandPool"); + } + return VK_SUCCESS; +} + +VkResult vkAllocateCommandBuffers( + VkDevice device, + const VkCommandBufferAllocateInfo* pAllocateInfo, + VkCommandBuffer* pCommandBuffers) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkAllocateCommandBuffers"); + *pCommandBuffers = + reinterpret_cast(mock_device->NewCommandBuffer()); + return VK_SUCCESS; +} + +VkResult vkBeginCommandBuffer(VkCommandBuffer commandBuffer, + const VkCommandBufferBeginInfo* pBeginInfo) { + return VK_SUCCESS; +} + +VkResult vkCreateImage(VkDevice device, + const VkImageCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkImage* pImage) { + *pImage = reinterpret_cast(0xD0D0CACA); + return VK_SUCCESS; +} + +void vkGetImageMemoryRequirements2KHR( + VkDevice device, + const VkImageMemoryRequirementsInfo2* pInfo, + VkMemoryRequirements2* pMemoryRequirements) { + pMemoryRequirements->memoryRequirements.size = 1024; + pMemoryRequirements->memoryRequirements.memoryTypeBits = 1; +} + +VkResult vkAllocateMemory(VkDevice device, + const VkMemoryAllocateInfo* pAllocateInfo, + const VkAllocationCallbacks* pAllocator, + VkDeviceMemory* pMemory) { + *pMemory = reinterpret_cast(0xCAFEB0BA); + return VK_SUCCESS; +} + +VkResult vkBindImageMemory(VkDevice device, + VkImage image, + VkDeviceMemory memory, + VkDeviceSize memoryOffset) { + return VK_SUCCESS; +} + +VkResult vkCreateImageView(VkDevice device, + const VkImageViewCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkImageView* pView) { + *pView = reinterpret_cast(0xFEE1DEAD); + return VK_SUCCESS; +} + +VkResult vkCreateBuffer(VkDevice device, + const VkBufferCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkBuffer* pBuffer) { + *pBuffer = reinterpret_cast(0xDEADDEAD); + return VK_SUCCESS; +} + +void vkGetBufferMemoryRequirements2KHR( + VkDevice device, + const VkBufferMemoryRequirementsInfo2* pInfo, + VkMemoryRequirements2* pMemoryRequirements) { + pMemoryRequirements->memoryRequirements.size = 1024; + pMemoryRequirements->memoryRequirements.memoryTypeBits = 1; +} + +VkResult vkBindBufferMemory(VkDevice device, + VkBuffer buffer, + VkDeviceMemory memory, + VkDeviceSize memoryOffset) { + return VK_SUCCESS; +} + +VkResult vkCreateRenderPass(VkDevice device, + const VkRenderPassCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkRenderPass* pRenderPass) { + *pRenderPass = reinterpret_cast(0x12341234); + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateRenderPass"); + return VK_SUCCESS; +} + +VkResult vkCreateDescriptorSetLayout( + VkDevice device, + const VkDescriptorSetLayoutCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkDescriptorSetLayout* pSetLayout) { + *pSetLayout = reinterpret_cast(0x77777777); + return VK_SUCCESS; +} + +VkResult vkCreatePipelineLayout(VkDevice device, + const VkPipelineLayoutCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkPipelineLayout* pPipelineLayout) { + *pPipelineLayout = reinterpret_cast(0x88888888); + return VK_SUCCESS; +} + +VkResult vkCreateGraphicsPipelines( + VkDevice device, + VkPipelineCache pipelineCache, + uint32_t createInfoCount, + const VkGraphicsPipelineCreateInfo* pCreateInfos, + const VkAllocationCallbacks* pAllocator, + VkPipeline* pPipelines) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateGraphicsPipelines"); + *pPipelines = reinterpret_cast(0x99999999); + return VK_SUCCESS; +} + +void vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyDevice"); + delete reinterpret_cast(device); +} + +void vkDestroyPipeline(VkDevice device, + VkPipeline pipeline, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyPipeline"); +} + +VkResult vkCreateShaderModule(VkDevice device, + const VkShaderModuleCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkShaderModule* pShaderModule) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateShaderModule"); + *pShaderModule = reinterpret_cast(0x11111111); + return VK_SUCCESS; +} + +void vkDestroyShaderModule(VkDevice device, + VkShaderModule shaderModule, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyShaderModule"); +} + +void vkDestroyPipelineCache(VkDevice device, + VkPipelineCache pipelineCache, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyPipelineCache"); +} + +void vkDestroySurfaceKHR(VkInstance instance, + VkSurfaceKHR surface, + const VkAllocationCallbacks* pAllocator) { + return; +} + +void vkCmdBindPipeline(VkCommandBuffer commandBuffer, + VkPipelineBindPoint pipelineBindPoint, + VkPipeline pipeline) { + MockCommandBuffer* mock_command_buffer = + reinterpret_cast(commandBuffer); + mock_command_buffer->called_functions_->push_back("vkCmdBindPipeline"); +} + +void vkCmdSetStencilReference(VkCommandBuffer commandBuffer, + VkStencilFaceFlags faceMask, + uint32_t reference) { + MockCommandBuffer* mock_command_buffer = + reinterpret_cast(commandBuffer); + mock_command_buffer->called_functions_->push_back("vkCmdSetStencilReference"); +} + +void vkCmdSetScissor(VkCommandBuffer commandBuffer, + uint32_t firstScissor, + uint32_t scissorCount, + const VkRect2D* pScissors) { + MockCommandBuffer* mock_command_buffer = + reinterpret_cast(commandBuffer); + mock_command_buffer->called_functions_->push_back("vkCmdSetScissor"); +} + +void vkCmdSetViewport(VkCommandBuffer commandBuffer, + uint32_t firstViewport, + uint32_t viewportCount, + const VkViewport* pViewports) { + MockCommandBuffer* mock_command_buffer = + reinterpret_cast(commandBuffer); + mock_command_buffer->called_functions_->push_back("vkCmdSetViewport"); +} + +void vkFreeCommandBuffers(VkDevice device, + VkCommandPool commandPool, + uint32_t commandBufferCount, + const VkCommandBuffer* pCommandBuffers) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkFreeCommandBuffers"); +} + +void vkDestroyCommandPool(VkDevice device, + VkCommandPool commandPool, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->DeleteCommandPool( + reinterpret_cast(commandPool)); + mock_device->AddCalledFunction("vkDestroyCommandPool"); +} + +VkResult vkEndCommandBuffer(VkCommandBuffer commandBuffer) { + return VK_SUCCESS; +} + +VkResult vkCreateFence(VkDevice device, + const VkFenceCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkFence* pFence) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateFence"); + *pFence = reinterpret_cast(new MockFence()); + return VK_SUCCESS; +} + +VkResult vkDestroyFence(VkDevice device, + VkFence fence, + const VkAllocationCallbacks* pAllocator) { + delete reinterpret_cast(fence); + return VK_SUCCESS; +} + +VkResult vkQueueSubmit(VkQueue queue, + uint32_t submitCount, + const VkSubmitInfo* pSubmits, + VkFence fence) { + return VK_SUCCESS; +} + +VkResult vkWaitForFences(VkDevice device, + uint32_t fenceCount, + const VkFence* pFences, + VkBool32 waitAll, + uint64_t timeout) { + return VK_SUCCESS; +} + +VkResult vkGetFenceStatus(VkDevice device, VkFence fence) { + MockDevice* mock_device = reinterpret_cast(device); + MockFence* mock_fence = reinterpret_cast(fence); + return mock_fence->GetStatus(); +} + +VkResult vkResetFences(VkDevice device, + uint32_t fenceCount, + const VkFence* fences) { + return VK_SUCCESS; +} + +VkResult vkCreateDebugUtilsMessengerEXT( + VkInstance instance, + const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkDebugUtilsMessengerEXT* pMessenger) { + return VK_SUCCESS; +} + +VkResult vkSetDebugUtilsObjectNameEXT( + VkDevice device, + const VkDebugUtilsObjectNameInfoEXT* pNameInfo) { + return VK_SUCCESS; +} + +VkResult vkCreateQueryPool(VkDevice device, + const VkQueryPoolCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkQueryPool* pQueryPool) { + *pQueryPool = reinterpret_cast(new MockQueryPool()); + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkCreateQueryPool"); + return VK_SUCCESS; +} + +void vkDestroyQueryPool(VkDevice device, + VkQueryPool queryPool, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyQueryPool"); + delete reinterpret_cast(queryPool); +} + +VkResult vkGetQueryPoolResults(VkDevice device, + VkQueryPool queryPool, + uint32_t firstQuery, + uint32_t queryCount, + size_t dataSize, + void* pData, + VkDeviceSize stride, + VkQueryResultFlags flags) { + MockDevice* mock_device = reinterpret_cast(device); + if (dataSize == sizeof(uint32_t)) { + uint32_t* data = static_cast(pData); + for (auto i = firstQuery; i < queryCount; i++) { + data[0] = i; + } + } else if (dataSize == sizeof(int64_t)) { + uint64_t* data = static_cast(pData); + for (auto i = firstQuery; i < queryCount; i++) { + data[0] = i; + } + } + mock_device->AddCalledFunction("vkGetQueryPoolResults"); + return VK_SUCCESS; +} + +VkResult vkCreateDescriptorPool(VkDevice device, + const VkDescriptorPoolCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkDescriptorPool* pDescriptorPool) { + MockDevice* mock_device = reinterpret_cast(device); + *pDescriptorPool = + reinterpret_cast(new MockDescriptorPool()); + mock_device->AddCalledFunction("vkCreateDescriptorPool"); + return VK_SUCCESS; +} + +void vkDestroyDescriptorPool(VkDevice device, + VkDescriptorPool descriptorPool, + const VkAllocationCallbacks* pAllocator) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkDestroyDescriptorPool"); + delete reinterpret_cast(descriptorPool); +} + +VkResult vkResetDescriptorPool(VkDevice device, + VkDescriptorPool descriptorPool, + VkDescriptorPoolResetFlags flags) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkResetDescriptorPool"); + return VK_SUCCESS; +} + +VkResult vkAllocateDescriptorSets( + VkDevice device, + const VkDescriptorSetAllocateInfo* pAllocateInfo, + VkDescriptorSet* pDescriptorSets) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkAllocateDescriptorSets"); + return VK_SUCCESS; +} + +VkResult vkGetPhysicalDeviceSurfaceFormatsKHR( + VkPhysicalDevice physicalDevice, + VkSurfaceKHR surface, + uint32_t* pSurfaceFormatCount, + VkSurfaceFormatKHR* pSurfaceFormats) { + *pSurfaceFormatCount = 1u; + if (pSurfaceFormats != nullptr) { + pSurfaceFormats[0] = + VkSurfaceFormatKHR{.format = VK_FORMAT_R8G8B8A8_UNORM, + .colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; + } + return VK_SUCCESS; +} + +VkResult vkGetPhysicalDeviceSurfaceCapabilitiesKHR( + VkPhysicalDevice physicalDevice, + VkSurfaceKHR surface, + VkSurfaceCapabilitiesKHR* pSurfaceCapabilities) { + *pSurfaceCapabilities = VkSurfaceCapabilitiesKHR{ + .minImageCount = 3, + .maxImageCount = 6, + .currentExtent = + VkExtent2D{ + .width = static_cast(currentImageSize.width), + .height = static_cast(currentImageSize.height), + }, + .minImageExtent = + VkExtent2D{ + .width = 0, + .height = 0, + }, + .maxImageExtent = + VkExtent2D{ + .width = static_cast(currentImageSize.width), + .height = static_cast(currentImageSize.height), + }, + .maxImageArrayLayers = 1, + .supportedTransforms = + VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + .currentTransform = + VkSurfaceTransformFlagBitsKHR::VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + .supportedCompositeAlpha = VkCompositeAlphaFlagBitsKHR:: + VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, + .supportedUsageFlags = + VkImageUsageFlagBits::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT}; + return VK_SUCCESS; +} + +VkResult vkGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, + uint32_t queueFamilyIndex, + VkSurfaceKHR surface, + VkBool32* pSupported) { + *pSupported = VK_TRUE; + return VK_SUCCESS; +} + +VkResult vkCreateSwapchainKHR(VkDevice device, + const VkSwapchainCreateInfoKHR* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkSwapchainKHR* pSwapchain) { + *pSwapchain = reinterpret_cast(new MockSwapchainKHR()); + return VK_SUCCESS; +} + +void vkDestroySwapchainKHR(VkDevice device, + VkSwapchainKHR swapchain, + const VkAllocationCallbacks* pAllocator) { + delete reinterpret_cast(swapchain); +} + +VkResult vkGetSwapchainImagesKHR(VkDevice device, + VkSwapchainKHR swapchain, + uint32_t* pSwapchainImageCount, + VkImage* pSwapchainImages) { + MockSwapchainKHR* mock_swapchain = + reinterpret_cast(swapchain); + auto& images = mock_swapchain->images; + *pSwapchainImageCount = images.size(); + if (pSwapchainImages != nullptr) { + for (size_t i = 0; i < images.size(); i++) { + pSwapchainImages[i] = reinterpret_cast(&images[i]); + } + } + return VK_SUCCESS; +} + +VkResult vkCreateSemaphore(VkDevice device, + const VkSemaphoreCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkSemaphore* pSemaphore) { + *pSemaphore = reinterpret_cast(new MockSemaphore()); + return VK_SUCCESS; +} + +void vkDestroySemaphore(VkDevice device, + VkSemaphore semaphore, + const VkAllocationCallbacks* pAllocator) { + delete reinterpret_cast(semaphore); +} + +VkResult vkAcquireNextImageKHR(VkDevice device, + VkSwapchainKHR swapchain, + uint64_t timeout, + VkSemaphore semaphore, + VkFence fence, + uint32_t* pImageIndex) { + auto current_index = + reinterpret_cast(swapchain)->current_image++; + *pImageIndex = (current_index + 1) % 3u; + return VK_SUCCESS; +} + +VkResult vkCreateFramebuffer(VkDevice device, + const VkFramebufferCreateInfo* pCreateInfo, + const VkAllocationCallbacks* pAllocator, + VkFramebuffer* pFramebuffer) { + *pFramebuffer = reinterpret_cast(new MockFramebuffer()); + return VK_SUCCESS; +} + +void vkDestroyFramebuffer(VkDevice device, + VkFramebuffer framebuffer, + const VkAllocationCallbacks* pAllocator) { + delete reinterpret_cast(framebuffer); +} + +void vkTrimCommandPool(VkDevice device, + VkCommandPool commandPool, + VkCommandPoolTrimFlags flags) { + MockDevice* mock_device = reinterpret_cast(device); + mock_device->AddCalledFunction("vkTrimCommandPool"); +} + +PFN_vkVoidFunction GetMockVulkanProcAddress(VkInstance instance, + const char* pName) { + if (strcmp("vkEnumerateInstanceExtensionProperties", pName) == 0) { + return reinterpret_cast( + vkEnumerateInstanceExtensionProperties); + } else if (strcmp("vkEnumerateInstanceLayerProperties", pName) == 0) { + return reinterpret_cast( + vkEnumerateInstanceLayerProperties); + } else if (strcmp("vkEnumeratePhysicalDevices", pName) == 0) { + return reinterpret_cast(vkEnumeratePhysicalDevices); + } else if (strcmp("vkGetPhysicalDeviceFormatProperties", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceFormatProperties); + } else if (strcmp("vkGetPhysicalDeviceProperties", pName) == 0) { + return reinterpret_cast(vkGetPhysicalDeviceProperties); + } else if (strcmp("vkGetPhysicalDeviceQueueFamilyProperties", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceQueueFamilyProperties); + } else if (strcmp("vkEnumerateDeviceExtensionProperties", pName) == 0) { + return reinterpret_cast( + vkEnumerateDeviceExtensionProperties); + } else if (strcmp("vkCreateDevice", pName) == 0) { + return reinterpret_cast(vkCreateDevice); + } else if (strcmp("vkCreateInstance", pName) == 0) { + return reinterpret_cast(vkCreateInstance); + } else if (strcmp("vkGetPhysicalDeviceMemoryProperties", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceMemoryProperties); + } else if (strcmp("vkCreatePipelineCache", pName) == 0) { + return reinterpret_cast(vkCreatePipelineCache); + } else if (strcmp("vkCreateCommandPool", pName) == 0) { + return reinterpret_cast(vkCreateCommandPool); + } else if (strcmp("vkResetCommandPool", pName) == 0) { + return reinterpret_cast(vkResetCommandPool); + } else if (strcmp("vkAllocateCommandBuffers", pName) == 0) { + return reinterpret_cast(vkAllocateCommandBuffers); + } else if (strcmp("vkBeginCommandBuffer", pName) == 0) { + return reinterpret_cast(vkBeginCommandBuffer); + } else if (strcmp("vkCreateImage", pName) == 0) { + return reinterpret_cast(vkCreateImage); + } else if (strcmp("vkGetInstanceProcAddr", pName) == 0) { + return reinterpret_cast(GetMockVulkanProcAddress); + } else if (strcmp("vkGetDeviceProcAddr", pName) == 0) { + return reinterpret_cast(GetMockVulkanProcAddress); + } else if (strcmp("vkGetImageMemoryRequirements2KHR", pName) == 0 || + strcmp("vkGetImageMemoryRequirements2", pName) == 0) { + return reinterpret_cast( + vkGetImageMemoryRequirements2KHR); + } else if (strcmp("vkAllocateMemory", pName) == 0) { + return reinterpret_cast(vkAllocateMemory); + } else if (strcmp("vkBindImageMemory", pName) == 0) { + return reinterpret_cast(vkBindImageMemory); + } else if (strcmp("vkCreateImageView", pName) == 0) { + return reinterpret_cast(vkCreateImageView); + } else if (strcmp("vkCreateBuffer", pName) == 0) { + return reinterpret_cast(vkCreateBuffer); + } else if (strcmp("vkGetBufferMemoryRequirements2KHR", pName) == 0 || + strcmp("vkGetBufferMemoryRequirements2", pName) == 0) { + return reinterpret_cast( + vkGetBufferMemoryRequirements2KHR); + } else if (strcmp("vkBindBufferMemory", pName) == 0) { + return reinterpret_cast(vkBindBufferMemory); + } else if (strcmp("vkCreateRenderPass", pName) == 0) { + return reinterpret_cast(vkCreateRenderPass); + } else if (strcmp("vkCreateDescriptorSetLayout", pName) == 0) { + return reinterpret_cast(vkCreateDescriptorSetLayout); + } else if (strcmp("vkCreatePipelineLayout", pName) == 0) { + return reinterpret_cast(vkCreatePipelineLayout); + } else if (strcmp("vkCreateGraphicsPipelines", pName) == 0) { + return reinterpret_cast(vkCreateGraphicsPipelines); + } else if (strcmp("vkDestroyDevice", pName) == 0) { + return reinterpret_cast(vkDestroyDevice); + } else if (strcmp("vkDestroyPipeline", pName) == 0) { + return reinterpret_cast(vkDestroyPipeline); + } else if (strcmp("vkCreateShaderModule", pName) == 0) { + return reinterpret_cast(vkCreateShaderModule); + } else if (strcmp("vkDestroyShaderModule", pName) == 0) { + return reinterpret_cast(vkDestroyShaderModule); + } else if (strcmp("vkDestroyPipelineCache", pName) == 0) { + return reinterpret_cast(vkDestroyPipelineCache); + } else if (strcmp("vkCmdBindPipeline", pName) == 0) { + return reinterpret_cast(vkCmdBindPipeline); + } else if (strcmp("vkCmdSetStencilReference", pName) == 0) { + return reinterpret_cast(vkCmdSetStencilReference); + } else if (strcmp("vkCmdSetScissor", pName) == 0) { + return reinterpret_cast(vkCmdSetScissor); + } else if (strcmp("vkCmdSetViewport", pName) == 0) { + return reinterpret_cast(vkCmdSetViewport); + } else if (strcmp("vkDestroyCommandPool", pName) == 0) { + return reinterpret_cast(vkDestroyCommandPool); + } else if (strcmp("vkFreeCommandBuffers", pName) == 0) { + return reinterpret_cast(vkFreeCommandBuffers); + } else if (strcmp("vkEndCommandBuffer", pName) == 0) { + return reinterpret_cast(vkEndCommandBuffer); + } else if (strcmp("vkCreateFence", pName) == 0) { + return reinterpret_cast(vkCreateFence); + } else if (strcmp("vkDestroyFence", pName) == 0) { + return reinterpret_cast(vkDestroyFence); + } else if (strcmp("vkQueueSubmit", pName) == 0) { + return reinterpret_cast(vkQueueSubmit); + } else if (strcmp("vkWaitForFences", pName) == 0) { + return reinterpret_cast(vkWaitForFences); + } else if (strcmp("vkGetFenceStatus", pName) == 0) { + return reinterpret_cast(vkGetFenceStatus); + } else if (strcmp("vkResetFences", pName) == 0) { + return reinterpret_cast(vkResetFences); + } else if (strcmp("vkCreateDebugUtilsMessengerEXT", pName) == 0) { + return reinterpret_cast(vkCreateDebugUtilsMessengerEXT); + } else if (strcmp("vkSetDebugUtilsObjectNameEXT", pName) == 0) { + return reinterpret_cast(vkSetDebugUtilsObjectNameEXT); + } else if (strcmp("vkCreateQueryPool", pName) == 0) { + return reinterpret_cast(vkCreateQueryPool); + } else if (strcmp("vkDestroyQueryPool", pName) == 0) { + return reinterpret_cast(vkDestroyQueryPool); + } else if (strcmp("vkGetQueryPoolResults", pName) == 0) { + return reinterpret_cast(vkGetQueryPoolResults); + } else if (strcmp("vkCreateDescriptorPool", pName) == 0) { + return reinterpret_cast(vkCreateDescriptorPool); + } else if (strcmp("vkDestroyDescriptorPool", pName) == 0) { + return reinterpret_cast(vkDestroyDescriptorPool); + } else if (strcmp("vkResetDescriptorPool", pName) == 0) { + return reinterpret_cast(vkResetDescriptorPool); + } else if (strcmp("vkAllocateDescriptorSets", pName) == 0) { + return reinterpret_cast(vkAllocateDescriptorSets); + } else if (strcmp("vkGetPhysicalDeviceSurfaceFormatsKHR", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceSurfaceFormatsKHR); + } else if (strcmp("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceSurfaceCapabilitiesKHR); + } else if (strcmp("vkGetPhysicalDeviceSurfaceSupportKHR", pName) == 0) { + return reinterpret_cast( + vkGetPhysicalDeviceSurfaceSupportKHR); + } else if (strcmp("vkCreateSwapchainKHR", pName) == 0) { + return reinterpret_cast(vkCreateSwapchainKHR); + } else if (strcmp("vkDestroySwapchainKHR", pName) == 0) { + return reinterpret_cast(vkDestroySwapchainKHR); + } else if (strcmp("vkGetSwapchainImagesKHR", pName) == 0) { + return reinterpret_cast(vkGetSwapchainImagesKHR); + } else if (strcmp("vkCreateSemaphore", pName) == 0) { + return reinterpret_cast(vkCreateSemaphore); + } else if (strcmp("vkDestroySemaphore", pName) == 0) { + return reinterpret_cast(vkDestroySemaphore); + } else if (strcmp("vkDestroySurfaceKHR", pName) == 0) { + return reinterpret_cast(vkDestroySurfaceKHR); + } else if (strcmp("vkAcquireNextImageKHR", pName) == 0) { + return reinterpret_cast(vkAcquireNextImageKHR); + } else if (strcmp("vkCreateFramebuffer", pName) == 0) { + return reinterpret_cast(vkCreateFramebuffer); + } else if (strcmp("vkDestroyFramebuffer", pName) == 0) { + return reinterpret_cast(vkDestroyFramebuffer); + } else if (strcmp("vkTrimCommandPool", pName) == 0) { + return reinterpret_cast(vkTrimCommandPool); + } + return noop; +} + +} // namespace + +MockVulkanContextBuilder::MockVulkanContextBuilder() + : instance_extensions_({"VK_KHR_surface", "VK_MVK_macos_surface"}), + format_properties_callback_([](VkPhysicalDevice physicalDevice, + VkFormat format, + VkFormatProperties* pFormatProperties) { + if (format == VK_FORMAT_R8G8B8A8_UNORM) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eColorAttachment); + } else if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eDepthStencilAttachment); + } else if (format == VK_FORMAT_S8_UINT) { + pFormatProperties->optimalTilingFeatures = + static_cast( + vk::FormatFeatureFlagBits::eDepthStencilAttachment); + } + }) {} + +std::shared_ptr MockVulkanContextBuilder::Build() { + auto message_loop = fml::ConcurrentMessageLoop::Create(); + ContextVK::Settings settings; + settings.proc_address_callback = GetMockVulkanProcAddress; + if (settings_callback_) { + settings_callback_(settings); + } + g_instance_extensions = instance_extensions_; + g_instance_layers = instance_layers_; + g_format_properties_callback = format_properties_callback_; + g_physical_device_properties_callback = physical_properties_callback_; + settings.embedder_data = embedder_data_; + std::shared_ptr result = ContextVK::Create(std::move(settings)); + return result; +} + +std::shared_ptr> GetMockVulkanFunctions( + VkDevice device) { + MockDevice* mock_device = reinterpret_cast(device); + return mock_device->GetCalledFunctions(); +} + +void SetSwapchainImageSize(ISize size) { + currentImageSize = size; +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.h new file mode 100644 index 0000000000000000000000000000000000000000..25da5720c3b5afca9f0a6c1614b2a3da119aac30 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.h @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_ + +#include +#include +#include +#include + +#include "impeller/base/thread.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "vulkan/vulkan_core.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { +namespace testing { + +std::shared_ptr> GetMockVulkanFunctions( + VkDevice device); + +// A test-controlled version of |vk::Fence|. +class MockFence final { + public: + MockFence() = default; + + // Returns the result that was set in the constructor or |SetStatus|. + VkResult GetStatus() { return static_cast(result_.load()); } + + // Sets the result that will be returned by `GetFenceStatus`. + void SetStatus(vk::Result result) { result_ = result; } + + // Sets the result that will be returned by `GetFenceStatus`. + static void SetStatus(vk::UniqueFence& fence, vk::Result result) { + // Cast the fence to a MockFence and set the result. + VkFence raw_fence = fence.get(); + MockFence* mock_fence = reinterpret_cast(raw_fence); + mock_fence->SetStatus(result); + } + + // Gets a raw pointer to manipulate the fence after it's been moved. + static MockFence* GetRawPointer(vk::UniqueFence& fence) { + // Cast the fence to a MockFence and get the result. + VkFence raw_fence = fence.get(); + MockFence* mock_fence = reinterpret_cast(raw_fence); + return mock_fence; + } + + private: + std::atomic result_ = vk::Result::eSuccess; + + MockFence(const MockFence&) = delete; + + MockFence& operator=(const MockFence&) = delete; +}; + +class MockVulkanContextBuilder { + public: + MockVulkanContextBuilder(); + + //------------------------------------------------------------------------------ + /// @brief Create a Vulkan context with Vulkan functions mocked. The + /// caller is given a chance to tinker on the settings right + /// before a context is created. + /// + /// @return A context if one can be created. + /// + std::shared_ptr Build(); + + /// A callback that allows the modification of the ContextVK::Settings before + /// the context is made. + MockVulkanContextBuilder& SetSettingsCallback( + const std::function& settings_callback) { + settings_callback_ = settings_callback; + return *this; + } + + MockVulkanContextBuilder& SetInstanceExtensions( + const std::vector& instance_extensions) { + instance_extensions_ = instance_extensions; + return *this; + } + + MockVulkanContextBuilder& SetInstanceLayers( + const std::vector& instance_layers) { + instance_layers_ = instance_layers; + return *this; + } + + /// Set the behavior of vkGetPhysicalDeviceFormatProperties, which needs to + /// respond differently for different formats. + MockVulkanContextBuilder& SetPhysicalDeviceFormatPropertiesCallback( + std::function + format_properties_callback) { + format_properties_callback_ = std::move(format_properties_callback); + return *this; + } + + MockVulkanContextBuilder& SetPhysicalPropertiesCallback( + std::function + physical_properties_callback) { + physical_properties_callback_ = std::move(physical_properties_callback); + return *this; + } + + MockVulkanContextBuilder SetEmbedderData( + const ContextVK::EmbedderData& embedder_data) { + embedder_data_ = embedder_data; + return *this; + } + + private: + std::function settings_callback_; + std::vector instance_extensions_; + std::vector instance_layers_; + std::optional embedder_data_; + std::function + format_properties_callback_; + std::function + physical_properties_callback_; +}; + +/// @brief Override the image size returned by all swapchain images. +void SetSwapchainImageSize(ISize size); + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEST_MOCK_VULKAN_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..1688b12e49c46c18edc7dd1179382e2a0228e50b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan_unittests.cc @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "vulkan/vulkan_enums.hpp" + +namespace impeller { +namespace testing { + +TEST(MockVulkanContextTest, IsThreadSafe) { + // In a typical app, there is a single ContextVK per app, shared b/w threads. + // + // This test ensures that the (mock) ContextVK is thread-safe. + auto const context = MockVulkanContextBuilder().Build(); + + // Spawn two threads, and have them create a CommandPoolVK each. + std::thread thread1([&context]() { + auto const pool = context->GetCommandPoolRecycler()->Get(); + EXPECT_TRUE(pool); + }); + + std::thread thread2([&context]() { + auto const pool = context->GetCommandPoolRecycler()->Get(); + EXPECT_TRUE(pool); + }); + + thread1.join(); + thread2.join(); + + context->Shutdown(); +} + +TEST(MockVulkanContextTest, DefaultFenceAlwaysReportsSuccess) { + auto const context = MockVulkanContextBuilder().Build(); + auto const device = context->GetDevice(); + + auto fence = device.createFenceUnique({}).value; + EXPECT_EQ(vk::Result::eSuccess, device.getFenceStatus(*fence)); +} + +TEST(MockVulkanContextTest, MockedFenceReportsStatus) { + auto const context = MockVulkanContextBuilder().Build(); + + auto const device = context->GetDevice(); + auto fence = device.createFenceUnique({}).value; + MockFence::SetStatus(fence, vk::Result::eNotReady); + + EXPECT_EQ(vk::Result::eNotReady, device.getFenceStatus(fence.get())); + + MockFence::SetStatus(fence, vk::Result::eSuccess); + EXPECT_EQ(vk::Result::eSuccess, device.getFenceStatus(*fence)); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/sampler_library_vk_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/sampler_library_vk_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ac0ff30bc32589488a314c2cf4aed54269f53c7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/sampler_library_vk_unittests.cc @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_library_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" + +namespace impeller { +namespace testing { + +TEST(SamplerLibraryVK, WorkaroundsCanDisableReadingFromMipLevels) { + auto const context = MockVulkanContextBuilder().Build(); + + auto library_vk = + std::make_shared(context->GetDeviceHolder()); + std::shared_ptr library = library_vk; + + SamplerDescriptor desc; + desc.mip_filter = MipFilter::kLinear; + + auto sampler = library->GetSampler(desc); + EXPECT_EQ(sampler->GetDescriptor().mip_filter, MipFilter::kLinear); + + // Apply mips disabled workaround. + library_vk->ApplyWorkarounds(WorkaroundsVK{.broken_mipmap_generation = true}); + + sampler = library->GetSampler(desc); + EXPECT_EQ(sampler->GetDescriptor().mip_filter, MipFilter::kBase); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/swapchain_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/swapchain_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..4347df46aa561838c3ceb6471bf145ee2cfe2a5d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/test/swapchain_unittests.cc @@ -0,0 +1,130 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" // IWYU pragma: keep +#include "gtest/gtest.h" +#include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_vk.h" +#include "impeller/renderer/backend/vulkan/test/mock_vulkan.h" +#include "impeller/renderer/backend/vulkan/texture_vk.h" +#include "impeller/renderer/render_pass.h" +#include "vulkan/vulkan_enums.hpp" +#include "vulkan/vulkan_handles.hpp" + +namespace impeller { +namespace testing { + +vk::UniqueSurfaceKHR CreateSurface(const ContextVK& context) { +#if FML_OS_DARWIN + impeller::vk::MetalSurfaceCreateInfoEXT createInfo = {}; + auto [result, surface] = + context.GetInstance().createMetalSurfaceEXTUnique(createInfo); + FML_DCHECK(result == vk::Result::eSuccess); + return std::move(surface); +#else + return {}; +#endif // FML_OS_DARWIN +} + +TEST(SwapchainTest, CanCreateSwapchain) { + auto const context = MockVulkanContextBuilder().Build(); + + auto surface = CreateSurface(*context); + auto swapchain = + KHRSwapchainVK::Create(context, std::move(surface), ISize{1, 1}); + + EXPECT_TRUE(swapchain->IsValid()); +} + +TEST(SwapchainTest, RecreateSwapchainWhenSizeChanges) { + auto const context = MockVulkanContextBuilder().Build(); + + auto surface = CreateSurface(*context); + SetSwapchainImageSize(ISize{1, 1}); + auto swapchain = + KHRSwapchainVK::Create(context, std::move(surface), ISize{1, 1}, + /*enable_msaa=*/false); + auto image = swapchain->AcquireNextDrawable(); + auto expected_size = ISize{1, 1}; + EXPECT_EQ(image->GetSize(), expected_size); + + SetSwapchainImageSize(ISize{100, 100}); + swapchain->UpdateSurfaceSize(ISize{100, 100}); + + auto image_b = swapchain->AcquireNextDrawable(); + expected_size = ISize{100, 100}; + EXPECT_EQ(image_b->GetSize(), expected_size); +} + +TEST(SwapchainTest, CachesRenderPassOnSwapchainImage) { + auto const context = MockVulkanContextBuilder().Build(); + + auto surface = CreateSurface(*context); + auto swapchain = + KHRSwapchainVK::Create(context, std::move(surface), ISize{1, 1}); + + EXPECT_TRUE(swapchain->IsValid()); + + // The mock swapchain will always create 3 images, verify each one starts + // out with the same MSAA and depth+stencil texture, and no cached + // framebuffer. + std::vector> msaa_textures; + std::vector> depth_stencil_textures; + for (auto i = 0u; i < 3u; i++) { + auto drawable = swapchain->AcquireNextDrawable(); + RenderTarget render_target = drawable->GetRenderTarget(); + + auto texture = render_target.GetRenderTargetTexture(); + auto& texture_vk = TextureVK::Cast(*texture); + EXPECT_EQ(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_EQ(texture_vk.GetCachedRenderPass(), nullptr); + + auto command_buffer = context->CreateCommandBuffer(); + auto render_pass = command_buffer->CreateRenderPass(render_target); + render_pass->EncodeCommands(); + + auto& depth = render_target.GetDepthAttachment(); + depth_stencil_textures.push_back(depth.has_value() ? depth->texture + : nullptr); + msaa_textures.push_back(render_target.GetColorAttachment(0).texture); + } + + for (auto i = 1; i < 3; i++) { + EXPECT_EQ(msaa_textures[i - 1], msaa_textures[i]); + EXPECT_EQ(depth_stencil_textures[i - 1], depth_stencil_textures[i]); + } + + // After each images has been acquired once and the render pass presented, + // each should have a cached framebuffer and render pass. + + std::vector> framebuffers; + std::vector> render_passes; + for (auto i = 0u; i < 3u; i++) { + auto drawable = swapchain->AcquireNextDrawable(); + RenderTarget render_target = drawable->GetRenderTarget(); + + auto texture = render_target.GetRenderTargetTexture(); + auto& texture_vk = TextureVK::Cast(*texture); + + EXPECT_NE(texture_vk.GetCachedFramebuffer(), nullptr); + EXPECT_NE(texture_vk.GetCachedRenderPass(), nullptr); + framebuffers.push_back(texture_vk.GetCachedFramebuffer()); + render_passes.push_back(texture_vk.GetCachedRenderPass()); + } + + // Iterate through once more to verify render passes and framebuffers are + // unchanged. + for (auto i = 0u; i < 3u; i++) { + auto drawable = swapchain->AcquireNextDrawable(); + RenderTarget render_target = drawable->GetRenderTarget(); + + auto texture = render_target.GetRenderTargetTexture(); + auto& texture_vk = TextureVK::Cast(*texture); + + EXPECT_EQ(texture_vk.GetCachedFramebuffer(), framebuffers[i]); + EXPECT_EQ(texture_vk.GetCachedRenderPass(), render_passes[i]); + } +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..d8b6f6d6f320933fad5cae1e31abd8157301fabd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.cc @@ -0,0 +1,77 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" + +namespace impeller { + +TextureSourceVK::TextureSourceVK(TextureDescriptor desc) : desc_(desc) {} + +TextureSourceVK::~TextureSourceVK() = default; + +const TextureDescriptor& TextureSourceVK::GetTextureDescriptor() const { + return desc_; +} + +std::shared_ptr TextureSourceVK::GetYUVConversion() const { + return nullptr; +} + +vk::ImageLayout TextureSourceVK::GetLayout() const { + return layout_; +} + +vk::ImageLayout TextureSourceVK::SetLayoutWithoutEncoding( + vk::ImageLayout layout) const { + const auto old_layout = layout_; + layout_ = layout; + return old_layout; +} + +fml::Status TextureSourceVK::SetLayout(const BarrierVK& barrier) const { + const auto old_layout = SetLayoutWithoutEncoding(barrier.new_layout); + vk::ImageMemoryBarrier image_barrier; + image_barrier.srcAccessMask = barrier.src_access; + image_barrier.dstAccessMask = barrier.dst_access; + image_barrier.oldLayout = old_layout; + image_barrier.newLayout = barrier.new_layout; + image_barrier.image = GetImage(); + image_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_barrier.subresourceRange.aspectMask = ToImageAspectFlags(desc_.format); + image_barrier.subresourceRange.baseMipLevel = 0u; + image_barrier.subresourceRange.levelCount = desc_.mip_count; + image_barrier.subresourceRange.baseArrayLayer = 0u; + image_barrier.subresourceRange.layerCount = ToArrayLayerCount(desc_.type); + + barrier.cmd_buffer.pipelineBarrier(barrier.src_stage, // src stage + barrier.dst_stage, // dst stage + {}, // dependency flags + nullptr, // memory barriers + nullptr, // buffer barriers + image_barrier // image barriers + ); + + return {}; +} + +void TextureSourceVK::SetCachedFramebuffer( + const SharedHandleVK& framebuffer) { + framebuffer_ = framebuffer; +} + +void TextureSourceVK::SetCachedRenderPass( + const SharedHandleVK& render_pass) { + render_pass_ = render_pass; +} + +SharedHandleVK TextureSourceVK::GetCachedFramebuffer() const { + return framebuffer_; +} + +SharedHandleVK TextureSourceVK::GetCachedRenderPass() const { + return render_pass_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..77c78be1605cbe99388f87f2ab663fa5e1fd3cdf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_source_vk.h @@ -0,0 +1,165 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_ + +#include "flutter/fml/status.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/vulkan/barrier_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Abstract base class that represents a vkImage and an +/// vkImageView. +/// +/// This is intended to be used with an impeller::TextureVK. Example +/// implementations represent swapchain images, uploaded textures, +/// Android Hardware Buffer backend textures, etc... +/// +class TextureSourceVK { + public: + virtual ~TextureSourceVK(); + + //---------------------------------------------------------------------------- + /// @brief Gets the texture descriptor for this image source. + /// + /// @warning Texture descriptors from texture sources whose capabilities + /// are a superset of those that can be expressed with Vulkan + /// (like Android Hardware Buffer) are inferred. Stuff like size, + /// mip-counts, types is reliable. So use these descriptors as + /// advisory. Creating copies of texture sources from these + /// descriptors is usually not possible and depends on the + /// allocator used. + /// + /// @return The texture descriptor. + /// + const TextureDescriptor& GetTextureDescriptor() const; + + //---------------------------------------------------------------------------- + /// @brief Get the image handle for this texture source. + /// + /// @return The image. + /// + virtual vk::Image GetImage() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Retrieve the image view used for sampling/blitting/compute + /// with this texture source. + /// + /// @return The image view. + /// + virtual vk::ImageView GetImageView() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Retrieve the image view used for render target attachments + /// with this texture source. + /// + /// ImageViews used as render target attachments cannot have any + /// mip levels. In cases where we want to generate mipmaps with + /// the result of this texture, we need to create multiple image + /// views. + /// + /// @return The render target view. + /// + virtual vk::ImageView GetRenderTargetView() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Encodes the layout transition `barrier` to + /// `barrier.cmd_buffer` for the image. + /// + /// The transition is from the layout stored via + /// `SetLayoutWithoutEncoding` to `barrier.new_layout`. + /// + /// @param[in] barrier The barrier. + /// + /// @return If the layout transition was successfully made. + /// + fml::Status SetLayout(const BarrierVK& barrier) const; + + //---------------------------------------------------------------------------- + /// @brief Store the layout of the image. + /// + /// This just is bookkeeping on the CPU, to actually set the + /// layout use `SetLayout`. + /// + /// @param[in] layout The new layout. + /// + /// @return The old layout. + /// + vk::ImageLayout SetLayoutWithoutEncoding(vk::ImageLayout layout) const; + + //---------------------------------------------------------------------------- + /// @brief Get the last layout assigned to the TextureSourceVK. + /// + /// This value is synchronized with the GPU via SetLayout so it + /// may not reflect the actual layout. + /// + /// @return The last known layout of the texture source. + /// + vk::ImageLayout GetLayout() const; + + //---------------------------------------------------------------------------- + /// @brief When sampling from textures whose formats are not known to + /// Vulkan, a custom conversion is necessary to setup custom + /// samplers. This accessor provides this conversion if one is + /// present. Most texture source have none. + /// + /// @return The sampler conversion. + /// + virtual std::shared_ptr GetYUVConversion() const; + + //---------------------------------------------------------------------------- + /// @brief Determines if swapchain image. That is, an image used as the + /// root render target. + /// + /// @return Whether or not this is a swapchain image. + /// + virtual bool IsSwapchainImage() const = 0; + + // These methods should only be used by render_pass_vk.h + + /// Store the last framebuffer object used with this texture. + /// + /// This field is only set if this texture is used as the resolve texture + /// of a render pass. By construction, this framebuffer should be compatible + /// with any future render passes. + void SetCachedFramebuffer(const SharedHandleVK& framebuffer); + + /// Store the last render pass object used with this texture. + /// + /// This field is only set if this texture is used as the resolve texture + /// of a render pass. By construction, this framebuffer should be compatible + /// with any future render passes. + void SetCachedRenderPass(const SharedHandleVK& render_pass); + + /// Retrieve the last framebuffer object used with this texture. + /// + /// May be nullptr if no previous framebuffer existed. + SharedHandleVK GetCachedFramebuffer() const; + + /// Retrieve the last render pass object used with this texture. + /// + /// May be nullptr if no previous render pass existed. + SharedHandleVK GetCachedRenderPass() const; + + protected: + const TextureDescriptor desc_; + + explicit TextureSourceVK(TextureDescriptor desc); + + private: + SharedHandleVK framebuffer_; + SharedHandleVK render_pass_; + mutable vk::ImageLayout layout_ = vk::ImageLayout::eUndefined; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_SOURCE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..7acb2da73463ca579a2d5bf8147a78bc962bda82 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.cc @@ -0,0 +1,239 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/texture_vk.h" + +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/backend/vulkan/command_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" + +namespace impeller { + +TextureVK::TextureVK(std::weak_ptr context, + std::shared_ptr source) + : Texture(source->GetTextureDescriptor()), + context_(std::move(context)), + source_(std::move(source)) { +#ifdef IMPELLER_DEBUG + has_validation_layers_ = HasValidationLayers(); +#endif // IMPELLER_DEBUG +} + +TextureVK::~TextureVK() = default; + +void TextureVK::SetLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + if (!has_validation_layers_) { + return; + } + auto context = context_.lock(); + if (!context) { + // The context may have died. + return; + } + ContextVK::Cast(*context).SetDebugName(GetImage(), label); + ContextVK::Cast(*context).SetDebugName(GetImageView(), label); +#endif // IMPELLER_DEBUG +} + +void TextureVK::SetLabel(std::string_view label, std::string_view trailing) { +#ifdef IMPELLER_DEBUG + auto context = context_.lock(); + if (!context) { + // The context may have died. + return; + } + + ContextVK::Cast(*context).SetDebugName(GetImage(), label, trailing); + ContextVK::Cast(*context).SetDebugName(GetImageView(), label, trailing); +#endif // IMPELLER_DEBUG +} + +bool TextureVK::OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) { + if (!IsValid() || !contents) { + return false; + } + + const auto& desc = GetTextureDescriptor(); + + // Out of bounds access. + if (length != desc.GetByteSizeOfBaseMipLevel()) { + VALIDATION_LOG << "Illegal to set contents for invalid size."; + return false; + } + + auto context = context_.lock(); + if (!context) { + VALIDATION_LOG << "Context died before setting contents on texture."; + return false; + } + + auto staging_buffer = + context->GetResourceAllocator()->CreateBufferWithCopy(contents, length); + + if (!staging_buffer) { + VALIDATION_LOG << "Could not create staging buffer."; + return false; + } + + auto cmd_buffer = context->CreateCommandBuffer(); + + if (!cmd_buffer) { + return false; + } + + auto& cmd_buffer_vk = CommandBufferVK::Cast(*cmd_buffer); + + if (!cmd_buffer_vk.Track(staging_buffer) || !cmd_buffer_vk.Track(source_)) { + return false; + } + + const auto& vk_cmd_buffer = cmd_buffer_vk.GetCommandBuffer(); + + BarrierVK barrier; + barrier.cmd_buffer = vk_cmd_buffer; + barrier.new_layout = vk::ImageLayout::eTransferDstOptimal; + barrier.src_access = {}; + barrier.src_stage = vk::PipelineStageFlagBits::eTopOfPipe; + barrier.dst_access = vk::AccessFlagBits::eTransferWrite; + barrier.dst_stage = vk::PipelineStageFlagBits::eTransfer; + + if (!SetLayout(barrier)) { + return false; + } + + vk::BufferImageCopy copy; + copy.bufferOffset = 0u; + copy.bufferRowLength = 0u; // 0u means tightly packed per spec. + copy.bufferImageHeight = 0u; // 0u means tightly packed per spec. + copy.imageOffset.x = 0u; + copy.imageOffset.y = 0u; + copy.imageOffset.z = 0u; + copy.imageExtent.width = desc.size.width; + copy.imageExtent.height = desc.size.height; + copy.imageExtent.depth = 1u; + copy.imageSubresource.aspectMask = + ToImageAspectFlags(GetTextureDescriptor().format); + copy.imageSubresource.mipLevel = 0u; + copy.imageSubresource.baseArrayLayer = slice; + copy.imageSubresource.layerCount = 1u; + + vk_cmd_buffer.copyBufferToImage( + DeviceBufferVK::Cast(*staging_buffer).GetBuffer(), // src buffer + GetImage(), // dst image + barrier.new_layout, // dst image layout + 1u, // region count + © // regions + ); + + // Transition to shader-read. + { + BarrierVK barrier; + barrier.cmd_buffer = vk_cmd_buffer; + barrier.src_access = vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eTransferWrite; + barrier.src_stage = vk::PipelineStageFlagBits::eColorAttachmentOutput | + vk::PipelineStageFlagBits::eTransfer; + barrier.dst_access = vk::AccessFlagBits::eShaderRead; + barrier.dst_stage = vk::PipelineStageFlagBits::eFragmentShader; + + barrier.new_layout = vk::ImageLayout::eShaderReadOnlyOptimal; + + if (!SetLayout(barrier)) { + return false; + } + } + + return context->GetCommandQueue()->Submit({cmd_buffer}).ok(); +} + +bool TextureVK::OnSetContents(std::shared_ptr mapping, + size_t slice) { + // Vulkan has no threading restrictions. So we can pass this data along to the + // client rendering API immediately. + return OnSetContents(mapping->GetMapping(), mapping->GetSize(), slice); +} + +bool TextureVK::IsValid() const { + return !!source_; +} + +ISize TextureVK::GetSize() const { + return GetTextureDescriptor().size; +} + +vk::Image TextureVK::GetImage() const { + return source_->GetImage(); +} + +vk::ImageView TextureVK::GetImageView() const { + return source_->GetImageView(); +} + +std::shared_ptr TextureVK::GetTextureSource() const { + return source_; +} + +bool TextureVK::SetLayout(const BarrierVK& barrier) const { + return source_ ? source_->SetLayout(barrier).ok() : false; +} + +vk::ImageLayout TextureVK::SetLayoutWithoutEncoding( + vk::ImageLayout layout) const { + return source_ ? source_->SetLayoutWithoutEncoding(layout) + : vk::ImageLayout::eUndefined; +} + +vk::ImageLayout TextureVK::GetLayout() const { + return source_ ? source_->GetLayout() : vk::ImageLayout::eUndefined; +} + +vk::ImageView TextureVK::GetRenderTargetView() const { + return source_->GetRenderTargetView(); +} + +void TextureVK::SetCachedFramebuffer( + const SharedHandleVK& framebuffer) { + source_->SetCachedFramebuffer(framebuffer); +} + +void TextureVK::SetCachedRenderPass( + const SharedHandleVK& render_pass) { + source_->SetCachedRenderPass(render_pass); +} + +SharedHandleVK TextureVK::GetCachedFramebuffer() const { + return source_->GetCachedFramebuffer(); +} + +SharedHandleVK TextureVK::GetCachedRenderPass() const { + return source_->GetCachedRenderPass(); +} + +void TextureVK::SetMipMapGenerated() { + mipmap_generated_ = true; +} + +bool TextureVK::IsSwapchainImage() const { + return source_->IsSwapchainImage(); +} + +std::shared_ptr TextureVK::GetImmutableSamplerVariant( + const SamplerVK& sampler) const { + if (!source_) { + return nullptr; + } + std::shared_ptr conversion = source_->GetYUVConversion(); + if (!conversion) { + // Most textures don't need a sampler conversion and will go down this path. + // Only needed for YUV sampling from external textures. + return nullptr; + } + return sampler.CreateVariantForConversion(std::move(conversion)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..7b454eca3b5397529a9a477d45410072ae88e1c1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/texture_vk.h @@ -0,0 +1,107 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_VK_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/device_buffer_vk.h" +#include "impeller/renderer/backend/vulkan/formats_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +class TextureVK final : public Texture, public BackendCast { + public: + TextureVK(std::weak_ptr context, + std::shared_ptr source); + + // |Texture| + ~TextureVK() override; + + vk::Image GetImage() const; + + vk::ImageView GetImageView() const; + + vk::ImageView GetRenderTargetView() const; + + bool SetLayout(const BarrierVK& barrier) const; + + vk::ImageLayout SetLayoutWithoutEncoding(vk::ImageLayout layout) const; + + vk::ImageLayout GetLayout() const; + + std::shared_ptr GetTextureSource() const; + + // |Texture| + ISize GetSize() const override; + + void SetMipMapGenerated(); + + bool IsSwapchainImage() const; + + std::shared_ptr GetImmutableSamplerVariant( + const SamplerVK& sampler) const; + + // These methods should only be used by render_pass_vk.h + + /// Store the last framebuffer object used with this texture. + /// + /// This field is only set if this texture is used as the resolve texture + /// of a render pass. By construction, this framebuffer should be compatible + /// with any future render passes. + void SetCachedFramebuffer(const SharedHandleVK& framebuffer); + + /// Store the last render pass object used with this texture. + /// + /// This field is only set if this texture is used as the resolve texture + /// of a render pass. By construction, this framebuffer should be compatible + /// with any future render passes. + void SetCachedRenderPass(const SharedHandleVK& render_pass); + + /// Retrieve the last framebuffer object used with this texture. + /// + /// May be nullptr if no previous framebuffer existed. + SharedHandleVK GetCachedFramebuffer() const; + + /// Retrieve the last render pass object used with this texture. + /// + /// May be nullptr if no previous render pass existed. + SharedHandleVK GetCachedRenderPass() const; + + private: + std::weak_ptr context_; + std::shared_ptr source_; + bool has_validation_layers_ = false; + + // |Texture| + void SetLabel(std::string_view label) override; + + // |Texture| + void SetLabel(std::string_view label, std::string_view trailing) override; + + // |Texture| + bool OnSetContents(const uint8_t* contents, + size_t length, + size_t slice) override; + + // |Texture| + bool OnSetContents(std::shared_ptr mapping, + size_t slice) override; + + // |Texture| + bool IsValid() const override; + + TextureVK(const TextureVK&) = delete; + + TextureVK& operator=(const TextureVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TEXTURE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..055e5c4697b1eec9fa751e33320e805d7d70acfc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.cc @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/tracked_objects_vk.h" + +#include "impeller/renderer/backend/vulkan/command_pool_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" + +namespace impeller { + +TrackedObjectsVK::TrackedObjectsVK( + const std::weak_ptr& context, + const std::shared_ptr& pool, + std::shared_ptr descriptor_pool, + std::unique_ptr probe) + : desc_pool_(std::move(descriptor_pool)), probe_(std::move(probe)) { + if (!pool) { + return; + } + auto buffer = pool->CreateCommandBuffer(); + if (!buffer) { + return; + } + pool_ = pool; + buffer_ = std::move(buffer); + is_valid_ = true; + // Starting values were selected by looking at values from + // AiksTest.CanRenderMultipleBackdropBlurWithSingleBackdropId. + tracked_objects_.reserve(5); + tracked_buffers_.reserve(5); + tracked_textures_.reserve(5); +} + +TrackedObjectsVK::~TrackedObjectsVK() { + if (!buffer_) { + return; + } + pool_->CollectCommandBuffer(std::move(buffer_)); +} + +bool TrackedObjectsVK::IsValid() const { + return is_valid_; +} + +void TrackedObjectsVK::Track(const std::shared_ptr& object) { + if (!object || (!tracked_objects_.empty() && + object.get() == tracked_objects_.back().get())) { + return; + } + tracked_objects_.emplace_back(object); +} + +void TrackedObjectsVK::Track( + const std::shared_ptr& buffer) { + if (!buffer || (!tracked_buffers_.empty() && + buffer.get() == tracked_buffers_.back().get())) { + return; + } + tracked_buffers_.emplace_back(buffer); +} + +void TrackedObjectsVK::Track( + const std::shared_ptr& texture) { + if (!texture || (!tracked_textures_.empty() && + texture.get() == tracked_textures_.back().get())) { + return; + } + tracked_textures_.emplace_back(texture); +} + +vk::CommandBuffer TrackedObjectsVK::GetCommandBuffer() const { + return *buffer_; +} + +DescriptorPoolVK& TrackedObjectsVK::GetDescriptorPool() { + return *desc_pool_; +} + +GPUProbe& TrackedObjectsVK::GetGPUProbe() const { + return *probe_.get(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..2ce5d6c81b2b566b5e522310e1db7bcd4441b1da --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/tracked_objects_vk.h @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_ + +#include + +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/backend/vulkan/descriptor_pool_vk.h" +#include "impeller/renderer/backend/vulkan/gpu_tracer_vk.h" +#include "impeller/renderer/backend/vulkan/texture_source_vk.h" + +namespace impeller { + +/// @brief A per-frame object used to track resource lifetimes and allocate +/// command buffers and descriptor sets. +class TrackedObjectsVK { + public: + explicit TrackedObjectsVK(const std::weak_ptr& context, + const std::shared_ptr& pool, + std::shared_ptr descriptor_pool, + std::unique_ptr probe); + + ~TrackedObjectsVK(); + + bool IsValid() const; + + void Track(const std::shared_ptr& object); + + void Track(const std::shared_ptr& buffer); + + void Track(const std::shared_ptr& texture); + + vk::CommandBuffer GetCommandBuffer() const; + + DescriptorPoolVK& GetDescriptorPool(); + + GPUProbe& GetGPUProbe() const; + + private: + std::shared_ptr desc_pool_; + // `shared_ptr` since command buffers have a link to the command pool. + std::shared_ptr pool_; + vk::UniqueCommandBuffer buffer_; + std::vector> tracked_objects_; + std::vector> tracked_buffers_; + std::vector> tracked_textures_; + std::unique_ptr probe_; + bool is_valid_ = false; + + TrackedObjectsVK(const TrackedObjectsVK&) = delete; + + TrackedObjectsVK& operator=(const TrackedObjectsVK&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_TRACKED_OBJECTS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..83c344f555484529c57755d5a100d5fde1c8989b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.cc @@ -0,0 +1,167 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/vertex_descriptor_vk.h" + +#include + +namespace impeller { + +vk::Format ToVertexDescriptorFormat(const ShaderStageIOSlot& input) { + if (input.columns != 1) { + // All matrix types are unsupported as vertex inputs. + return vk::Format::eUndefined; + } + + switch (input.type) { + case ShaderType::kFloat: { + if (input.bit_width == 8 * sizeof(float)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR32Sfloat; + case 2: + return vk::Format::eR32G32Sfloat; + case 3: + return vk::Format::eR32G32B32Sfloat; + case 4: + return vk::Format::eR32G32B32A32Sfloat; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kHalfFloat: { + if (input.bit_width == 8 * sizeof(float) / 2) { + switch (input.vec_size) { + case 1: + return vk::Format::eR16Sfloat; + case 2: + return vk::Format::eR16G16Sfloat; + case 3: + return vk::Format::eR16G16B16Sfloat; + case 4: + return vk::Format::eR16G16B16A16Sfloat; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kDouble: { + // Unsupported. + return vk::Format::eUndefined; + } + case ShaderType::kBoolean: { + if (input.bit_width == 8 * sizeof(bool) && input.vec_size == 1) { + return vk::Format::eR8Uint; + } + return vk::Format::eUndefined; + } + case ShaderType::kSignedByte: { + if (input.bit_width == 8 * sizeof(char)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR8Sint; + case 2: + return vk::Format::eR8G8Sint; + case 3: + return vk::Format::eR8G8B8Sint; + case 4: + return vk::Format::eR8G8B8A8Sint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kUnsignedByte: { + if (input.bit_width == 8 * sizeof(char)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR8Uint; + case 2: + return vk::Format::eR8G8Uint; + case 3: + return vk::Format::eR8G8B8Uint; + case 4: + return vk::Format::eR8G8B8A8Uint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kSignedShort: { + if (input.bit_width == 8 * sizeof(int16_t)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR16Sint; + case 2: + return vk::Format::eR16G16Sint; + case 3: + return vk::Format::eR16G16B16Sint; + case 4: + return vk::Format::eR16G16B16A16Sint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kUnsignedShort: { + if (input.bit_width == 8 * sizeof(uint16_t)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR16Uint; + case 2: + return vk::Format::eR16G16Uint; + case 3: + return vk::Format::eR16G16B16Uint; + case 4: + return vk::Format::eR16G16B16A16Uint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kSignedInt: { + if (input.bit_width == 8 * sizeof(int32_t)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR32Sint; + case 2: + return vk::Format::eR32G32Sint; + case 3: + return vk::Format::eR32G32B32Sint; + case 4: + return vk::Format::eR32G32B32A32Sint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kUnsignedInt: { + if (input.bit_width == 8 * sizeof(uint32_t)) { + switch (input.vec_size) { + case 1: + return vk::Format::eR32Uint; + case 2: + return vk::Format::eR32G32Uint; + case 3: + return vk::Format::eR32G32B32Uint; + case 4: + return vk::Format::eR32G32B32A32Uint; + } + } + return vk::Format::eUndefined; + } + case ShaderType::kSignedInt64: { + // Unsupported. + return vk::Format::eUndefined; + } + case ShaderType::kUnsignedInt64: { + // Unsupported. + return vk::Format::eUndefined; + } + case ShaderType::kAtomicCounter: + case ShaderType::kStruct: + case ShaderType::kImage: + case ShaderType::kSampledImage: + case ShaderType::kUnknown: + case ShaderType::kVoid: + case ShaderType::kSampler: + return vk::Format::eUndefined; + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..fda492cae8217021fbf89d9dab18f9c28e2aaf20 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vertex_descriptor_vk.h @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_ + +#include "impeller/core/shader_types.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +vk::Format ToVertexDescriptorFormat(const ShaderStageIOSlot& input); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VERTEX_DESCRIPTOR_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h new file mode 100644 index 0000000000000000000000000000000000000000..ea992ce0e2d9d655061da8e7cabe75c353d06d72 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vk.h @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_ + +#include "flutter/fml/build_config.h" +#include "flutter/fml/logging.h" + +#define VK_NO_PROTOTYPES + +#if FML_OS_IOS + +// #ifndef VK_USE_PLATFORM_IOS_MVK +// #define VK_USE_PLATFORM_IOS_MVK +// #endif // VK_USE_PLATFORM_IOS_MVK + +#ifndef VK_USE_PLATFORM_METAL_EXT +#define VK_USE_PLATFORM_METAL_EXT +#endif // VK_USE_PLATFORM_METAL_EXT + +#elif FML_OS_MACOSX + +// #ifndef VK_USE_PLATFORM_MACOS_MVK +// #define VK_USE_PLATFORM_MACOS_MVK +// #endif // VK_USE_PLATFORM_MACOS_MVK + +#ifndef VK_USE_PLATFORM_METAL_EXT +#define VK_USE_PLATFORM_METAL_EXT +#endif // VK_USE_PLATFORM_METAL_EXT + +#elif FML_OS_ANDROID + +#ifndef VK_USE_PLATFORM_ANDROID_KHR +#define VK_USE_PLATFORM_ANDROID_KHR +#endif // VK_USE_PLATFORM_ANDROID_KHR + +#elif FML_OS_LINUX + +// Nothing for now. + +#elif FML_OS_WIN + +#ifndef VK_USE_PLATFORM_WIN32_KHR +#define VK_USE_PLATFORM_WIN32_KHR +#endif // VK_USE_PLATFORM_WIN32_KHR + +#elif OS_FUCHSIA + +#ifndef VK_USE_PLATFORM_ANDROID_KHR +#define VK_USE_PLATFORM_ANDROID_KHR +#endif // VK_USE_PLATFORM_ANDROID_KHR + +#endif // FML_OS + +#if !defined(NDEBUG) +#define VULKAN_HPP_ASSERT FML_CHECK +#else +#define VULKAN_HPP_ASSERT(ignored) \ + {} +#endif + +#define VULKAN_HPP_NAMESPACE impeller::vk +#define VULKAN_HPP_ASSERT_ON_RESULT(ignored) \ + { [[maybe_unused]] auto res = (ignored); } +#define VULKAN_HPP_NO_EXCEPTIONS + +#include "vulkan/vulkan.hpp" // IWYU pragma: keep. + +static_assert(VK_HEADER_VERSION >= 215, "Vulkan headers must not be too old."); + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.cc new file mode 100644 index 0000000000000000000000000000000000000000..5c28daa885f42749c709a008d2707949129b5ed5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/vma.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.h new file mode 100644 index 0000000000000000000000000000000000000000..6787bee93c5766a8a8893679543091c70345363d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/vma.h @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_ + +#include "flutter/flutter_vma/flutter_vma.h" +#include "flutter/fml/trace_event.h" +#include "flutter/fml/unique_object.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +// ----------------------------------------------------------------------------- +// Unique handles to VMA allocators. +// ----------------------------------------------------------------------------- +struct AllocatorVMATraits { + static VmaAllocator InvalidValue() { return {}; } + + static bool IsValid(const VmaAllocator& value) { + return value != InvalidValue(); + } + + static void Free(VmaAllocator allocator) { + TRACE_EVENT0("impeller", "DestroyAllocator"); + ::vmaDestroyAllocator(allocator); + } +}; + +using UniqueAllocatorVMA = fml::UniqueObject; + +// ----------------------------------------------------------------------------- +// Unique handles to VMA pools. +// ----------------------------------------------------------------------------- + +struct PoolVMA { + VmaAllocator allocator = {}; + VmaPool pool = {}; + + constexpr bool operator==(const PoolVMA& other) const { + return allocator == other.allocator && pool == other.pool; + } + + constexpr bool operator!=(const PoolVMA& other) const { + return !(*this == other); + } +}; + +struct PoolVMATraits { + static PoolVMA InvalidValue() { return {}; } + + static bool IsValid(const PoolVMA& value) { + return value.allocator != VmaAllocator{}; + } + + static void Free(const PoolVMA& pool) { + TRACE_EVENT0("impeller", "DestroyPool"); + ::vmaDestroyPool(pool.allocator, pool.pool); + } +}; + +using UniquePoolVMA = fml::UniqueObject; + +// ----------------------------------------------------------------------------- +// Unique handles to VMA buffers. +// ----------------------------------------------------------------------------- + +struct BufferVMA { + VmaAllocator allocator = {}; + VmaAllocation allocation = {}; + vk::Buffer buffer = {}; + + constexpr bool operator==(const BufferVMA& other) const { + return allocator == other.allocator && allocation == other.allocation && + buffer == other.buffer; + } + + constexpr bool operator!=(const BufferVMA& other) const { + return !(*this == other); + } +}; + +struct BufferVMATraits { + static BufferVMA InvalidValue() { return {}; } + + static bool IsValid(const BufferVMA& value) { + return value.allocator != VmaAllocator{}; + } + + static void Free(const BufferVMA& buffer) { + TRACE_EVENT0("impeller", "DestroyBuffer"); + ::vmaDestroyBuffer(buffer.allocator, static_cast(buffer.buffer), + buffer.allocation); + } +}; + +using UniqueBufferVMA = fml::UniqueObject; + +// ----------------------------------------------------------------------------- +// Unique handles to VMA images. +// ----------------------------------------------------------------------------- + +struct ImageVMA { + VmaAllocator allocator = {}; + VmaAllocation allocation = {}; + vk::Image image = {}; + + constexpr bool operator==(const ImageVMA& other) const { + return allocator == other.allocator && allocation == other.allocation && + image == other.image; + } + + constexpr bool operator!=(const ImageVMA& other) const { + return !(*this == other); + } +}; + +struct ImageVMATraits { + static ImageVMA InvalidValue() { return {}; } + + static bool IsValid(const ImageVMA& value) { + return value.allocator != VmaAllocator{}; + } + + static void Free(const ImageVMA& image) { + TRACE_EVENT0("impeller", "DestroyImage"); + ::vmaDestroyImage(image.allocator, static_cast(image.image), + image.allocation); + } +}; + +using UniqueImageVMA = fml::UniqueObject; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_VMA_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..a2908707e313a6e8956a6644e6488813d09fd802 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.cc @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/workarounds_vk.h" +#include "impeller/renderer/backend/vulkan/driver_info_vk.h" + +namespace impeller { + +WorkaroundsVK GetWorkaroundsFromDriverInfo(DriverInfoVK& driver_info) { + WorkaroundsVK workarounds; + + const auto& adreno_gpu = driver_info.GetAdrenoGPUInfo(); + const auto& powervr_gpu = driver_info.GetPowerVRGPUInfo(); + + if (adreno_gpu.has_value()) { + workarounds.slow_primitive_restart_performance = true; + workarounds.broken_mipmap_generation = true; + + if (adreno_gpu.value() <= AdrenoGPU::kAdreno630) { + workarounds.input_attachment_self_dependency_broken = true; + workarounds.batch_submit_command_buffer_timeout = true; + } + } else if (powervr_gpu.has_value()) { + workarounds.input_attachment_self_dependency_broken = true; + } + return workarounds; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..4c35cbae89939dd369c40e6a73771ac4efdde50b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/workarounds_vk.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_WORKAROUNDS_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_WORKAROUNDS_VK_H_ + +#include "impeller/renderer/backend/vulkan/driver_info_vk.h" + +namespace impeller { + +/// A non-exhaustive set of driver specific workarounds. +struct WorkaroundsVK { + // Adreno GPUs exhibit terrible performance when primitive + // restart is used. This was confirmed up to Adreno 640 (Pixel 4). + // Because this feature is fairly marginal, we disable it for _all_ + // Adreno GPUs until we have an upper bound for this bug. + bool slow_primitive_restart_performance = false; + + /// Early 600 series Adreno drivers would deadlock if a command + /// buffer submission had too much work attached to it, this + /// requires the renderer to split up command buffers that could + /// be logically combined. + bool batch_submit_command_buffer_timeout = false; + + /// On older 600 Series Adreno the input attachment / self dependency + /// cycle for programmable blending is broken. + /// + /// Also broken on newer PowerVR. + bool input_attachment_self_dependency_broken = false; + + /// Almost all Adreno series GPU (from 600 up to 800) have problems + /// generating mipmaps, resulting in corruption of the mip levels. + /// See: + /// * https://github.com/flutter/flutter/issues/160441 + /// * https://github.com/flutter/flutter/issues/159876 + /// * https://github.com/flutter/flutter/issues/160587 + bool broken_mipmap_generation = false; +}; + +WorkaroundsVK GetWorkaroundsFromDriverInfo(DriverInfoVK& driver_info); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_WORKAROUNDS_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d42de5ca0f48bc9fdafafd19ba5b6f0ecb18307 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h" + +#include "impeller/base/validation.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" + +namespace impeller { + +YUVConversionLibraryVK::YUVConversionLibraryVK( + std::weak_ptr device_holder) + : device_holder_(std::move(device_holder)) {} + +YUVConversionLibraryVK::~YUVConversionLibraryVK() = default; + +std::shared_ptr YUVConversionLibraryVK::GetConversion( + const YUVConversionDescriptorVK& desc) { + Lock lock(conversions_mutex_); + auto found = conversions_.find(desc); + if (found != conversions_.end()) { + return found->second; + } + auto device_holder = device_holder_.lock(); + if (!device_holder) { + VALIDATION_LOG << "Context loss during creation of YUV conversion."; + return nullptr; + } + return (conversions_[desc] = std::shared_ptr( + new YUVConversionVK(device_holder->GetDevice(), desc))); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..755ffccaa581885ccdc69b0eedddd3d4df6d75f4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_library_vk.h @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_ + +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" + +namespace impeller { + +class DeviceHolderVK; + +//------------------------------------------------------------------------------ +/// @brief Due the way the Vulkan spec. treats "identically defined" +/// conversions, creating two conversion with identical descriptors, +/// using one with the image and the other with the sampler, is +/// invalid use. +/// +/// A conversion library hashes and caches identical descriptors to +/// de-duplicate conversions. +/// +/// There can only be one conversion library (the constructor is +/// private to force this) and it found in the context. +/// +class YUVConversionLibraryVK { + public: + ~YUVConversionLibraryVK(); + + YUVConversionLibraryVK(const YUVConversionLibraryVK&) = delete; + + YUVConversionLibraryVK& operator=(const YUVConversionLibraryVK&) = delete; + + //---------------------------------------------------------------------------- + /// @brief Get a conversion for the given descriptor. If there is already + /// a conversion created for an equivalent descriptor, a reference + /// to that descriptor is returned instead. + /// + /// @param[in] desc The descriptor. + /// + /// @return The conversion. A previously created conversion if one was + /// present and a new one if not. A newly created conversion is + /// cached for subsequent accesses. + /// + std::shared_ptr GetConversion( + const YUVConversionDescriptorVK& chain); + + private: + friend class ContextVK; + + using ConversionsMap = std::unordered_map, + YUVConversionDescriptorVKHash, + YUVConversionDescriptorVKEqual>; + + std::weak_ptr device_holder_; + Mutex conversions_mutex_; + ConversionsMap conversions_ IPLR_GUARDED_BY(conversions_mutex_); + + explicit YUVConversionLibraryVK(std::weak_ptr device_holder); +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_LIBRARY_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.cc b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a7e0210172f0e6340de388042cb9c5a13a40097 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.cc @@ -0,0 +1,121 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/backend/vulkan/yuv_conversion_vk.h" + +#include "flutter/fml/hash_combine.h" +#include "impeller/base/validation.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/renderer/backend/vulkan/device_holder_vk.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" + +namespace impeller { + +YUVConversionVK::YUVConversionVK(const vk::Device& device, + const YUVConversionDescriptorVK& chain) + : chain_(chain) { + auto conversion = device.createSamplerYcbcrConversionUnique(chain_.get()); + if (conversion.result != vk::Result::eSuccess) { + VALIDATION_LOG << "Could not create YUV conversion: " + << vk::to_string(conversion.result); + return; + } + conversion_ = std::move(conversion.value); +} + +YUVConversionVK::~YUVConversionVK() = default; + +bool YUVConversionVK::IsValid() const { + return conversion_ && !!conversion_.get(); +} + +vk::SamplerYcbcrConversion YUVConversionVK::GetConversion() const { + return conversion_ ? conversion_.get() + : static_cast(VK_NULL_HANDLE); +} + +const YUVConversionDescriptorVK& YUVConversionVK::GetDescriptor() const { + return chain_; +} + +std::size_t YUVConversionDescriptorVKHash::operator()( + const YUVConversionDescriptorVK& desc) const { + // Hashers in Vulkan HPP hash the pNext member which isn't what we want for + // these to be stable. + const auto& conv = desc.get(); + + std::size_t hash = fml::HashCombine(conv.format, // + conv.ycbcrModel, // + conv.ycbcrRange, // + conv.components.r, // + conv.components.g, // + conv.components.b, // + conv.components.a, // + conv.xChromaOffset, // + conv.yChromaOffset, // + conv.chromaFilter, // + conv.forceExplicitReconstruction // + ); +#if FML_OS_ANDROID + const auto external_format = desc.get(); + fml::HashCombineSeed(hash, external_format.externalFormat); +#endif // FML_OS_ANDROID + + return hash; +}; + +bool YUVConversionDescriptorVKEqual::operator()( + const YUVConversionDescriptorVK& lhs_desc, + const YUVConversionDescriptorVK& rhs_desc) const { + // Default equality checks in Vulkan HPP checks pNext member members by + // pointer which isn't what we want. + { + const auto& lhs = lhs_desc.get(); + const auto& rhs = rhs_desc.get(); + + if (lhs.format != rhs.format || // + lhs.ycbcrModel != rhs.ycbcrModel || // + lhs.ycbcrRange != rhs.ycbcrRange || // + lhs.components.r != rhs.components.r || // + lhs.components.g != rhs.components.g || // + lhs.components.b != rhs.components.b || // + lhs.components.a != rhs.components.a || // + lhs.xChromaOffset != rhs.xChromaOffset || // + lhs.yChromaOffset != rhs.yChromaOffset || // + lhs.chromaFilter != rhs.chromaFilter || // + lhs.forceExplicitReconstruction != rhs.forceExplicitReconstruction // + ) { + return false; + } + } +#if FML_OS_ANDROID + { + const auto lhs = lhs_desc.get(); + const auto rhs = rhs_desc.get(); + return lhs.externalFormat == rhs.externalFormat; + } +#else // FML_OS_ANDROID + return true; +#endif // FML_OS_ANDROID +} + +ImmutableSamplerKeyVK::ImmutableSamplerKeyVK(const SamplerVK& sampler) + : sampler(sampler.GetDescriptor()) { + if (const auto& conversion = sampler.GetYUVConversion()) { + yuv_conversion = conversion->GetDescriptor(); + } +} + +bool ImmutableSamplerKeyVK::IsEqual(const ImmutableSamplerKeyVK& other) const { + return SamplerDescriptor::ToKey(sampler) == + SamplerDescriptor::ToKey(other.sampler) && + YUVConversionDescriptorVKEqual{}(yuv_conversion, other.yuv_conversion); +} + +std::size_t ImmutableSamplerKeyVK::GetHash() const { + return fml::HashCombine(SamplerDescriptor::ToKey(sampler), + YUVConversionDescriptorVKHash{}(yuv_conversion)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.h b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..88c17ec6b9ad3729001c7fa2e7489bacb4be2cdf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/backend/vulkan/yuv_conversion_vk.h @@ -0,0 +1,109 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_VK_H_ +#define FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_VK_H_ + +#include + +#include "flutter/fml/build_config.h" +#include "impeller/base/comparable.h" +#include "impeller/base/thread.h" +#include "impeller/core/sampler.h" +#include "impeller/renderer/backend/vulkan/sampler_vk.h" +#include "impeller/renderer/backend/vulkan/shared_object_vk.h" +#include "impeller/renderer/backend/vulkan/vk.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// A descriptor used to create a new YUV conversion in a conversion library. +/// +using YUVConversionDescriptorVK = + vk::StructureChain; + +class YUVConversionLibraryVK; + +//------------------------------------------------------------------------------ +/// @brief It is sometimes necessary to deal with formats not native to +/// Vulkan. In such cases, extra information is necessary to access +/// images. A YUV conversion object is needed in such instances. +/// +/// There are usually only a handful of viable conversions in a +/// given context. However, due to the way the Vulkan spec. treats +/// "identically defined" conversions, only a single conversion +/// object is valid for an equivalent `YUVConversionDescriptorVK`. +/// Because of this restriction, it is not possible to just create a +/// conversion from a descriptor (as the underlying handles will be +/// equivalent but different). Instead, a conversion may only be +/// obtained from a conversion library. Libraries handle hashing and +/// caching conversions by descriptor. Caller can find a library on +/// the top-level context. They may not create their own (the +/// constructor is private). +/// +class YUVConversionVK final { + public: + ~YUVConversionVK(); + + YUVConversionVK(const YUVConversionVK&) = delete; + + YUVConversionVK& operator=(const YUVConversionVK&) = delete; + + //---------------------------------------------------------------------------- + /// @return `true` if this conversion is valid for use with images and + /// samplers. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Get the descriptor used to create this conversion. + /// + const YUVConversionDescriptorVK& GetDescriptor() const; + + //---------------------------------------------------------------------------- + /// @return The Vulkan handle of the YUV conversion. + /// + vk::SamplerYcbcrConversion GetConversion() const; + + private: + friend class YUVConversionLibraryVK; + + YUVConversionDescriptorVK chain_; + vk::UniqueSamplerYcbcrConversion conversion_; + + YUVConversionVK(const vk::Device& device, + const YUVConversionDescriptorVK& chain); +}; + +struct YUVConversionDescriptorVKHash { + std::size_t operator()(const YUVConversionDescriptorVK& object) const; +}; + +struct YUVConversionDescriptorVKEqual { + bool operator()(const YUVConversionDescriptorVK& lhs, + const YUVConversionDescriptorVK& rhs) const; +}; + +struct ImmutableSamplerKeyVK : public Comparable { + SamplerDescriptor sampler; + YUVConversionDescriptorVK yuv_conversion; + + explicit ImmutableSamplerKeyVK(const SamplerVK& sampler); + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const ImmutableSamplerKeyVK& other) const override; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_YUV_CONVERSION_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/blit_command.cc b/flutter/engine/src/flutter/impeller/renderer/blit_command.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e01e8dccf5651e7428ee4c388000c99cdbb6255 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/blit_command.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/blit_command.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/blit_command.h b/flutter/engine/src/flutter/impeller/renderer/blit_command.h new file mode 100644 index 0000000000000000000000000000000000000000..a3a82cc8b482029b77f593f1d923e14752ade760 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/blit_command.h @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BLIT_COMMAND_H_ +#define FLUTTER_IMPELLER_RENDERER_BLIT_COMMAND_H_ + +#include +#include "impeller/core/device_buffer.h" +#include "impeller/core/texture.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +struct BlitCommand { + std::string label; +}; + +struct BlitCopyTextureToTextureCommand : public BlitCommand { + std::shared_ptr source; + std::shared_ptr destination; + IRect source_region; + IPoint destination_origin; +}; + +struct BlitResizeTextureCommand : public BlitCommand { + std::shared_ptr source; + std::shared_ptr destination; +}; + +struct BlitCopyTextureToBufferCommand : public BlitCommand { + std::shared_ptr source; + std::shared_ptr destination; + IRect source_region; + size_t destination_offset; +}; + +struct BlitCopyBufferToTextureCommand : public BlitCommand { + BufferView source; + std::shared_ptr destination; + IRect destination_region; + uint32_t mip_level = 0; + uint32_t slice = 0; +}; + +struct BlitGenerateMipmapCommand : public BlitCommand { + std::shared_ptr texture; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BLIT_COMMAND_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/blit_pass.cc b/flutter/engine/src/flutter/impeller/renderer/blit_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..c7c225dce5c1af1327bd5df0973e33b9e30f4c8f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/blit_pass.cc @@ -0,0 +1,179 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/blit_pass.h" +#include +#include + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" + +namespace impeller { + +BlitPass::BlitPass() {} + +BlitPass::~BlitPass() = default; + +void BlitPass::SetLabel(std::string_view label) { + if (label.empty()) { + return; + } + OnSetLabel(label); +} + +bool BlitPass::AddCopy(std::shared_ptr source, + std::shared_ptr destination, + std::optional source_region, + IPoint destination_origin, + std::string_view label) { + if (!source) { + VALIDATION_LOG << "Attempted to add a texture blit with no source."; + return false; + } + if (!destination) { + VALIDATION_LOG << "Attempted to add a texture blit with no destination."; + return false; + } + + if (source->GetTextureDescriptor().sample_count != + destination->GetTextureDescriptor().sample_count) { + VALIDATION_LOG << SPrintF( + "The source sample count (%d) must match the destination sample count " + "(%d) for blits.", + static_cast(source->GetTextureDescriptor().sample_count), + static_cast(destination->GetTextureDescriptor().sample_count)); + return false; + } + if (source->GetTextureDescriptor().format != + destination->GetTextureDescriptor().format) { + VALIDATION_LOG << SPrintF( + "The source pixel format (%s) must match the destination pixel format " + "(%s) " + "for blits.", + PixelFormatToString(source->GetTextureDescriptor().format), + PixelFormatToString(destination->GetTextureDescriptor().format)); + return false; + } + + if (!source_region.has_value()) { + source_region = IRect::MakeSize(source->GetSize()); + } + + // Clip the source image. + source_region = + source_region->Intersection(IRect::MakeSize(source->GetSize())); + if (!source_region.has_value()) { + return true; // Nothing to blit. + } + + return OnCopyTextureToTextureCommand( + std::move(source), std::move(destination), source_region.value(), + destination_origin, label); +} + +bool BlitPass::AddCopy(std::shared_ptr source, + std::shared_ptr destination, + std::optional source_region, + size_t destination_offset, + std::string_view label) { + if (!source) { + VALIDATION_LOG << "Attempted to add a texture blit with no source."; + return false; + } + if (!destination) { + VALIDATION_LOG << "Attempted to add a texture blit with no destination."; + return false; + } + + if (!source_region.has_value()) { + source_region = IRect::MakeSize(source->GetSize()); + } + + auto bytes_per_pixel = + BytesPerPixelForPixelFormat(source->GetTextureDescriptor().format); + auto bytes_per_image = source_region->Area() * bytes_per_pixel; + if (destination_offset + bytes_per_image > + destination->GetDeviceBufferDescriptor().size) { + VALIDATION_LOG + << "Attempted to add a texture blit with out of bounds access."; + return false; + } + + // Clip the source image. + source_region = + source_region->Intersection(IRect::MakeSize(source->GetSize())); + if (!source_region.has_value()) { + return true; // Nothing to blit. + } + + return OnCopyTextureToBufferCommand(std::move(source), std::move(destination), + source_region.value(), destination_offset, + label); +} + +bool BlitPass::AddCopy(BufferView source, + std::shared_ptr destination, + std::optional destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) { + if (!destination) { + VALIDATION_LOG << "Attempted to add a texture blit with no destination."; + return false; + } + ISize destination_size = destination->GetSize(); + IRect destination_region_value = + destination_region.value_or(IRect::MakeSize(destination_size)); + if (destination_region_value.GetX() < 0 || + destination_region_value.GetY() < 0 || + destination_region_value.GetRight() > destination_size.width || + destination_region_value.GetBottom() > destination_size.height) { + VALIDATION_LOG << "Blit region cannot be larger than destination texture."; + return false; + } + + auto bytes_per_pixel = + BytesPerPixelForPixelFormat(destination->GetTextureDescriptor().format); + auto bytes_per_region = destination_region_value.Area() * bytes_per_pixel; + + if (source.GetRange().length != bytes_per_region) { + VALIDATION_LOG + << "Attempted to add a texture blit with out of bounds access."; + return false; + } + if (mip_level >= destination->GetMipCount()) { + VALIDATION_LOG << "Invalid value for mip_level: " << mip_level << ". " + << "The destination texture has " + << destination->GetMipCount() << " mip levels."; + return false; + } + if (slice > 5) { + VALIDATION_LOG << "Invalid value for slice: " << slice; + return false; + } + + return OnCopyBufferToTextureCommand(std::move(source), std::move(destination), + destination_region_value, label, + mip_level, slice, convert_to_read); +} + +bool BlitPass::ConvertTextureToShaderRead( + const std::shared_ptr& texture) { + return true; +} + +bool BlitPass::GenerateMipmap(std::shared_ptr texture, + std::string_view label) { + if (!texture) { + VALIDATION_LOG << "Attempted to add an invalid mipmap generation command " + "with no texture."; + return false; + } + + return OnGenerateMipmapCommand(std::move(texture), label); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/blit_pass.h b/flutter/engine/src/flutter/impeller/renderer/blit_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..62388168c327a69f985e2b91fa3fdd7fb51b9001 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/blit_pass.h @@ -0,0 +1,193 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_ +#define FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_ + +#include +#include + +#include "impeller/core/device_buffer.h" +#include "impeller/core/texture.h" + +namespace impeller { + +class HostBuffer; +class Allocator; + +//------------------------------------------------------------------------------ +/// @brief Blit passes encode blit into the underlying command buffer. +/// +/// Blit passes can be obtained from the command buffer in which +/// the pass is meant to encode commands into. +/// +/// @see `CommandBuffer` +/// +class BlitPass { + public: + virtual ~BlitPass(); + + virtual bool IsValid() const = 0; + + void SetLabel(std::string_view label); + + //---------------------------------------------------------------------------- + /// @brief If the texture is not already in a shader read internal + /// state, then convert it to that state. + /// + /// This API is only used by Vulkan. + virtual bool ConvertTextureToShaderRead( + const std::shared_ptr& texture); + + //---------------------------------------------------------------------------- + /// @brief Resize the [source] texture into the [destination] texture. + /// + /// On Metal platforms, [destination] is required to be non-lossy + /// and have the Shader read capability. + virtual bool ResizeTexture(const std::shared_ptr& source, + const std::shared_ptr& destination) = 0; + + //---------------------------------------------------------------------------- + /// @brief Record a command to copy the contents of one texture to + /// another texture. The blit area is limited by the intersection + /// of the texture coverage with respect the source region and + /// destination origin. + /// + /// @param[in] source The texture to read for copying. + /// @param[in] destination The texture to overwrite using the source + /// contents. + /// @param[in] source_region The optional region of the source texture + /// to use for copying. If not specified, the + /// full size of the source texture is used. + /// @param[in] destination_origin The origin to start writing to in the + /// destination texture. + /// @param[in] label The optional debug label to give the + /// command. + /// + /// @return If the command was valid for subsequent commitment. + /// + bool AddCopy(std::shared_ptr source, + std::shared_ptr destination, + std::optional source_region = std::nullopt, + IPoint destination_origin = {}, + std::string_view label = ""); + + //---------------------------------------------------------------------------- + /// @brief Record a command to copy the contents of a texture to a + /// buffer. + /// + /// @param[in] source The texture to read for copying. + /// @param[in] destination The buffer to overwrite using the source + /// contents. + /// @param[in] source_region The optional region of the source texture + /// to use for copying. If not specified, the + /// full size of the source texture is used. + /// @param[in] destination_origin The origin to start writing to in the + /// destination texture. + /// @param[in] label The optional debug label to give the + /// command. + /// + /// @return If the command was valid for subsequent commitment. + /// + bool AddCopy(std::shared_ptr source, + std::shared_ptr destination, + std::optional source_region = std::nullopt, + size_t destination_offset = 0, + std::string_view label = ""); + + //---------------------------------------------------------------------------- + /// @brief Record a command to copy the contents of a buffer to a + /// texture. + /// + /// @param[in] source The buffer view to read for copying. + /// @param[in] destination The texture to overwrite using the source + /// contents. + /// @param[in] destination_region The offset to start writing to in the + /// destination texture. If not provided, this + /// defaults to the entire texture. + /// @param[in] label The optional debug label to give the + /// command. + /// @param[in] mip_level The mip level to write to. + /// @param[in] slice For cubemap textures, the slice to write + /// data to. + /// @param[in] convert_to_read Whether to convert the texture to a shader + /// read state. Defaults to true. + /// + /// @return If the command was valid for subsequent commitment. + /// + /// If a region smaller than the texture size is provided, the + /// contents are treated as containing tightly packed pixel data of + /// that region. Only the portion of the texture in this region is + /// replaced and existing data is preserved. + /// + /// For example, to replace the top left 10 x 10 region of a larger + /// 100 x 100 texture, the region is {0, 0, 10, 10} and the expected + /// buffer size in bytes is 100 x bpp. + bool AddCopy(BufferView source, + std::shared_ptr destination, + std::optional destination_region = std::nullopt, + std::string_view label = "", + uint32_t mip_level = 0, + uint32_t slice = 0, + bool convert_to_read = true); + + //---------------------------------------------------------------------------- + /// @brief Record a command to generate all mip levels for a texture. + /// + /// @param[in] texture The texture to generate mipmaps for. + /// @param[in] label The optional debug label to give the command. + /// + /// @return If the command was valid for subsequent commitment. + /// + bool GenerateMipmap(std::shared_ptr texture, + std::string_view label = ""); + + //---------------------------------------------------------------------------- + /// @brief Encode the recorded commands to the underlying command buffer. + /// + /// @return If the commands were encoded to the underlying command + /// buffer. + /// + virtual bool EncodeCommands() const = 0; + + protected: + explicit BlitPass(); + + virtual void OnSetLabel(std::string_view label) = 0; + + virtual bool OnCopyTextureToTextureCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label) = 0; + + virtual bool OnCopyTextureToBufferCommand( + std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label) = 0; + + virtual bool OnCopyBufferToTextureCommand( + BufferView source, + std::shared_ptr destination, + IRect destination_region, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read) = 0; + + virtual bool OnGenerateMipmapCommand(std::shared_ptr texture, + std::string_view label) = 0; + + private: + BlitPass(const BlitPass&) = delete; + + BlitPass& operator=(const BlitPass&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_BLIT_PASS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/blit_pass_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/blit_pass_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..a6f5aa096fc973b5fb6a55bba9d0604599a130e9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/blit_pass_unittests.cc @@ -0,0 +1,273 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include "flutter/display_list/dl_builder.h" +#include "flutter/impeller/display_list/aiks_unittests.h" +#include "flutter/impeller/display_list/dl_image_impeller.h" +#include "fml/mapping.h" +#include "gtest/gtest.h" +#include "impeller/base/validation.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { +namespace testing { + +using flutter::DisplayListBuilder; +using flutter::DlColor; +using flutter::DlImageSampling; +using flutter::DlPaint; + +using BlitPassTest = AiksTest; +INSTANTIATE_PLAYGROUND_SUITE(BlitPassTest); + +TEST_P(BlitPassTest, BlitAcrossDifferentPixelFormatsFails) { + ScopedValidationDisable scope; // avoid noise in output. + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor src_desc; + src_desc.format = PixelFormat::kA8UNormInt; + src_desc.size = {100, 100}; + src_desc.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateTexture(src_desc); + + TextureDescriptor dst_format; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {100, 100}; + dst_format.storage_mode = StorageMode::kHostVisible; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + EXPECT_FALSE(blit_pass->AddCopy(src, dst)); +} + +TEST_P(BlitPassTest, BlitAcrossDifferentSampleCountsFails) { + ScopedValidationDisable scope; // avoid noise in output. + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor src_desc; + src_desc.format = PixelFormat::kR8G8B8A8UNormInt; + src_desc.sample_count = SampleCount::kCount4; + src_desc.size = {100, 100}; + auto src = context->GetResourceAllocator()->CreateTexture(src_desc); + + TextureDescriptor dst_format; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {100, 100}; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + EXPECT_FALSE(blit_pass->AddCopy(src, dst)); +} + +TEST_P(BlitPassTest, BlitPassesForMatchingFormats) { + ScopedValidationDisable scope; // avoid noise in output. + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor src_desc; + src_desc.format = PixelFormat::kR8G8B8A8UNormInt; + src_desc.size = {100, 100}; + src_desc.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateTexture(src_desc); + + TextureDescriptor dst_format; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {100, 100}; + dst_format.storage_mode = StorageMode::kHostVisible; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + EXPECT_TRUE(blit_pass->AddCopy(src, dst)); +} + +TEST_P(BlitPassTest, ChecksInvalidSliceParameters) { + ScopedValidationDisable scope; // avoid noise in output. + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {100, 100}; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + DeviceBufferDescriptor src_format; + src_format.size = 40000; + src_format.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateBuffer(src_format); + + ASSERT_TRUE(dst); + ASSERT_TRUE(src); + + EXPECT_FALSE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + std::nullopt, "", /*mip_level=*/0, + /*slice=*/25)); + EXPECT_FALSE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + std::nullopt, "", /*mip_level=*/0, + /*slice=*/6)); + EXPECT_TRUE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + std::nullopt, "", /*mip_level=*/0, + /*slice=*/0)); +} + +TEST_P(BlitPassTest, CanBlitSmallRegionToUninitializedTexture) { + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {1000, 1000}; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + DeviceBufferDescriptor src_format; + src_format.size = 4; + src_format.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateBuffer(src_format); + + ASSERT_TRUE(dst); + + EXPECT_TRUE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + IRect::MakeLTRB(0, 0, 1, 1), "", + /*mip_level=*/0, /*slice=*/0)); + EXPECT_TRUE(blit_pass->EncodeCommands()); + EXPECT_TRUE(context->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()); +} + +TEST_P(BlitPassTest, ChecksInvalidMipLevelParameter) { + ScopedValidationDisable scope; + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {1000, 1000}; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + DeviceBufferDescriptor src_format; + src_format.size = 4; + src_format.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateBuffer(src_format); + + ASSERT_TRUE(dst); + + EXPECT_FALSE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + IRect::MakeLTRB(0, 0, 1, 1), "", + /*mip_level=*/1, /*slice=*/0)); + + EXPECT_TRUE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + IRect::MakeLTRB(0, 0, 1, 1), "", + /*mip_level=*/0, /*slice=*/0)); +} + +TEST_P(BlitPassTest, CanBlitToHigherTextureMipLevels) { + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {1000, 1000}; + dst_format.mip_count = 4; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + DeviceBufferDescriptor src_format; + src_format.size = 4; + src_format.storage_mode = StorageMode::kHostVisible; + auto src = context->GetResourceAllocator()->CreateBuffer(src_format); + + ASSERT_TRUE(dst); + + EXPECT_TRUE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(src), dst, + IRect::MakeLTRB(0, 0, 1, 1), "", + /*mip_level=*/1, /*slice=*/0)); + EXPECT_TRUE(blit_pass->EncodeCommands()); + EXPECT_TRUE(context->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()); +} + +TEST_P(BlitPassTest, CanResizeTextures) { + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {10, 10}; + dst_format.usage = TextureUsage::kShaderRead | TextureUsage::kShaderWrite; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + TextureDescriptor src_format; + src_format.storage_mode = StorageMode::kDevicePrivate; + src_format.format = PixelFormat::kR8G8B8A8UNormInt; + src_format.size = {100, 100}; + auto src = context->GetResourceAllocator()->CreateTexture(src_format); + + std::vector bytes(src_format.GetByteSizeOfBaseMipLevel()); + for (auto i = 0u; i < src_format.GetByteSizeOfBaseMipLevel(); i += 4) { + // RGBA + bytes[i + 0] = 255; + bytes[i + 1] = 0; + bytes[i + 2] = 0; + bytes[i + 3] = 255; + } + auto mapping = fml::DataMapping(bytes); + auto staging = context->GetResourceAllocator()->CreateBufferWithCopy(mapping); + + ASSERT_TRUE(dst); + ASSERT_TRUE(src); + ASSERT_TRUE(staging); + + EXPECT_TRUE(blit_pass->AddCopy(DeviceBuffer::AsBufferView(staging), src)); + EXPECT_TRUE(blit_pass->ResizeTexture(src, dst)); + EXPECT_TRUE(blit_pass->EncodeCommands()); + EXPECT_TRUE(context->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()); +} + +TEST_P(BlitPassTest, CanResizeTexturesPlayground) { + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto blit_pass = cmd_buffer->CreateBlitPass(); + + std::shared_ptr src = CreateTextureForFixture("kalimba.jpg"); + + TextureDescriptor dst_format; + dst_format.storage_mode = StorageMode::kDevicePrivate; + dst_format.format = PixelFormat::kR8G8B8A8UNormInt; + dst_format.size = {src->GetSize().width / 2, src->GetSize().height}; + dst_format.usage = TextureUsage::kShaderRead | TextureUsage::kShaderWrite; + auto dst = context->GetResourceAllocator()->CreateTexture(dst_format); + + ASSERT_TRUE(dst); + ASSERT_TRUE(src); + + EXPECT_TRUE(blit_pass->ResizeTexture(src, dst)); + EXPECT_TRUE(blit_pass->EncodeCommands()); + EXPECT_TRUE(context->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()); + + DisplayListBuilder builder; + builder.Scale(GetContentScale().x, GetContentScale().y); + DlPaint paint; + paint.setColor(DlColor::kRed()); + auto image = DlImageImpeller::Make(dst); + builder.DrawImage(image, flutter::DlPoint(100.0, 100.0), + DlImageSampling::kNearestNeighbor, &paint); + ASSERT_TRUE(OpenPlaygroundHere(builder.Build())); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/capabilities.cc b/flutter/engine/src/flutter/impeller/renderer/capabilities.cc new file mode 100644 index 0000000000000000000000000000000000000000..4a2eb6732667a80b9291f1994db0bb189e0395d5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/capabilities.cc @@ -0,0 +1,277 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/capabilities.h" +#include "impeller/core/formats.h" + +namespace impeller { + +Capabilities::Capabilities() = default; + +Capabilities::~Capabilities() = default; + +class StandardCapabilities final : public Capabilities { + public: + // |Capabilities| + ~StandardCapabilities() override = default; + + // |Capabilities| + bool SupportsOffscreenMSAA() const override { + return supports_offscreen_msaa_; + } + + // |Capabilities| + bool SupportsImplicitResolvingMSAA() const override { return false; } + + // |Capabilities| + bool SupportsSSBO() const override { return supports_ssbo_; } + + // |Capabilities| + bool SupportsTextureToTextureBlits() const override { + return supports_texture_to_texture_blits_; + } + + // |Capabilities| + bool SupportsFramebufferFetch() const override { + return supports_framebuffer_fetch_; + } + + // |Capabilities| + bool SupportsCompute() const override { return supports_compute_; } + + // |Capabilities| + bool SupportsComputeSubgroups() const override { + return supports_compute_subgroups_; + } + + // |Capabilities| + bool SupportsReadFromResolve() const override { + return supports_read_from_resolve_; + } + + // |Capabilities| + bool SupportsDecalSamplerAddressMode() const override { + return supports_decal_sampler_address_mode_; + } + + // |Capabilities| + bool SupportsTriangleFan() const override { return supports_triangle_fan_; } + + // |Capabilities| + PixelFormat GetDefaultColorFormat() const override { + return default_color_format_; + } + + // |Capabilities| + PixelFormat GetDefaultStencilFormat() const override { + return default_stencil_format_; + } + + // |Capabilities| + PixelFormat GetDefaultDepthStencilFormat() const override { + return default_depth_stencil_format_; + } + + // |Capabilities| + bool SupportsDeviceTransientTextures() const override { + return supports_device_transient_textures_; + } + + // |Capabilities| + PixelFormat GetDefaultGlyphAtlasFormat() const override { + return default_glyph_atlas_format_; + } + + // |Capabilities| + ISize GetMaximumRenderPassAttachmentSize() const override { + return default_maximum_render_pass_attachment_size_; + } + + // |Capabilities| + bool SupportsPrimitiveRestart() const override { return true; } + + // |Capabilities| + bool SupportsExtendedRangeFormats() const override { + return supports_extended_range_formats_; + } + + private: + StandardCapabilities(bool supports_offscreen_msaa, + bool supports_ssbo, + bool supports_texture_to_texture_blits, + bool supports_framebuffer_fetch, + bool supports_compute, + bool supports_compute_subgroups, + bool supports_read_from_resolve, + bool supports_decal_sampler_address_mode, + bool supports_device_transient_textures, + bool supports_triangle_fan, + bool supports_extended_range_formats, + PixelFormat default_color_format, + PixelFormat default_stencil_format, + PixelFormat default_depth_stencil_format, + PixelFormat default_glyph_atlas_format, + ISize default_maximum_render_pass_attachment_size) + : supports_offscreen_msaa_(supports_offscreen_msaa), + supports_ssbo_(supports_ssbo), + supports_texture_to_texture_blits_(supports_texture_to_texture_blits), + supports_framebuffer_fetch_(supports_framebuffer_fetch), + supports_compute_(supports_compute), + supports_compute_subgroups_(supports_compute_subgroups), + supports_read_from_resolve_(supports_read_from_resolve), + supports_decal_sampler_address_mode_( + supports_decal_sampler_address_mode), + supports_device_transient_textures_(supports_device_transient_textures), + supports_triangle_fan_(supports_triangle_fan), + supports_extended_range_formats_(supports_extended_range_formats), + default_color_format_(default_color_format), + default_stencil_format_(default_stencil_format), + default_depth_stencil_format_(default_depth_stencil_format), + default_glyph_atlas_format_(default_glyph_atlas_format), + default_maximum_render_pass_attachment_size_( + default_maximum_render_pass_attachment_size) {} + + friend class CapabilitiesBuilder; + + bool supports_offscreen_msaa_ = false; + bool supports_ssbo_ = false; + bool supports_texture_to_texture_blits_ = false; + bool supports_framebuffer_fetch_ = false; + bool supports_compute_ = false; + bool supports_compute_subgroups_ = false; + bool supports_read_from_resolve_ = false; + bool supports_decal_sampler_address_mode_ = false; + bool supports_device_transient_textures_ = false; + bool supports_triangle_fan_ = false; + bool supports_extended_range_formats_ = false; + PixelFormat default_color_format_ = PixelFormat::kUnknown; + PixelFormat default_stencil_format_ = PixelFormat::kUnknown; + PixelFormat default_depth_stencil_format_ = PixelFormat::kUnknown; + PixelFormat default_glyph_atlas_format_ = PixelFormat::kUnknown; + ISize default_maximum_render_pass_attachment_size_ = ISize(1, 1); + + StandardCapabilities(const StandardCapabilities&) = delete; + + StandardCapabilities& operator=(const StandardCapabilities&) = delete; +}; + +CapabilitiesBuilder::CapabilitiesBuilder() = default; + +CapabilitiesBuilder::~CapabilitiesBuilder() = default; + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsOffscreenMSAA(bool value) { + supports_offscreen_msaa_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsSSBO(bool value) { + supports_ssbo_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsTextureToTextureBlits( + bool value) { + supports_texture_to_texture_blits_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsFramebufferFetch( + bool value) { + supports_framebuffer_fetch_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsCompute(bool value) { + supports_compute_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsComputeSubgroups( + bool value) { + supports_compute_subgroups_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetDefaultColorFormat( + PixelFormat value) { + default_color_format_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetDefaultStencilFormat( + PixelFormat value) { + default_stencil_format_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetDefaultDepthStencilFormat( + PixelFormat value) { + default_depth_stencil_format_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsReadFromResolve( + bool read_from_resolve) { + supports_read_from_resolve_ = read_from_resolve; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsDecalSamplerAddressMode( + bool value) { + supports_decal_sampler_address_mode_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsDeviceTransientTextures( + bool value) { + supports_device_transient_textures_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetDefaultGlyphAtlasFormat( + PixelFormat value) { + default_glyph_atlas_format_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsTriangleFan(bool value) { + supports_triangle_fan_ = value; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetMaximumRenderPassAttachmentSize( + ISize size) { + default_maximum_render_pass_attachment_size_ = size; + return *this; +} + +CapabilitiesBuilder& CapabilitiesBuilder::SetSupportsExtendedRangeFormats( + bool value) { + supports_extended_range_formats_ = value; + return *this; +} + +std::unique_ptr CapabilitiesBuilder::Build() { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return std::unique_ptr(new StandardCapabilities( // + supports_offscreen_msaa_, // + supports_ssbo_, // + supports_texture_to_texture_blits_, // + supports_framebuffer_fetch_, // + supports_compute_, // + supports_compute_subgroups_, // + supports_read_from_resolve_, // + supports_decal_sampler_address_mode_, // + supports_device_transient_textures_, // + supports_triangle_fan_, // + supports_extended_range_formats_, // + default_color_format_.value_or(PixelFormat::kUnknown), // + default_stencil_format_.value_or(PixelFormat::kUnknown), // + default_depth_stencil_format_.value_or(PixelFormat::kUnknown), // + default_glyph_atlas_format_.value_or(PixelFormat::kUnknown), // + default_maximum_render_pass_attachment_size_.value_or(ISize{1, 1}) // + )); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/capabilities.h b/flutter/engine/src/flutter/impeller/renderer/capabilities.h new file mode 100644 index 0000000000000000000000000000000000000000..8e2ffc0b728de5c4256334432c979aa30e54228a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/capabilities.h @@ -0,0 +1,200 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_CAPABILITIES_H_ +#define FLUTTER_IMPELLER_RENDERER_CAPABILITIES_H_ + +#include + +#include "impeller/core/formats.h" + +namespace impeller { + +class Capabilities { + public: + virtual ~Capabilities(); + + /// @brief Whether the context backend supports attaching offscreen MSAA + /// color/stencil textures. + virtual bool SupportsOffscreenMSAA() const = 0; + + /// @brief Whether the context backend supports multisampled rendering to + /// the on-screen surface without requiring an explicit resolve of + /// the MSAA color attachment. + virtual bool SupportsImplicitResolvingMSAA() const = 0; + + /// @brief Whether the context backend supports binding Shader Storage Buffer + /// Objects (SSBOs) to pipelines. + virtual bool SupportsSSBO() const = 0; + + /// @brief Whether the context backend supports blitting from one texture + /// region to another texture region (via the relevant + /// `BlitPass::AddCopy` overloads). + virtual bool SupportsTextureToTextureBlits() const = 0; + + /// @brief Whether the context backend is able to support pipelines with + /// shaders that read from the framebuffer (i.e. pixels that have been + /// written by previous draw calls in the current render pass). + /// + /// Example of reading from the first color attachment in a GLSL + /// shader: + /// ``` + /// uniform subpassInput subpass_input; + /// + /// out vec4 frag_color; + /// + /// void main() { + /// vec4 color = subpassLoad(subpass_input); + /// // Invert the colors drawn to the framebuffer. + /// frag_color = vec4(vec3(1) - color.rgb, color.a); + /// } + /// ``` + virtual bool SupportsFramebufferFetch() const = 0; + + /// @brief Whether the context backend supports `ComputePass`. + virtual bool SupportsCompute() const = 0; + + /// @brief Whether the context backend supports configuring `ComputePass` + /// command subgroups. + virtual bool SupportsComputeSubgroups() const = 0; + + /// @brief Whether the context backend supports binding the current + /// `RenderPass` attachments. This is supported if the backend can + /// guarantee that attachment textures will not be mutated until the + /// render pass has fully completed. + /// + /// This is possible because many mobile graphics cards track + /// `RenderPass` attachment state in intermediary tile memory prior to + /// Storing the pass in the heap allocated attachments on DRAM. + /// Metal's hazard tracking and Vulkan's barriers are granular enough + /// to allow for safely accessing attachment textures prior to storage + /// in the same `RenderPass`. + virtual bool SupportsReadFromResolve() const = 0; + + /// @brief Whether the context backend supports `SamplerAddressMode::Decal`. + virtual bool SupportsDecalSamplerAddressMode() const = 0; + + /// @brief Whether the context backend supports allocating + /// `StorageMode::kDeviceTransient` (aka "memoryless") textures, which + /// are temporary textures kept in tile memory for the duration of the + /// `RenderPass` it's attached to. + /// + /// This feature is especially useful for MSAA and stencils. + virtual bool SupportsDeviceTransientTextures() const = 0; + + /// @brief Whether the primitive type TriangleFan is supported by the backend. + virtual bool SupportsTriangleFan() const = 0; + + /// @brief Whether primitive restart is supported. + virtual bool SupportsPrimitiveRestart() const = 0; + + /// @brief Returns a supported `PixelFormat` for textures that store + /// 4-channel colors (red/green/blue/alpha). + virtual PixelFormat GetDefaultColorFormat() const = 0; + + /// @brief Returns a supported `PixelFormat` for textures that store stencil + /// information. May include a depth channel if a stencil-only format + /// is not available. + virtual PixelFormat GetDefaultStencilFormat() const = 0; + + /// @brief Returns a supported `PixelFormat` for textures that store both a + /// stencil and depth component. This will never return a depth-only + /// or stencil-only texture. + /// Returns `PixelFormat::kUnknown` if no suitable depth+stencil + /// format was found. + virtual PixelFormat GetDefaultDepthStencilFormat() const = 0; + + /// @brief Returns the default pixel format for the alpha bitmap glyph atlas. + /// + /// Some backends may use Red channel while others use grey. This + /// should not have any impact + virtual PixelFormat GetDefaultGlyphAtlasFormat() const = 0; + + /// @brief Return the maximum size of a render pass attachment. + /// + /// Note that this may be smaller than the maximum allocatable texture size. + virtual ISize GetMaximumRenderPassAttachmentSize() const = 0; + + /// @brief Whether the XR formats are supported on this device. + /// + /// This is only ever true for iOS and macOS devices. We may need + /// to revisit this API when approaching wide gamut rendering for + /// Vulkan and GLES. + virtual bool SupportsExtendedRangeFormats() const = 0; + + protected: + Capabilities(); + + Capabilities(const Capabilities&) = delete; + + Capabilities& operator=(const Capabilities&) = delete; +}; + +class CapabilitiesBuilder { + public: + CapabilitiesBuilder(); + + ~CapabilitiesBuilder(); + + CapabilitiesBuilder& SetSupportsOffscreenMSAA(bool value); + + CapabilitiesBuilder& SetSupportsSSBO(bool value); + + CapabilitiesBuilder& SetSupportsTextureToTextureBlits(bool value); + + CapabilitiesBuilder& SetSupportsFramebufferFetch(bool value); + + CapabilitiesBuilder& SetSupportsCompute(bool value); + + CapabilitiesBuilder& SetSupportsComputeSubgroups(bool value); + + CapabilitiesBuilder& SetSupportsReadFromResolve(bool value); + + CapabilitiesBuilder& SetDefaultColorFormat(PixelFormat value); + + CapabilitiesBuilder& SetDefaultStencilFormat(PixelFormat value); + + CapabilitiesBuilder& SetDefaultDepthStencilFormat(PixelFormat value); + + CapabilitiesBuilder& SetSupportsDecalSamplerAddressMode(bool value); + + CapabilitiesBuilder& SetSupportsDeviceTransientTextures(bool value); + + CapabilitiesBuilder& SetSupportsExtendedRangeFormats(bool value); + + CapabilitiesBuilder& SetDefaultGlyphAtlasFormat(PixelFormat value); + + CapabilitiesBuilder& SetSupportsTriangleFan(bool value); + + CapabilitiesBuilder& SetMaximumRenderPassAttachmentSize(ISize size); + + std::unique_ptr Build(); + + private: + bool supports_offscreen_msaa_ = false; + bool supports_ssbo_ = false; + bool supports_texture_to_texture_blits_ = false; + bool supports_framebuffer_fetch_ = false; + bool supports_compute_ = false; + bool supports_compute_subgroups_ = false; + bool supports_read_from_resolve_ = false; + bool supports_decal_sampler_address_mode_ = false; + bool supports_device_transient_textures_ = false; + bool supports_triangle_fan_ = false; + bool supports_extended_range_formats_ = false; + std::optional default_color_format_ = std::nullopt; + std::optional default_stencil_format_ = std::nullopt; + std::optional default_depth_stencil_format_ = std::nullopt; + std::optional default_glyph_atlas_format_ = std::nullopt; + std::optional default_maximum_render_pass_attachment_size_ = + std::nullopt; + + CapabilitiesBuilder(const CapabilitiesBuilder&) = delete; + + CapabilitiesBuilder& operator=(const CapabilitiesBuilder&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_CAPABILITIES_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/capabilities_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/capabilities_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..e0b59b227fdbb6355f388bc5ab821382b8ac3038 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/capabilities_unittests.cc @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/renderer/capabilities.h" + +#include "gtest/gtest.h" + +namespace impeller { +namespace testing { + +#define CAPABILITY_TEST(name, default_value) \ + TEST(CapabilitiesTest, name) { \ + auto defaults = CapabilitiesBuilder().Build(); \ + ASSERT_EQ(defaults->name(), default_value); \ + auto opposite = CapabilitiesBuilder().Set##name(!default_value).Build(); \ + ASSERT_EQ(opposite->name(), !default_value); \ + } + +CAPABILITY_TEST(SupportsOffscreenMSAA, false); +CAPABILITY_TEST(SupportsSSBO, false); +CAPABILITY_TEST(SupportsTextureToTextureBlits, false); +CAPABILITY_TEST(SupportsFramebufferFetch, false); +CAPABILITY_TEST(SupportsCompute, false); +CAPABILITY_TEST(SupportsComputeSubgroups, false); +CAPABILITY_TEST(SupportsReadFromResolve, false); +CAPABILITY_TEST(SupportsDecalSamplerAddressMode, false); +CAPABILITY_TEST(SupportsDeviceTransientTextures, false); +CAPABILITY_TEST(SupportsTriangleFan, false); +CAPABILITY_TEST(SupportsExtendedRangeFormats, false); + +TEST(CapabilitiesTest, DefaultColorFormat) { + auto defaults = CapabilitiesBuilder().Build(); + EXPECT_EQ(defaults->GetDefaultColorFormat(), PixelFormat::kUnknown); + auto mutated = CapabilitiesBuilder() + .SetDefaultColorFormat(PixelFormat::kB10G10R10A10XR) + .Build(); + EXPECT_EQ(mutated->GetDefaultColorFormat(), PixelFormat::kB10G10R10A10XR); +} + +TEST(CapabilitiesTest, DefaultStencilFormat) { + auto defaults = CapabilitiesBuilder().Build(); + EXPECT_EQ(defaults->GetDefaultStencilFormat(), PixelFormat::kUnknown); + auto mutated = CapabilitiesBuilder() + .SetDefaultStencilFormat(PixelFormat::kS8UInt) + .Build(); + EXPECT_EQ(mutated->GetDefaultStencilFormat(), PixelFormat::kS8UInt); +} + +TEST(CapabilitiesTest, DefaultDepthStencilFormat) { + auto defaults = CapabilitiesBuilder().Build(); + EXPECT_EQ(defaults->GetDefaultDepthStencilFormat(), PixelFormat::kUnknown); + auto mutated = CapabilitiesBuilder() + .SetDefaultDepthStencilFormat(PixelFormat::kD32FloatS8UInt) + .Build(); + EXPECT_EQ(mutated->GetDefaultDepthStencilFormat(), + PixelFormat::kD32FloatS8UInt); +} + +TEST(CapabilitiesTest, DefaultGlyphAtlasFormat) { + auto defaults = CapabilitiesBuilder().Build(); + EXPECT_EQ(defaults->GetDefaultGlyphAtlasFormat(), PixelFormat::kUnknown); + auto mutated = CapabilitiesBuilder() + .SetDefaultGlyphAtlasFormat(PixelFormat::kA8UNormInt) + .Build(); + EXPECT_EQ(mutated->GetDefaultGlyphAtlasFormat(), PixelFormat::kA8UNormInt); +} + +TEST(CapabilitiesTest, MaxRenderPassAttachmentSize) { + auto defaults = CapabilitiesBuilder().Build(); + EXPECT_EQ(defaults->GetMaximumRenderPassAttachmentSize(), ISize(1, 1)); + auto mutated = CapabilitiesBuilder() + .SetMaximumRenderPassAttachmentSize({100, 100}) + .Build(); + EXPECT_EQ(mutated->GetMaximumRenderPassAttachmentSize(), ISize(100, 100)); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/command.cc b/flutter/engine/src/flutter/impeller/renderer/command.cc new file mode 100644 index 0000000000000000000000000000000000000000..a981cac62651d2ae267fbf5330b487b8ad28138b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/command.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/command.h b/flutter/engine/src/flutter/impeller/renderer/command.h new file mode 100644 index 0000000000000000000000000000000000000000..c3c0fa2114e93b0b0bf6c94227fac5b68517bd5a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command.h @@ -0,0 +1,156 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMMAND_H_ +#define FLUTTER_IMPELLER_RENDERER_COMMAND_H_ + +#include +#include +#include +#include + +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/core/sampler.h" +#include "impeller/core/shader_types.h" +#include "impeller/core/texture.h" +#include "impeller/geometry/rect.h" +#include "impeller/renderer/pipeline.h" + +namespace impeller { + +template +class Resource { + public: + using ResourceType = T; + ResourceType resource; + + Resource() {} + + Resource(const ShaderMetadata* metadata, ResourceType p_resource) + : resource(p_resource), metadata_(metadata) {} + + const ShaderMetadata* GetMetadata() const { + return dynamic_metadata_ ? dynamic_metadata_.get() : metadata_; + } + + static Resource MakeDynamic(std::unique_ptr metadata, + ResourceType p_resource) { + return Resource(std::move(metadata), p_resource); + } + + private: + Resource(std::unique_ptr metadata, ResourceType p_resource) + : resource(p_resource), dynamic_metadata_(std::move(metadata)) {} + + // Static shader metadata (typically generated by ImpellerC). + const ShaderMetadata* metadata_ = nullptr; + + // Dynamically generated shader metadata. + std::unique_ptr dynamic_metadata_ = nullptr; +}; + +using BufferResource = Resource; +using TextureResource = Resource>; + +/// @brief combines the texture, sampler and sampler slot information. +struct TextureAndSampler { + SampledImageSlot slot; + ShaderStage stage; + TextureResource texture; + raw_ptr sampler; +}; + +//------------------------------------------------------------------------------ +/// @brief An object used to specify work to the GPU along with references +/// to resources the GPU will used when doing said work. +/// +/// To construct a valid command, follow these steps: +/// * Specify a valid pipeline. +/// * Specify vertex information via a call `BindVertices` +/// * Specify any stage bindings. +/// * (Optional) Specify a debug label. +/// +/// Command can be created frequently and on demand. The resources +/// referenced in commands views into buffers managed by other +/// allocators and resource managers. +/// +struct Command { + //---------------------------------------------------------------------------- + /// The pipeline to use for this command. + /// + PipelineRef pipeline; + + /// An offset into render pass storage where bound buffers/texture metadata is + /// stored. + Range bound_buffers = Range{0, 0}; + Range bound_textures = Range{0, 0}; + +#ifdef IMPELLER_DEBUG + //---------------------------------------------------------------------------- + /// The debugging label to use for the command. + /// + std::string label; +#endif // IMPELLER_DEBUG + + //---------------------------------------------------------------------------- + /// The reference value to use in stenciling operations. Stencil configuration + /// is part of pipeline setup and can be read from the pipelines descriptor. + /// + /// @see `Pipeline` + /// @see `PipelineDescriptor` + /// + uint32_t stencil_reference = 0u; + //---------------------------------------------------------------------------- + /// The offset used when indexing into the vertex buffer. + /// + uint64_t base_vertex = 0u; + //---------------------------------------------------------------------------- + /// The viewport coordinates that the rasterizer linearly maps normalized + /// device coordinates to. + /// If unset, the viewport is the size of the render target with a zero + /// origin, znear=0, and zfar=1. + /// + std::optional viewport; + //---------------------------------------------------------------------------- + /// The scissor rect to use for clipping writes to the render target. The + /// scissor rect must lie entirely within the render target. + /// If unset, no scissor is applied. + /// + std::optional scissor; + //---------------------------------------------------------------------------- + /// The number of instances of the given set of vertices to render. Not all + /// backends support rendering more than one instance at a time. + /// + /// @warning Setting this to more than one will limit the availability of + /// backends to use with this command. + /// + size_t instance_count = 1u; + + //---------------------------------------------------------------------------- + /// An offset and range of vertex buffers bound for this draw call. + /// + /// The vertex buffers are stored on the render pass object. + Range vertex_buffers; + + //---------------------------------------------------------------------------- + /// The index buffer binding used by the vertex shader stage. + BufferView index_buffer; + + //---------------------------------------------------------------------------- + /// The number of elements to draw. When only a vertex buffer is set, this is + /// the vertex count. When an index buffer is set, this is the index count. + size_t element_count = 0u; + + //---------------------------------------------------------------------------- + /// The type of indices in the index buffer. The indices must be tightly + /// packed in the index buffer. + IndexType index_type = IndexType::kUnknown; + + bool IsValid() const { return pipeline && pipeline->IsValid(); } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMMAND_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/command_buffer.cc b/flutter/engine/src/flutter/impeller/renderer/command_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6cf95908b72d298311a6cad4a8c9fcf9ebbe2f5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command_buffer.cc @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/command_buffer.h" + +#include "impeller/renderer/compute_pass.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +CommandBuffer::CommandBuffer(std::weak_ptr context) + : context_(std::move(context)) {} + +CommandBuffer::~CommandBuffer() = default; + +bool CommandBuffer::SubmitCommands(bool block_on_schedule, + const CompletionCallback& callback) { + if (!IsValid()) { + // Already committed or was never valid. Either way, this is caller error. + if (callback) { + callback(Status::kError); + } + return false; + } + return OnSubmitCommands(block_on_schedule, callback); +} + +bool CommandBuffer::SubmitCommands(bool block_on_schedule) { + return SubmitCommands(block_on_schedule, nullptr); +} + +void CommandBuffer::WaitUntilCompleted() { + return OnWaitUntilCompleted(); +} + +void CommandBuffer::WaitUntilScheduled() { + return OnWaitUntilScheduled(); +} + +std::shared_ptr CommandBuffer::CreateRenderPass( + const RenderTarget& render_target) { + auto pass = OnCreateRenderPass(render_target); + if (pass && pass->IsValid()) { + pass->SetLabel("RenderPass"); + return pass; + } + return nullptr; +} + +std::shared_ptr CommandBuffer::CreateBlitPass() { + auto pass = OnCreateBlitPass(); + if (pass && pass->IsValid()) { + pass->SetLabel("BlitPass"); + return pass; + } + return nullptr; +} + +std::shared_ptr CommandBuffer::CreateComputePass() { + if (!IsValid()) { + return nullptr; + } + auto pass = OnCreateComputePass(); + if (pass && pass->IsValid()) { + pass->SetLabel("ComputePass"); + return pass; + } + return nullptr; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/command_buffer.h b/flutter/engine/src/flutter/impeller/renderer/command_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..90701495f9701cb86a31f2009b07ab2e65a500f9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command_buffer.h @@ -0,0 +1,148 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMMAND_BUFFER_H_ +#define FLUTTER_IMPELLER_RENDERER_COMMAND_BUFFER_H_ + +#include +#include + +#include "impeller/renderer/blit_pass.h" +#include "impeller/renderer/compute_pass.h" + +namespace impeller { + +class ComputePass; +class Context; +class RenderPass; +class RenderTarget; +class CommandQueue; + +namespace testing { +class CommandBufferMock; +} + +//------------------------------------------------------------------------------ +/// @brief A collection of encoded commands to be submitted to the GPU for +/// execution. A command buffer is obtained from a graphics +/// `Context`. +/// +/// To submit commands to the GPU, acquire a `RenderPass` from the +/// command buffer and record `Command`s into that pass. A +/// `RenderPass` describes the configuration of the various +/// attachments when the command is submitted. +/// +/// A command buffer is only meant to be used on a single thread. If +/// a frame workload needs to be encoded from multiple threads, +/// set up and record into multiple command buffers. The order of +/// submission of commands encoded in multiple command buffers can +/// be controlled via either the order in which the command buffers +/// were created, or, using the `ReserveSpotInQueue` command which +/// allows for encoding commands for submission in an order that is +/// different from the encoding order. +/// +class CommandBuffer { + friend class testing::CommandBufferMock; + + public: + enum class Status { + kPending, + kError, + kCompleted, + }; + + using CompletionCallback = std::function; + + virtual ~CommandBuffer(); + + virtual bool IsValid() const = 0; + + virtual void SetLabel(std::string_view label) const = 0; + + //---------------------------------------------------------------------------- + /// @brief Block the current thread until the GPU has completed execution + /// of the commands. + /// + void WaitUntilCompleted(); + + //---------------------------------------------------------------------------- + /// @brief Block the current thread until the GPU has completed + /// scheduling execution of the commands. + /// + void WaitUntilScheduled(); + + //---------------------------------------------------------------------------- + /// @brief Create a render pass to record render commands into. + /// + /// @param[in] render_target The description of the render target this pass + /// will target. + /// + /// @return A valid render pass or null. + /// + std::shared_ptr CreateRenderPass( + const RenderTarget& render_target); + + //---------------------------------------------------------------------------- + /// @brief Create a blit pass to record blit commands into. + /// + /// @return A valid blit pass or null. + /// + std::shared_ptr CreateBlitPass(); + + //---------------------------------------------------------------------------- + /// @brief Create a compute pass to record compute commands into. + /// + /// @return A valid compute pass or null. + /// + std::shared_ptr CreateComputePass(); + + protected: + std::weak_ptr context_; + + explicit CommandBuffer(std::weak_ptr context); + + virtual std::shared_ptr OnCreateRenderPass( + RenderTarget render_target) = 0; + + virtual std::shared_ptr OnCreateBlitPass() = 0; + + /// @brief Submit the command buffer to the GPU for execution. + /// + /// See also: [SubmitCommands]. + [[nodiscard]] virtual bool OnSubmitCommands(bool block_on_schedule, + CompletionCallback callback) = 0; + + virtual void OnWaitUntilCompleted() = 0; + + virtual void OnWaitUntilScheduled() = 0; + + virtual std::shared_ptr OnCreateComputePass() = 0; + + private: + friend class CommandQueue; + + //---------------------------------------------------------------------------- + /// @brief Schedule the command encoded by render passes within this + /// command buffer on the GPU. The encoding of these commnands is + /// performed immediately on the calling thread. + /// + /// A command buffer may only be committed once. + /// @param[in] block_on_schedule If true, this function will not return + /// until the command buffer has been scheduled. This only impacts + /// the Metal backend. + /// @param[in] callback The completion callback. + /// + [[nodiscard]] bool SubmitCommands(bool block_on_schedule, + const CompletionCallback& callback); + + [[nodiscard]] bool SubmitCommands(bool block_on_schedule); + + CommandBuffer(const CommandBuffer&) = delete; + + CommandBuffer& operator=(const CommandBuffer&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMMAND_BUFFER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/command_queue.cc b/flutter/engine/src/flutter/impeller/renderer/command_queue.cc new file mode 100644 index 0000000000000000000000000000000000000000..02c9300564f3e6273ddf225df07362e487b1e5a1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command_queue.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +CommandQueue::CommandQueue() = default; + +CommandQueue::~CommandQueue() = default; + +fml::Status CommandQueue::Submit( + const std::vector>& buffers, + const CompletionCallback& completion_callback, + bool block_on_schedule) { + if (buffers.empty()) { + if (completion_callback) { + completion_callback(CommandBuffer::Status::kError); + } + return fml::Status(fml::StatusCode::kInvalidArgument, + "No command buffers provided."); + } + for (const std::shared_ptr& buffer : buffers) { + if (!buffer->SubmitCommands(block_on_schedule, completion_callback)) { + return fml::Status(fml::StatusCode::kCancelled, + "Failed to submit command buffer."); + } + } + return fml::Status(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/command_queue.h b/flutter/engine/src/flutter/impeller/renderer/command_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..2abd7f11d9e09ccccfe2e127b31cd4b1f2343f81 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/command_queue.h @@ -0,0 +1,55 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMMAND_QUEUE_H_ +#define FLUTTER_IMPELLER_RENDERER_COMMAND_QUEUE_H_ + +#include + +#include "fml/status.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +/// @brief An interface for submitting command buffers to the GPU for +/// encoding and execution. +class CommandQueue { + public: + using CompletionCallback = std::function; + + CommandQueue(); + + virtual ~CommandQueue(); + + /// @brief Submit one or more command buffer objects to be encoded and + /// executed on the GPU. + /// + /// The order of the provided buffers determines the ordering in which + /// they are submitted. + /// + /// The returned status only indicates if the command buffer was + /// successfully submitted. Successful completion of the command buffer + /// can only be checked in the optional completion callback. + /// + /// Only the Metal and Vulkan backends can give a status beyond + /// successful encoding. This callback may be called more than once and + /// potentially on a different thread. + /// + /// If [block_on_schedule] is true, this function will not return until + /// the command buffer has been scheduled. This only impacts the Metal + /// backend. + virtual fml::Status Submit( + const std::vector>& buffers, + const CompletionCallback& completion_callback = {}, + bool block_on_schedule = false); + + private: + CommandQueue(const CommandQueue&) = delete; + + CommandQueue& operator=(const CommandQueue&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMMAND_QUEUE_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pass.cc b/flutter/engine/src/flutter/impeller/renderer/compute_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..e069aca32e1ccaa0b90c701c184ec4a61ddd595d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pass.cc @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/compute_pass.h" + +namespace impeller { + +ComputePass::ComputePass(std::shared_ptr context) + : context_(std::move(context)) {} + +ComputePass::~ComputePass() = default; + +void ComputePass::SetLabel(const std::string& label) { + if (label.empty()) { + return; + } + OnSetLabel(label); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pass.h b/flutter/engine/src/flutter/impeller/renderer/compute_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..50b65c432e86b667e664f59ef26d6bb2cb485b0e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pass.h @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMPUTE_PASS_H_ +#define FLUTTER_IMPELLER_RENDERER_COMPUTE_PASS_H_ + +#include + +#include "fml/status.h" +#include "impeller/core/resource_binder.h" +#include "impeller/renderer/compute_pipeline_descriptor.h" +#include "impeller/renderer/pipeline_descriptor.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Compute passes encode compute shader into the underlying command +/// buffer. +/// +/// @see `CommandBuffer` +/// +class ComputePass : public ResourceBinder { + public: + virtual ~ComputePass(); + + virtual bool IsValid() const = 0; + + void SetLabel(const std::string& label); + + virtual void SetCommandLabel(std::string_view label) = 0; + + virtual void SetPipeline( + const std::shared_ptr>& pipeline) = 0; + + virtual fml::Status Compute(const ISize& grid_size) = 0; + + /// @brief Ensures all previously encoded compute command's buffer writes are + /// visible to any subsequent compute commands. + /// + /// On Vulkan, it does not matter if the compute command is in a + /// different command buffer, only that it is executed later in queue + /// order. + virtual void AddBufferMemoryBarrier() = 0; + + /// @brief Ensures all previously encoded compute command's texture writes are + /// visible to any subsequent compute commands. + /// + /// On Vulkan, it does not matter if the compute command is in a + /// different command buffer, only that it is executed later in queue + /// order. + virtual void AddTextureMemoryBarrier() = 0; + + //---------------------------------------------------------------------------- + /// @brief Encode the recorded commands to the underlying command buffer. + /// + /// @return If the commands were encoded to the underlying command + /// buffer. + /// + virtual bool EncodeCommands() const = 0; + + const Context& GetContext() const { return *context_; } + + protected: + const std::shared_ptr context_; + + explicit ComputePass(std::shared_ptr context); + + virtual void OnSetLabel(const std::string& label) = 0; + + private: + ComputePass(const ComputePass&) = delete; + + ComputePass& operator=(const ComputePass&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMPUTE_PASS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.cc b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..5bc86027add958d9c7088d7331724b660b714779 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/compute_pipeline_builder.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.h b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..1e9938ea406ac992472ccc07aab89a9467908a7f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_builder.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_BUILDER_H_ +#define FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_BUILDER_H_ + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/renderer/compute_pipeline_descriptor.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief An optional (but highly recommended) utility for creating +/// pipelines from reflected shader information. +/// +/// @tparam Compute_Shader The reflected compute shader information. Found +/// in a generated header file called +/// .comp.h. +/// +template +struct ComputePipelineBuilder { + public: + using ComputeShader = ComputeShader_; + + //---------------------------------------------------------------------------- + /// @brief Create a default pipeline descriptor using the combination + /// reflected shader information. The descriptor can be configured + /// further before a pipeline state object is created using it. + /// + /// @param[in] context The context + /// + /// @return If the combination of reflected shader information is + /// compatible and the requisite functions can be found in the + /// context, a pipeline descriptor. + /// + static std::optional MakeDefaultPipelineDescriptor( + const Context& context) { + ComputePipelineDescriptor desc; + if (InitializePipelineDescriptorDefaults(context, desc)) { + return {std::move(desc)}; + } + return std::nullopt; + } + + [[nodiscard]] static bool InitializePipelineDescriptorDefaults( + const Context& context, + ComputePipelineDescriptor& desc) { + // Setup debug instrumentation. + desc.SetLabel(SPrintF("%s Pipeline", ComputeShader::kLabel.data())); + + // Resolve pipeline entrypoints. + { + auto compute_function = context.GetShaderLibrary()->GetFunction( + ComputeShader::kEntrypointName, ShaderStage::kCompute); + + if (!compute_function) { + VALIDATION_LOG << "Could not resolve compute pipeline entrypoint '" + << ComputeShader::kEntrypointName + << "' for pipeline named '" << ComputeShader::kLabel + << "'."; + return false; + } + + if (!desc.RegisterDescriptorSetLayouts( + ComputeShader::kDescriptorSetLayouts)) { + VALIDATION_LOG << "Could not configure compute descriptor set layout " + "for pipeline named '" + << ComputeShader::kLabel << "'."; + return false; + } + + desc.SetStageEntrypoint(std::move(compute_function)); + } + return true; + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.cc b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..801eaee115ac4129ff945e0e3c72ed989ae6877c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/compute_pipeline_descriptor.h" + +#include "impeller/core/formats.h" +#include "impeller/renderer/shader_function.h" +#include "impeller/renderer/shader_library.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +ComputePipelineDescriptor::ComputePipelineDescriptor() = default; + +ComputePipelineDescriptor::~ComputePipelineDescriptor() = default; + +// Comparable +std::size_t ComputePipelineDescriptor::GetHash() const { + auto seed = fml::HashCombine(); + fml::HashCombineSeed(seed, label_); + if (entrypoint_) { + fml::HashCombineSeed(seed, entrypoint_->GetHash()); + } + return seed; +} + +// Comparable +bool ComputePipelineDescriptor::IsEqual( + const ComputePipelineDescriptor& other) const { + return label_ == other.label_ && + DeepComparePointer(entrypoint_, other.entrypoint_); +} + +ComputePipelineDescriptor& ComputePipelineDescriptor::SetLabel( + std::string_view label) { + label_ = label; + return *this; +} + +ComputePipelineDescriptor& ComputePipelineDescriptor::SetStageEntrypoint( + std::shared_ptr function) { + FML_DCHECK(!function || function->GetStage() == ShaderStage::kCompute); + if (!function || function->GetStage() != ShaderStage::kCompute) { + return *this; + } + + if (function->GetStage() == ShaderStage::kUnknown) { + return *this; + } + + entrypoint_ = std::move(function); + + return *this; +} + +std::shared_ptr +ComputePipelineDescriptor::GetStageEntrypoint() const { + return entrypoint_; +} + +const std::string& ComputePipelineDescriptor::GetLabel() const { + return label_; +} + +bool ComputePipelineDescriptor::RegisterDescriptorSetLayouts( + const DescriptorSetLayout desc_set_layout[], + size_t count) { + descriptor_set_layouts_.reserve(descriptor_set_layouts_.size() + count); + for (size_t i = 0; i < count; i++) { + descriptor_set_layouts_.emplace_back(desc_set_layout[i]); + } + return true; +} + +const std::vector& +ComputePipelineDescriptor::GetDescriptorSetLayouts() const { + return descriptor_set_layouts_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.h b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..112894bf5c09e7b2db032a86ab5432b5b2dadf98 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_pipeline_descriptor.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_ +#define FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_ + +#include +#include + +#include "impeller/base/comparable.h" +#include "impeller/core/shader_types.h" + +namespace impeller { + +class ShaderFunction; +template +class Pipeline; + +class ComputePipelineDescriptor final + : public Comparable { + public: + ComputePipelineDescriptor(); + + ~ComputePipelineDescriptor(); + + ComputePipelineDescriptor& SetLabel(std::string_view label); + + const std::string& GetLabel() const; + + ComputePipelineDescriptor& SetStageEntrypoint( + std::shared_ptr function); + + std::shared_ptr GetStageEntrypoint() const; + + // Comparable + std::size_t GetHash() const override; + + // Comparable + bool IsEqual(const ComputePipelineDescriptor& other) const override; + + template + bool RegisterDescriptorSetLayouts( + const std::array& inputs) { + return RegisterDescriptorSetLayouts(inputs.data(), inputs.size()); + } + + bool RegisterDescriptorSetLayouts(const DescriptorSetLayout desc_set_layout[], + size_t count); + + const std::vector& GetDescriptorSetLayouts() const; + + private: + std::string label_; + std::shared_ptr entrypoint_; + std::vector descriptor_set_layouts_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_COMPUTE_PIPELINE_DESCRIPTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/compute_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/compute_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d2ae2194e2e24bc36b46157891b74287dc38c73 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/compute_unittests.cc @@ -0,0 +1,509 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "impeller/core/host_buffer.h" +#include "impeller/fixtures/sample.comp.h" +#include "impeller/fixtures/stage1.comp.h" +#include "impeller/fixtures/stage2.comp.h" +#include "impeller/playground/compute_playground_test.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/compute_pipeline_builder.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/prefix_sum_test.comp.h" +#include "impeller/renderer/threadgroup_sizing_test.comp.h" + +namespace impeller { +namespace testing { +using ComputeTest = ComputePlaygroundTest; +INSTANTIATE_COMPUTE_SUITE(ComputeTest); + +TEST_P(ComputeTest, CapabilitiesReportSupport) { + auto context = GetContext(); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); +} + +TEST_P(ComputeTest, CanCreateComputePass) { + using CS = SampleComputeShader; + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc.has_value()); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(compute_pipeline); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount = 5; + + pass->SetPipeline(compute_pipeline); + + CS::Info info{.count = kCount}; + CS::Input0 input_0; + CS::Input1 input_1; + for (size_t i = 0; i < kCount; i++) { + input_0.elements[i] = Vector4(2.0 + i, 3.0 + i, 4.0 + i, 5.0 * i); + input_1.elements[i] = Vector4(6.0, 7.0, 8.0, 9.0); + } + + input_0.fixed_array[1] = IPoint32(2, 2); + input_1.fixed_array[0] = UintPoint32(3, 3); + input_0.some_int = 5; + input_1.some_struct = CS::SomeStruct{.vf = Point(3, 4), .i = 42}; + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindInfo(*pass, host_buffer->EmplaceUniform(info)); + CS::BindInput0(*pass, host_buffer->EmplaceStorageBuffer(input_0)); + CS::BindInput1(*pass, host_buffer->EmplaceStorageBuffer(input_1)); + CS::BindOutput(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + ASSERT_TRUE(pass->Compute(ISize(kCount, 1)).ok()); + ASSERT_TRUE(pass->EncodeCommands()); + + fml::AutoResetWaitableEvent latch; + ASSERT_TRUE( + context->GetCommandQueue() + ->Submit( + {cmd_buffer}, + [&latch, output_buffer, &input_0, + &input_1](CommandBuffer::Status status) { + EXPECT_EQ(status, CommandBuffer::Status::kCompleted); + + auto view = DeviceBuffer::AsBufferView(output_buffer); + EXPECT_EQ(view.GetRange().length, sizeof(CS::Output)); + + CS::Output* output = + reinterpret_cast*>( + output_buffer->OnGetContents()); + EXPECT_TRUE(output); + for (size_t i = 0; i < kCount; i++) { + Vector4 vector = output->elements[i]; + Vector4 computed = input_0.elements[i] * input_1.elements[i]; + EXPECT_EQ(vector, + Vector4(computed.x + 2 + input_1.some_struct.i, + computed.y + 3 + input_1.some_struct.vf.x, + computed.z + 5 + input_1.some_struct.vf.y, + computed.w)); + } + latch.Signal(); + }) + .ok()); + + latch.Wait(); +} + +TEST_P(ComputeTest, CanComputePrefixSum) { + using CS = PrefixSumTestComputeShader; + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc.has_value()); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(compute_pipeline); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount = 5; + + pass->SetPipeline(compute_pipeline); + + CS::InputData input_data; + input_data.count = kCount; + for (size_t i = 0; i < kCount; i++) { + input_data.data[i] = 1 + i; + } + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindInputData(*pass, host_buffer->EmplaceStorageBuffer(input_data)); + CS::BindOutputData(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + ASSERT_TRUE(pass->Compute(ISize(kCount, 1)).ok()); + ASSERT_TRUE(pass->EncodeCommands()); + + fml::AutoResetWaitableEvent latch; + ASSERT_TRUE( + context->GetCommandQueue() + ->Submit({cmd_buffer}, + [&latch, output_buffer](CommandBuffer::Status status) { + EXPECT_EQ(status, CommandBuffer::Status::kCompleted); + + auto view = DeviceBuffer::AsBufferView(output_buffer); + EXPECT_EQ(view.GetRange().length, + sizeof(CS::OutputData)); + + CS::OutputData* output = + reinterpret_cast*>( + output_buffer->OnGetContents()); + EXPECT_TRUE(output); + + constexpr uint32_t expected[kCount] = {1, 3, 6, 10, 15}; + for (size_t i = 0; i < kCount; i++) { + auto computed_sum = output->data[i]; + EXPECT_EQ(computed_sum, expected[i]); + } + latch.Signal(); + }) + .ok()); + + latch.Wait(); +} + +TEST_P(ComputeTest, 1DThreadgroupSizingIsCorrect) { + using CS = ThreadgroupSizingTestComputeShader; + auto context = GetContext(); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc.has_value()); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(compute_pipeline); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount = 2048; + + pass->SetPipeline(compute_pipeline); + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindOutputData(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + ASSERT_TRUE(pass->Compute(ISize(kCount, 1)).ok()); + ASSERT_TRUE(pass->EncodeCommands()); + + fml::AutoResetWaitableEvent latch; + ASSERT_TRUE( + context->GetCommandQueue() + ->Submit({cmd_buffer}, + [&latch, output_buffer](CommandBuffer::Status status) { + EXPECT_EQ(status, CommandBuffer::Status::kCompleted); + + auto view = DeviceBuffer::AsBufferView(output_buffer); + EXPECT_EQ(view.GetRange().length, + sizeof(CS::OutputData)); + + CS::OutputData* output = + reinterpret_cast*>( + output_buffer->OnGetContents()); + EXPECT_TRUE(output); + EXPECT_EQ(output->data[kCount - 1], kCount - 1); + latch.Signal(); + }) + .ok()); + + latch.Wait(); +} + +TEST_P(ComputeTest, CanComputePrefixSumLargeInteractive) { + using CS = PrefixSumTestComputeShader; + + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + auto callback = [&](RenderPass& render_pass) -> bool { + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + + static constexpr size_t kCount = 1023; + + pass->SetPipeline(compute_pipeline); + + CS::InputData input_data; + input_data.count = kCount; + for (size_t i = 0; i < kCount; i++) { + input_data.data[i] = 1 + i; + } + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindInputData(*pass, host_buffer->EmplaceStorageBuffer(input_data)); + CS::BindOutputData(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + pass->Compute(ISize(kCount, 1)); + pass->EncodeCommands(); + host_buffer->Reset(); + return context->GetCommandQueue()->Submit({cmd_buffer}).ok(); + }; + ASSERT_TRUE(OpenPlaygroundHere(callback)); +} + +TEST_P(ComputeTest, MultiStageInputAndOutput) { + using CS1 = Stage1ComputeShader; + using Stage1PipelineBuilder = ComputePipelineBuilder; + using CS2 = Stage2ComputeShader; + using Stage2PipelineBuilder = ComputePipelineBuilder; + + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + auto pipeline_desc_1 = + Stage1PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc_1.has_value()); + auto compute_pipeline_1 = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc_1).Get(); + ASSERT_TRUE(compute_pipeline_1); + + auto pipeline_desc_2 = + Stage2PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc_2.has_value()); + auto compute_pipeline_2 = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc_2).Get(); + ASSERT_TRUE(compute_pipeline_2); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount1 = 5; + static constexpr size_t kCount2 = kCount1 * 2; + + CS1::Input input_1; + input_1.count = kCount1; + for (size_t i = 0; i < kCount1; i++) { + input_1.elements[i] = i; + } + + CS2::Input input_2; + input_2.count = kCount2; + for (size_t i = 0; i < kCount2; i++) { + input_2.elements[i] = i; + } + + auto output_buffer_1 = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer Stage 1"); + auto output_buffer_2 = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer Stage 2"); + + { + pass->SetPipeline(compute_pipeline_1); + + CS1::BindInput(*pass, host_buffer->EmplaceStorageBuffer(input_1)); + CS1::BindOutput(*pass, DeviceBuffer::AsBufferView(output_buffer_1)); + + ASSERT_TRUE(pass->Compute(ISize(512, 1)).ok()); + pass->AddBufferMemoryBarrier(); + } + + { + pass->SetPipeline(compute_pipeline_2); + + CS1::BindInput(*pass, DeviceBuffer::AsBufferView(output_buffer_1)); + CS2::BindOutput(*pass, DeviceBuffer::AsBufferView(output_buffer_2)); + ASSERT_TRUE(pass->Compute(ISize(512, 1)).ok()); + } + + ASSERT_TRUE(pass->EncodeCommands()); + + fml::AutoResetWaitableEvent latch; + ASSERT_TRUE( + context->GetCommandQueue() + ->Submit({cmd_buffer}, + [&latch, &output_buffer_1, + &output_buffer_2](CommandBuffer::Status status) { + EXPECT_EQ(status, CommandBuffer::Status::kCompleted); + + CS1::Output* output_1 = + reinterpret_cast*>( + output_buffer_1->OnGetContents()); + EXPECT_TRUE(output_1); + EXPECT_EQ(output_1->count, 10u); + EXPECT_THAT( + output_1->elements, + ::testing::ElementsAre(0, 0, 2, 3, 4, 6, 6, 9, 8, 12)); + + CS2::Output* output_2 = + reinterpret_cast*>( + output_buffer_2->OnGetContents()); + EXPECT_TRUE(output_2); + EXPECT_EQ(output_2->count, 10u); + EXPECT_THAT(output_2->elements, + ::testing::ElementsAre(0, 0, 4, 6, 8, 12, 12, + 18, 16, 24)); + + latch.Signal(); + }) + .ok()); + + latch.Wait(); +} + +TEST_P(ComputeTest, CanCompute1DimensionalData) { + using CS = SampleComputeShader; + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc.has_value()); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(compute_pipeline); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount = 5; + + pass->SetPipeline(compute_pipeline); + + CS::Info info{.count = kCount}; + CS::Input0 input_0; + CS::Input1 input_1; + for (size_t i = 0; i < kCount; i++) { + input_0.elements[i] = Vector4(2.0 + i, 3.0 + i, 4.0 + i, 5.0 * i); + input_1.elements[i] = Vector4(6.0, 7.0, 8.0, 9.0); + } + + input_0.fixed_array[1] = IPoint32(2, 2); + input_1.fixed_array[0] = UintPoint32(3, 3); + input_0.some_int = 5; + input_1.some_struct = CS::SomeStruct{.vf = Point(3, 4), .i = 42}; + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindInfo(*pass, host_buffer->EmplaceUniform(info)); + CS::BindInput0(*pass, host_buffer->EmplaceStorageBuffer(input_0)); + CS::BindInput1(*pass, host_buffer->EmplaceStorageBuffer(input_1)); + CS::BindOutput(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + ASSERT_TRUE(pass->Compute(ISize(kCount, 1)).ok()); + ASSERT_TRUE(pass->EncodeCommands()); + + fml::AutoResetWaitableEvent latch; + ASSERT_TRUE( + context->GetCommandQueue() + ->Submit( + {cmd_buffer}, + [&latch, output_buffer, &input_0, + &input_1](CommandBuffer::Status status) { + EXPECT_EQ(status, CommandBuffer::Status::kCompleted); + + auto view = DeviceBuffer::AsBufferView(output_buffer); + EXPECT_EQ(view.GetRange().length, sizeof(CS::Output)); + + CS::Output* output = + reinterpret_cast*>( + output_buffer->OnGetContents()); + EXPECT_TRUE(output); + for (size_t i = 0; i < kCount; i++) { + Vector4 vector = output->elements[i]; + Vector4 computed = input_0.elements[i] * input_1.elements[i]; + EXPECT_EQ(vector, + Vector4(computed.x + 2 + input_1.some_struct.i, + computed.y + 3 + input_1.some_struct.vf.x, + computed.z + 5 + input_1.some_struct.vf.y, + computed.w)); + } + latch.Signal(); + }) + .ok()); + + latch.Wait(); +} + +TEST_P(ComputeTest, ReturnsEarlyWhenAnyGridDimensionIsZero) { + using CS = SampleComputeShader; + auto context = GetContext(); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + ASSERT_TRUE(context); + ASSERT_TRUE(context->GetCapabilities()->SupportsCompute()); + + using SamplePipelineBuilder = ComputePipelineBuilder; + auto pipeline_desc = + SamplePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_desc.has_value()); + auto compute_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(compute_pipeline); + + auto cmd_buffer = context->CreateCommandBuffer(); + auto pass = cmd_buffer->CreateComputePass(); + ASSERT_TRUE(pass && pass->IsValid()); + + static constexpr size_t kCount = 5; + + pass->SetPipeline(compute_pipeline); + + CS::Info info{.count = kCount}; + CS::Input0 input_0; + CS::Input1 input_1; + for (size_t i = 0; i < kCount; i++) { + input_0.elements[i] = Vector4(2.0 + i, 3.0 + i, 4.0 + i, 5.0 * i); + input_1.elements[i] = Vector4(6.0, 7.0, 8.0, 9.0); + } + + input_0.fixed_array[1] = IPoint32(2, 2); + input_1.fixed_array[0] = UintPoint32(3, 3); + input_0.some_int = 5; + input_1.some_struct = CS::SomeStruct{.vf = Point(3, 4), .i = 42}; + + auto output_buffer = CreateHostVisibleDeviceBuffer>( + context, "Output Buffer"); + + CS::BindInfo(*pass, host_buffer->EmplaceUniform(info)); + CS::BindInput0(*pass, host_buffer->EmplaceStorageBuffer(input_0)); + CS::BindInput1(*pass, host_buffer->EmplaceStorageBuffer(input_1)); + CS::BindOutput(*pass, DeviceBuffer::AsBufferView(output_buffer)); + + // Intentionally making the grid size zero in one dimension. No GPU will + // tolerate this. + EXPECT_FALSE(pass->Compute(ISize(0, 1)).ok()); + pass->EncodeCommands(); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/context.cc b/flutter/engine/src/flutter/impeller/renderer/context.cc new file mode 100644 index 0000000000000000000000000000000000000000..cab4104b3b8282e3019175c37224f75d2b76d7ee --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/context.cc @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/context.h" + +#include + +namespace impeller { + +Context::~Context() = default; + +Context::Context(const Flags& flags) : flags_(flags) {} + +bool Context::UpdateOffscreenLayerPixelFormat(PixelFormat format) { + return false; +} + +bool Context::EnqueueCommandBuffer( + std::shared_ptr command_buffer) { + return GetCommandQueue()->Submit({std::move(command_buffer)}).ok(); +} + +bool Context::FlushCommandBuffers() { + return true; +} + +std::shared_ptr Context::GetIdleWaiter() const { + return nullptr; +} + +void Context::ResetThreadLocalState() const { + // Nothing to do. +} + +bool Context::AddTrackingFence(const std::shared_ptr& texture) const { + return false; +} + +bool Context::SubmitOnscreen(std::shared_ptr cmd_buffer) { + return EnqueueCommandBuffer(std::move(cmd_buffer)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/context.h b/flutter/engine/src/flutter/impeller/renderer/context.h new file mode 100644 index 0000000000000000000000000000000000000000..36e88e9bf58ed1e4f8e65039579305fd1e02e474 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/context.h @@ -0,0 +1,265 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_CONTEXT_H_ +#define FLUTTER_IMPELLER_RENDERER_CONTEXT_H_ + +#include +#include + +#include "fml/closure.h" +#include "impeller/base/flags.h" +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/capabilities.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/sampler_library.h" + +namespace impeller { + +class ShaderLibrary; +class CommandBuffer; +class PipelineLibrary; + +//------------------------------------------------------------------------------ +/// @brief To do anything rendering related with Impeller, you need a +/// context. +/// +/// Contexts are expensive to construct and typically you only need +/// one in the process. The context represents a connection to a +/// graphics or compute accelerator on the device. +/// +/// If there are multiple context in a process, it would typically +/// be for separation of concerns (say, use with multiple engines in +/// Flutter), talking to multiple accelerators, or talking to the +/// same accelerator using different client APIs (Metal, Vulkan, +/// OpenGL ES, etc..). +/// +/// Contexts are thread-safe. They may be created, used, and +/// collected (though not from a thread used by an internal pool) on +/// any thread. They may also be accessed simultaneously from +/// multiple threads. +/// +/// Contexts are abstract and a concrete instance must be created +/// using one of the subclasses of `Context` in +/// `//impeller/renderer/backend`. +class Context { + public: + enum class BackendType { + kMetal, + kOpenGLES, + kVulkan, + }; + + /// The maximum number of tasks that should ever be stored for + /// `StoreTaskForGPU`. + /// + /// This number was arbitrarily chosen. The idea is that this is a somewhat + /// rare situation where tasks happen to get executed in that tiny amount of + /// time while an app is being backgrounded but still executing. + static constexpr int32_t kMaxTasksAwaitingGPU = 64; + + //---------------------------------------------------------------------------- + /// @brief Destroys an Impeller context. + /// + virtual ~Context(); + + //---------------------------------------------------------------------------- + /// @brief Get the graphics backend of an Impeller context. + /// + /// This is useful for cases where a renderer needs to track and + /// lookup backend-specific resources, like shaders or uniform + /// layout information. + /// + /// It's not recommended to use this as a substitute for + /// per-backend capability checking. Instead, check for specific + /// capabilities via `GetCapabilities()`. + /// + /// @return The graphics backend of the `Context`. + /// + virtual BackendType GetBackendType() const = 0; + + // TODO(129920): Refactor and move to capabilities. + virtual std::string DescribeGpuModel() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Determines if a context is valid. If the caller ever receives + /// an invalid context, they must discard it and construct a new + /// context. There is no recovery mechanism to repair a bad + /// context. + /// + /// It is convention in Impeller to never return an invalid + /// context from a call that returns an pointer to a context. The + /// call implementation performs validity checks itself and return + /// a null context instead of a pointer to an invalid context. + /// + /// How a context goes invalid is backend specific. It could + /// happen due to device loss, or any other unrecoverable error. + /// + /// @return If the context is valid. + /// + virtual bool IsValid() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Get the capabilities of Impeller context. All optionally + /// supported feature of the platform, client-rendering API, and + /// device can be queried using the `Capabilities`. + /// + /// @return The capabilities. Can never be `nullptr` for a valid context. + /// + virtual const std::shared_ptr& GetCapabilities() + const = 0; + + // TODO(129920): Refactor and move to capabilities. + virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format); + + //---------------------------------------------------------------------------- + /// @brief Returns the allocator used to create textures and buffers on + /// the device. + /// + /// @return The resource allocator. Can never be `nullptr` for a valid + /// context. + /// + virtual std::shared_ptr GetResourceAllocator() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns the library of shaders used to specify the + /// programmable stages of a pipeline. + /// + /// @return The shader library. Can never be `nullptr` for a valid + /// context. + /// + virtual std::shared_ptr GetShaderLibrary() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns the library of combined image samplers used in + /// shaders. + /// + /// @return The sampler library. Can never be `nullptr` for a valid + /// context. + /// + virtual std::shared_ptr GetSamplerLibrary() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns the library of pipelines used by render or compute + /// commands. + /// + /// @return The pipeline library. Can never be `nullptr` for a valid + /// context. + /// + virtual std::shared_ptr GetPipelineLibrary() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Create a new command buffer. Command buffers can be used to + /// encode graphics, blit, or compute commands to be submitted to + /// the device. + /// + /// A command buffer can only be used on a single thread. + /// Multi-threaded render, blit, or compute passes must create a + /// new command buffer on each thread. + /// + /// @return A new command buffer. + /// + virtual std::shared_ptr CreateCommandBuffer() const = 0; + + /// @brief Return the graphics queue for submitting command buffers. + virtual std::shared_ptr GetCommandQueue() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Force all pending asynchronous work to finish. This is + /// achieved by deleting all owned concurrent message loops. + /// + virtual void Shutdown() = 0; + + /// Stores a task on the `ContextMTL` that is awaiting access for the GPU. + /// + /// The task will be executed in the event that the GPU access has changed to + /// being available or that the task has been canceled. The task should + /// operate with the `SyncSwitch` to make sure the GPU is accessible. + /// + /// If the queue of pending tasks is cleared without GPU access, then the + /// failure callback will be invoked and the primary task function will not + /// + /// Threadsafe. + /// + /// `task` will be executed on the platform thread. + virtual void StoreTaskForGPU(const fml::closure& task, + const fml::closure& failure) { + FML_CHECK(false && "not supported in this context"); + } + + /// Run backend specific additional setup and create common shader variants. + /// + /// This bootstrap is intended to improve the performance of several + /// first frame benchmarks that are tracked in the flutter device lab. + /// The workload includes initializing commonly used but not default + /// shader variants, as well as forcing driver initialization. + virtual void InitializeCommonlyUsedShadersIfNeeded() const {} + + /// Dispose resources that are cached on behalf of the current thread. + /// + /// Some backends such as Vulkan may cache resources that can be reused while + /// executing a rendering operation. This API can be called after the + /// operation completes in order to clear the cache. + virtual void DisposeThreadLocalCachedResources() {} + + /// @brief Enqueue command_buffer for submission by the end of the frame. + /// + /// Certain backends may immediately flush the command buffer if batch + /// submission is not supported. This functionality is not thread safe + /// and should only be used via the ContentContext for rendering a + /// 2D workload. + /// + /// Returns true if submission has succeeded. If the buffer is enqueued + /// then no error may be returned until FlushCommandBuffers is called. + [[nodiscard]] virtual bool EnqueueCommandBuffer( + std::shared_ptr command_buffer); + + /// @brief Flush all pending command buffers. + /// + /// Returns whether or not submission was successful. This functionality + /// is not threadsafe and should only be used via the ContentContext for + /// rendering a 2D workload. + [[nodiscard]] virtual bool FlushCommandBuffers(); + + virtual bool AddTrackingFence(const std::shared_ptr& texture) const; + + virtual std::shared_ptr GetIdleWaiter() const; + + //---------------------------------------------------------------------------- + /// Resets any thread local state that may interfere with embedders. + /// + /// Today, only the OpenGL backend can trample on thread local state that the + /// embedder can access. This call puts the GL state in a sane "clean" state. + /// + /// Impeller itself is resilient to a dirty thread local state table. + /// + virtual void ResetThreadLocalState() const; + + /// @brief Retrieve the runtime stage for this context type. + /// + /// This is used by the engine shell and other subsystems for loading the + /// correct shader types. + virtual RuntimeStageBackend GetRuntimeStageBackend() const = 0; + + /// @brief Submit the command buffer that renders to the onscreen surface. + virtual bool SubmitOnscreen(std::shared_ptr cmd_buffer); + + const Flags& GetFlags() const { return flags_; } + + protected: + explicit Context(const Flags& flags); + + Flags flags_; + std::vector> per_frame_task_; + + private: + Context(const Context&) = delete; + + Context& operator=(const Context&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/device_buffer_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/device_buffer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..95d53812cda536e957333b4878784eba04fa7890 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/device_buffer_unittests.cc @@ -0,0 +1,15 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/core/device_buffer.h" +#include "impeller/playground/playground.h" + +namespace impeller { +namespace testing { + +using DeviceBufferTest = Playground; + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline.cc b/flutter/engine/src/flutter/impeller/renderer/pipeline.cc new file mode 100644 index 0000000000000000000000000000000000000000..79adb18078fa82634b68e18bc59e3a9182e70d54 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/pipeline.h" +#include + +#include "compute_pipeline_descriptor.h" +#include "impeller/base/promise.h" +#include "impeller/renderer/compute_pipeline_descriptor.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/pipeline_library.h" +#include "pipeline_descriptor.h" + +namespace impeller { + +template +Pipeline::Pipeline(std::weak_ptr library, T desc) + : library_(std::move(library)), desc_(std::move(desc)) {} + +template +Pipeline::~Pipeline() = default; + +PipelineFuture CreatePipelineFuture( + const Context& context, + std::optional desc, + bool async) { + if (!context.IsValid()) { + return {desc, RealizedFuture>>( + nullptr)}; + } + + return context.GetPipelineLibrary()->GetPipeline(std::move(desc), + /*async=*/async); +} + +PipelineFuture CreatePipelineFuture( + const Context& context, + std::optional desc) { + if (!context.IsValid()) { + return { + desc, + RealizedFuture>>( + nullptr)}; + } + + return context.GetPipelineLibrary()->GetPipeline(std::move(desc)); +} + +template +const T& Pipeline::GetDescriptor() const { + return desc_; +} + +template +PipelineFuture Pipeline::CreateVariant( + bool async, + std::function descriptor_callback) const { + if (!descriptor_callback) { + return {std::nullopt, + RealizedFuture>>(nullptr)}; + } + + auto copied_desc = desc_; + + descriptor_callback(copied_desc); + + auto library = library_.lock(); + if (!library) { + VALIDATION_LOG << "The library from which this pipeline was created was " + "already collected."; + return {desc_, RealizedFuture>>(nullptr)}; + } + + return library->GetPipeline(std::move(copied_desc), async); +} + +template class Pipeline; +template class Pipeline; + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline.h b/flutter/engine/src/flutter/impeller/renderer/pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..2dec9431bcdc74db55056ae0d29278ac67d3c4b6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline.h @@ -0,0 +1,206 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_H_ +#define FLUTTER_IMPELLER_RENDERER_PIPELINE_H_ + +#include + +#include "compute_pipeline_descriptor.h" +#include "impeller/core/raw_ptr.h" +#include "impeller/renderer/compute_pipeline_builder.h" +#include "impeller/renderer/compute_pipeline_descriptor.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/pipeline_builder.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/shader_stage_compatibility_checker.h" + +namespace impeller { + +using PipelineKey = int64_t; + +class PipelineLibrary; +template +class Pipeline; + +template +struct PipelineFuture { + std::optional descriptor; + std::shared_future>> future; + + const std::shared_ptr> Get() const { return future.get(); } + + bool IsValid() const { return future.valid(); } +}; + +//------------------------------------------------------------------------------ +/// @brief Describes the fixed function and programmable aspects of +/// rendering and compute operations performed by commands submitted +/// to the GPU via a command buffer. +/// +/// A pipeline handle must be allocated upfront and kept alive for +/// as long as possible. Do not create a pipeline object within a +/// frame workload. +/// +/// This pipeline object is almost never used directly as it is +/// untyped. Use reflected shader information generated by the +/// Impeller offline shader compiler to generate a typed pipeline +/// object. +/// +template +class Pipeline { + public: + virtual ~Pipeline(); + + virtual bool IsValid() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Get the descriptor that was responsible for creating this + /// pipeline. It may be copied and modified to create a pipeline + /// variant. + /// + /// @return The descriptor. + /// + const T& GetDescriptor() const; + + PipelineFuture CreateVariant( + bool async, + std::function descriptor_callback) const; + + protected: + const std::weak_ptr library_; + + const T desc_; + + Pipeline(std::weak_ptr library, T desc); + + private: + Pipeline(const Pipeline&) = delete; + + Pipeline& operator=(const Pipeline&) = delete; +}; + +/// @brief A raw ptr to a pipeline object. +/// +/// These pipeline refs are safe to use as the context will keep the +/// pipelines alive throughout rendering. +using PipelineRef = raw_ptr>; + +extern template class Pipeline; +extern template class Pipeline; + +/// @brief Create a pipeline for the given descriptor. +/// +/// If `async` is true, the compilation is performed on a worker thread. The +/// returned future will complete once that work is done. If `async` is false, +/// the work is done on the current thread. +/// +/// It is more performant to set async to false than to spawn a +/// worker and immediately block on the future completion. +PipelineFuture CreatePipelineFuture( + const Context& context, + std::optional desc, + bool async = true); + +PipelineFuture CreatePipelineFuture( + const Context& context, + std::optional desc); + +/// Holds a reference to a Pipeline used for rendering while also maintaining +/// the vertex shader and fragment shader types at compile-time. +/// +/// See also: +/// - impeller::ContentContext::Variants - the typical container for +/// RenderPipelineHandles. +template +class RenderPipelineHandle { + public: + using VertexShader = VertexShader_; + using FragmentShader = FragmentShader_; + using Builder = PipelineBuilder; + + explicit RenderPipelineHandle(const Context& context, bool async = true) + : RenderPipelineHandle(CreatePipelineFuture( + context, + Builder::MakeDefaultPipelineDescriptor(context), + async)) {} + + explicit RenderPipelineHandle(const Context& context, + std::optional desc, + bool async = true) + : RenderPipelineHandle( + CreatePipelineFuture(context, desc, /*async=*/async)) {} + + explicit RenderPipelineHandle(PipelineFuture future) + : pipeline_future_(std::move(future)) {} + + std::shared_ptr> WaitAndGet() { + if (did_wait_) { + return pipeline_; + } + did_wait_ = true; + if (pipeline_future_.IsValid()) { + pipeline_ = pipeline_future_.Get(); + } + return pipeline_; + } + + std::optional GetDescriptor() const { + return pipeline_future_.descriptor; + } + + private: + PipelineFuture pipeline_future_; + std::shared_ptr> pipeline_; + bool did_wait_ = false; + + RenderPipelineHandle(const RenderPipelineHandle&) = delete; + + RenderPipelineHandle& operator=(const RenderPipelineHandle&) = delete; +}; + +template +class ComputePipelineHandle { + public: + using ComputeShader = ComputeShader_; + using Builder = ComputePipelineBuilder; + + explicit ComputePipelineHandle(const Context& context) + : ComputePipelineHandle(CreatePipelineFuture( + context, + Builder::MakeDefaultPipelineDescriptor(context))) {} + + explicit ComputePipelineHandle( + const Context& context, + std::optional compute_desc) + : ComputePipelineHandle(CreatePipelineFuture(context, compute_desc)) {} + + explicit ComputePipelineHandle( + PipelineFuture future) + : pipeline_future_(std::move(future)) {} + + std::shared_ptr> WaitAndGet() { + if (did_wait_) { + return pipeline_; + } + did_wait_ = true; + if (pipeline_future_.IsValid()) { + pipeline_ = pipeline_future_.Get(); + } + return pipeline_; + } + + private: + PipelineFuture pipeline_future_; + std::shared_ptr> pipeline_; + bool did_wait_ = false; + + ComputePipelineHandle(const ComputePipelineHandle&) = delete; + + ComputePipelineHandle& operator=(const ComputePipelineHandle&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.cc b/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..79efa7bf3855bd2b49fd09c76b44d3cccaf26257 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/pipeline_builder.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.h b/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..8882d44fe2d55a14b61bf171bbbb7c95dfe7dbda --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_builder.h @@ -0,0 +1,132 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_BUILDER_H_ +#define FLUTTER_IMPELLER_RENDERER_PIPELINE_BUILDER_H_ + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/shader_library.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief An optional (but highly recommended) utility for creating +/// pipelines from reflected shader information. +/// +/// @tparam VertexShader_ The reflected vertex shader information. Found +/// in a generated header file called +/// .vert.h. +/// @tparam FragmentShader_ The reflected fragment shader information. +/// Found in a generated header file called +/// .frag.h. +/// +template +struct PipelineBuilder { + public: + using VertexShader = VertexShader_; + using FragmentShader = FragmentShader_; + + static constexpr size_t kVertexBufferIndex = + VertexDescriptor::kReservedVertexBufferIndex; + + //---------------------------------------------------------------------------- + /// @brief Create a default pipeline descriptor using the combination + /// reflected shader information. The descriptor can be configured + /// further before a pipeline state object is created using it. + /// + /// @param[in] context The context + /// + /// @return If the combination of reflected shader information is + /// compatible and the requisite functions can be found in the + /// context, a pipeline descriptor. + /// + static std::optional MakeDefaultPipelineDescriptor( + const Context& context, + const std::vector& constants = {}) { + PipelineDescriptor desc; + desc.SetSpecializationConstants(constants); + if (InitializePipelineDescriptorDefaults(context, desc)) { + return {std::move(desc)}; + } + return std::nullopt; + } + + [[nodiscard]] static bool InitializePipelineDescriptorDefaults( + const Context& context, + PipelineDescriptor& desc) { + // Setup debug instrumentation. + desc.SetLabel(SPrintF("%s Pipeline", FragmentShader::kLabel.data())); + + // Resolve pipeline entrypoints. + { + auto vertex_function = context.GetShaderLibrary()->GetFunction( + VertexShader::kEntrypointName, ShaderStage::kVertex); + auto fragment_function = context.GetShaderLibrary()->GetFunction( + FragmentShader::kEntrypointName, ShaderStage::kFragment); + + if (!vertex_function || !fragment_function) { + VALIDATION_LOG << "Could not resolve pipeline entrypoint(s) '" + << VertexShader::kEntrypointName << "' and '" + << FragmentShader::kEntrypointName + << "' for pipeline named '" << VertexShader::kLabel + << "'."; + return false; + } + + desc.AddStageEntrypoint(std::move(vertex_function)); + desc.AddStageEntrypoint(std::move(fragment_function)); + } + + // Setup the vertex descriptor from reflected information. + { + auto vertex_descriptor = std::make_shared(); + vertex_descriptor->SetStageInputs(VertexShader::kAllShaderStageInputs, + VertexShader::kInterleavedBufferLayout); + vertex_descriptor->RegisterDescriptorSetLayouts( + VertexShader::kDescriptorSetLayouts); + vertex_descriptor->RegisterDescriptorSetLayouts( + FragmentShader::kDescriptorSetLayouts); + desc.SetVertexDescriptor(std::move(vertex_descriptor)); + } + + // Setup fragment shader output descriptions. + { + // Configure the sole color attachments pixel format. This is by + // convention. + ColorAttachmentDescriptor color0; + color0.format = context.GetCapabilities()->GetDefaultColorFormat(); + color0.blending_enabled = true; + desc.SetColorAttachmentDescriptor(0u, color0); + } + + // Setup default depth buffer descriptions. + { + DepthAttachmentDescriptor depth0; + depth0.depth_compare = CompareFunction::kAlways; + desc.SetDepthStencilAttachmentDescriptor(depth0); + desc.SetDepthPixelFormat( + context.GetCapabilities()->GetDefaultDepthStencilFormat()); + } + + // Setup default stencil buffer descriptions. + { + StencilAttachmentDescriptor stencil0; + stencil0.stencil_compare = CompareFunction::kEqual; + desc.SetStencilAttachmentDescriptors(stencil0); + desc.SetStencilPixelFormat( + context.GetCapabilities()->GetDefaultDepthStencilFormat()); + } + + return true; + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e6243ea289ea516c7a9e76ea661c1e872686bdf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.cc @@ -0,0 +1,294 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/pipeline_descriptor.h" + +#include + +#include "impeller/base/comparable.h" +#include "impeller/core/formats.h" +#include "impeller/renderer/shader_function.h" +#include "impeller/renderer/shader_library.h" +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +PipelineDescriptor::PipelineDescriptor() = default; + +PipelineDescriptor::~PipelineDescriptor() = default; + +// Comparable +std::size_t PipelineDescriptor::GetHash() const { + auto seed = fml::HashCombine(); + fml::HashCombineSeed(seed, label_); + fml::HashCombineSeed(seed, sample_count_); + for (const auto& entry : entrypoints_) { + fml::HashCombineSeed(seed, entry.first); + if (auto second = entry.second) { + fml::HashCombineSeed(seed, second->GetHash()); + } + } + for (const auto& des : color_attachment_descriptors_) { + fml::HashCombineSeed(seed, des.first); + fml::HashCombineSeed(seed, des.second.Hash()); + } + if (vertex_descriptor_) { + fml::HashCombineSeed(seed, vertex_descriptor_->GetHash()); + } + fml::HashCombineSeed(seed, depth_pixel_format_); + fml::HashCombineSeed(seed, stencil_pixel_format_); + fml::HashCombineSeed(seed, depth_attachment_descriptor_); + fml::HashCombineSeed(seed, front_stencil_attachment_descriptor_); + fml::HashCombineSeed(seed, back_stencil_attachment_descriptor_); + fml::HashCombineSeed(seed, winding_order_); + fml::HashCombineSeed(seed, cull_mode_); + fml::HashCombineSeed(seed, primitive_type_); + fml::HashCombineSeed(seed, polygon_mode_); + return seed; +} + +// Comparable +bool PipelineDescriptor::IsEqual(const PipelineDescriptor& other) const { + return label_ == other.label_ && sample_count_ == other.sample_count_ && + DeepCompareMap(entrypoints_, other.entrypoints_) && + color_attachment_descriptors_ == other.color_attachment_descriptors_ && + DeepComparePointer(vertex_descriptor_, other.vertex_descriptor_) && + stencil_pixel_format_ == other.stencil_pixel_format_ && + depth_pixel_format_ == other.depth_pixel_format_ && + depth_attachment_descriptor_ == other.depth_attachment_descriptor_ && + front_stencil_attachment_descriptor_ == + other.front_stencil_attachment_descriptor_ && + back_stencil_attachment_descriptor_ == + other.back_stencil_attachment_descriptor_ && + winding_order_ == other.winding_order_ && + cull_mode_ == other.cull_mode_ && + primitive_type_ == other.primitive_type_ && + polygon_mode_ == other.polygon_mode_ && + specialization_constants_ == other.specialization_constants_; +} + +PipelineDescriptor& PipelineDescriptor::SetLabel(std::string_view label) { + label_ = std::string(label); + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetSampleCount(SampleCount samples) { + sample_count_ = samples; + return *this; +} + +PipelineDescriptor& PipelineDescriptor::AddStageEntrypoint( + std::shared_ptr function) { + if (!function) { + return *this; + } + + if (function->GetStage() == ShaderStage::kUnknown) { + return *this; + } + + entrypoints_[function->GetStage()] = std::move(function); + + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetVertexDescriptor( + std::shared_ptr vertex_descriptor) { + vertex_descriptor_ = std::move(vertex_descriptor); + return *this; +} + +size_t PipelineDescriptor::GetMaxColorAttacmentBindIndex() const { + size_t max = 0; + for (const auto& color : color_attachment_descriptors_) { + max = std::max(color.first, max); + } + return max; +} + +PipelineDescriptor& PipelineDescriptor::SetColorAttachmentDescriptor( + size_t index, + ColorAttachmentDescriptor desc) { + color_attachment_descriptors_[index] = desc; + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetColorAttachmentDescriptors( + std::map descriptors) { + color_attachment_descriptors_ = std::move(descriptors); + return *this; +} + +const ColorAttachmentDescriptor* +PipelineDescriptor::GetColorAttachmentDescriptor(size_t index) const { + auto found = color_attachment_descriptors_.find(index); + return found == color_attachment_descriptors_.end() ? nullptr + : &found->second; +} + +const ColorAttachmentDescriptor* +PipelineDescriptor::GetLegacyCompatibleColorAttachment() const { + // Legacy renderers may only render to a single color attachment at index 0u. + if (color_attachment_descriptors_.size() != 1u) { + return nullptr; + } + return GetColorAttachmentDescriptor(0u); +} + +PipelineDescriptor& PipelineDescriptor::SetDepthPixelFormat( + PixelFormat format) { + depth_pixel_format_ = format; + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetStencilPixelFormat( + PixelFormat format) { + stencil_pixel_format_ = format; + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetDepthStencilAttachmentDescriptor( + std::optional desc) { + depth_attachment_descriptor_ = desc; + return *this; +} + +PipelineDescriptor& PipelineDescriptor::SetStencilAttachmentDescriptors( + std::optional front_and_back) { + return SetStencilAttachmentDescriptors(front_and_back, front_and_back); +} + +PipelineDescriptor& PipelineDescriptor::SetStencilAttachmentDescriptors( + std::optional front, + std::optional back) { + front_stencil_attachment_descriptor_ = front; + back_stencil_attachment_descriptor_ = back; + return *this; +} + +void PipelineDescriptor::ClearStencilAttachments() { + back_stencil_attachment_descriptor_.reset(); + front_stencil_attachment_descriptor_.reset(); + SetStencilPixelFormat(impeller::PixelFormat::kUnknown); +} + +void PipelineDescriptor::ClearDepthAttachment() { + depth_attachment_descriptor_.reset(); + SetDepthPixelFormat(impeller::PixelFormat::kUnknown); +} + +void PipelineDescriptor::ClearColorAttachment(size_t index) { + if (color_attachment_descriptors_.find(index) == + color_attachment_descriptors_.end()) { + return; + } + + color_attachment_descriptors_.erase(index); +} + +void PipelineDescriptor::ResetAttachments() { + color_attachment_descriptors_.clear(); + depth_attachment_descriptor_.reset(); + front_stencil_attachment_descriptor_.reset(); + back_stencil_attachment_descriptor_.reset(); +} + +PixelFormat PipelineDescriptor::GetStencilPixelFormat() const { + return stencil_pixel_format_; +} + +std::optional +PipelineDescriptor::GetFrontStencilAttachmentDescriptor() const { + return front_stencil_attachment_descriptor_; +} + +std::optional +PipelineDescriptor::GetDepthStencilAttachmentDescriptor() const { + return depth_attachment_descriptor_; +} + +const std::map& +PipelineDescriptor::GetColorAttachmentDescriptors() const { + return color_attachment_descriptors_; +} + +const std::shared_ptr& +PipelineDescriptor::GetVertexDescriptor() const { + return vertex_descriptor_; +} + +const std::map>& +PipelineDescriptor::GetStageEntrypoints() const { + return entrypoints_; +} + +std::shared_ptr PipelineDescriptor::GetEntrypointForStage( + ShaderStage stage) const { + if (auto found = entrypoints_.find(stage); found != entrypoints_.end()) { + return found->second; + } + return nullptr; +} + +std::string_view PipelineDescriptor::GetLabel() const { + return label_; +} + +PixelFormat PipelineDescriptor::GetDepthPixelFormat() const { + return depth_pixel_format_; +} + +std::optional +PipelineDescriptor::GetBackStencilAttachmentDescriptor() const { + return back_stencil_attachment_descriptor_; +} + +bool PipelineDescriptor::HasStencilAttachmentDescriptors() const { + return front_stencil_attachment_descriptor_.has_value() || + back_stencil_attachment_descriptor_.has_value(); +} + +void PipelineDescriptor::SetCullMode(CullMode mode) { + cull_mode_ = mode; +} + +CullMode PipelineDescriptor::GetCullMode() const { + return cull_mode_; +} + +void PipelineDescriptor::SetWindingOrder(WindingOrder order) { + winding_order_ = order; +} + +WindingOrder PipelineDescriptor::GetWindingOrder() const { + return winding_order_; +} + +void PipelineDescriptor::SetPrimitiveType(PrimitiveType type) { + primitive_type_ = type; +} + +PrimitiveType PipelineDescriptor::GetPrimitiveType() const { + return primitive_type_; +} + +void PipelineDescriptor::SetPolygonMode(PolygonMode mode) { + polygon_mode_ = mode; +} + +PolygonMode PipelineDescriptor::GetPolygonMode() const { + return polygon_mode_; +} + +void PipelineDescriptor::SetSpecializationConstants( + std::vector values) { + specialization_constants_ = std::move(values); +} + +const std::vector& PipelineDescriptor::GetSpecializationConstants() + const { + return specialization_constants_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.h b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..83eb56f986f6500e62cdf09350ed2b61b71e6f8c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor.h @@ -0,0 +1,155 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_DESCRIPTOR_H_ +#define FLUTTER_IMPELLER_RENDERER_PIPELINE_DESCRIPTOR_H_ + +#include +#include +#include + +#include "impeller/base/comparable.h" +#include "impeller/core/formats.h" +#include "impeller/core/shader_types.h" +#include "impeller/tessellator/tessellator.h" + +namespace impeller { + +class ShaderFunction; +class VertexDescriptor; +template +class Pipeline; + +class PipelineDescriptor final : public Comparable { + public: + PipelineDescriptor(); + + ~PipelineDescriptor(); + + PipelineDescriptor& SetLabel(std::string_view label); + + std::string_view GetLabel() const; + + PipelineDescriptor& SetSampleCount(SampleCount samples); + + SampleCount GetSampleCount() const { return sample_count_; } + + PipelineDescriptor& AddStageEntrypoint( + std::shared_ptr function); + + const std::map>& + GetStageEntrypoints() const; + + std::shared_ptr GetEntrypointForStage( + ShaderStage stage) const; + + PipelineDescriptor& SetVertexDescriptor( + std::shared_ptr vertex_descriptor); + + const std::shared_ptr& GetVertexDescriptor() const; + + size_t GetMaxColorAttacmentBindIndex() const; + + PipelineDescriptor& SetColorAttachmentDescriptor( + size_t index, + ColorAttachmentDescriptor desc); + + PipelineDescriptor& SetColorAttachmentDescriptors( + std::map descriptors); + + const ColorAttachmentDescriptor* GetColorAttachmentDescriptor( + size_t index) const; + + const std::map& + GetColorAttachmentDescriptors() const; + + const ColorAttachmentDescriptor* GetLegacyCompatibleColorAttachment() const; + + PipelineDescriptor& SetDepthStencilAttachmentDescriptor( + std::optional desc); + + std::optional GetDepthStencilAttachmentDescriptor() + const; + + PipelineDescriptor& SetStencilAttachmentDescriptors( + std::optional front_and_back); + + PipelineDescriptor& SetStencilAttachmentDescriptors( + std::optional front, + std::optional back); + + void ClearStencilAttachments(); + + void ClearDepthAttachment(); + + void ClearColorAttachment(size_t index); + + std::optional + GetFrontStencilAttachmentDescriptor() const; + + std::optional + GetBackStencilAttachmentDescriptor() const; + + bool HasStencilAttachmentDescriptors() const; + + PipelineDescriptor& SetDepthPixelFormat(PixelFormat format); + + PixelFormat GetDepthPixelFormat() const; + + PipelineDescriptor& SetStencilPixelFormat(PixelFormat format); + + PixelFormat GetStencilPixelFormat() const; + + // Comparable + std::size_t GetHash() const override; + + // Comparable + bool IsEqual(const PipelineDescriptor& other) const override; + + void ResetAttachments(); + + void SetCullMode(CullMode mode); + + CullMode GetCullMode() const; + + void SetWindingOrder(WindingOrder order); + + WindingOrder GetWindingOrder() const; + + void SetPrimitiveType(PrimitiveType type); + + PrimitiveType GetPrimitiveType() const; + + void SetPolygonMode(PolygonMode mode); + + PolygonMode GetPolygonMode() const; + + void SetSpecializationConstants(std::vector values); + + const std::vector& GetSpecializationConstants() const; + + private: + std::string label_; + SampleCount sample_count_ = SampleCount::kCount1; + WindingOrder winding_order_ = WindingOrder::kClockwise; + CullMode cull_mode_ = CullMode::kNone; + std::map> entrypoints_; + std::map + color_attachment_descriptors_; + std::shared_ptr vertex_descriptor_; + PixelFormat depth_pixel_format_ = PixelFormat::kUnknown; + PixelFormat stencil_pixel_format_ = PixelFormat::kUnknown; + std::optional depth_attachment_descriptor_; + std::optional + front_stencil_attachment_descriptor_; + std::optional + back_stencil_attachment_descriptor_; + PrimitiveType primitive_type_ = PrimitiveType::kTriangle; + PolygonMode polygon_mode_ = PolygonMode::kFill; + std::vector specialization_constants_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_DESCRIPTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..88e038c05107feb033958e1497ab468eaf764fb8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_descriptor_unittests.cc @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/testing/testing.h" +#include "impeller/renderer/pipeline_descriptor.h" + +namespace impeller { +namespace testing { + +TEST(PipelineDescriptorTest, PrimitiveTypeHashEquality) { + PipelineDescriptor descA; + PipelineDescriptor descB; + + ASSERT_TRUE(descA.IsEqual(descB)); + ASSERT_EQ(descA.GetHash(), descB.GetHash()); + + descA.SetPrimitiveType(PrimitiveType::kTriangleStrip); + + ASSERT_FALSE(descA.IsEqual(descB)); + ASSERT_NE(descA.GetHash(), descB.GetHash()); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_library.cc b/flutter/engine/src/flutter/impeller/renderer/pipeline_library.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef4950b8191d27379f5495be694fbd3b1e34ad2b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_library.cc @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/pipeline_library.h" + +namespace impeller { + +PipelineLibrary::PipelineLibrary() = default; + +PipelineLibrary::~PipelineLibrary() = default; + +PipelineFuture PipelineLibrary::GetPipeline( + std::optional descriptor, + bool async) { + if (descriptor.has_value()) { + return GetPipeline(descriptor.value(), async); + } + auto promise = std::make_shared< + std::promise>>>(); + promise->set_value(nullptr); + return {descriptor, promise->get_future()}; +} + +PipelineFuture PipelineLibrary::GetPipeline( + std::optional descriptor, + bool async) { + if (descriptor.has_value()) { + return GetPipeline(descriptor.value(), async); + } + auto promise = std::make_shared< + std::promise>>>(); + promise->set_value(nullptr); + return {descriptor, promise->get_future()}; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/pipeline_library.h b/flutter/engine/src/flutter/impeller/renderer/pipeline_library.h new file mode 100644 index 0000000000000000000000000000000000000000..f44b4e1dbb503ee6d8208721be11ce825f351582 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pipeline_library.h @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_ +#define FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_ + +#include + +#include "compute_pipeline_descriptor.h" +#include "impeller/renderer/pipeline.h" +#include "impeller/renderer/pipeline_descriptor.h" + +namespace impeller { + +class Context; + +using PipelineMap = std::unordered_map, + ComparableHash, + ComparableEqual>; + +using ComputePipelineMap = + std::unordered_map, + ComparableHash, + ComparableEqual>; + +class PipelineLibrary : public std::enable_shared_from_this { + public: + virtual ~PipelineLibrary(); + + PipelineFuture GetPipeline( + std::optional descriptor, + bool async = true); + + PipelineFuture GetPipeline( + std::optional descriptor, + bool async = true); + + virtual bool IsValid() const = 0; + + virtual PipelineFuture GetPipeline( + PipelineDescriptor descriptor, + bool async = true) = 0; + + virtual PipelineFuture GetPipeline( + ComputePipelineDescriptor descriptor, + bool async = true) = 0; + + virtual bool HasPipeline(const PipelineDescriptor& descriptor) = 0; + + virtual void RemovePipelinesWithEntryPoint( + std::shared_ptr function) = 0; + + protected: + PipelineLibrary(); + + private: + PipelineLibrary(const PipelineLibrary&) = delete; + + PipelineLibrary& operator=(const PipelineLibrary&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/pool.h b/flutter/engine/src/flutter/impeller/renderer/pool.h new file mode 100644 index 0000000000000000000000000000000000000000..399236fd238b311e92e24c06a3355d2cc3fccdb1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pool.h @@ -0,0 +1,58 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_POOL_H_ +#define FLUTTER_IMPELLER_RENDERER_POOL_H_ + +#include +#include +#include + +namespace impeller { + +/// @brief A thread-safe pool with a limited byte size. +/// @tparam T The type that the pool will contain. +template +class Pool { + public: + explicit Pool(uint32_t limit_bytes) : limit_bytes_(limit_bytes) {} + + std::shared_ptr Grab() { + std::scoped_lock lock(mutex_); + if (pool_.empty()) { + return T::Create(); + } + std::shared_ptr result = std::move(pool_.back()); + pool_.pop_back(); + size_ -= result->GetSize(); + return result; + } + + void Recycle(std::shared_ptr object) { + std::scoped_lock lock(mutex_); + size_t object_size = object->GetSize(); + if (size_ + object_size <= limit_bytes_ && + object_size < (limit_bytes_ / 2)) { + object->Reset(); + size_ += object_size; + pool_.emplace_back(std::move(object)); + } + } + + uint32_t GetSize() const { + std::scoped_lock lock(mutex_); + return size_; + } + + private: + std::vector> pool_; + const uint32_t limit_bytes_; + uint32_t size_ = 0; + // Note: This would perform better as a lockless ring buffer. + mutable std::mutex mutex_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_POOL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/pool_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/pool_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..65c7d84f5676bf3a2f87716c3183d60039d1d33e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/pool_unittests.cc @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "gtest/gtest.h" + +#include "impeller/renderer/pool.h" + +namespace impeller { +namespace testing { + +namespace { +class Foobar { + public: + static std::shared_ptr Create() { return std::make_shared(); } + + size_t GetSize() const { return size_; } + + void SetSize(size_t size) { size_ = size; } + + void Reset() { is_reset_ = true; } + + bool GetIsReset() const { return is_reset_; } + + void SetIsReset(bool is_reset) { is_reset_ = is_reset; } + + private: + size_t size_; + bool is_reset_ = false; +}; +} // namespace + +TEST(PoolTest, Simple) { + Pool pool(1'000); + { + auto grabbed = pool.Grab(); + grabbed->SetSize(123); + pool.Recycle(grabbed); + EXPECT_EQ(pool.GetSize(), 123u); + } + auto grabbed = pool.Grab(); + EXPECT_EQ(grabbed->GetSize(), 123u); + EXPECT_TRUE(grabbed->GetIsReset()); + EXPECT_EQ(pool.GetSize(), 0u); +} + +TEST(PoolTest, Overload) { + Pool pool(1'000); + { + std::vector> values; + values.reserve(20); + for (int i = 0; i < 20; i++) { + values.push_back(pool.Grab()); + } + for (const auto& value : values) { + value->SetSize(100); + pool.Recycle(value); + } + } + EXPECT_EQ(pool.GetSize(), 1'000u); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/prefix_sum_test.comp b/flutter/engine/src/flutter/impeller/renderer/prefix_sum_test.comp new file mode 100644 index 0000000000000000000000000000000000000000..7cc940fb1251e9a3cd90ef1898946103ac752fe0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/prefix_sum_test.comp @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +layout(local_size_x_id = 0) in; +layout(std430) buffer; + +#include + +#define BLOCK_SIZE 1024 + +layout(binding = 0) readonly buffer InputData { + uint count; + uint data[]; +} +input_data; + +layout(binding = 1) writeonly buffer OutputData { + uint data[]; +} +output_data; + +// Needs to be number of threads per threadgroup. +shared uint memory[BLOCK_SIZE]; + +void main() { + uint ident = gl_GlobalInvocationID.x; + + uint value = 0; + if (ident < input_data.count) { + value = input_data.data[ident]; + } + + if (ident < BLOCK_SIZE) { + memory[ident] = value; + } + + barrier(); + + ExclusivePrefixSum(ident, memory, BLOCK_SIZE); + + if (ident < input_data.count) { + // Convert exclusive to inclusive sum. + output_data.data[ident] = memory[ident] + value; + } +} diff --git a/flutter/engine/src/flutter/impeller/renderer/render_pass.cc b/flutter/engine/src/flutter/impeller/renderer/render_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..73626e28ac163d4fd07b1e9c511d3e28a3e62434 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/render_pass.cc @@ -0,0 +1,322 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/render_pass.h" + +#include +#include "fml/status.h" +#include "impeller/base/validation.h" +#include "impeller/core/vertex_buffer.h" + +namespace impeller { + +RenderPass::RenderPass(std::shared_ptr context, + const RenderTarget& target) + : context_(std::move(context)), + sample_count_(target.GetSampleCount()), + pixel_format_(target.GetRenderTargetPixelFormat()), + has_depth_attachment_(target.GetDepthAttachment().has_value()), + has_stencil_attachment_(target.GetStencilAttachment().has_value()), + render_target_size_(target.GetRenderTargetSize()), + render_target_(target), + orthographic_(Matrix::MakeOrthographic(render_target_size_)) {} + +RenderPass::~RenderPass() {} + +SampleCount RenderPass::GetSampleCount() const { + return sample_count_; +} + +PixelFormat RenderPass::GetRenderTargetPixelFormat() const { + return pixel_format_; +} + +bool RenderPass::HasDepthAttachment() const { + return has_depth_attachment_; +} + +bool RenderPass::HasStencilAttachment() const { + return has_stencil_attachment_; +} + +const RenderTarget& RenderPass::GetRenderTarget() const { + return render_target_; +} + +ISize RenderPass::GetRenderTargetSize() const { + return render_target_size_; +} + +const Matrix& RenderPass::GetOrthographicTransform() const { + return orthographic_; +} + +void RenderPass::SetLabel(std::string_view label) { + if (label.empty()) { + return; + } + OnSetLabel(label); +} + +bool RenderPass::AddCommand(Command&& command) { + if (!command.IsValid()) { + VALIDATION_LOG << "Attempted to add an invalid command to the render pass."; + return false; + } + + if (command.element_count == 0u || command.instance_count == 0u) { + // Essentially a no-op. Don't record the command but this is not necessary + // an error either. + return true; + } + + commands_.emplace_back(std::move(command)); + return true; +} + +bool RenderPass::EncodeCommands() const { + return OnEncodeCommands(*context_); +} + +const std::shared_ptr& RenderPass::GetContext() const { + return context_; +} + +void RenderPass::SetPipeline(PipelineRef pipeline) { + // On debug this makes a difference, but not on release builds. + // NOLINTNEXTLINE(performance-move-const-arg) + pending_.pipeline = std::move(pipeline); +} + +void RenderPass::SetPipeline( + const std::shared_ptr>& pipeline) { + SetPipeline(PipelineRef(pipeline)); +} + +void RenderPass::SetCommandLabel(std::string_view label) { +#ifdef IMPELLER_DEBUG + pending_.label = std::string(label); +#endif // IMPELLER_DEBUG +} + +void RenderPass::SetStencilReference(uint32_t value) { + pending_.stencil_reference = value; +} + +void RenderPass::SetBaseVertex(uint64_t value) { + pending_.base_vertex = value; +} + +void RenderPass::SetViewport(Viewport viewport) { + pending_.viewport = viewport; +} + +void RenderPass::SetScissor(IRect scissor) { + pending_.scissor = scissor; +} + +void RenderPass::SetElementCount(size_t count) { + pending_.element_count = count; +} + +void RenderPass::SetInstanceCount(size_t count) { + pending_.instance_count = count; +} + +bool RenderPass::SetVertexBuffer(VertexBuffer buffer) { + if (!SetVertexBuffer(&buffer.vertex_buffer, 1u)) { + return false; + } + if (!SetIndexBuffer(buffer.index_buffer, buffer.index_type)) { + return false; + } + SetElementCount(buffer.vertex_count); + + return true; +} + +bool RenderPass::SetVertexBuffer(BufferView vertex_buffer) { + return SetVertexBuffer(&vertex_buffer, 1); +} + +bool RenderPass::SetVertexBuffer(std::vector vertex_buffers) { + return SetVertexBuffer(vertex_buffers.data(), vertex_buffers.size()); +} + +bool RenderPass::SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count) { + if (!ValidateVertexBuffers(vertex_buffers, vertex_buffer_count)) { + return false; + } + + if (!vertex_buffers_start_.has_value()) { + vertex_buffers_start_ = vertex_buffers_.size(); + } + + pending_.vertex_buffers.length += vertex_buffer_count; + for (size_t i = 0; i < vertex_buffer_count; i++) { + vertex_buffers_.push_back(vertex_buffers[i]); + } + return true; +} + +bool RenderPass::SetIndexBuffer(BufferView index_buffer, IndexType index_type) { + if (!ValidateIndexBuffer(index_buffer, index_type)) { + return false; + } + + pending_.index_buffer = std::move(index_buffer); + pending_.index_type = index_type; + return true; +} + +bool RenderPass::ValidateVertexBuffers(const BufferView vertex_buffers[], + size_t vertex_buffer_count) { + if (vertex_buffer_count > kMaxVertexBuffers) { + VALIDATION_LOG << "Attempted to bind " << vertex_buffer_count + << " vertex buffers, but the maximum is " + << kMaxVertexBuffers << "."; + return false; + } + + for (size_t i = 0; i < vertex_buffer_count; i++) { + if (!vertex_buffers[i]) { + VALIDATION_LOG << "Attempted to bind an invalid vertex buffer."; + return false; + } + } + + return true; +} + +bool RenderPass::ValidateIndexBuffer(const BufferView& index_buffer, + IndexType index_type) { + if (index_type == IndexType::kUnknown) { + VALIDATION_LOG << "Cannot bind an index buffer with an unknown index type."; + return false; + } + + if (index_type != IndexType::kNone && !index_buffer) { + VALIDATION_LOG << "Attempted to bind an invalid index buffer."; + return false; + } + + return true; +} + +fml::Status RenderPass::Draw() { + pending_.bound_buffers.offset = bound_buffers_start_.value_or(0u); + pending_.bound_textures.offset = bound_textures_start_.value_or(0u); + pending_.vertex_buffers.offset = vertex_buffers_start_.value_or(0u); + auto result = AddCommand(std::move(pending_)); + pending_ = Command{}; + bound_textures_start_ = std::nullopt; + bound_buffers_start_ = std::nullopt; + vertex_buffers_start_ = std::nullopt; + if (result) { + return fml::Status(); + } + return fml::Status(fml::StatusCode::kInvalidArgument, + "Failed to encode command"); +} + +// |ResourceBinder| +bool RenderPass::BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) { + FML_DCHECK(slot.ext_res_0 != VertexDescriptor::kReservedVertexBufferIndex); + if (!view) { + return false; + } + BufferResource resouce = BufferResource(metadata, std::move(view)); + return BindBuffer(stage, slot, std::move(resouce)); +} + +// |ResourceBinder| +bool RenderPass::BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr sampler) { + if (!sampler) { + return false; + } + if (!texture || !texture->IsValid()) { + return false; + } + TextureResource resource = TextureResource(metadata, std::move(texture)); + return BindTexture(stage, slot, std::move(resource), sampler); +} + +bool RenderPass::BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view) { + FML_DCHECK(slot.ext_res_0 != VertexDescriptor::kReservedVertexBufferIndex); + if (!view) { + return false; + } + BufferResource resouce = + BufferResource::MakeDynamic(std::move(metadata), std::move(view)); + + return BindBuffer(stage, slot, std::move(resouce)); +} + +bool RenderPass::BindDynamicResource( + ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr + sampler // NOLINT(performance-unnecessary-value-param) +) { + if (!sampler) { + return false; + } + if (!texture || !texture->IsValid()) { + return false; + } + TextureResource resource = + TextureResource::MakeDynamic(std::move(metadata), std::move(texture)); + return BindTexture(stage, slot, std::move(resource), sampler); +} + +bool RenderPass::BindBuffer(ShaderStage stage, + const ShaderUniformSlot& slot, + BufferResource resource) { + if (!bound_buffers_start_.has_value()) { + bound_buffers_start_ = bound_buffers_.size(); + } + + pending_.bound_buffers.length++; + bound_buffers_.push_back(std::move(resource)); + return true; +} + +bool RenderPass::BindTexture(ShaderStage stage, + const SampledImageSlot& slot, + TextureResource resource, + raw_ptr sampler) { + TextureAndSampler data = TextureAndSampler{ + .stage = stage, + .texture = std::move(resource), + // NOLINTNEXTLINE(performance-move-const-arg) + .sampler = sampler, + }; + + if (!bound_textures_start_.has_value()) { + bound_textures_start_ = bound_textures_.size(); + } + + pending_.bound_textures.length++; + bound_textures_.push_back(std::move(data)); + return true; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/render_pass.h b/flutter/engine/src/flutter/impeller/renderer/render_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..dcc6493dedc51d6d8c36f3d60586ae8527037532 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/render_pass.h @@ -0,0 +1,300 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_ +#define FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_ + +#include + +#include "fml/status.h" +#include "impeller/core/formats.h" +#include "impeller/core/resource_binder.h" +#include "impeller/core/shader_types.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/renderer/command.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_target.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Render passes encode render commands directed as one specific +/// render target into an underlying command buffer. +/// +/// Render passes can be obtained from the command buffer in which +/// the pass is meant to encode commands into. +/// +/// @see `CommandBuffer` +/// +class RenderPass : public ResourceBinder { + public: + virtual ~RenderPass(); + + const std::shared_ptr& GetContext() const; + + const RenderTarget& GetRenderTarget() const; + + ISize GetRenderTargetSize() const; + + const Matrix& GetOrthographicTransform() const; + + virtual bool IsValid() const = 0; + + void SetLabel(std::string_view label); + + //---------------------------------------------------------------------------- + /// The pipeline to use for this command. + virtual void SetPipeline(PipelineRef pipeline); + + //---------------------------------------------------------------------------- + /// The pipeline to use for this command. + void SetPipeline( + const std::shared_ptr>& pipeline); + + //---------------------------------------------------------------------------- + /// The debugging label to use for the command. + virtual void SetCommandLabel(std::string_view label); + + //---------------------------------------------------------------------------- + /// The reference value to use in stenciling operations. Stencil configuration + /// is part of pipeline setup and can be read from the pipelines descriptor. + /// + /// @see `Pipeline` + /// @see `PipelineDescriptor` + /// + virtual void SetStencilReference(uint32_t value); + + virtual void SetBaseVertex(uint64_t value); + + //---------------------------------------------------------------------------- + /// The viewport coordinates that the rasterizer linearly maps normalized + /// device coordinates to. + /// If unset, the viewport is the size of the render target with a zero + /// origin, znear=0, and zfar=1. + /// + virtual void SetViewport(Viewport viewport); + + //---------------------------------------------------------------------------- + /// The scissor rect to use for clipping writes to the render target. The + /// scissor rect must lie entirely within the render target. + /// If unset, no scissor is applied. + /// + virtual void SetScissor(IRect scissor); + + //---------------------------------------------------------------------------- + /// The number of elements to draw. When only a vertex buffer is set, this is + /// the vertex count. When an index buffer is set, this is the index count. + /// + virtual void SetElementCount(size_t count); + + //---------------------------------------------------------------------------- + /// The number of instances of the given set of vertices to render. Not all + /// backends support rendering more than one instance at a time. + /// + /// @warning Setting this to more than one will limit the availability of + /// backends to use with this command. + /// + virtual void SetInstanceCount(size_t count); + + //---------------------------------------------------------------------------- + /// @deprecated Use SetVertexBuffer(BufferView[], size_t, size_t) instead. + /// + /// @brief Specify the vertex and index buffer to use for this command. + /// + /// @param[in] buffer The vertex and index buffer definition. If possible, + /// this value should be moved and not copied. + /// + /// @return returns if the binding was updated. + /// + virtual bool SetVertexBuffer(VertexBuffer buffer); + + //---------------------------------------------------------------------------- + /// @brief Specify a vertex buffer to use for this command. + /// + /// @param[in] vertex_buffer The buffer view to use for sourcing vertices. + /// + /// @return Returns false if the given buffer view is invalid. + /// + bool SetVertexBuffer(BufferView vertex_buffer); + + //---------------------------------------------------------------------------- + /// @brief Specify a set of vertex buffers to use for this command. + /// + /// @warning This method takes ownership of each buffer view in the vector. + /// Attempting to use the given buffer views after this call is + /// invalid. + /// + /// @param[in] vertex_buffers The array of vertex buffer views to use. + /// The maximum number of vertex buffers is 16. + /// + /// @return Returns false if any of the given buffer views are invalid. + /// + bool SetVertexBuffer(std::vector vertex_buffers); + + //---------------------------------------------------------------------------- + /// @brief Specify a set of vertex buffers to use for this command. + /// + /// @warning This method takes ownership of each buffer view in the vector. + /// Attempting to use the given buffer views after this call is + /// invalid. + /// + /// @param[in] vertex_buffers Pointer to an array of vertex buffers to + /// be copied. The maximum number of vertex + /// buffers is 16. + /// + /// @param[in] vertex_buffer_count The number of vertex buffers to copy from + /// the array (max 16). + /// + /// @return Returns false if any of the given buffer views are invalid. + /// + virtual bool SetVertexBuffer(BufferView vertex_buffers[], + size_t vertex_buffer_count); + + //---------------------------------------------------------------------------- + /// @brief Specify an index buffer to use for this command. + /// To unset the index buffer, pass IndexType::kNone to + /// index_type. + /// + /// @param[in] index_buffer The buffer view to use for sourcing indices. + /// When an index buffer is bound, the + /// `vertex_count` set via `SetVertexBuffer` is used + /// as the number of indices to draw. + /// + /// @param[in] index_type The size of each index in the index buffer. Pass + /// IndexType::kNone to unset the index buffer. + /// + /// @return Returns false if the index buffer view is invalid. + /// + virtual bool SetIndexBuffer(BufferView index_buffer, IndexType index_type); + + /// Record the currently pending command. + virtual fml::Status Draw(); + + // |ResourceBinder| + virtual bool BindResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + const ShaderMetadata* metadata, + BufferView view) override; + + // |ResourceBinder| + virtual bool BindResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + const ShaderMetadata* metadata, + std::shared_ptr texture, + raw_ptr) override; + + /// @brief Bind with dynamically generated shader metadata. + virtual bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const SampledImageSlot& slot, + std::unique_ptr metadata, + std::shared_ptr texture, + raw_ptr); + + /// @brief Bind with dynamically generated shader metadata. + virtual bool BindDynamicResource(ShaderStage stage, + DescriptorType type, + const ShaderUniformSlot& slot, + std::unique_ptr metadata, + BufferView view); + + //---------------------------------------------------------------------------- + /// @brief Encode the recorded commands to the underlying command buffer. + /// + /// @return If the commands were encoded to the underlying command + /// buffer. + /// + bool EncodeCommands() const; + + //---------------------------------------------------------------------------- + /// @brief Accessor for the current Commands. + /// + /// @details Visible for testing. + /// + virtual const std::vector& GetCommands() const { return commands_; } + + //---------------------------------------------------------------------------- + /// @brief The sample count of the attached render target. + SampleCount GetSampleCount() const; + + //---------------------------------------------------------------------------- + /// @brief The pixel format of the attached render target. + PixelFormat GetRenderTargetPixelFormat() const; + + //---------------------------------------------------------------------------- + /// @brief Whether the render target has a depth attachment. + bool HasDepthAttachment() const; + + //---------------------------------------------------------------------------- + /// @brief Whether the render target has an stencil attachment. + bool HasStencilAttachment() const; + + protected: + const std::shared_ptr context_; + // The following properties: sample_count, pixel_format, + // has_stencil_attachment, and render_target_size are cached on the + // RenderTarget to speed up numerous lookups during rendering. This is safe as + // the RenderTarget itself is copied into the RenderTarget and only exposed as + // a const reference. + const SampleCount sample_count_; + const PixelFormat pixel_format_; + const bool has_depth_attachment_; + const bool has_stencil_attachment_; + const ISize render_target_size_; + const RenderTarget render_target_; + std::vector commands_; + std::vector vertex_buffers_; + std::vector bound_buffers_; + std::vector bound_textures_; + const Matrix orthographic_; + + //---------------------------------------------------------------------------- + /// @brief Record a command for subsequent encoding to the underlying + /// command buffer. No work is encoded into the command buffer at + /// this time. + /// + /// @param[in] command The command + /// + /// @return If the command was valid for subsequent commitment. + /// + bool AddCommand(Command&& command); + + RenderPass(std::shared_ptr context, + const RenderTarget& target); + + static bool ValidateVertexBuffers(const BufferView vertex_buffers[], + size_t vertex_buffer_count); + + static bool ValidateIndexBuffer(const BufferView& index_buffer, + IndexType index_type); + + virtual void OnSetLabel(std::string_view label) = 0; + + virtual bool OnEncodeCommands(const Context& context) const = 0; + + private: + RenderPass(const RenderPass&) = delete; + + RenderPass& operator=(const RenderPass&) = delete; + + bool BindBuffer(ShaderStage stage, + const ShaderUniformSlot& slot, + BufferResource resource); + + bool BindTexture(ShaderStage stage, + const SampledImageSlot& slot, + TextureResource resource, + raw_ptr); + + Command pending_; + std::optional bound_buffers_start_ = std::nullopt; + std::optional bound_textures_start_ = std::nullopt; + std::optional vertex_buffers_start_ = std::nullopt; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_RENDER_PASS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/render_target.cc b/flutter/engine/src/flutter/impeller/renderer/render_target.cc new file mode 100644 index 0000000000000000000000000000000000000000..b3621e706b659a5b6dc11e4019685d0b88bfbc80 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/render_target.cc @@ -0,0 +1,521 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/render_target.h" + +#include + +#include "impeller/base/strings.h" +#include "impeller/base/validation.h" +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/core/texture.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +RenderTarget::RenderTarget() = default; + +RenderTarget::~RenderTarget() = default; + +bool RenderTarget::IsValid() const { + // Validate that there is a color attachment at zero index. + if (!HasColorAttachment(0u)) { + VALIDATION_LOG + << "Render target does not have color attachment at index 0."; + return false; + } + +#ifndef NDEBUG + // Validate that all attachments are of the same size. + { + std::optional size; + bool sizes_are_same = true; + auto iterator = [&](const Attachment& attachment) -> bool { + if (!size.has_value()) { + size = attachment.texture->GetSize(); + } + if (size != attachment.texture->GetSize()) { + sizes_are_same = false; + return false; + } + return true; + }; + IterateAllAttachments(iterator); + if (!sizes_are_same) { + VALIDATION_LOG + << "Sizes of all render target attachments are not the same."; + return false; + } + } + + // Validate that all attachments are of the same type and sample counts. + { + std::optional texture_type; + std::optional sample_count; + bool passes_type_validation = true; + auto iterator = [&](const Attachment& attachment) -> bool { + if (!texture_type.has_value() || !sample_count.has_value()) { + texture_type = attachment.texture->GetTextureDescriptor().type; + sample_count = attachment.texture->GetTextureDescriptor().sample_count; + } + + if (texture_type != attachment.texture->GetTextureDescriptor().type) { + passes_type_validation = false; + VALIDATION_LOG << "Render target has incompatible texture types: " + << TextureTypeToString(texture_type.value()) << " != " + << TextureTypeToString( + attachment.texture->GetTextureDescriptor().type) + << " on target " << ToString(); + return false; + } + + if (sample_count != + attachment.texture->GetTextureDescriptor().sample_count) { + passes_type_validation = false; + VALIDATION_LOG << "Render target (" << ToString() + << ") has incompatible sample counts."; + + return false; + } + + return true; + }; + IterateAllAttachments(iterator); + if (!passes_type_validation) { + return false; + } + } +#endif // NDEBUG + + return true; +} + +bool RenderTarget::IterateAllColorAttachments( + const std::function& + iterator) const { + if (color0_.has_value()) { + if (!iterator(0, color0_.value())) { + return false; + } + } + for (const auto& [index, attachment] : colors_) { + if (!iterator(index, attachment)) { + return false; + } + } + return true; +} + +void RenderTarget::IterateAllAttachments( + const std::function& iterator) const { + if (color0_.has_value()) { + if (!iterator(color0_.value())) { + return; + } + } + for (const auto& color : colors_) { + if (!iterator(color.second)) { + return; + } + } + + if (depth_.has_value()) { + if (!iterator(depth_.value())) { + return; + } + } + + if (stencil_.has_value()) { + if (!iterator(stencil_.value())) { + return; + } + } +} + +SampleCount RenderTarget::GetSampleCount() const { + if (color0_.has_value()) { + return color0_.value().texture->GetTextureDescriptor().sample_count; + } + return SampleCount::kCount1; +} + +bool RenderTarget::HasColorAttachment(size_t index) const { + if (index == 0u) { + return color0_.has_value(); + } + if (auto found = colors_.find(index); found != colors_.end()) { + return true; + } + return false; +} + +std::optional RenderTarget::GetColorAttachmentSize(size_t index) const { + if (index == 0u) { + if (color0_.has_value()) { + return color0_.value().texture->GetSize(); + } + return std::nullopt; + } + auto found = colors_.find(index); + + if (found == colors_.end()) { + return std::nullopt; + } + + return found->second.texture->GetSize(); +} + +ISize RenderTarget::GetRenderTargetSize() const { + auto size = GetColorAttachmentSize(0u); + return size.has_value() ? size.value() : ISize{}; +} + +std::shared_ptr RenderTarget::GetRenderTargetTexture() const { + if (!color0_.has_value()) { + return nullptr; + } + return color0_->resolve_texture ? color0_->resolve_texture : color0_->texture; +} + +PixelFormat RenderTarget::GetRenderTargetPixelFormat() const { + if (auto texture = GetRenderTargetTexture(); texture != nullptr) { + return texture->GetTextureDescriptor().format; + } + + return PixelFormat::kUnknown; +} + +size_t RenderTarget::GetMaxColorAttacmentBindIndex() const { + size_t max = 0; + for (const auto& color : colors_) { + max = std::max(color.first, max); + } + return max; +} + +RenderTarget& RenderTarget::SetColorAttachment( + const ColorAttachment& attachment, + size_t index) { + if (!attachment.IsValid()) { + return *this; + } + if (index == 0u) { + color0_ = attachment; + } else { + colors_[index] = attachment; + } + return *this; +} + +RenderTarget& RenderTarget::SetDepthAttachment( + std::optional attachment) { + if (!attachment.has_value()) { + depth_ = std::nullopt; + } else if (attachment->IsValid()) { + depth_ = std::move(attachment); + } + return *this; +} + +RenderTarget& RenderTarget::SetStencilAttachment( + std::optional attachment) { + if (!attachment.has_value()) { + stencil_ = std::nullopt; + } else if (attachment->IsValid()) { + stencil_ = std::move(attachment); + } + return *this; +} + +ColorAttachment RenderTarget::GetColorAttachment(size_t index) const { + if (index == 0) { + if (color0_.has_value()) { + return color0_.value(); + } + return ColorAttachment{}; + } + std::map::const_iterator it = colors_.find(index); + if (it != colors_.end()) { + return it->second; + } + return ColorAttachment{}; +} + +const std::optional& RenderTarget::GetDepthAttachment() const { + return depth_; +} + +const std::optional& RenderTarget::GetStencilAttachment() + const { + return stencil_; +} + +size_t RenderTarget::GetTotalAttachmentCount() const { + size_t count = 0u; + for (const auto& [_, color] : colors_) { + if (color.texture) { + count++; + } + if (color.resolve_texture) { + count++; + } + } + if (color0_.has_value()) { + count++; + } + if (depth_.has_value()) { + count++; + } + if (stencil_.has_value()) { + count++; + } + return count; +} + +std::string RenderTarget::ToString() const { + std::stringstream stream; + + if (color0_.has_value()) { + stream << SPrintF("Color[%d]=(%s)", 0, + ColorAttachmentToString(color0_.value()).c_str()); + } + for (const auto& [index, color] : colors_) { + stream << SPrintF("Color[%zu]=(%s)", index, + ColorAttachmentToString(color).c_str()); + } + if (depth_) { + stream << ","; + stream << SPrintF("Depth=(%s)", + DepthAttachmentToString(depth_.value()).c_str()); + } + if (stencil_) { + stream << ","; + stream << SPrintF("Stencil=(%s)", + StencilAttachmentToString(stencil_.value()).c_str()); + } + return stream.str(); +} + +RenderTargetConfig RenderTarget::ToConfig() const { + if (!color0_.has_value()) { + return RenderTargetConfig{}; + } + const auto& color_attachment = color0_.value(); + return RenderTargetConfig{ + .size = color_attachment.texture->GetSize(), + .mip_count = color_attachment.texture->GetMipCount(), + .has_msaa = color_attachment.resolve_texture != nullptr, + .has_depth_stencil = depth_.has_value() && stencil_.has_value()}; +} + +RenderTargetAllocator::RenderTargetAllocator( + std::shared_ptr allocator) + : allocator_(std::move(allocator)) {} + +void RenderTargetAllocator::Start() {} + +void RenderTargetAllocator::End() {} + +RenderTarget RenderTargetAllocator::CreateOffscreen( + const Context& context, + ISize size, + int mip_count, + std::string_view label, + RenderTarget::AttachmentConfig color_attachment_config, + std::optional stencil_attachment_config, + const std::shared_ptr& existing_color_texture, + const std::shared_ptr& existing_depth_stencil_texture) { + if (size.IsEmpty()) { + return {}; + } + + RenderTarget target; + + std::shared_ptr color0_tex; + if (existing_color_texture) { + color0_tex = existing_color_texture; + } else { + PixelFormat pixel_format = + context.GetCapabilities()->GetDefaultColorFormat(); + TextureDescriptor color0_tex_desc; + color0_tex_desc.storage_mode = color_attachment_config.storage_mode; + color0_tex_desc.format = pixel_format; + color0_tex_desc.size = size; + color0_tex_desc.mip_count = mip_count; + color0_tex_desc.usage = + TextureUsage::kRenderTarget | TextureUsage::kShaderRead; + color0_tex = allocator_->CreateTexture(color0_tex_desc); + if (!color0_tex) { + return {}; + } + } + color0_tex->SetLabel(label, "Color Texture"); + + ColorAttachment color0; + color0.clear_color = color_attachment_config.clear_color; + color0.load_action = color_attachment_config.load_action; + color0.store_action = color_attachment_config.store_action; + color0.texture = color0_tex; + target.SetColorAttachment(color0, 0u); + + if (stencil_attachment_config.has_value()) { + target.SetupDepthStencilAttachments( + context, *allocator_, size, false, label, + stencil_attachment_config.value(), existing_depth_stencil_texture); + } else { + target.SetStencilAttachment(std::nullopt); + target.SetDepthAttachment(std::nullopt); + } + + return target; +} + +RenderTarget RenderTargetAllocator::CreateOffscreenMSAA( + const Context& context, + ISize size, + int mip_count, + std::string_view label, + RenderTarget::AttachmentConfigMSAA color_attachment_config, + std::optional stencil_attachment_config, + const std::shared_ptr& existing_color_msaa_texture, + const std::shared_ptr& existing_color_resolve_texture, + const std::shared_ptr& existing_depth_stencil_texture) { + if (size.IsEmpty()) { + return {}; + } + + RenderTarget target; + PixelFormat pixel_format = context.GetCapabilities()->GetDefaultColorFormat(); + + // Create MSAA color texture. + std::shared_ptr color0_msaa_tex; + if (existing_color_msaa_texture) { + color0_msaa_tex = existing_color_msaa_texture; + } else { + TextureDescriptor color0_tex_desc; + color0_tex_desc.storage_mode = color_attachment_config.storage_mode; + color0_tex_desc.type = TextureType::kTexture2DMultisample; + color0_tex_desc.sample_count = SampleCount::kCount4; + color0_tex_desc.format = pixel_format; + color0_tex_desc.size = size; + color0_tex_desc.usage = TextureUsage::kRenderTarget; + if (context.GetCapabilities()->SupportsImplicitResolvingMSAA()) { + // See below ("SupportsImplicitResolvingMSAA") for more details. + color0_tex_desc.storage_mode = StorageMode::kDevicePrivate; + } + color0_msaa_tex = allocator_->CreateTexture(color0_tex_desc); + if (!color0_msaa_tex) { + VALIDATION_LOG << "Could not create multisample color texture."; + return {}; + } + } + color0_msaa_tex->SetLabel(label, "Color Texture (Multisample)"); + + // Create color resolve texture. + std::shared_ptr color0_resolve_tex; + if (existing_color_resolve_texture) { + color0_resolve_tex = existing_color_resolve_texture; + } else { + TextureDescriptor color0_resolve_tex_desc; + color0_resolve_tex_desc.storage_mode = + color_attachment_config.resolve_storage_mode; + color0_resolve_tex_desc.format = pixel_format; + color0_resolve_tex_desc.size = size; + color0_resolve_tex_desc.compression_type = CompressionType::kLossy; + color0_resolve_tex_desc.usage = + TextureUsage::kRenderTarget | TextureUsage::kShaderRead; + color0_resolve_tex_desc.mip_count = mip_count; + color0_resolve_tex = allocator_->CreateTexture(color0_resolve_tex_desc); + if (!color0_resolve_tex) { + VALIDATION_LOG << "Could not create color texture."; + return {}; + } + } + color0_resolve_tex->SetLabel(label, "Color Texture"); + + // Color attachment. + + ColorAttachment color0; + color0.clear_color = color_attachment_config.clear_color; + color0.load_action = color_attachment_config.load_action; + color0.store_action = color_attachment_config.store_action; + color0.texture = color0_msaa_tex; + color0.resolve_texture = color0_resolve_tex; + + if (context.GetCapabilities()->SupportsImplicitResolvingMSAA()) { + // If implicit MSAA is supported, then the resolve texture is not needed + // because the multisample texture is automatically resolved. We instead + // provide a view of the multisample texture as the resolve texture (because + // the HAL does expect a resolve texture). + // + // In practice, this is used for GLES 2.0 EXT_multisampled_render_to_texture + // https://registry.khronos.org/OpenGL/extensions/EXT/EXT_multisampled_render_to_texture.txt + color0.resolve_texture = color0_msaa_tex; + } + + target.SetColorAttachment(color0, 0u); + + // Create MSAA stencil texture. + + if (stencil_attachment_config.has_value()) { + target.SetupDepthStencilAttachments(context, *allocator_, size, true, label, + stencil_attachment_config.value(), + existing_depth_stencil_texture); + } else { + target.SetDepthAttachment(std::nullopt); + target.SetStencilAttachment(std::nullopt); + } + + return target; +} + +void RenderTarget::SetupDepthStencilAttachments( + const Context& context, + Allocator& allocator, + ISize size, + bool msaa, + std::string_view label, + RenderTarget::AttachmentConfig stencil_attachment_config, + const std::shared_ptr& existing_depth_stencil_texture) { + std::shared_ptr depth_stencil_texture; + if (existing_depth_stencil_texture) { + depth_stencil_texture = existing_depth_stencil_texture; + } else { + TextureDescriptor depth_stencil_texture_desc; + depth_stencil_texture_desc.storage_mode = + stencil_attachment_config.storage_mode; + if (msaa) { + depth_stencil_texture_desc.type = TextureType::kTexture2DMultisample; + depth_stencil_texture_desc.sample_count = SampleCount::kCount4; + } + depth_stencil_texture_desc.format = + context.GetCapabilities()->GetDefaultDepthStencilFormat(); + depth_stencil_texture_desc.size = size; + depth_stencil_texture_desc.usage = TextureUsage::kRenderTarget; + depth_stencil_texture = allocator.CreateTexture(depth_stencil_texture_desc); + if (!depth_stencil_texture) { + return; // Error messages are handled by `Allocator::CreateTexture`. + } + } + + DepthAttachment depth0; + depth0.load_action = stencil_attachment_config.load_action; + depth0.store_action = stencil_attachment_config.store_action; + depth0.clear_depth = 0u; + depth0.texture = depth_stencil_texture; + + StencilAttachment stencil0; + stencil0.load_action = stencil_attachment_config.load_action; + stencil0.store_action = stencil_attachment_config.store_action; + stencil0.clear_stencil = 0u; + stencil0.texture = std::move(depth_stencil_texture); + stencil0.texture->SetLabel(label, "Depth+Stencil Texture"); + + SetDepthAttachment(std::move(depth0)); + SetStencilAttachment(std::move(stencil0)); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/render_target.h b/flutter/engine/src/flutter/impeller/renderer/render_target.h new file mode 100644 index 0000000000000000000000000000000000000000..c1a16db6846e9aa343a1478ce019a7c0240373bf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/render_target.h @@ -0,0 +1,203 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_RENDER_TARGET_H_ +#define FLUTTER_IMPELLER_RENDERER_RENDER_TARGET_H_ + +#include +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "impeller/core/allocator.h" +#include "impeller/core/formats.h" +#include "impeller/geometry/size.h" + +namespace impeller { + +class Context; + +struct RenderTargetConfig { + ISize size = ISize{0, 0}; + size_t mip_count = 0; + bool has_msaa = false; + bool has_depth_stencil = false; + + constexpr bool operator==(const RenderTargetConfig& o) const { + return size == o.size && mip_count == o.mip_count && + has_msaa == o.has_msaa && has_depth_stencil == o.has_depth_stencil; + } + + constexpr size_t Hash() const { + return fml::HashCombine(size.width, size.height, mip_count, has_msaa, + has_depth_stencil); + } +}; + +class RenderTarget final { + public: + struct AttachmentConfig { + StorageMode storage_mode; + LoadAction load_action; + StoreAction store_action; + Color clear_color; + }; + + struct AttachmentConfigMSAA { + StorageMode storage_mode; + StorageMode resolve_storage_mode; + LoadAction load_action; + StoreAction store_action; + Color clear_color; + }; + + static constexpr AttachmentConfig kDefaultColorAttachmentConfig = { + .storage_mode = StorageMode::kDevicePrivate, + .load_action = LoadAction::kClear, + .store_action = StoreAction::kStore, + .clear_color = Color::BlackTransparent()}; + + static constexpr AttachmentConfigMSAA kDefaultColorAttachmentConfigMSAA = { + .storage_mode = StorageMode::kDeviceTransient, + .resolve_storage_mode = StorageMode::kDevicePrivate, + .load_action = LoadAction::kClear, + .store_action = StoreAction::kMultisampleResolve, + .clear_color = Color::BlackTransparent()}; + + static constexpr AttachmentConfig kDefaultStencilAttachmentConfig = { + .storage_mode = StorageMode::kDeviceTransient, + .load_action = LoadAction::kClear, + .store_action = StoreAction::kDontCare, + .clear_color = Color::BlackTransparent()}; + + RenderTarget(); + + ~RenderTarget(); + + bool IsValid() const; + + void SetupDepthStencilAttachments( + const Context& context, + Allocator& allocator, + ISize size, + bool msaa, + std::string_view label = "Offscreen", + RenderTarget::AttachmentConfig stencil_attachment_config = + RenderTarget::kDefaultStencilAttachmentConfig, + const std::shared_ptr& depth_stencil_texture = nullptr); + + SampleCount GetSampleCount() const; + + bool HasColorAttachment(size_t index) const; + + ISize GetRenderTargetSize() const; + + std::shared_ptr GetRenderTargetTexture() const; + + PixelFormat GetRenderTargetPixelFormat() const; + + std::optional GetColorAttachmentSize(size_t index) const; + + RenderTarget& SetColorAttachment(const ColorAttachment& attachment, + size_t index); + + /// @brief Get the color attachment at [index]. + /// + /// This function does not validate whether or not the attachment was + /// previously defined and will return a default constructed attachment + /// if none is set. + ColorAttachment GetColorAttachment(size_t index) const; + + RenderTarget& SetDepthAttachment(std::optional attachment); + + RenderTarget& SetStencilAttachment( + std::optional attachment); + + size_t GetMaxColorAttacmentBindIndex() const; + + const std::optional& GetDepthAttachment() const; + + const std::optional& GetStencilAttachment() const; + + size_t GetTotalAttachmentCount() const; + + bool IterateAllColorAttachments( + const std::function& iterator) + const; + + void IterateAllAttachments( + const std::function& iterator) const; + + std::string ToString() const; + + RenderTargetConfig ToConfig() const; + + private: + std::optional color0_; + std::optional depth_; + std::optional stencil_; + // Note: color0 is stored in the color0_ field above and not in this map, + // to avoid heap allocations for the commonly created render target formats + // in Flutter. + std::map colors_; +}; + +/// @brief a wrapper around the impeller [Allocator] instance that can be used +/// to provide caching of allocated render target textures. +class RenderTargetAllocator { + public: + explicit RenderTargetAllocator(std::shared_ptr allocator); + + virtual ~RenderTargetAllocator() = default; + + virtual RenderTarget CreateOffscreen( + const Context& context, + ISize size, + int mip_count, + std::string_view label = "Offscreen", + RenderTarget::AttachmentConfig color_attachment_config = + RenderTarget::kDefaultColorAttachmentConfig, + std::optional stencil_attachment_config = + RenderTarget::kDefaultStencilAttachmentConfig, + const std::shared_ptr& existing_color_texture = nullptr, + const std::shared_ptr& existing_depth_stencil_texture = nullptr); + + virtual RenderTarget CreateOffscreenMSAA( + const Context& context, + ISize size, + int mip_count, + std::string_view label = "Offscreen MSAA", + RenderTarget::AttachmentConfigMSAA color_attachment_config = + RenderTarget::kDefaultColorAttachmentConfigMSAA, + std::optional stencil_attachment_config = + RenderTarget::kDefaultStencilAttachmentConfig, + const std::shared_ptr& existing_color_msaa_texture = nullptr, + const std::shared_ptr& existing_color_resolve_texture = nullptr, + const std::shared_ptr& existing_depth_stencil_texture = nullptr); + + /// @brief Disable any caching until the next call to `EnabledCache`. + virtual void DisableCache() {} + + /// @brief Re-enable any caching if disabled. + virtual void EnableCache() {} + + /// @brief Mark the beginning of a frame workload. + /// + /// This may be used to reset any tracking state on whether or not a + /// particular texture instance is still in use. + virtual void Start(); + + /// @brief Mark the end of a frame workload. + /// + /// This may be used to deallocate any unused textures. + virtual void End(); + + private: + std::shared_ptr allocator_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_RENDER_TARGET_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/renderer_dart_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/renderer_dart_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..3368ae759e742c2c0a57473d0fa2bbc150dd7676 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/renderer_dart_unittests.cc @@ -0,0 +1,304 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#define FML_USED_ON_EMBEDDER + +#include + +#include "flutter/common/settings.h" +#include "flutter/common/task_runners.h" +#include "flutter/lib/gpu/context.h" +#include "flutter/lib/gpu/shader_library.h" +#include "flutter/lib/gpu/texture.h" +#include "flutter/runtime/dart_isolate.h" +#include "flutter/runtime/dart_vm_lifecycle.h" +#include "flutter/testing/dart_fixture.h" +#include "flutter/testing/dart_isolate_runner.h" +#include "flutter/testing/test_dart_native_resolver.h" +#include "flutter/testing/testing.h" +#include "fml/memory/ref_ptr.h" +#include "impeller/fixtures/texture.frag.h" +#include "impeller/fixtures/texture.vert.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/vertex_buffer_builder.h" + +#include "gtest/gtest.h" +#include "third_party/imgui/imgui.h" + +namespace impeller { +namespace testing { + +static void InstantiateTestShaderLibrary(Context::BackendType backend_type) { + auto fixture = + flutter::testing::OpenFixtureAsMapping("playground.shaderbundle"); + auto library = flutter::gpu::ShaderLibrary::MakeFromFlatbuffer( + backend_type, std::move(fixture)); + flutter::gpu::ShaderLibrary::SetOverride(library); +} + +class RendererDartTest : public PlaygroundTest, + public flutter::testing::DartFixture { + public: + RendererDartTest() + : settings_(CreateSettingsForFixture()), + vm_ref_(flutter::DartVMRef::Create(settings_)) { + fml::MessageLoop::EnsureInitializedForCurrentThread(); + + current_task_runner_ = fml::MessageLoop::GetCurrent().GetTaskRunner(); + + isolate_ = CreateDartIsolate(); + assert(isolate_); + assert(isolate_->get()->GetPhase() == flutter::DartIsolate::Phase::Running); + + // Set up native callbacks. + // + // Note: The Dart isolate is configured (by + // `RendererDartTest::CreateDartIsolate`) to use the main thread, so + // there's no need for additional synchronization. + { + auto set_display_texture = [this](Dart_NativeArguments args) { + flutter::gpu::Texture* texture = + tonic::DartConverter::FromDart( + Dart_GetNativeArgument(args, 0)); + assert(texture != nullptr); // Should always be a valid pointer. + received_texture_ = texture->GetTexture(); + }; + AddNativeCallback("SetDisplayTexture", + CREATE_NATIVE_ENTRY(set_display_texture)); + } + } + + flutter::testing::AutoIsolateShutdown* GetIsolate() { + // Sneak the context into the Flutter GPU API. + assert(GetContext() != nullptr); + flutter::gpu::Context::SetOverrideContext(GetContext()); + + InstantiateTestShaderLibrary(GetContext()->GetBackendType()); + + return isolate_.get(); + } + + /// @brief Run a Dart function that's expected to create a texture and pass + /// it back for rendering via `drawToPlayground`. + std::shared_ptr GetRenderedTextureFromDart( + const char* dart_function_name) { + bool success = + GetIsolate()->RunInIsolateScope([this, &dart_function_name]() -> bool { + Dart_Handle args[] = {tonic::ToDart(GetWindowSize().width), + tonic::ToDart(GetWindowSize().height)}; + if (tonic::CheckAndHandleError( + ::Dart_Invoke(Dart_RootLibrary(), + tonic::ToDart(dart_function_name), 2, args))) { + return false; + } + return true; + }); + if (!success) { + FML_LOG(ERROR) << "Failed to invoke dart test function:" + << dart_function_name; + return nullptr; + } + if (!received_texture_) { + FML_LOG(ERROR) << "Dart test function `" << dart_function_name + << "` did not invoke `drawToPlaygroundSurface`."; + return nullptr; + } + return received_texture_; + } + + /// @brief Invokes a Dart function. + /// + /// Returns false if invoking the function failed or if any unhandled + /// exceptions were thrown. + bool RunDartFunction(const char* dart_function_name) { + return GetIsolate()->RunInIsolateScope([&dart_function_name]() -> bool { + if (tonic::CheckAndHandleError( + ::Dart_Invoke(Dart_RootLibrary(), + tonic::ToDart(dart_function_name), 0, nullptr))) { + return false; + } + return true; + }); + } + + /// @brief Invokes a Dart function with the window's width and height as + /// arguments. + /// + /// Returns false if invoking the function failed or if any unhandled + /// exceptions were thrown. + bool RunDartFunctionWithWindowSize(const char* dart_function_name) { + return GetIsolate()->RunInIsolateScope( + [this, &dart_function_name]() -> bool { + Dart_Handle args[] = {tonic::ToDart(GetWindowSize().width), + tonic::ToDart(GetWindowSize().height)}; + if (tonic::CheckAndHandleError( + ::Dart_Invoke(Dart_RootLibrary(), + tonic::ToDart(dart_function_name), 2, args))) { + return false; + } + return true; + }); + } + + /// @brief Call a dart function that produces a texture and render the result + /// in the playground. + /// + /// If the playground isn't enabled, the function is simply run once + /// in order to verify that it doesn't throw any unhandled exceptions. + bool RenderDartToPlayground(const char* dart_function_name) { + if (!IsPlaygroundEnabled()) { + // If the playground is not enabled, run the function instead to at least + // verify that it doesn't crash. + return RunDartFunctionWithWindowSize(dart_function_name); + } + + auto context = GetContext(); + assert(context != nullptr); + + //------------------------------------------------------------------------------ + /// Prepare pipeline. + /// + + using TextureVS = TextureVertexShader; + using TextureFS = TextureFragmentShader; + using TexturePipelineBuilder = PipelineBuilder; + + auto pipeline_desc = + TexturePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + if (!pipeline_desc.has_value()) { + FML_LOG(ERROR) << "Failed to create default pipeline descriptor."; + return false; + } + pipeline_desc->SetSampleCount(SampleCount::kCount4); + pipeline_desc->SetStencilAttachmentDescriptors(std::nullopt); + pipeline_desc->SetDepthStencilAttachmentDescriptor(std::nullopt); + pipeline_desc->SetStencilPixelFormat(PixelFormat::kUnknown); + pipeline_desc->SetDepthPixelFormat(PixelFormat::kUnknown); + + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + if (!pipeline || !pipeline->IsValid()) { + FML_LOG(ERROR) << "Failed to create default pipeline."; + return false; + } + + //------------------------------------------------------------------------------ + /// Prepare vertex data. + /// + + VertexBufferBuilder texture_vtx_builder; + + // Always stretch out the texture to fill the screen. + + // clang-format off + texture_vtx_builder.AddVertices({ + {{-0.5, -0.5, 0.0}, {0.0, 0.0}}, // 1 + {{ 0.5, -0.5, 0.0}, {1.0, 0.0}}, // 2 + {{ 0.5, 0.5, 0.0}, {1.0, 1.0}}, // 3 + {{-0.5, -0.5, 0.0}, {0.0, 0.0}}, // 1 + {{ 0.5, 0.5, 0.0}, {1.0, 1.0}}, // 3 + {{-0.5, 0.5, 0.0}, {0.0, 1.0}}, // 4 + }); + // clang-format on + + //------------------------------------------------------------------------------ + /// Prepare sampler. + /// + + const auto& sampler = context->GetSamplerLibrary()->GetSampler({}); + if (!sampler) { + FML_LOG(ERROR) << "Failed to create default sampler."; + return false; + } + + //------------------------------------------------------------------------------ + /// Render to playground. + /// + + SinglePassCallback callback = [&](RenderPass& pass) { + auto texture = GetRenderedTextureFromDart(dart_function_name); + if (!texture) { + return false; + } + + auto buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + pass.SetVertexBuffer(texture_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + + TextureVS::UniformBuffer uniforms; + uniforms.mvp = Matrix(); + TextureVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + TextureFS::BindTextureContents(pass, texture, sampler); + + pass.SetPipeline(pipeline); + + if (!pass.Draw().ok()) { + return false; + } + return true; + }; + return OpenPlaygroundHere(callback); + } + + private: + std::unique_ptr CreateDartIsolate() { + const auto settings = CreateSettingsForFixture(); + flutter::TaskRunners task_runners(flutter::testing::GetCurrentTestName(), + current_task_runner_, // + current_task_runner_, // + current_task_runner_, // + current_task_runner_ // + ); + return flutter::testing::RunDartCodeInIsolate( + vm_ref_, settings, task_runners, "main", {}, + flutter::testing::GetDefaultKernelFilePath()); + } + + const flutter::Settings settings_; + flutter::DartVMRef vm_ref_; + fml::RefPtr current_task_runner_; + std::unique_ptr isolate_; + + std::shared_ptr received_texture_; +}; + +INSTANTIATE_PLAYGROUND_SUITE(RendererDartTest); + +TEST_P(RendererDartTest, CanRunDartInPlaygroundFrame) { + SinglePassCallback callback = [&](RenderPass& pass) { + ImGui::Begin("Dart test", nullptr); + ImGui::Text( + "This test executes Dart code during the playground frame callback."); + ImGui::End(); + + return RunDartFunction("sayHi"); + }; + ASSERT_TRUE(OpenPlaygroundHere(callback)); +} + +/// These test entries correspond to Dart functions located in +/// `flutter/impeller/fixtures/dart_tests.dart` + +TEST_P(RendererDartTest, CanInstantiateFlutterGPUContext) { + ASSERT_TRUE(RunDartFunction("instantiateDefaultContext")); +} + +TEST_P(RendererDartTest, CanCreateShaderLibrary) { + ASSERT_TRUE(RunDartFunction("canCreateShaderLibrary")); +} + +TEST_P(RendererDartTest, CanReflectUniformStructs) { + ASSERT_TRUE(RunDartFunction("canReflectUniformStructs")); +} + +TEST_P(RendererDartTest, CanCreateRenderPassAndSubmit) { + ASSERT_TRUE(RenderDartToPlayground("canCreateRenderPassAndSubmit")); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/renderer_unittests.cc b/flutter/engine/src/flutter/impeller/renderer/renderer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..14540bc3c14608a6bf2d8ae8053f71a113deb581 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/renderer_unittests.cc @@ -0,0 +1,1630 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/logging.h" +#include "flutter/fml/time/time_point.h" +#include "impeller/core/device_buffer_descriptor.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/fixtures/array.frag.h" +#include "impeller/fixtures/array.vert.h" +#include "impeller/fixtures/baby.frag.h" +#include "impeller/fixtures/baby.vert.h" +#include "impeller/fixtures/box_fade.frag.h" +#include "impeller/fixtures/box_fade.vert.h" +#include "impeller/fixtures/colors.frag.h" +#include "impeller/fixtures/colors.vert.h" +#include "impeller/fixtures/impeller.frag.h" +#include "impeller/fixtures/impeller.vert.h" +#include "impeller/fixtures/inactive_uniforms.frag.h" +#include "impeller/fixtures/inactive_uniforms.vert.h" +#include "impeller/fixtures/instanced_draw.frag.h" +#include "impeller/fixtures/instanced_draw.vert.h" +#include "impeller/fixtures/mipmaps.frag.h" +#include "impeller/fixtures/mipmaps.vert.h" +#include "impeller/fixtures/planet.frag.h" +#include "impeller/fixtures/planet.vert.h" +#include "impeller/fixtures/sepia.frag.h" +#include "impeller/fixtures/sepia.vert.h" +#include "impeller/fixtures/swizzle.frag.h" +#include "impeller/fixtures/texture.frag.h" +#include "impeller/fixtures/texture.vert.h" +#include "impeller/playground/playground.h" +#include "impeller/playground/playground_test.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/pipeline_builder.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" +#include "impeller/renderer/vertex_buffer_builder.h" +#include "third_party/imgui/imgui.h" + +// TODO(zanderso): https://github.com/flutter/flutter/issues/127701 +// NOLINTBEGIN(bugprone-unchecked-optional-access) + +namespace impeller { +namespace testing { + +using RendererTest = PlaygroundTest; +INSTANTIATE_PLAYGROUND_SUITE(RendererTest); + +TEST_P(RendererTest, CanCreateBoxPrimitive) { + using VS = BoxFadeVertexShader; + using FS = BoxFadeFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + using BoxPipelineBuilder = PipelineBuilder; + auto desc = BoxPipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + vertex_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + SinglePassCallback callback = [&](RenderPass& pass) { + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + static bool wireframe; + ImGui::Checkbox("Wireframe", &wireframe); + ImGui::End(); + + desc->SetPolygonMode(wireframe ? PolygonMode::kLine : PolygonMode::kFill); + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get(); + + assert(pipeline && pipeline->IsValid()); + + pass.SetCommandLabel("Box"); + pass.SetPipeline(pipeline); + pass.SetVertexBuffer( + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator())); + + VS::UniformBuffer uniforms; + EXPECT_EQ(pass.GetOrthographicTransform(), + Matrix::MakeOrthographic(pass.GetRenderTargetSize())); + uniforms.mvp = + pass.GetOrthographicTransform() * Matrix::MakeScale(GetContentScale()); + VS::BindUniformBuffer(pass, host_buffer->EmplaceUniform(uniforms)); + + FS::FrameInfo frame_info; + frame_info.current_time = GetSecondsElapsed(); + frame_info.cursor_position = GetCursorPosition(); + frame_info.window_size.x = GetWindowSize().width; + frame_info.window_size.y = GetWindowSize().height; + + FS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + FS::BindContents1(pass, boston, sampler); + FS::BindContents2(pass, bridge, sampler); + + host_buffer->Reset(); + return pass.Draw().ok(); + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, BabysFirstTriangle) { + auto context = GetContext(); + ASSERT_TRUE(context); + + // Declare a shorthand for the shaders we are going to use. + using VS = BabyVertexShader; + using FS = BabyFragmentShader; + + // Create a pipeline descriptor that uses the shaders together and default + // initializes the fixed function state. + // + // If the vertex shader outputs disagree with the fragment shader inputs, this + // will be a compile time error. + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + + // Modify the descriptor for our environment. This is specific to our test. + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + + // Create a pipeline from our descriptor. This is expensive to do. So just do + // it once. + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get(); + + // Create a host side buffer to build the vertex and uniform information. + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + // Specify the vertex buffer information. + VertexBufferBuilder vertex_buffer_builder; + vertex_buffer_builder.AddVertices({ + {{-0.5, -0.5}, Color::Red(), Color::Green()}, + {{0.0, 0.5}, Color::Green(), Color::Blue()}, + {{0.5, -0.5}, Color::Blue(), Color::Red()}, + }); + + auto vertex_buffer = vertex_buffer_builder.CreateVertexBuffer( + *context->GetResourceAllocator()); + + SinglePassCallback callback = [&](RenderPass& pass) { + pass.SetPipeline(pipeline); + pass.SetVertexBuffer(vertex_buffer); + + FS::FragInfo frag_info; + frag_info.time = fml::TimePoint::Now().ToEpochDelta().ToSecondsF(); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + FS::BindFragInfo(pass, host_buffer->EmplaceUniform(frag_info)); + + return pass.Draw().ok(); + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanRenderPerspectiveCube) { + using VS = ColorsVertexShader; + using FS = ColorsFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetCullMode(CullMode::kBackFace); + desc->SetWindingOrder(WindingOrder::kCounterClockwise); + desc->SetSampleCount(SampleCount::kCount4); + desc->ClearStencilAttachments(); + + // Setup the vertex layout to take two bindings. The first for positions and + // the second for colors. + auto vertex_desc = std::make_shared(); + ShaderStageIOSlot position_slot = VS::kInputPosition; + ShaderStageIOSlot color_slot = VS::kInputColor; + position_slot.binding = 0; + position_slot.offset = 0; + color_slot.binding = 1; + color_slot.offset = 0; + const std::vector io_slots = {position_slot, color_slot}; + const std::vector layouts = { + ShaderStageBufferLayout{.stride = 12u, .binding = 0}, + ShaderStageBufferLayout{.stride = 16u, .binding = 1}}; + vertex_desc->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts); + vertex_desc->RegisterDescriptorSetLayouts(FS::kDescriptorSetLayouts); + vertex_desc->SetStageInputs(io_slots, layouts); + desc->SetVertexDescriptor(std::move(vertex_desc)); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + ASSERT_TRUE(pipeline); + + struct Cube { + Vector3 positions[8] = { + // -Z + {-1, -1, -1}, + {1, -1, -1}, + {1, 1, -1}, + {-1, 1, -1}, + // +Z + {-1, -1, 1}, + {1, -1, 1}, + {1, 1, 1}, + {-1, 1, 1}, + }; + Color colors[8] = { + Color::Red(), Color::Yellow(), Color::Green(), Color::Blue(), + Color::Green(), Color::Blue(), Color::Red(), Color::Yellow(), + }; + uint16_t indices[36] = { + 1, 5, 2, 2, 5, 6, // +X + 4, 0, 7, 7, 0, 3, // -X + 4, 5, 0, 0, 5, 1, // +Y + 3, 2, 7, 7, 2, 6, // -Y + 5, 4, 6, 6, 4, 7, // +Z + 0, 1, 3, 3, 1, 2, // -Z + }; + } cube; + + auto device_buffer = context->GetResourceAllocator()->CreateBufferWithCopy( + reinterpret_cast(&cube), sizeof(cube)); + + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + Vector3 euler_angles; + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + SinglePassCallback callback = [&](RenderPass& pass) { + static Degrees fov_y(60); + static Scalar distance = 10; + + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::SliderFloat("Field of view", &fov_y.degrees, 0, 180); + ImGui::SliderFloat("Camera distance", &distance, 0, 30); + ImGui::End(); + + pass.SetCommandLabel("Perspective Cube"); + pass.SetPipeline(pipeline); + + std::array vertex_buffers = { + BufferView(device_buffer, + Range(offsetof(Cube, positions), sizeof(Cube::positions))), + BufferView(device_buffer, + Range(offsetof(Cube, colors), sizeof(Cube::colors))), + }; + + BufferView index_buffer( + device_buffer, Range(offsetof(Cube, indices), sizeof(Cube::indices))); + pass.SetVertexBuffer(vertex_buffers.data(), vertex_buffers.size()); + pass.SetElementCount(36); + pass.SetIndexBuffer(index_buffer, IndexType::k16bit); + + VS::UniformBuffer uniforms; + Scalar time = GetSecondsElapsed(); + euler_angles = Vector3(0.19 * time, 0.7 * time, 0.43 * time); + + uniforms.mvp = + Matrix::MakePerspective(fov_y, pass.GetRenderTargetSize(), 0, 10) * + Matrix::MakeTranslation({0, 0, distance}) * + Matrix::MakeRotationX(Radians(euler_angles.x)) * + Matrix::MakeRotationY(Radians(euler_angles.y)) * + Matrix::MakeRotationZ(Radians(euler_angles.z)); + VS::BindUniformBuffer(pass, host_buffer->EmplaceUniform(uniforms)); + + host_buffer->Reset(); + return pass.Draw().ok(); + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanRenderMultiplePrimitives) { + using VS = BoxFadeVertexShader; + using FS = BoxFadeFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + using BoxPipelineBuilder = PipelineBuilder; + auto desc = BoxPipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + auto box_pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + ASSERT_TRUE(box_pipeline); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + vertex_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + SinglePassCallback callback = [&](RenderPass& pass) { + for (size_t i = 0; i < 1; i++) { + for (size_t j = 0; j < 1; j++) { + pass.SetCommandLabel("Box"); + pass.SetPipeline(box_pipeline); + pass.SetVertexBuffer(vertex_buffer); + + FS::FrameInfo frame_info; + frame_info.current_time = GetSecondsElapsed(); + frame_info.cursor_position = GetCursorPosition(); + frame_info.window_size.x = GetWindowSize().width; + frame_info.window_size.y = GetWindowSize().height; + + FS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + FS::BindContents1(pass, boston, sampler); + FS::BindContents2(pass, bridge, sampler); + + VS::UniformBuffer uniforms; + EXPECT_EQ(pass.GetOrthographicTransform(), + Matrix::MakeOrthographic(pass.GetRenderTargetSize())); + uniforms.mvp = pass.GetOrthographicTransform() * + Matrix::MakeScale(GetContentScale()) * + Matrix::MakeTranslation({i * 50.0f, j * 50.0f, 0.0f}); + VS::BindUniformBuffer(pass, host_buffer->EmplaceUniform(uniforms)); + if (!pass.Draw().ok()) { + return false; + } + } + } + + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanRenderToTexture) { + using VS = BoxFadeVertexShader; + using FS = BoxFadeFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + using BoxPipelineBuilder = PipelineBuilder; + auto pipeline_desc = + BoxPipelineBuilder::MakeDefaultPipelineDescriptor(*context); + pipeline_desc->SetSampleCount(SampleCount::kCount1); + pipeline_desc->ClearDepthAttachment(); + pipeline_desc->SetStencilPixelFormat(PixelFormat::kS8UInt); + + ASSERT_TRUE(pipeline_desc.has_value()); + auto box_pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + ASSERT_TRUE(box_pipeline); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + vertex_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + std::shared_ptr r2t_pass; + auto cmd_buffer = context->CreateCommandBuffer(); + ASSERT_TRUE(cmd_buffer); + { + ColorAttachment color0; + color0.load_action = LoadAction::kClear; + color0.store_action = StoreAction::kStore; + + TextureDescriptor texture_descriptor; + ASSERT_NE(pipeline_desc->GetColorAttachmentDescriptor(0u), nullptr); + texture_descriptor.format = + pipeline_desc->GetColorAttachmentDescriptor(0u)->format; + texture_descriptor.storage_mode = StorageMode::kHostVisible; + texture_descriptor.size = {400, 400}; + texture_descriptor.mip_count = 1u; + texture_descriptor.usage = TextureUsage::kRenderTarget; + + color0.texture = + context->GetResourceAllocator()->CreateTexture(texture_descriptor); + + ASSERT_TRUE(color0.IsValid()); + + color0.texture->SetLabel("r2t_target"); + + StencilAttachment stencil0; + stencil0.load_action = LoadAction::kClear; + stencil0.store_action = StoreAction::kDontCare; + TextureDescriptor stencil_texture_desc; + stencil_texture_desc.storage_mode = StorageMode::kDeviceTransient; + stencil_texture_desc.size = texture_descriptor.size; + stencil_texture_desc.format = PixelFormat::kS8UInt; + stencil_texture_desc.usage = TextureUsage::kRenderTarget; + stencil0.texture = + context->GetResourceAllocator()->CreateTexture(stencil_texture_desc); + + RenderTarget r2t_desc; + r2t_desc.SetColorAttachment(color0, 0u); + r2t_desc.SetStencilAttachment(stencil0); + r2t_pass = cmd_buffer->CreateRenderPass(r2t_desc); + ASSERT_TRUE(r2t_pass && r2t_pass->IsValid()); + } + + r2t_pass->SetCommandLabel("Box"); + r2t_pass->SetPipeline(box_pipeline); + r2t_pass->SetVertexBuffer(vertex_buffer); + + FS::FrameInfo frame_info; + frame_info.current_time = GetSecondsElapsed(); + frame_info.cursor_position = GetCursorPosition(); + frame_info.window_size.x = GetWindowSize().width; + frame_info.window_size.y = GetWindowSize().height; + + FS::BindFrameInfo(*r2t_pass, host_buffer->EmplaceUniform(frame_info)); + FS::BindContents1(*r2t_pass, boston, sampler); + FS::BindContents2(*r2t_pass, bridge, sampler); + + VS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(ISize{1024, 768}) * + Matrix::MakeTranslation({50.0f, 50.0f, 0.0f}); + VS::BindUniformBuffer(*r2t_pass, host_buffer->EmplaceUniform(uniforms)); + ASSERT_TRUE(r2t_pass->Draw().ok()); + ASSERT_TRUE(r2t_pass->EncodeCommands()); +} + +TEST_P(RendererTest, CanRenderInstanced) { + if (GetParam() == PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() << "Instancing is not supported on OpenGL."; + } + using VS = InstancedDrawVertexShader; + using FS = InstancedDrawFragmentShader; + + VertexBufferBuilder builder; + builder.AddVertices({ + VS::PerVertexData{Point{10, 10}}, + VS::PerVertexData{Point{10, 110}}, + VS::PerVertexData{Point{110, 10}}, + VS::PerVertexData{Point{10, 110}}, + VS::PerVertexData{Point{110, 10}}, + VS::PerVertexData{Point{110, 110}}, + }); + + ASSERT_NE(GetContext(), nullptr); + auto pipeline = + GetContext() + ->GetPipelineLibrary() + ->GetPipeline(PipelineBuilder::MakeDefaultPipelineDescriptor( + *GetContext()) + ->SetSampleCount(SampleCount::kCount4) + .SetStencilAttachmentDescriptors(std::nullopt)) + + .Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + + static constexpr size_t kInstancesCount = 5u; + VS::InstanceInfo instances; + for (size_t i = 0; i < kInstancesCount; i++) { + instances.colors[i] = Color::Random(); + } + + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + ASSERT_TRUE(OpenPlaygroundHere([&](RenderPass& pass) -> bool { + pass.SetPipeline(pipeline); + pass.SetCommandLabel("InstancedDraw"); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass.GetOrthographicTransform(), + Matrix::MakeOrthographic(pass.GetRenderTargetSize())); + frame_info.mvp = + pass.GetOrthographicTransform() * Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + VS::BindInstanceInfo(pass, host_buffer->EmplaceStorageBuffer(instances)); + pass.SetVertexBuffer(builder.CreateVertexBuffer(*host_buffer)); + + pass.SetInstanceCount(kInstancesCount); + pass.Draw(); + + host_buffer->Reset(); + return true; + })); +} + +TEST_P(RendererTest, CanBlitTextureToTexture) { + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() << "Mipmap test shader not supported on GLES."; + } + auto context = GetContext(); + ASSERT_TRUE(context); + + using VS = MipmapsVertexShader; + using FS = MipmapsFragmentShader; + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + auto mipmaps_pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + ASSERT_TRUE(mipmaps_pipeline); + + TextureDescriptor texture_desc; + texture_desc.storage_mode = StorageMode::kHostVisible; + texture_desc.format = PixelFormat::kR8G8B8A8UNormInt; + texture_desc.size = {800, 600}; + texture_desc.mip_count = 1u; + texture_desc.usage = TextureUsage::kRenderTarget | TextureUsage::kShaderRead; + auto texture = context->GetResourceAllocator()->CreateTexture(texture_desc); + ASSERT_TRUE(texture); + + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + auto size = Point(boston->GetSize()); + vertex_builder.AddVertices({ + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, 0}, {1.0, 0.0}}, // 2 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, size.y}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + Playground::RenderCallback callback = [&](RenderTarget& render_target) { + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + + { + auto pass = buffer->CreateBlitPass(); + if (!pass) { + return false; + } + pass->SetLabel("Playground Blit Pass"); + + // Blit `bridge` to the top left corner of the texture. + pass->AddCopy(bridge, texture); + + if (!pass->EncodeCommands()) { + return false; + } + } + + { + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + return false; + } + pass->SetLabel("Playground Render Pass"); + { + pass->SetCommandLabel("Image"); + pass->SetPipeline(mipmaps_pipeline); + pass->SetVertexBuffer(vertex_buffer); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass->GetOrthographicTransform(), + Matrix::MakeOrthographic(pass->GetRenderTargetSize())); + frame_info.mvp = pass->GetOrthographicTransform() * + Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(*pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo frag_info; + frag_info.lod = 0; + FS::BindFragInfo(*pass, host_buffer->EmplaceUniform(frag_info)); + + auto sampler = context->GetSamplerLibrary()->GetSampler({}); + FS::BindTex(*pass, texture, sampler); + + pass->Draw(); + } + pass->EncodeCommands(); + } + + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanBlitTextureToBuffer) { + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() << "Mipmap test shader not supported on GLES."; + } + auto context = GetContext(); + ASSERT_TRUE(context); + + using VS = MipmapsVertexShader; + using FS = MipmapsFragmentShader; + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + auto mipmaps_pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + ASSERT_TRUE(mipmaps_pipeline); + + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + TextureDescriptor texture_desc; + texture_desc.storage_mode = StorageMode::kHostVisible; + texture_desc.format = PixelFormat::kR8G8B8A8UNormInt; + texture_desc.size = bridge->GetTextureDescriptor().size; + texture_desc.mip_count = 1u; + texture_desc.usage = TextureUsage::kRenderTarget | + TextureUsage::kShaderWrite | TextureUsage::kShaderRead; + DeviceBufferDescriptor device_buffer_desc; + device_buffer_desc.storage_mode = StorageMode::kHostVisible; + device_buffer_desc.size = + bridge->GetTextureDescriptor().GetByteSizeOfBaseMipLevel(); + auto device_buffer = + context->GetResourceAllocator()->CreateBuffer(device_buffer_desc); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + auto size = Point(boston->GetSize()); + vertex_builder.AddVertices({ + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, 0}, {1.0, 0.0}}, // 2 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, size.y}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + Playground::RenderCallback callback = [&](RenderTarget& render_target) { + { + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + auto pass = buffer->CreateBlitPass(); + if (!pass) { + return false; + } + pass->SetLabel("Playground Blit Pass"); + + // Blit `bridge` to the top left corner of the texture. + pass->AddCopy(bridge, device_buffer); + pass->EncodeCommands(); + + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + } + + { + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + return false; + } + pass->SetLabel("Playground Render Pass"); + { + pass->SetCommandLabel("Image"); + pass->SetPipeline(mipmaps_pipeline); + pass->SetVertexBuffer(vertex_buffer); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass->GetOrthographicTransform(), + Matrix::MakeOrthographic(pass->GetRenderTargetSize())); + frame_info.mvp = pass->GetOrthographicTransform() * + Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(*pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo frag_info; + frag_info.lod = 0; + FS::BindFragInfo(*pass, host_buffer->EmplaceUniform(frag_info)); + + raw_ptr sampler = + context->GetSamplerLibrary()->GetSampler({}); + auto buffer_view = DeviceBuffer::AsBufferView(device_buffer); + auto texture = + context->GetResourceAllocator()->CreateTexture(texture_desc); + if (!texture->SetContents(device_buffer->OnGetContents(), + buffer_view.GetRange().length)) { + VALIDATION_LOG << "Could not upload texture to device memory"; + return false; + } + FS::BindTex(*pass, texture, sampler); + + pass->Draw().ok(); + } + pass->EncodeCommands(); + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + } + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanGenerateMipmaps) { + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() << "Mipmap test shader not supported on GLES."; + } + auto context = GetContext(); + ASSERT_TRUE(context); + + using VS = MipmapsVertexShader; + using FS = MipmapsFragmentShader; + auto desc = PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + auto mipmaps_pipeline = + context->GetPipelineLibrary()->GetPipeline(std::move(desc)).Get(); + ASSERT_TRUE(mipmaps_pipeline); + + auto boston = CreateTextureForFixture("boston.jpg", true); + ASSERT_TRUE(boston); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + auto size = Point(boston->GetSize()); + vertex_builder.AddVertices({ + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, 0}, {1.0, 0.0}}, // 2 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, 0}, {0.0, 0.0}}, // 1 + {{size.x, size.y}, {1.0, 1.0}}, // 3 + {{0, size.y}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + bool first_frame = true; + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + Playground::RenderCallback callback = [&](RenderTarget& render_target) { + const char* mip_filter_names[] = {"Base", "Nearest", "Linear"}; + const MipFilter mip_filters[] = {MipFilter::kBase, MipFilter::kNearest, + MipFilter::kLinear}; + const char* min_filter_names[] = {"Nearest", "Linear"}; + const MinMagFilter min_filters[] = {MinMagFilter::kNearest, + MinMagFilter::kLinear}; + + // UI state. + static int selected_mip_filter = 1; + static int selected_min_filter = 0; + static float lod = 4.5; + + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Combo("Mip filter", &selected_mip_filter, mip_filter_names, + sizeof(mip_filter_names) / sizeof(char*)); + ImGui::Combo("Min filter", &selected_min_filter, min_filter_names, + sizeof(min_filter_names) / sizeof(char*)); + ImGui::SliderFloat("LOD", &lod, 0, boston->GetMipCount() - 1); + ImGui::End(); + + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + + if (first_frame) { + auto pass = buffer->CreateBlitPass(); + if (!pass) { + return false; + } + pass->SetLabel("Playground Blit Pass"); + + pass->GenerateMipmap(boston, "Boston Mipmap"); + + pass->EncodeCommands(); + } + + first_frame = false; + + { + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + return false; + } + pass->SetLabel("Playground Render Pass"); + { + pass->SetCommandLabel("Image LOD"); + pass->SetPipeline(mipmaps_pipeline); + pass->SetVertexBuffer(vertex_buffer); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass->GetOrthographicTransform(), + Matrix::MakeOrthographic(pass->GetRenderTargetSize())); + frame_info.mvp = pass->GetOrthographicTransform() * + Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(*pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo frag_info; + frag_info.lod = lod; + FS::BindFragInfo(*pass, host_buffer->EmplaceUniform(frag_info)); + + SamplerDescriptor sampler_desc; + sampler_desc.mip_filter = mip_filters[selected_mip_filter]; + sampler_desc.min_filter = min_filters[selected_min_filter]; + raw_ptr sampler = + context->GetSamplerLibrary()->GetSampler(sampler_desc); + FS::BindTex(*pass, boston, sampler); + + pass->Draw(); + } + pass->EncodeCommands(); + } + + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, TheImpeller) { + using VS = ImpellerVertexShader; + using FS = ImpellerFragmentShader; + + auto context = GetContext(); + auto pipeline_descriptor = + PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_descriptor.has_value()); + pipeline_descriptor->SetSampleCount(SampleCount::kCount4); + pipeline_descriptor->SetStencilAttachmentDescriptors(std::nullopt); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_descriptor).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + + auto blue_noise = CreateTextureForFixture("blue_noise.png"); + SamplerDescriptor noise_sampler_desc; + noise_sampler_desc.width_address_mode = SamplerAddressMode::kRepeat; + noise_sampler_desc.height_address_mode = SamplerAddressMode::kRepeat; + raw_ptr noise_sampler = + context->GetSamplerLibrary()->GetSampler(noise_sampler_desc); + + auto cube_map = CreateTextureCubeForFixture( + {"table_mountain_px.png", "table_mountain_nx.png", + "table_mountain_py.png", "table_mountain_ny.png", + "table_mountain_pz.png", "table_mountain_nz.png"}); + raw_ptr cube_map_sampler = + context->GetSamplerLibrary()->GetSampler({}); + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + SinglePassCallback callback = [&](RenderPass& pass) { + auto size = pass.GetRenderTargetSize(); + + pass.SetPipeline(pipeline); + pass.SetCommandLabel("Impeller SDF scene"); + VertexBufferBuilder builder; + builder.AddVertices({{Point()}, + {Point(0, size.height)}, + {Point(size.width, 0)}, + {Point(size.width, 0)}, + {Point(0, size.height)}, + {Point(size.width, size.height)}}); + pass.SetVertexBuffer(builder.CreateVertexBuffer(*host_buffer)); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass.GetOrthographicTransform(), Matrix::MakeOrthographic(size)); + frame_info.mvp = pass.GetOrthographicTransform(); + VS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo fs_uniform; + fs_uniform.texture_size = Point(size); + fs_uniform.time = GetSecondsElapsed(); + FS::BindFragInfo(pass, host_buffer->EmplaceUniform(fs_uniform)); + FS::BindBlueNoise(pass, blue_noise, noise_sampler); + FS::BindCubeMap(pass, cube_map, cube_map_sampler); + + pass.Draw().ok(); + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, Planet) { + using VS = PlanetVertexShader; + using FS = PlanetFragmentShader; + + auto context = GetContext(); + auto pipeline_descriptor = + PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_descriptor.has_value()); + pipeline_descriptor->SetSampleCount(SampleCount::kCount4); + pipeline_descriptor->SetStencilAttachmentDescriptors(std::nullopt); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_descriptor).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + SinglePassCallback callback = [&](RenderPass& pass) { + static Scalar speed = 0.1; + static Scalar planet_size = 550.0; + static bool show_normals = false; + static bool show_noise = false; + static Scalar seed_value = 42.0; + + auto size = pass.GetRenderTargetSize(); + + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::SliderFloat("Speed", &speed, 0.0, 10.0); + ImGui::SliderFloat("Planet Size", &planet_size, 0.1, 1000); + ImGui::Checkbox("Show Normals", &show_normals); + ImGui::Checkbox("Show Noise", &show_noise); + ImGui::InputFloat("Seed Value", &seed_value); + ImGui::End(); + + pass.SetPipeline(pipeline); + pass.SetCommandLabel("Planet scene"); + VertexBufferBuilder builder; + builder.AddVertices({{Point()}, + {Point(0, size.height)}, + {Point(size.width, 0)}, + {Point(size.width, 0)}, + {Point(0, size.height)}, + {Point(size.width, size.height)}}); + pass.SetVertexBuffer(builder.CreateVertexBuffer(*host_buffer)); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass.GetOrthographicTransform(), Matrix::MakeOrthographic(size)); + frame_info.mvp = pass.GetOrthographicTransform(); + VS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo fs_uniform; + fs_uniform.resolution = Point(size); + fs_uniform.time = GetSecondsElapsed(); + fs_uniform.speed = speed; + fs_uniform.planet_size = planet_size; + fs_uniform.show_normals = show_normals ? 1.0 : 0.0; + fs_uniform.show_noise = show_noise ? 1.0 : 0.0; + fs_uniform.seed_value = seed_value; + FS::BindFragInfo(pass, host_buffer->EmplaceUniform(fs_uniform)); + + pass.Draw().ok(); + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, ArrayUniforms) { + using VS = ArrayVertexShader; + using FS = ArrayFragmentShader; + + auto context = GetContext(); + auto pipeline_descriptor = + PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_descriptor.has_value()); + pipeline_descriptor->SetSampleCount(SampleCount::kCount4); + pipeline_descriptor->SetStencilAttachmentDescriptors(std::nullopt); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_descriptor).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + SinglePassCallback callback = [&](RenderPass& pass) { + auto size = pass.GetRenderTargetSize(); + + pass.SetPipeline(pipeline); + pass.SetCommandLabel("Google Dots"); + VertexBufferBuilder builder; + builder.AddVertices({{Point()}, + {Point(0, size.height)}, + {Point(size.width, 0)}, + {Point(size.width, 0)}, + {Point(0, size.height)}, + {Point(size.width, size.height)}}); + pass.SetVertexBuffer(builder.CreateVertexBuffer(*host_buffer)); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass.GetOrthographicTransform(), Matrix::MakeOrthographic(size)); + frame_info.mvp = + pass.GetOrthographicTransform() * Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + + auto time = GetSecondsElapsed(); + auto y_pos = [&time](float x) { + return 400 + 10 * std::cos(time * 5 + x / 6); + }; + + FS::FragInfo fs_uniform = { + .circle_positions = {Point(430, y_pos(0)), Point(480, y_pos(1)), + Point(530, y_pos(2)), Point(580, y_pos(3))}, + .colors = {Color::MakeRGBA8(66, 133, 244, 255), + Color::MakeRGBA8(219, 68, 55, 255), + Color::MakeRGBA8(244, 180, 0, 255), + Color::MakeRGBA8(15, 157, 88, 255)}, + }; + FS::BindFragInfo(pass, host_buffer->EmplaceUniform(fs_uniform)); + + pass.Draw(); + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, InactiveUniforms) { + using VS = InactiveUniformsVertexShader; + using FS = InactiveUniformsFragmentShader; + + auto context = GetContext(); + auto pipeline_descriptor = + PipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(pipeline_descriptor.has_value()); + pipeline_descriptor->SetSampleCount(SampleCount::kCount4); + pipeline_descriptor->SetStencilAttachmentDescriptors(std::nullopt); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_descriptor).Get(); + ASSERT_TRUE(pipeline && pipeline->IsValid()); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + SinglePassCallback callback = [&](RenderPass& pass) { + auto size = pass.GetRenderTargetSize(); + + pass.SetPipeline(pipeline); + pass.SetCommandLabel("Inactive Uniform"); + + VertexBufferBuilder builder; + builder.AddVertices({{Point()}, + {Point(0, size.height)}, + {Point(size.width, 0)}, + {Point(size.width, 0)}, + {Point(0, size.height)}, + {Point(size.width, size.height)}}); + pass.SetVertexBuffer(builder.CreateVertexBuffer(*host_buffer)); + + VS::FrameInfo frame_info; + EXPECT_EQ(pass.GetOrthographicTransform(), Matrix::MakeOrthographic(size)); + frame_info.mvp = + pass.GetOrthographicTransform() * Matrix::MakeScale(GetContentScale()); + VS::BindFrameInfo(pass, host_buffer->EmplaceUniform(frame_info)); + + FS::FragInfo fs_uniform = {.unused_color = Color::Red(), + .color = Color::Green()}; + FS::BindFragInfo(pass, host_buffer->EmplaceUniform(fs_uniform)); + + pass.Draw().ok(); + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, DefaultIndexSize) { + using VS = BoxFadeVertexShader; + + // Default to 16bit index buffer size, as this is a reasonable default and + // supported on all backends without extensions. + VertexBufferBuilder vertex_builder; + vertex_builder.AppendIndex(0u); + ASSERT_EQ(vertex_builder.GetIndexType(), IndexType::k16bit); +} + +TEST_P(RendererTest, DefaultIndexBehavior) { + using VS = BoxFadeVertexShader; + + // Do not create any index buffer if no indices were provided. + VertexBufferBuilder vertex_builder; + ASSERT_EQ(vertex_builder.GetIndexType(), IndexType::kNone); +} + +TEST_P(RendererTest, VertexBufferBuilder) { + // Does not create index buffer if one is provided. + using VS = BoxFadeVertexShader; + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + vertex_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + vertex_builder.AppendIndex(0); + vertex_builder.AppendIndex(1); + vertex_builder.AppendIndex(2); + vertex_builder.AppendIndex(1); + vertex_builder.AppendIndex(2); + vertex_builder.AppendIndex(3); + + ASSERT_EQ(vertex_builder.GetIndexCount(), 6u); + ASSERT_EQ(vertex_builder.GetVertexCount(), 4u); +} + +class CompareFunctionUIData { + public: + CompareFunctionUIData() { + labels_.push_back("Never"); + functions_.push_back(CompareFunction::kNever); + labels_.push_back("Always"); + functions_.push_back(CompareFunction::kAlways); + labels_.push_back("Less"); + functions_.push_back(CompareFunction::kLess); + labels_.push_back("Equal"); + functions_.push_back(CompareFunction::kEqual); + labels_.push_back("LessEqual"); + functions_.push_back(CompareFunction::kLessEqual); + labels_.push_back("Greater"); + functions_.push_back(CompareFunction::kGreater); + labels_.push_back("NotEqual"); + functions_.push_back(CompareFunction::kNotEqual); + labels_.push_back("GreaterEqual"); + functions_.push_back(CompareFunction::kGreaterEqual); + assert(labels_.size() == functions_.size()); + } + + const char* const* labels() const { return &labels_[0]; } + + int size() const { return labels_.size(); } + + int IndexOf(CompareFunction func) const { + for (size_t i = 0; i < functions_.size(); i++) { + if (functions_[i] == func) { + return i; + } + } + FML_UNREACHABLE(); + return -1; + } + + CompareFunction FunctionOf(int index) const { return functions_[index]; } + + private: + std::vector labels_; + std::vector functions_; +}; + +static const CompareFunctionUIData& CompareFunctionUI() { + static CompareFunctionUIData data; + return data; +} + +TEST_P(RendererTest, StencilMask) { + using VS = BoxFadeVertexShader; + using FS = BoxFadeFragmentShader; + auto context = GetContext(); + ASSERT_TRUE(context); + using BoxFadePipelineBuilder = PipelineBuilder; + auto desc = BoxFadePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + ASSERT_TRUE(desc.has_value()); + + // Vertex buffer. + VertexBufferBuilder vertex_builder; + vertex_builder.SetLabel("Box"); + vertex_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + auto vertex_buffer = + vertex_builder.CreateVertexBuffer(*context->GetResourceAllocator()); + ASSERT_TRUE(vertex_buffer); + + desc->SetSampleCount(SampleCount::kCount4); + desc->SetStencilAttachmentDescriptors(std::nullopt); + + auto bridge = CreateTextureForFixture("bay_bridge.jpg"); + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(bridge && boston); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + static bool mirror = false; + static int stencil_reference_write = 0xFF; + static int stencil_reference_read = 0x1; + std::vector stencil_contents; + static int last_stencil_contents_reference_value = 0; + static int current_front_compare = + CompareFunctionUI().IndexOf(CompareFunction::kLessEqual); + static int current_back_compare = + CompareFunctionUI().IndexOf(CompareFunction::kLessEqual); + + auto host_buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + Playground::RenderCallback callback = [&](RenderTarget& render_target) { + auto buffer = context->CreateCommandBuffer(); + if (!buffer) { + return false; + } + buffer->SetLabel("Playground Command Buffer"); + + { + // Configure the stencil attachment for the test. + RenderTarget::AttachmentConfig stencil_config; + stencil_config.load_action = LoadAction::kLoad; + stencil_config.store_action = StoreAction::kDontCare; + stencil_config.storage_mode = StorageMode::kHostVisible; + render_target.SetupDepthStencilAttachments( + *context, *context->GetResourceAllocator(), + render_target.GetRenderTargetSize(), true, "stencil", stencil_config); + // Fill the stencil buffer with an checkerboard pattern. + const auto target_width = render_target.GetRenderTargetSize().width; + const auto target_height = render_target.GetRenderTargetSize().height; + const size_t target_size = target_width * target_height; + if (stencil_contents.size() != target_size || + last_stencil_contents_reference_value != stencil_reference_write) { + stencil_contents.resize(target_size); + last_stencil_contents_reference_value = stencil_reference_write; + for (int y = 0; y < target_height; y++) { + for (int x = 0; x < target_width; x++) { + const auto index = y * target_width + x; + const auto kCheckSize = 64; + const auto value = + (((y / kCheckSize) + (x / kCheckSize)) % 2 == 0) * + stencil_reference_write; + stencil_contents[index] = value; + } + } + } + if (!render_target.GetStencilAttachment()->texture->SetContents( + stencil_contents.data(), stencil_contents.size(), 0, false)) { + VALIDATION_LOG << "Could not upload stencil contents to device memory"; + return false; + } + auto pass = buffer->CreateRenderPass(render_target); + if (!pass) { + return false; + } + pass->SetLabel("Stencil Buffer"); + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::SliderInt("Stencil Write Value", &stencil_reference_write, 0, + 0xFF); + ImGui::SliderInt("Stencil Compare Value", &stencil_reference_read, 0, + 0xFF); + ImGui::Checkbox("Back face mode", &mirror); + ImGui::ListBox("Front face compare function", ¤t_front_compare, + CompareFunctionUI().labels(), CompareFunctionUI().size()); + ImGui::ListBox("Back face compare function", ¤t_back_compare, + CompareFunctionUI().labels(), CompareFunctionUI().size()); + ImGui::End(); + + StencilAttachmentDescriptor front; + front.stencil_compare = + CompareFunctionUI().FunctionOf(current_front_compare); + StencilAttachmentDescriptor back; + back.stencil_compare = + CompareFunctionUI().FunctionOf(current_back_compare); + desc->SetStencilAttachmentDescriptors(front, back); + auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get(); + + assert(pipeline && pipeline->IsValid()); + + pass->SetCommandLabel("Box"); + pass->SetPipeline(pipeline); + pass->SetStencilReference(stencil_reference_read); + pass->SetVertexBuffer(vertex_buffer); + + VS::UniformBuffer uniforms; + EXPECT_EQ(pass->GetOrthographicTransform(), + Matrix::MakeOrthographic(pass->GetRenderTargetSize())); + uniforms.mvp = pass->GetOrthographicTransform() * + Matrix::MakeScale(GetContentScale()); + if (mirror) { + uniforms.mvp = Matrix::MakeScale(Vector2(-1, 1)) * uniforms.mvp; + } + VS::BindUniformBuffer(*pass, host_buffer->EmplaceUniform(uniforms)); + + FS::FrameInfo frame_info; + frame_info.current_time = GetSecondsElapsed(); + frame_info.cursor_position = GetCursorPosition(); + frame_info.window_size.x = GetWindowSize().width; + frame_info.window_size.y = GetWindowSize().height; + + FS::BindFrameInfo(*pass, host_buffer->EmplaceUniform(frame_info)); + FS::BindContents1(*pass, boston, sampler); + FS::BindContents2(*pass, bridge, sampler); + if (!pass->Draw().ok()) { + return false; + } + pass->EncodeCommands(); + } + + if (!context->GetCommandQueue()->Submit({buffer}).ok()) { + return false; + } + host_buffer->Reset(); + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanLookupRenderTargetProperties) { + auto context = GetContext(); + auto cmd_buffer = context->CreateCommandBuffer(); + auto render_target_cache = std::make_shared( + GetContext()->GetResourceAllocator()); + + auto render_target = render_target_cache->CreateOffscreen( + *context, {100, 100}, /*mip_count=*/1); + auto render_pass = cmd_buffer->CreateRenderPass(render_target); + + EXPECT_EQ(render_pass->GetSampleCount(), render_target.GetSampleCount()); + EXPECT_EQ(render_pass->GetRenderTargetPixelFormat(), + render_target.GetRenderTargetPixelFormat()); + EXPECT_EQ(render_pass->HasStencilAttachment(), + render_target.GetStencilAttachment().has_value()); + EXPECT_EQ(render_pass->GetRenderTargetSize(), + render_target.GetRenderTargetSize()); + render_pass->EncodeCommands(); +} + +TEST_P(RendererTest, + RenderTargetCreateOffscreenMSAASetsDefaultDepthStencilFormat) { + auto context = GetContext(); + auto render_target_cache = std::make_shared( + GetContext()->GetResourceAllocator()); + + RenderTarget render_target = render_target_cache->CreateOffscreenMSAA( + *context, {100, 100}, /*mip_count=*/1); + EXPECT_EQ(render_target.GetDepthAttachment() + ->texture->GetTextureDescriptor() + .format, + GetContext()->GetCapabilities()->GetDefaultDepthStencilFormat()); +} + +template +std::shared_ptr> CreateDefaultPipeline( + const std::shared_ptr& context) { + using TexturePipelineBuilder = PipelineBuilder; + auto pipeline_desc = + TexturePipelineBuilder::MakeDefaultPipelineDescriptor(*context); + if (!pipeline_desc.has_value()) { + return nullptr; + } + pipeline_desc->SetSampleCount(SampleCount::kCount4); + pipeline_desc->SetStencilAttachmentDescriptors(std::nullopt); + auto pipeline = + context->GetPipelineLibrary()->GetPipeline(pipeline_desc).Get(); + if (!pipeline || !pipeline->IsValid()) { + return nullptr; + } + return pipeline; +} + +TEST_P(RendererTest, CanSepiaToneWithSubpasses) { + // Define shader types + using TextureVS = TextureVertexShader; + using TextureFS = TextureFragmentShader; + + using SepiaVS = SepiaVertexShader; + using SepiaFS = SepiaFragmentShader; + + auto context = GetContext(); + ASSERT_TRUE(context); + + if (!context->GetCapabilities()->SupportsFramebufferFetch()) { + GTEST_SKIP() << "This test uses framebuffer fetch and the backend doesn't " + "support it."; + return; + } + + // Create pipelines. + auto texture_pipeline = CreateDefaultPipeline(context); + auto sepia_pipeline = CreateDefaultPipeline(context); + + ASSERT_TRUE(texture_pipeline); + ASSERT_TRUE(sepia_pipeline); + + // Vertex buffer builders. + VertexBufferBuilder texture_vtx_builder; + texture_vtx_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + + VertexBufferBuilder sepia_vtx_builder; + sepia_vtx_builder.AddVertices({ + {{100, 100, 0.0}}, // 1 + {{800, 100, 0.0}}, // 2 + {{800, 800, 0.0}}, // 3 + {{100, 100, 0.0}}, // 1 + {{800, 800, 0.0}}, // 3 + {{100, 800, 0.0}}, // 4 + }); + + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(boston); + + const auto& sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + SinglePassCallback callback = [&](RenderPass& pass) { + auto buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + // Draw the texture. + { + pass.SetPipeline(texture_pipeline); + pass.SetVertexBuffer(texture_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + TextureVS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + Matrix::MakeScale(GetContentScale()); + TextureVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + TextureFS::BindTextureContents(pass, boston, sampler); + if (!pass.Draw().ok()) { + return false; + } + } + + // Draw the sepia toner. + { + pass.SetPipeline(sepia_pipeline); + pass.SetVertexBuffer(sepia_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + SepiaVS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + Matrix::MakeScale(GetContentScale()); + SepiaVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + if (!pass.Draw().ok()) { + return false; + } + } + + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, CanSepiaToneThenSwizzleWithSubpasses) { + // Define shader types + using TextureVS = TextureVertexShader; + using TextureFS = TextureFragmentShader; + + using SwizzleVS = SepiaVertexShader; + using SwizzleFS = SwizzleFragmentShader; + + using SepiaVS = SepiaVertexShader; + using SepiaFS = SepiaFragmentShader; + + auto context = GetContext(); + ASSERT_TRUE(context); + + if (!context->GetCapabilities()->SupportsFramebufferFetch()) { + GTEST_SKIP() << "This test uses framebuffer fetch and the backend doesn't " + "support it."; + return; + } + + // Create pipelines. + auto texture_pipeline = CreateDefaultPipeline(context); + auto swizzle_pipeline = CreateDefaultPipeline(context); + auto sepia_pipeline = CreateDefaultPipeline(context); + + ASSERT_TRUE(texture_pipeline); + ASSERT_TRUE(swizzle_pipeline); + ASSERT_TRUE(sepia_pipeline); + + // Vertex buffer builders. + VertexBufferBuilder texture_vtx_builder; + texture_vtx_builder.AddVertices({ + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 100, 0.0}, {1.0, 0.0}}, // 2 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 100, 0.0}, {0.0, 0.0}}, // 1 + {{800, 800, 0.0}, {1.0, 1.0}}, // 3 + {{100, 800, 0.0}, {0.0, 1.0}}, // 4 + }); + + VertexBufferBuilder sepia_vtx_builder; + sepia_vtx_builder.AddVertices({ + {{100, 100, 0.0}}, // 1 + {{800, 100, 0.0}}, // 2 + {{800, 800, 0.0}}, // 3 + {{100, 100, 0.0}}, // 1 + {{800, 800, 0.0}}, // 3 + {{100, 800, 0.0}}, // 4 + }); + + auto boston = CreateTextureForFixture("boston.jpg"); + ASSERT_TRUE(boston); + + const auto& sampler = context->GetSamplerLibrary()->GetSampler({}); + ASSERT_TRUE(sampler); + + SinglePassCallback callback = [&](RenderPass& pass) { + auto buffer = HostBuffer::Create(context->GetResourceAllocator(), + context->GetIdleWaiter()); + + // Draw the texture. + { + pass.SetPipeline(texture_pipeline); + pass.SetVertexBuffer(texture_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + TextureVS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + Matrix::MakeScale(GetContentScale()); + TextureVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + TextureFS::BindTextureContents(pass, boston, sampler); + if (!pass.Draw().ok()) { + return false; + } + } + + // Draw the sepia toner. + { + pass.SetPipeline(sepia_pipeline); + pass.SetVertexBuffer(sepia_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + SepiaVS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + Matrix::MakeScale(GetContentScale()); + SepiaVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + if (!pass.Draw().ok()) { + return false; + } + } + + // Draw the swizzle. + { + pass.SetPipeline(swizzle_pipeline); + pass.SetVertexBuffer(sepia_vtx_builder.CreateVertexBuffer( + *context->GetResourceAllocator())); + SwizzleVS::UniformBuffer uniforms; + uniforms.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) * + Matrix::MakeScale(GetContentScale()); + SwizzleVS::BindUniformBuffer(pass, buffer->EmplaceUniform(uniforms)); + if (!pass.Draw().ok()) { + return false; + } + } + + return true; + }; + OpenPlaygroundHere(callback); +} + +TEST_P(RendererTest, BindingNullTexturesDoesNotCrash) { + using FS = BoxFadeFragmentShader; + + auto context = GetContext(); + raw_ptr sampler = context->GetSamplerLibrary()->GetSampler({}); + auto command_buffer = context->CreateCommandBuffer(); + + RenderTargetAllocator allocator(context->GetResourceAllocator()); + RenderTarget target = allocator.CreateOffscreen(*context, {1, 1}, 1); + + auto pass = command_buffer->CreateRenderPass(target); + EXPECT_FALSE(FS::BindContents2(*pass, nullptr, sampler)); +} + +} // namespace testing +} // namespace impeller + +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/flutter/engine/src/flutter/impeller/renderer/sampler_library.cc b/flutter/engine/src/flutter/impeller/renderer/sampler_library.cc new file mode 100644 index 0000000000000000000000000000000000000000..7aae0f779f851826c02a08da0f4452efd11db881 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/sampler_library.cc @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/sampler_library.h" + +namespace impeller { + +SamplerLibrary::SamplerLibrary() = default; + +SamplerLibrary::~SamplerLibrary() = default; + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/sampler_library.h b/flutter/engine/src/flutter/impeller/renderer/sampler_library.h new file mode 100644 index 0000000000000000000000000000000000000000..1371f2c857cafd85788157cd0ef8edae855ae78f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/sampler_library.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SAMPLER_LIBRARY_H_ +#define FLUTTER_IMPELLER_RENDERER_SAMPLER_LIBRARY_H_ + +#include "impeller/core/raw_ptr.h" +#include "impeller/core/sampler.h" +#include "impeller/core/sampler_descriptor.h" + +namespace impeller { + +class SamplerLibrary { + public: + virtual ~SamplerLibrary(); + + /// @brief Retrieve a backend specific sampler object for the given sampler + /// descriptor. + /// + /// If the descriptor is invalid or there is a loss of rendering + /// context, this method may return a nullptr. + /// + /// The sampler library implementations must cache this sampler object + /// and guarantee that the reference will continue to be valid + /// throughout the lifetime of the Impeller context. + virtual raw_ptr GetSampler( + const SamplerDescriptor& descriptor) = 0; + + protected: + SamplerLibrary(); + + private: + SamplerLibrary(const SamplerLibrary&) = delete; + + SamplerLibrary& operator=(const SamplerLibrary&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SAMPLER_LIBRARY_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_function.cc b/flutter/engine/src/flutter/impeller/renderer/shader_function.cc new file mode 100644 index 0000000000000000000000000000000000000000..7aa8053bd5e1005ed6c0ae19edb3e0ab92d5a2a9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_function.cc @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/shader_function.h" + +namespace impeller { + +ShaderFunction::ShaderFunction(UniqueID parent_library_id, + std::string name, + ShaderStage stage) + : parent_library_id_(parent_library_id), + name_(std::move(name)), + stage_(stage) {} + +ShaderFunction::~ShaderFunction() = default; + +ShaderStage ShaderFunction::GetStage() const { + return stage_; +} + +const std::string& ShaderFunction::GetName() const { + return name_; +} + +// |Comparable| +std::size_t ShaderFunction::GetHash() const { + return fml::HashCombine(parent_library_id_, name_, stage_); +} + +// |Comparable| +bool ShaderFunction::IsEqual(const ShaderFunction& other) const { + return parent_library_id_ == other.parent_library_id_ && + name_ == other.name_ && stage_ == other.stage_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_function.h b/flutter/engine/src/flutter/impeller/renderer/shader_function.h new file mode 100644 index 0000000000000000000000000000000000000000..05767b1bcf209c4ff92a316ed1045b436bb5ac7c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_function.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_ +#define FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_ + +#include + +#include "impeller/base/comparable.h" +#include "impeller/core/shader_types.h" + +namespace impeller { + +class ShaderFunction : public Comparable { + public: + // |Comparable| + virtual ~ShaderFunction(); + + ShaderStage GetStage() const; + + const std::string& GetName() const; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const ShaderFunction& other) const override; + + protected: + ShaderFunction(UniqueID parent_library_id, + std::string name, + ShaderStage stage); + + private: + UniqueID parent_library_id_; + std::string name_; + ShaderStage stage_; + + ShaderFunction(const ShaderFunction&) = delete; + + ShaderFunction& operator=(const ShaderFunction&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SHADER_FUNCTION_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_key.cc b/flutter/engine/src/flutter/impeller/renderer/shader_key.cc new file mode 100644 index 0000000000000000000000000000000000000000..c27e1e5c3f449d8eb67236970157ffab1ebef7ef --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_key.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/shader_key.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_key.h b/flutter/engine/src/flutter/impeller/renderer/shader_key.h new file mode 100644 index 0000000000000000000000000000000000000000..09f3a9cb3bfdd4b17414d475ea89ff3b8adcf4bb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_key.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SHADER_KEY_H_ +#define FLUTTER_IMPELLER_RENDERER_SHADER_KEY_H_ + +#include +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "impeller/core/shader_types.h" + +namespace impeller { + +struct ShaderKey { + std::string name; + ShaderStage stage = ShaderStage::kUnknown; + + ShaderKey(std::string_view p_name, ShaderStage p_stage) + : name({p_name.data(), p_name.size()}), stage(p_stage) {} + + struct Hash { + size_t operator()(const ShaderKey& key) const { + return fml::HashCombine(key.name, key.stage); + } + }; + + struct Equal { + constexpr bool operator()(const ShaderKey& k1, const ShaderKey& k2) const { + return k1.stage == k2.stage && k1.name == k2.name; + } + }; +}; + +class ShaderFunction; + +using ShaderFunctionMap = + std::unordered_map, + ShaderKey::Hash, + ShaderKey::Equal>; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SHADER_KEY_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_library.cc b/flutter/engine/src/flutter/impeller/renderer/shader_library.cc new file mode 100644 index 0000000000000000000000000000000000000000..85737fe8dddda53323d4273f8f2891680df8bb86 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_library.cc @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +ShaderLibrary::ShaderLibrary() = default; + +ShaderLibrary::~ShaderLibrary() = default; + +void ShaderLibrary::RegisterFunction( + std::string name, // NOLINT(performance-unnecessary-value-param) + ShaderStage stage, + std::shared_ptr + code, // NOLINT(performance-unnecessary-value-param) + RegistrationCallback + callback) { // NOLINT(performance-unnecessary-value-param) + if (callback) { + callback(false); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_library.h b/flutter/engine/src/flutter/impeller/renderer/shader_library.h new file mode 100644 index 0000000000000000000000000000000000000000..1421ea3e0d023afa065573e1f08d025e9d5accfd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_library.h @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SHADER_LIBRARY_H_ +#define FLUTTER_IMPELLER_RENDERER_SHADER_LIBRARY_H_ + +#include +#include +#include + +#include "fml/mapping.h" +#include "impeller/core/shader_types.h" + +namespace impeller { + +class Context; +class ShaderFunction; + +class ShaderLibrary : public std::enable_shared_from_this { + public: + virtual ~ShaderLibrary(); + + virtual bool IsValid() const = 0; + + virtual std::shared_ptr GetFunction( + std::string_view name, + ShaderStage stage) = 0; + + using RegistrationCallback = std::function; + virtual void RegisterFunction(std::string name, + ShaderStage stage, + std::shared_ptr code, + RegistrationCallback callback); + + virtual void UnregisterFunction(std::string name, ShaderStage stage) = 0; + + protected: + ShaderLibrary(); + + private: + ShaderLibrary(const ShaderLibrary&) = delete; + + ShaderLibrary& operator=(const ShaderLibrary&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SHADER_LIBRARY_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/shader_stage_compatibility_checker.h b/flutter/engine/src/flutter/impeller/renderer/shader_stage_compatibility_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..06871473d7c44a3efbc32d24bb35240eda23c662 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/shader_stage_compatibility_checker.h @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SHADER_STAGE_COMPATIBILITY_CHECKER_H_ +#define FLUTTER_IMPELLER_RENDERER_SHADER_STAGE_COMPATIBILITY_CHECKER_H_ + +#include + +#include "impeller/core/shader_types.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Checks, at C++ compile-time, if the two pipeline stages are +/// compatible. +/// +/// Stages may be incompatible if the outputs declared in the vertex +/// stage don't line up with the inputs declared in the fragment +/// stage. Additionally, the types of the inputs and outputs need to +/// be identical. Some drivers like the one on the PowerVR GE8320 +/// also have bugs the require the precision qualifier of the stage +/// interfaces to match exactly. +/// +/// Not ensuring stage compatibility will cause pipeline creation +/// errors that will only be caught at runtime. In addition to the +/// bugs discovered related to precision qualifier, some errors may +/// only manifest at runtime on some devices. +/// +/// This static compile-time C++ check ensures that all the possible +/// runtime errors will be caught at build time. +/// +/// There is no runtime overhead to using this class. +/// +/// @tparam VertexShaderT The vertex shader stage metadata. +/// @tparam FragmentShaderT The fragment shader stage metadata. +/// +template +class ShaderStageCompatibilityChecker { + public: + static constexpr bool CompileTimeStrEqual(const char* str1, + const char* str2) { + return *str1 == *str2 && + (*str1 == '\0' || CompileTimeStrEqual(str1 + 1, str2 + 1)); + } + + /// Returns `true` if the shader input slots for the fragment shader match the + /// ones declared as outputs in the vertex shader. + static constexpr bool Check() { + constexpr size_t num_outputs = VertexShaderT::kAllShaderStageOutputs.size(); + constexpr size_t num_inputs = FragmentShaderT::kAllShaderStageInputs.size(); + + if (num_inputs > num_outputs) { + return false; + } + + for (size_t i = 0; i < num_inputs; ++i) { + const ShaderStageIOSlot* input_slot = + FragmentShaderT::kAllShaderStageInputs[i]; + for (size_t j = 0; j < num_outputs; ++j) { + const ShaderStageIOSlot* output_slot = + VertexShaderT::kAllShaderStageOutputs[j]; + if (input_slot->location == output_slot->location) { + if (!CompileTimeStrEqual(input_slot->name, output_slot->name) || + input_slot->set != output_slot->set || + input_slot->binding != output_slot->binding || + input_slot->type != output_slot->type || + input_slot->bit_width != output_slot->bit_width || + input_slot->vec_size != output_slot->vec_size || + input_slot->columns != output_slot->columns || + input_slot->offset != output_slot->offset || + input_slot->relaxed_precision != output_slot->relaxed_precision) { + return false; + } + } + } + } + + return true; + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SHADER_STAGE_COMPATIBILITY_CHECKER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/snapshot.cc b/flutter/engine/src/flutter/impeller/renderer/snapshot.cc new file mode 100644 index 0000000000000000000000000000000000000000..b55a9717083a5694184d8d9e29d6597e894268a4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/snapshot.cc @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/snapshot.h" + +#include + +namespace impeller { + +std::optional Snapshot::GetCoverage() const { + if (!texture) { + return std::nullopt; + } + return Rect::MakeSize(texture->GetSize()).TransformBounds(transform); +} + +std::optional Snapshot::GetUVTransform() const { + if (!texture || texture->GetSize().IsEmpty()) { + return std::nullopt; + } + return Matrix::MakeScale(1 / Vector2(texture->GetSize())) * + transform.Invert(); +} + +std::optional> Snapshot::GetCoverageUVs( + const Rect& coverage) const { + auto uv_transform = GetUVTransform(); + if (!uv_transform.has_value()) { + return std::nullopt; + } + return coverage.GetTransformedPoints(uv_transform.value()); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/snapshot.h b/flutter/engine/src/flutter/impeller/renderer/snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..41c5ff08bcdff377fa46f90581a862cc4290c08d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/snapshot.h @@ -0,0 +1,51 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_ +#define FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_ + +#include +#include +#include + +#include "impeller/core/formats.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/core/texture.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/rect.h" + +namespace impeller { + +class ContentContext; +class Entity; + +/// Represents a texture and its intended draw transform/sampler configuration. +struct Snapshot { + std::shared_ptr texture; + /// The transform that should be applied to this texture for rendering. + Matrix transform; + + SamplerDescriptor sampler_descriptor = + SamplerDescriptor("Default Snapshot Sampler", + MinMagFilter::kLinear, + MinMagFilter::kLinear, + MipFilter::kNearest); + + Scalar opacity = 1.0f; + + std::optional GetCoverage() const; + + /// @brief Get the transform that converts screen space coordinates to the UV + /// space of this snapshot. + std::optional GetUVTransform() const; + + /// @brief Map a coverage rect to this filter input's UV space. + /// Result order: Top left, top right, bottom left, bottom right. + std::optional> GetCoverageUVs( + const Rect& coverage) const; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SNAPSHOT_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/surface.cc b/flutter/engine/src/flutter/impeller/renderer/surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..108e0e07b52d7635a2cba441e2f6270bd32be0bd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/surface.cc @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/surface.h" + +#include "flutter/fml/logging.h" + +namespace impeller { + +Surface::Surface() : Surface(RenderTarget{}) {} + +Surface::Surface(const RenderTarget& target_desc) : desc_(target_desc) { + if (auto size = desc_.GetColorAttachmentSize(0u); size.has_value()) { + size_ = size.value(); + } else { + return; + } + + is_valid_ = true; +} + +Surface::~Surface() = default; + +const ISize& Surface::GetSize() const { + return size_; +} + +bool Surface::IsValid() const { + return is_valid_; +} + +const RenderTarget& Surface::GetRenderTarget() const { + return desc_; +} + +bool Surface::Present() const { + return false; +}; + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/surface.h b/flutter/engine/src/flutter/impeller/renderer/surface.h new file mode 100644 index 0000000000000000000000000000000000000000..3a72a2481cd25ee1580a343840eb7a85eca4f45f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/surface.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_SURFACE_H_ +#define FLUTTER_IMPELLER_RENDERER_SURFACE_H_ + +#include "impeller/renderer/render_target.h" + +namespace impeller { + +class Surface { + public: + Surface(); + + explicit Surface(const RenderTarget& target_desc); + + virtual ~Surface(); + + const ISize& GetSize() const; + + bool IsValid() const; + + const RenderTarget& GetRenderTarget() const; + + virtual bool Present() const; + + private: + RenderTarget desc_; + ISize size_; + + bool is_valid_ = false; + + Surface(const Surface&) = delete; + + Surface& operator=(const Surface&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_SURFACE_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/testing/mocks.h b/flutter/engine/src/flutter/impeller/renderer/testing/mocks.h new file mode 100644 index 0000000000000000000000000000000000000000..f814fccde2cf3d43d8f17a4fa6e285f1dbcb6a09 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/testing/mocks.h @@ -0,0 +1,262 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_ +#define FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_ + +#include "gmock/gmock.h" +#include "impeller/core/allocator.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/sampler_descriptor.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/command_queue.h" +#include "impeller/renderer/context.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" +#include "impeller/renderer/sampler_library.h" + +#define FLT_FORWARD(mock, real, method) \ + EXPECT_CALL(*mock, method()) \ + .WillRepeatedly(::testing::Return(real->method())); + +namespace impeller { +namespace testing { + +class MockDeviceBuffer : public DeviceBuffer { + public: + explicit MockDeviceBuffer(const DeviceBufferDescriptor& desc) + : DeviceBuffer(desc) {} + + MOCK_METHOD(bool, SetLabel, (std::string_view label), (override)); + + MOCK_METHOD(bool, + SetLabel, + (std::string_view label, Range range), + (override)); + + MOCK_METHOD(uint8_t*, OnGetContents, (), (const, override)); + + MOCK_METHOD(bool, + OnCopyHostBuffer, + (const uint8_t* source, Range source_range, size_t offset), + (override)); +}; + +class MockAllocator : public Allocator { + public: + MOCK_METHOD(ISize, GetMaxTextureSizeSupported, (), (const, override)); + MOCK_METHOD(std::shared_ptr, + OnCreateBuffer, + (const DeviceBufferDescriptor& desc), + (override)); + MOCK_METHOD(std::shared_ptr, + OnCreateTexture, + (const TextureDescriptor& desc), + (override)); +}; + +class MockBlitPass : public BlitPass { + public: + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(bool, EncodeCommands, (), (const, override)); + MOCK_METHOD(void, OnSetLabel, (std::string_view label), (override)); + + MOCK_METHOD(bool, + ResizeTexture, + (const std::shared_ptr& source, + const std::shared_ptr& destination), + (override)); + + MOCK_METHOD(bool, + OnCopyTextureToTextureCommand, + (std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + IPoint destination_origin, + std::string_view label), + (override)); + + MOCK_METHOD(bool, + OnCopyTextureToBufferCommand, + (std::shared_ptr source, + std::shared_ptr destination, + IRect source_region, + size_t destination_offset, + std::string_view label), + (override)); + MOCK_METHOD(bool, + OnCopyBufferToTextureCommand, + (BufferView source, + std::shared_ptr destination, + IRect destination_rect, + std::string_view label, + uint32_t mip_level, + uint32_t slice, + bool convert_to_read), + (override)); + MOCK_METHOD(bool, + OnGenerateMipmapCommand, + (std::shared_ptr texture, std::string_view label), + (override)); +}; + +class MockRenderPass : public RenderPass { + public: + MockRenderPass(std::shared_ptr context, + const RenderTarget& target) + : RenderPass(std::move(context), target) {} + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(bool, + OnEncodeCommands, + (const Context& context), + (const, override)); + MOCK_METHOD(void, OnSetLabel, (std::string_view label), (override)); +}; + +class MockCommandBuffer : public CommandBuffer { + public: + explicit MockCommandBuffer(std::weak_ptr context) + : CommandBuffer(std::move(context)) {} + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(void, SetLabel, (std::string_view label), (const, override)); + MOCK_METHOD(std::shared_ptr, OnCreateBlitPass, (), (override)); + MOCK_METHOD(bool, + OnSubmitCommands, + (bool block_on_schedule, CompletionCallback callback), + (override)); + MOCK_METHOD(void, OnWaitUntilCompleted, (), (override)); + MOCK_METHOD(void, OnWaitUntilScheduled, (), (override)); + MOCK_METHOD(std::shared_ptr, + OnCreateComputePass, + (), + (override)); + MOCK_METHOD(std::shared_ptr, + OnCreateRenderPass, + (RenderTarget render_target), + (override)); +}; + +class MockImpellerContext : public Context { + public: + MockImpellerContext() : Context(Flags{}) {} + + MOCK_METHOD(Context::BackendType, GetBackendType, (), (const, override)); + + MOCK_METHOD(std::string, DescribeGpuModel, (), (const, override)); + + MOCK_METHOD(bool, IsValid, (), (const, override)); + + MOCK_METHOD(void, Shutdown, (), (override)); + + MOCK_METHOD(std::shared_ptr, + GetResourceAllocator, + (), + (const, override)); + + MOCK_METHOD(std::shared_ptr, + GetShaderLibrary, + (), + (const, override)); + + MOCK_METHOD(std::shared_ptr, + GetSamplerLibrary, + (), + (const, override)); + + MOCK_METHOD(std::shared_ptr, + GetPipelineLibrary, + (), + (const, override)); + + MOCK_METHOD(std::shared_ptr, + CreateCommandBuffer, + (), + (const, override)); + + MOCK_METHOD(const std::shared_ptr&, + GetCapabilities, + (), + (const, override)); + + MOCK_METHOD(std::shared_ptr, + GetCommandQueue, + (), + (const, override)); + + MOCK_METHOD(RuntimeStageBackend, + GetRuntimeStageBackend, + (), + (const, override)); +}; + +class MockTexture : public Texture { + public: + explicit MockTexture(const TextureDescriptor& desc) : Texture(desc) {} + MOCK_METHOD(void, SetLabel, (std::string_view label), (override)); + MOCK_METHOD(void, + SetLabel, + (std::string_view label, std::string_view trailing), + (override)); + MOCK_METHOD(bool, IsValid, (), (const, override)); + MOCK_METHOD(ISize, GetSize, (), (const, override)); + MOCK_METHOD(bool, + OnSetContents, + (const uint8_t* contents, size_t length, size_t slice), + (override)); + MOCK_METHOD(bool, + OnSetContents, + (std::shared_ptr mapping, size_t slice), + (override)); +}; + +class MockCapabilities : public Capabilities { + public: + MOCK_METHOD(bool, SupportsOffscreenMSAA, (), (const, override)); + MOCK_METHOD(bool, SupportsImplicitResolvingMSAA, (), (const, override)); + MOCK_METHOD(bool, SupportsSSBO, (), (const, override)); + MOCK_METHOD(bool, SupportsTextureToTextureBlits, (), (const, override)); + MOCK_METHOD(bool, SupportsFramebufferFetch, (), (const, override)); + MOCK_METHOD(bool, SupportsCompute, (), (const, override)); + MOCK_METHOD(bool, SupportsComputeSubgroups, (), (const, override)); + MOCK_METHOD(bool, SupportsReadFromResolve, (), (const, override)); + MOCK_METHOD(bool, SupportsDecalSamplerAddressMode, (), (const, override)); + MOCK_METHOD(bool, SupportsDeviceTransientTextures, (), (const, override)); + MOCK_METHOD(bool, SupportsTriangleFan, (), (const override)); + MOCK_METHOD(bool, SupportsPrimitiveRestart, (), (const override)); + MOCK_METHOD(bool, SupportsExtendedRangeFormats, (), (const override)); + MOCK_METHOD(PixelFormat, GetDefaultColorFormat, (), (const, override)); + MOCK_METHOD(PixelFormat, GetDefaultStencilFormat, (), (const, override)); + MOCK_METHOD(PixelFormat, GetDefaultDepthStencilFormat, (), (const, override)); + MOCK_METHOD(PixelFormat, GetDefaultGlyphAtlasFormat, (), (const, override)); + MOCK_METHOD(ISize, GetMaximumRenderPassAttachmentSize, (), (const override)); +}; + +class MockCommandQueue : public CommandQueue { + public: + MOCK_METHOD(fml::Status, + Submit, + (const std::vector>& buffers, + const CompletionCallback& cb, + bool block_on_schedule), + (override)); +}; + +class MockSamplerLibrary : public SamplerLibrary { + public: + MOCK_METHOD(raw_ptr, + GetSampler, + (const SamplerDescriptor& descriptor), + (override)); +}; + +class MockSampler : public Sampler { + public: + explicit MockSampler(const SamplerDescriptor& desc) : Sampler(desc) {} +}; + +} // namespace testing +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_TESTING_MOCKS_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/texture_util.cc b/flutter/engine/src/flutter/impeller/renderer/texture_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..b50f6f0de81d5773fa852a228c975fb4188b37a0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/texture_util.cc @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/texture_util.h" +#include "impeller/renderer/blit_pass.h" +#include "impeller/renderer/command_buffer.h" + +namespace impeller { + +std::shared_ptr CreateTexture( + const TextureDescriptor& texture_descriptor, + const std::vector& data, + const std::shared_ptr& context, + std::string_view debug_label) { + std::shared_ptr texture = + context->GetResourceAllocator()->CreateTexture(texture_descriptor); + + auto data_mapping = + std::make_shared(data.data(), data.size()); + std::shared_ptr buffer = + context->GetResourceAllocator()->CreateBufferWithCopy(*data_mapping); + + std::shared_ptr cmd_buffer = context->CreateCommandBuffer(); + std::shared_ptr blit_pass = cmd_buffer->CreateBlitPass(); + blit_pass->AddCopy(DeviceBuffer::AsBufferView(std::move(buffer)), texture); + + if (!blit_pass->EncodeCommands() || + !context->GetCommandQueue()->Submit({std::move(cmd_buffer)}).ok()) { + return nullptr; + } + + texture->SetLabel(debug_label); + return texture; +} + +fml::Status AddMipmapGeneration( + const std::shared_ptr& command_buffer, + const std::shared_ptr& context, + const std::shared_ptr& texture) { + std::shared_ptr blit_pass = command_buffer->CreateBlitPass(); + bool success = blit_pass->GenerateMipmap(texture); + if (!success) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + success = blit_pass->EncodeCommands(); + if (!success) { + return fml::Status(fml::StatusCode::kUnknown, ""); + } + return fml::Status(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/texture_util.h b/flutter/engine/src/flutter/impeller/renderer/texture_util.h new file mode 100644 index 0000000000000000000000000000000000000000..df4fd16fc7cbc99c5874e41c9e909942c55b8a15 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/texture_util.h @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_TEXTURE_UTIL_H_ +#define FLUTTER_IMPELLER_RENDERER_TEXTURE_UTIL_H_ + +#include "flutter/fml/status.h" +#include "impeller/core/texture.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/context.h" + +namespace impeller { + +std::shared_ptr CreateTexture( + const TextureDescriptor& texture_descriptor, + const std::vector& data, + const std::shared_ptr& context, + std::string_view debug_label); + +/// Adds a blit command to the render pass. +[[nodiscard]] fml::Status AddMipmapGeneration( + const std::shared_ptr& command_buffer, + const std::shared_ptr& context, + const std::shared_ptr& texture); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_TEXTURE_UTIL_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/threadgroup_sizing_test.comp b/flutter/engine/src/flutter/impeller/renderer/threadgroup_sizing_test.comp new file mode 100644 index 0000000000000000000000000000000000000000..3d2e02af507ca850eadc027295156ee5e04319d5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/threadgroup_sizing_test.comp @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Size is passed in via specialization constant. +layout(local_size_x_id = 0) in; + +layout(std430) buffer; + +layout(binding = 1) writeonly buffer OutputData { + uint data[]; +} +output_data; + +void main() { + uint ident = gl_GlobalInvocationID.x; + output_data.data[ident] = ident; +} diff --git a/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.cc b/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..b29e4032132a0117f8965b88f0fb22d0eea7553f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/vertex_buffer_builder.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.h b/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..974268caab98301e10b70a0b7ff309e211291714 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/vertex_buffer_builder.h @@ -0,0 +1,176 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_ +#define FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_ + +#include +#include +#include +#include + +#include "impeller/base/strings.h" +#include "impeller/core/allocator.h" +#include "impeller/core/device_buffer.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/vertex_buffer.h" + +namespace impeller { + +/// @brief Create an index-less vertex buffer from a fixed size array. +template +VertexBuffer CreateVertexBuffer(std::array input, + HostBuffer& host_buffer) { + return VertexBuffer{ + .vertex_buffer = host_buffer.Emplace( + input.data(), sizeof(VertexType) * size, alignof(VertexType)), // + .vertex_count = size, // + .index_type = IndexType::kNone, // + }; +} + +template +class VertexBufferBuilder { + public: + using VertexType = VertexType_; + using IndexType = IndexType_; + + VertexBufferBuilder() = default; + + ~VertexBufferBuilder() = default; + + constexpr impeller::IndexType GetIndexType() const { + if (indices_.size() == 0) { + return impeller::IndexType::kNone; + } + if constexpr (sizeof(IndexType) == 2) { + return impeller::IndexType::k16bit; + } + if (sizeof(IndexType) == 4) { + return impeller::IndexType::k32bit; + } + return impeller::IndexType::kUnknown; + } + + void SetLabel(const std::string& label) { label_ = label; } + + void Reserve(size_t count) { return vertices_.reserve(count); } + + void ReserveIndices(size_t count) { return indices_.reserve(count); } + + bool HasVertices() const { return !vertices_.empty(); } + + size_t GetVertexCount() const { return vertices_.size(); } + + size_t GetIndexCount() const { + return indices_.size() > 0 ? indices_.size() : vertices_.size(); + } + + const VertexType& Last() const { + FML_DCHECK(!vertices_.empty()); + return vertices_.back(); + } + + VertexBufferBuilder& AppendVertex(VertexType_ vertex) { + vertices_.emplace_back(std::move(vertex)); + return *this; + } + + VertexBufferBuilder& AddVertices( + std::initializer_list vertices) { + vertices_.reserve(vertices.size()); + for (auto& vertex : vertices) { + vertices_.emplace_back(std::move(vertex)); + } + return *this; + } + + VertexBufferBuilder& AppendIndex(IndexType_ index) { + indices_.emplace_back(index); + return *this; + } + + VertexBuffer CreateVertexBuffer(HostBuffer& host_buffer) const { + VertexBuffer buffer; + buffer.vertex_buffer = CreateVertexBufferView(host_buffer); + buffer.index_buffer = CreateIndexBufferView(host_buffer); + buffer.vertex_count = GetIndexCount(); + buffer.index_type = GetIndexType(); + return buffer; + }; + + VertexBuffer CreateVertexBuffer(Allocator& device_allocator) const { + VertexBuffer buffer; + // This can be merged into a single allocation. + buffer.vertex_buffer = CreateVertexBufferView(device_allocator); + buffer.index_buffer = CreateIndexBufferView(device_allocator); + buffer.vertex_count = GetIndexCount(); + buffer.index_type = GetIndexType(); + return buffer; + }; + + void IterateVertices(const std::function& iterator) { + for (auto& vertex : vertices_) { + iterator(vertex); + } + } + + private: + std::vector vertices_; + std::vector indices_; + std::string label_; + + BufferView CreateVertexBufferView(HostBuffer& buffer) const { + return buffer.Emplace(vertices_.data(), + vertices_.size() * sizeof(VertexType), + alignof(VertexType)); + } + + BufferView CreateVertexBufferView(Allocator& allocator) const { + auto buffer = allocator.CreateBufferWithCopy( + reinterpret_cast(vertices_.data()), + vertices_.size() * sizeof(VertexType)); + if (!buffer) { + return {}; + } + if (!label_.empty()) { + buffer->SetLabel(SPrintF("%s Vertices", label_.c_str())); + } + return DeviceBuffer::AsBufferView(std::move(buffer)); + } + + std::vector CreateIndexBuffer() const { return indices_; } + + BufferView CreateIndexBufferView(HostBuffer& buffer) const { + const auto index_buffer = CreateIndexBuffer(); + if (index_buffer.size() == 0) { + return {}; + } + return buffer.Emplace(index_buffer.data(), + index_buffer.size() * sizeof(IndexType), + alignof(IndexType)); + } + + BufferView CreateIndexBufferView(Allocator& allocator) const { + const auto index_buffer = CreateIndexBuffer(); + if (index_buffer.size() == 0) { + return {}; + } + auto buffer = allocator.CreateBufferWithCopy( + reinterpret_cast(index_buffer.data()), + index_buffer.size() * sizeof(IndexType)); + if (!buffer) { + return {}; + } + if (!label_.empty()) { + buffer->SetLabel(SPrintF("%s Indices", label_.c_str())); + } + return DeviceBuffer::AsBufferView(std::move(buffer)); + } +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_VERTEX_BUFFER_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.cc b/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8e4ee3422de1a0d686422acd5b423ac814077a6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/renderer/vertex_descriptor.h" + +namespace impeller { + +VertexDescriptor::VertexDescriptor() = default; + +VertexDescriptor::~VertexDescriptor() = default; + +void VertexDescriptor::SetStageInputs( + const ShaderStageIOSlot* const stage_inputs[], + size_t count, + const ShaderStageBufferLayout* const stage_layout[], + size_t layout_count) { + inputs_.reserve(inputs_.size() + count); + layouts_.reserve(layouts_.size() + layout_count); + for (size_t i = 0; i < count; i++) { + inputs_.emplace_back(*stage_inputs[i]); + } + for (size_t i = 0; i < layout_count; i++) { + layouts_.emplace_back(*stage_layout[i]); + } +} + +void VertexDescriptor::SetStageInputs( + const std::vector& inputs, + const std::vector& layout) { + inputs_.insert(inputs_.end(), inputs.begin(), inputs.end()); + layouts_.insert(layouts_.end(), layout.begin(), layout.end()); +} + +void VertexDescriptor::RegisterDescriptorSetLayouts( + const DescriptorSetLayout desc_set_layout[], + size_t count) { + desc_set_layouts_.reserve(desc_set_layouts_.size() + count); + for (size_t i = 0; i < count; i++) { + uses_input_attachments_ |= + desc_set_layout[i].descriptor_type == DescriptorType::kInputAttachment; + desc_set_layouts_.emplace_back(desc_set_layout[i]); + } +} + +// |Comparable| +size_t VertexDescriptor::GetHash() const { + auto seed = fml::HashCombine(); + for (const auto& input : inputs_) { + fml::HashCombineSeed(seed, input.GetHash()); + } + for (const auto& layout : layouts_) { + fml::HashCombineSeed(seed, layout.GetHash()); + } + return seed; +} + +// |Comparable| +bool VertexDescriptor::IsEqual(const VertexDescriptor& other) const { + return inputs_ == other.inputs_ && layouts_ == other.layouts_; +} + +const std::vector& VertexDescriptor::GetStageInputs() const { + return inputs_; +} + +const std::vector& VertexDescriptor::GetStageLayouts() + const { + return layouts_; +} + +const std::vector& +VertexDescriptor::GetDescriptorSetLayouts() const { + return desc_set_layouts_; +} + +bool VertexDescriptor::UsesInputAttacments() const { + return uses_input_attachments_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.h b/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.h new file mode 100644 index 0000000000000000000000000000000000000000..55c487e0cdf6a095ccb2e99ed5f8f6fc78469ea2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/renderer/vertex_descriptor.h @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RENDERER_VERTEX_DESCRIPTOR_H_ +#define FLUTTER_IMPELLER_RENDERER_VERTEX_DESCRIPTOR_H_ + +#include + +#include "impeller/base/comparable.h" +#include "impeller/core/shader_types.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Describes the format and layout of vertices expected by the +/// pipeline. While it is possible to construct these descriptors +/// manually, it would be tedious to do so. These are usually +/// constructed using shader information reflected using +/// `impellerc`. The usage of this class is indirectly via +/// `PipelineBuilder`. +/// +class VertexDescriptor final : public Comparable { + public: + static constexpr size_t kReservedVertexBufferIndex = + 30u; // The final slot available. Regular buffer indices go up from 0. + + VertexDescriptor(); + + // |Comparable| + virtual ~VertexDescriptor(); + + template + void SetStageInputs( + const std::array& inputs, + const std::array& layout) { + return SetStageInputs(inputs.data(), inputs.size(), layout.data(), + layout.size()); + } + + void SetStageInputs(const std::vector& inputs, + const std::vector& layout); + + template + void RegisterDescriptorSetLayouts( + const std::array& inputs) { + return RegisterDescriptorSetLayouts(inputs.data(), inputs.size()); + } + + void SetStageInputs(const ShaderStageIOSlot* const stage_inputs[], + size_t count, + const ShaderStageBufferLayout* const stage_layout[], + size_t layout_count); + + void RegisterDescriptorSetLayouts(const DescriptorSetLayout desc_set_layout[], + size_t count); + + const std::vector& GetStageInputs() const; + + const std::vector& GetStageLayouts() const; + + const std::vector& GetDescriptorSetLayouts() const; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const VertexDescriptor& other) const override; + + bool UsesInputAttacments() const; + + private: + std::vector inputs_; + std::vector layouts_; + std::vector desc_set_layouts_; + bool uses_input_attachments_ = false; + + VertexDescriptor(const VertexDescriptor&) = delete; + + VertexDescriptor& operator=(const VertexDescriptor&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RENDERER_VERTEX_DESCRIPTOR_H_ diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/BUILD.gn b/flutter/engine/src/flutter/impeller/runtime_stage/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8cc4f3b0a22355c16b1f995521e07b787499b082 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/third_party/flatbuffers/flatbuffers.gni") +import("../tools/impeller.gni") + +config("runtime_stage_config") { + configs = [ "//flutter/impeller:impeller_public_config" ] + include_dirs = [ + "$root_gen_dir/flutter", + "$root_gen_dir/flutter/impeller/runtime_stage", + ] +} + +flatbuffers("runtime_stage_types_flatbuffers") { + flatbuffers = [ "runtime_stage_types.fbs" ] + public_configs = [ ":runtime_stage_config" ] + public_deps = [ "//flutter/third_party/flatbuffers" ] +} + +flatbuffers("runtime_stage_flatbuffers") { + flatbuffers = [ "runtime_stage.fbs" ] + public_configs = [ ":runtime_stage_config" ] + public_deps = [ + ":runtime_stage_types_flatbuffers", + "//flutter/third_party/flatbuffers", + ] +} + +impeller_component("runtime_stage") { + sources = [ + "runtime_stage.cc", + "runtime_stage.h", + ] + public_deps = [ + ":runtime_stage_flatbuffers", + "../base", + "../core", + "//flutter/fml", + ] +} + +impeller_component("runtime_stage_unittests") { + testonly = true + + sources = [ + "runtime_stage_playground.cc", + "runtime_stage_playground.h", + "runtime_stage_unittests.cc", + ] + deps = [ + ":runtime_stage", + "../playground:playground_test", + "//flutter/testing", + ] +} diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.cc b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.cc new file mode 100644 index 0000000000000000000000000000000000000000..fb98148dfea5d95a9fbd56a0f5a3da89ac135069 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.cc @@ -0,0 +1,212 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/runtime_stage/runtime_stage.h" + +#include +#include + +#include "fml/mapping.h" +#include "impeller/base/validation.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/shader_types.h" +#include "impeller/runtime_stage/runtime_stage_flatbuffers.h" +#include "runtime_stage_types_flatbuffers.h" + +namespace impeller { + +static RuntimeUniformType ToType(fb::UniformDataType type) { + switch (type) { + case fb::UniformDataType::kFloat: + return RuntimeUniformType::kFloat; + case fb::UniformDataType::kSampledImage: + return RuntimeUniformType::kSampledImage; + case fb::UniformDataType::kStruct: + return RuntimeUniformType::kStruct; + } + FML_UNREACHABLE(); +} + +static RuntimeShaderStage ToShaderStage(fb::Stage stage) { + switch (stage) { + case fb::Stage::kVertex: + return RuntimeShaderStage::kVertex; + case fb::Stage::kFragment: + return RuntimeShaderStage::kFragment; + case fb::Stage::kCompute: + return RuntimeShaderStage::kCompute; + } + FML_UNREACHABLE(); +} + +/// The generated name from GLSLang/shaderc for the UBO containing non-opaque +/// uniforms specified in the user-written runtime effect shader. +/// +/// Vulkan does not allow non-opaque uniforms outside of a UBO. +const char* RuntimeStage::kVulkanUBOName = + "_RESERVED_IDENTIFIER_FIXUP_gl_DefaultUniformBlock"; + +std::unique_ptr RuntimeStage::RuntimeStageIfPresent( + const fb::RuntimeStage* runtime_stage, + const std::shared_ptr& payload) { + if (!runtime_stage) { + return nullptr; + } + + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + return std::unique_ptr( + new RuntimeStage(runtime_stage, payload)); +} + +RuntimeStage::Map RuntimeStage::DecodeRuntimeStages( + const std::shared_ptr& payload) { + if (payload == nullptr || !payload->GetMapping()) { + return {}; + } + if (!fb::RuntimeStagesBufferHasIdentifier(payload->GetMapping())) { + return {}; + } + + auto raw_stages = fb::GetRuntimeStages(payload->GetMapping()); + return { + {RuntimeStageBackend::kSkSL, + RuntimeStageIfPresent(raw_stages->sksl(), payload)}, + {RuntimeStageBackend::kMetal, + RuntimeStageIfPresent(raw_stages->metal(), payload)}, + {RuntimeStageBackend::kOpenGLES, + RuntimeStageIfPresent(raw_stages->opengles(), payload)}, + {RuntimeStageBackend::kOpenGLES3, + RuntimeStageIfPresent(raw_stages->opengles3(), payload)}, + {RuntimeStageBackend::kVulkan, + RuntimeStageIfPresent(raw_stages->vulkan(), payload)}, + }; +} + +RuntimeStage::RuntimeStage(const fb::RuntimeStage* runtime_stage, + const std::shared_ptr& payload) + : payload_(payload) { + FML_DCHECK(runtime_stage); + + stage_ = ToShaderStage(runtime_stage->stage()); + entrypoint_ = runtime_stage->entrypoint()->str(); + + auto* uniforms = runtime_stage->uniforms(); + + // Note: image bindings are screwy and will always have the same offset. + // track the binding of the UBO to determine where the image bindings go. + // This is only guaranteed to give us the correct bindings if there is a + // single sampler2D. + std::optional ubo_id; + if (uniforms) { + for (auto i = uniforms->begin(), end = uniforms->end(); i != end; i++) { + RuntimeUniformDescription desc; + desc.name = i->name()->str(); + desc.location = i->location(); + desc.binding = i->binding(); + desc.type = ToType(i->type()); + if (desc.type == kStruct) { + ubo_id = desc.location; + desc.binding = desc.location; + } + desc.dimensions = RuntimeUniformDimensions{ + static_cast(i->rows()), static_cast(i->columns())}; + desc.bit_width = i->bit_width(); + desc.array_elements = i->array_elements(); + if (i->struct_layout()) { + for (const auto& byte_type : *i->struct_layout()) { + desc.struct_layout.push_back(static_cast(byte_type)); + } + } + desc.struct_float_count = i->struct_float_count(); + uniforms_.push_back(std::move(desc)); + } + } + + code_mapping_ = std::make_shared( + runtime_stage->shader()->data(), // + runtime_stage->shader()->size(), // + [payload = payload_](auto, auto) {} // + ); + + size_t binding = 64; + if (ubo_id.has_value() && ubo_id.value() == binding) { + binding++; + } + for (auto& uniform : uniforms_) { + if (uniform.type == kSampledImage) { + uniform.binding = binding; + binding++; + if (ubo_id.has_value() && ubo_id.value() == binding) { + binding++; + } + } + } + + for (const auto& uniform : GetUniforms()) { + if (uniform.type == kStruct) { + descriptor_set_layouts_.push_back(DescriptorSetLayout{ + static_cast(uniform.location), + DescriptorType::kUniformBuffer, + ShaderStage::kFragment, + }); + } else if (uniform.type == kSampledImage) { + descriptor_set_layouts_.push_back(DescriptorSetLayout{ + static_cast(uniform.binding), + DescriptorType::kSampledImage, + ShaderStage::kFragment, + }); + } + } + is_valid_ = true; +} + +RuntimeStage::~RuntimeStage() = default; +RuntimeStage::RuntimeStage(RuntimeStage&&) = default; +RuntimeStage& RuntimeStage::operator=(RuntimeStage&&) = default; + +bool RuntimeStage::IsValid() const { + return is_valid_; +} + +const std::shared_ptr& RuntimeStage::GetCodeMapping() const { + return code_mapping_; +} + +const std::vector& RuntimeStage::GetUniforms() + const { + return uniforms_; +} + +const RuntimeUniformDescription* RuntimeStage::GetUniform( + const std::string& name) const { + for (const auto& uniform : uniforms_) { + if (uniform.name == name) { + return &uniform; + } + } + return nullptr; +} + +const std::string& RuntimeStage::GetEntrypoint() const { + return entrypoint_; +} + +RuntimeShaderStage RuntimeStage::GetShaderStage() const { + return stage_; +} + +bool RuntimeStage::IsDirty() const { + return is_dirty_; +} + +void RuntimeStage::SetClean() { + is_dirty_ = false; +} + +const std::vector& RuntimeStage::GetDescriptorSetLayouts() + const { + return descriptor_set_layouts_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.fbs b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.fbs new file mode 100644 index 0000000000000000000000000000000000000000..189fbf04340498eea01634a766b5cdd131ba6844 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.fbs @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +include "runtime_stage_types.fbs"; + +namespace impeller.fb; + +root_type RuntimeStages; +file_identifier "IPLR"; diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.h b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.h new file mode 100644 index 0000000000000000000000000000000000000000..86af3111f84ab36e2e144742098cf31b0d4299a9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage.h @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_H_ +#define FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_H_ + +#include +#include +#include + +#include "flutter/fml/mapping.h" + +#include "flutter/impeller/core/runtime_types.h" +#include "impeller/core/shader_types.h" +#include "runtime_stage_types_flatbuffers.h" + +namespace impeller { + +class RuntimeStage { + public: + static const char* kVulkanUBOName; + + using Map = std::map>; + static Map DecodeRuntimeStages(const std::shared_ptr& payload); + + RuntimeStage(const fb::RuntimeStage* runtime_stage, + const std::shared_ptr& payload); + ~RuntimeStage(); + RuntimeStage(RuntimeStage&&); + RuntimeStage& operator=(RuntimeStage&&); + + bool IsValid() const; + + RuntimeShaderStage GetShaderStage() const; + + const std::vector& GetUniforms() const; + + const std::vector& GetDescriptorSetLayouts() const; + + const std::string& GetEntrypoint() const; + + const RuntimeUniformDescription* GetUniform(const std::string& name) const; + + const std::shared_ptr& GetCodeMapping() const; + + bool IsDirty() const; + + void SetClean(); + + private: + std::shared_ptr payload_; + RuntimeShaderStage stage_ = RuntimeShaderStage::kVertex; + std::string entrypoint_; + std::shared_ptr code_mapping_; + std::vector uniforms_; + std::vector descriptor_set_layouts_; + bool is_valid_ = false; + bool is_dirty_ = true; + + RuntimeStage(const RuntimeStage&) = delete; + + static std::unique_ptr RuntimeStageIfPresent( + const fb::RuntimeStage* runtime_stage, + const std::shared_ptr& payload); + + RuntimeStage& operator=(const RuntimeStage&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_H_ diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.cc b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.cc new file mode 100644 index 0000000000000000000000000000000000000000..1267b6031dbcec5dbb3abd307a332a780bfd862e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/runtime_stage/runtime_stage_playground.h" + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/testing/testing.h" +#include "impeller/core/shader_types.h" +#include "impeller/renderer/shader_library.h" + +namespace impeller { + +RuntimeStagePlayground::RuntimeStagePlayground() = default; + +RuntimeStagePlayground::~RuntimeStagePlayground() = default; + +bool RuntimeStagePlayground::RegisterStage(const RuntimeStage& stage) { + std::promise registration; + auto future = registration.get_future(); + const std::shared_ptr& library = + GetContext()->GetShaderLibrary(); + GetContext()->GetShaderLibrary()->RegisterFunction( + stage.GetEntrypoint(), ToShaderStage(stage.GetShaderStage()), + stage.GetCodeMapping(), + fml::MakeCopyable([reg = std::move(registration)](bool result) mutable { + reg.set_value(result); + })); + return future.get(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.h b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.h new file mode 100644 index 0000000000000000000000000000000000000000..385089f4fc010261f0f80ff991e80733e8c0bb8a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_playground.h @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_ +#define FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_ + +#include "impeller/playground/playground_test.h" +#include "impeller/runtime_stage/runtime_stage.h" + +namespace impeller { + +class RuntimeStagePlayground : public PlaygroundTest { + public: + RuntimeStagePlayground(); + + ~RuntimeStagePlayground(); + + bool RegisterStage(const RuntimeStage& stage); + + private: + RuntimeStagePlayground(const RuntimeStagePlayground&) = delete; + + RuntimeStagePlayground& operator=(const RuntimeStagePlayground&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_RUNTIME_STAGE_RUNTIME_STAGE_PLAYGROUND_H_ diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_types.fbs b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_types.fbs new file mode 100644 index 0000000000000000000000000000000000000000..dd9f7f5a66d7199b985d3c7b92f658cc1c788405 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_types.fbs @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +namespace impeller.fb; + +enum Stage:byte { + kVertex, + kFragment, + kCompute, +} + +// The subset of impeller::ShaderType that may be used for uniform bindings. +// kStruct is only supported for Impeller Vulkan. +// kFloat encompases multiple float-based types e.g. vec2. +enum UniformDataType:uint32 { + kFloat, + kSampledImage, + kStruct, +} + +// A struct is made up solely of 4 byte floats and 4-byte paddings between +// them. +// This enum describes whether a particular byte is a float or padding. +enum StructByteType:uint8 { + kPadding = 0, + kFloat = 1, +} + +table UniformDescription { + name: string; + location: uint64; + binding: uint64; + type: UniformDataType; + bit_width: uint64; + rows: uint64; + columns: uint64; + array_elements: uint64; + struct_layout: [StructByteType]; + struct_float_count: uint64; +} + +// The subset of impeller::ShaderType that may be used for vertex attributes. +enum InputDataType:uint32 { + kBoolean, + kSignedByte, + kUnsignedByte, + kSignedShort, + kUnsignedShort, + kSignedInt, + kUnsignedInt, + kSignedInt64, + kUnsignedInt64, + kFloat, + kDouble, +} + +// This contains the same attribute reflection data as +// impeller::ShaderStageIOSlot. +table StageInput { + name: string; + location: uint64; + set: uint64; + binding: uint64; + type: InputDataType; + bit_width: uint64; + vec_size: uint64; + columns: uint64; + offset: uint64; +} + +table RuntimeStage { + stage: Stage; + entrypoint: string; + inputs: [StageInput]; + uniforms: [UniformDescription]; + shader: [ubyte]; + struct_byte_length: uint64; + float_count: uint64; +} + +table RuntimeStages { + sksl: RuntimeStage; + metal: RuntimeStage; + opengles: RuntimeStage; + opengles3: RuntimeStage; + vulkan: RuntimeStage; +} diff --git a/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_unittests.cc b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..8d6e466e04eaf9870c3c3dacd1c407550538dca0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/runtime_stage/runtime_stage_unittests.cc @@ -0,0 +1,372 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/fml/make_copyable.h" +#include "flutter/testing/testing.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "impeller/base/allocation.h" +#include "impeller/base/validation.h" +#include "impeller/core/runtime_types.h" +#include "impeller/core/shader_types.h" +#include "impeller/entity/runtime_effect.vert.h" +#include "impeller/playground/playground.h" +#include "impeller/renderer/pipeline_descriptor.h" +#include "impeller/renderer/pipeline_library.h" +#include "impeller/renderer/shader_library.h" +#include "impeller/runtime_stage/runtime_stage.h" +#include "impeller/runtime_stage/runtime_stage_playground.h" + +namespace impeller { +namespace testing { + +using RuntimeStageTest = RuntimeStagePlayground; +INSTANTIATE_PLAYGROUND_SUITE(RuntimeStageTest); + +TEST_P(RuntimeStageTest, CanReadValidBlob) { + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr"); + ASSERT_TRUE(fixture); + ASSERT_GT(fixture->GetSize(), 0u); + auto stages = RuntimeStage::DecodeRuntimeStages(fixture); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + ASSERT_TRUE(stage->IsValid()); + ASSERT_EQ(stage->GetShaderStage(), RuntimeShaderStage::kFragment); +} + +TEST_P(RuntimeStageTest, CanRejectInvalidBlob) { + ScopedValidationDisable disable_validation; + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr"); + ASSERT_TRUE(fixture); + auto junk_allocation = std::make_shared(); + ASSERT_TRUE(junk_allocation->Truncate(Bytes{fixture->GetSize()}, false)); + // Not meant to be secure. Just reject obviously bad blobs using magic + // numbers. + ::memset(junk_allocation->GetBuffer(), 127, + junk_allocation->GetLength().GetByteSize()); + auto stages = RuntimeStage::DecodeRuntimeStages( + CreateMappingFromAllocation(junk_allocation)); + ASSERT_FALSE(stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]); +} + +TEST_P(RuntimeStageTest, CanReadUniforms) { + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr"); + ASSERT_TRUE(fixture); + ASSERT_GT(fixture->GetSize(), 0u); + auto stages = RuntimeStage::DecodeRuntimeStages(fixture); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + + ASSERT_TRUE(stage->IsValid()); + switch (GetBackend()) { + case PlaygroundBackend::kMetal: + [[fallthrough]]; + case PlaygroundBackend::kOpenGLES: { + ASSERT_EQ(stage->GetUniforms().size(), 17u); + { + auto uni = stage->GetUniform("u_color"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 4u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 0u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_alpha"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 1u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_sparkle_color"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 4u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 2u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_sparkle_alpha"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 3u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_blur"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 4u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_radius_scale"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 6u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_max_radius"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 7u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_resolution_scale"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 8u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_noise_scale"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 9u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_noise_phase"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 1u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 10u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + + { + auto uni = stage->GetUniform("u_circle1"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 11u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_circle2"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 12u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_circle3"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 13u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_rotation1"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 14u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_rotation2"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 15u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + { + auto uni = stage->GetUniform("u_rotation3"); + ASSERT_NE(uni, nullptr); + EXPECT_EQ(uni->dimensions.rows, 2u); + EXPECT_EQ(uni->dimensions.cols, 1u); + EXPECT_EQ(uni->location, 16u); + EXPECT_EQ(uni->type, RuntimeUniformType::kFloat); + } + break; + } + case PlaygroundBackend::kVulkan: { + EXPECT_EQ(stage->GetUniforms().size(), 1u); + auto uni = stage->GetUniform(RuntimeStage::kVulkanUBOName); + ASSERT_TRUE(uni); + EXPECT_EQ(uni->type, RuntimeUniformType::kStruct); + EXPECT_EQ(uni->struct_float_count, 32u); + + // There are 36 4 byte chunks in the UBO: 32 for the 32 floats, and 4 for + // padding. Initialize a vector as if they'll all be floats, then manually + // set the few padding bytes. If the shader changes, the padding locations + // will change as well. For example, if `u_alpha` was moved to the end, + // three bytes of padding could potentially be dropped - or if some of the + // scalar floats were changed to vec2 or vec4s, or if any vec3s are + // introduced. + // This means 36 * 4 = 144 bytes total. + + EXPECT_EQ(uni->GetSize(), 144u); + std::vector layout(uni->GetSize() / sizeof(float), 1); + layout[5] = 0; + layout[6] = 0; + layout[7] = 0; + layout[23] = 0; + + EXPECT_THAT(uni->struct_layout, ::testing::ElementsAreArray(layout)); + break; + } + } +} + +TEST_P(RuntimeStageTest, CanReadUniformsSamplerBeforeUBO) { + if (GetBackend() != PlaygroundBackend::kVulkan) { + GTEST_SKIP() << "Test only relevant for Vulkan"; + } + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping( + "uniforms_and_sampler_1.frag.iplr"); + ASSERT_TRUE(fixture); + ASSERT_GT(fixture->GetSize(), 0u); + auto stages = RuntimeStage::DecodeRuntimeStages(fixture); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + + EXPECT_EQ(stage->GetUniforms().size(), 2u); + auto uni = stage->GetUniform(RuntimeStage::kVulkanUBOName); + ASSERT_TRUE(uni); + // Struct must be offset at 65. + EXPECT_EQ(uni->type, RuntimeUniformType::kStruct); + EXPECT_EQ(uni->binding, 65u); + // Sampler should be offset at 64 but due to current bug + // has offset of 0, the correct offset is computed at runtime. + auto sampler_uniform = stage->GetUniform("u_texture"); + EXPECT_EQ(sampler_uniform->type, RuntimeUniformType::kSampledImage); + EXPECT_EQ(sampler_uniform->binding, 64u); +} + +TEST_P(RuntimeStageTest, CanReadUniformsSamplerAfterUBO) { + if (GetBackend() != PlaygroundBackend::kVulkan) { + GTEST_SKIP() << "Test only relevant for Vulkan"; + } + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping( + "uniforms_and_sampler_2.frag.iplr"); + ASSERT_TRUE(fixture); + ASSERT_GT(fixture->GetSize(), 0u); + auto stages = RuntimeStage::DecodeRuntimeStages(fixture); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + + EXPECT_EQ(stage->GetUniforms().size(), 2u); + auto uni = stage->GetUniform(RuntimeStage::kVulkanUBOName); + ASSERT_TRUE(uni); + // Struct must be offset at 45. + EXPECT_EQ(uni->type, RuntimeUniformType::kStruct); + EXPECT_EQ(uni->binding, 64u); + // Sampler should be offset at 64 but due to current bug + // has offset of 0, the correct offset is computed at runtime. + auto sampler_uniform = stage->GetUniform("u_texture"); + EXPECT_EQ(sampler_uniform->type, RuntimeUniformType::kSampledImage); + EXPECT_EQ(sampler_uniform->binding, 65u); +} + +TEST_P(RuntimeStageTest, CanRegisterStage) { + const std::shared_ptr fixture = + flutter::testing::OpenFixtureAsMapping("ink_sparkle.frag.iplr"); + ASSERT_TRUE(fixture); + ASSERT_GT(fixture->GetSize(), 0u); + auto stages = RuntimeStage::DecodeRuntimeStages(fixture); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + ASSERT_TRUE(stage->IsValid()); + std::promise registration; + auto future = registration.get_future(); + auto library = GetContext()->GetShaderLibrary(); + library->RegisterFunction( + stage->GetEntrypoint(), // + ToShaderStage(stage->GetShaderStage()), // + stage->GetCodeMapping(), // + fml::MakeCopyable([reg = std::move(registration)](bool result) mutable { + reg.set_value(result); + })); + ASSERT_TRUE(future.get()); + { + auto function = + library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment); + ASSERT_NE(function, nullptr); + } + + // Check if unregistering works. + + library->UnregisterFunction(stage->GetEntrypoint(), ShaderStage::kFragment); + { + auto function = + library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment); + ASSERT_EQ(function, nullptr); + } +} + +TEST_P(RuntimeStageTest, CanCreatePipelineFromRuntimeStage) { + auto stages = OpenAssetAsRuntimeStage("ink_sparkle.frag.iplr"); + auto stage = stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; + + ASSERT_TRUE(stage); + ASSERT_NE(stage, nullptr); + ASSERT_TRUE(RegisterStage(*stage)); + auto library = GetContext()->GetShaderLibrary(); + using VS = RuntimeEffectVertexShader; + PipelineDescriptor desc; + desc.SetLabel("Runtime Stage InkSparkle"); + desc.AddStageEntrypoint( + library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex)); + desc.AddStageEntrypoint( + library->GetFunction(stage->GetEntrypoint(), ShaderStage::kFragment)); + auto vertex_descriptor = std::make_shared(); + vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs, + VS::kInterleavedBufferLayout); + + std::array descriptor_set_layouts = { + VS::kDescriptorSetLayouts[0], + DescriptorSetLayout{ + .binding = 64u, + .descriptor_type = DescriptorType::kUniformBuffer, + .shader_stage = ShaderStage::kFragment, + }, + }; + vertex_descriptor->RegisterDescriptorSetLayouts(descriptor_set_layouts); + + desc.SetVertexDescriptor(std::move(vertex_descriptor)); + ColorAttachmentDescriptor color0; + color0.format = GetContext()->GetCapabilities()->GetDefaultColorFormat(); + StencilAttachmentDescriptor stencil0; + stencil0.stencil_compare = CompareFunction::kEqual; + desc.SetColorAttachmentDescriptor(0u, color0); + desc.SetStencilAttachmentDescriptors(stencil0); + const auto stencil_fmt = + GetContext()->GetCapabilities()->GetDefaultStencilFormat(); + desc.SetStencilPixelFormat(stencil_fmt); + auto pipeline = GetContext()->GetPipelineLibrary()->GetPipeline(desc).Get(); + ASSERT_NE(pipeline, nullptr); +} + +TEST_P(RuntimeStageTest, ContainsExpectedShaderTypes) { + auto stages = OpenAssetAsRuntimeStage("ink_sparkle.frag.iplr"); + // Right now, SkSL gets implicitly bundled regardless of what the build rule + // for this test requested. After + // https://github.com/flutter/flutter/issues/138919, this may require a build + // rule change or a new test. + EXPECT_TRUE(stages[RuntimeStageBackend::kSkSL]); + + EXPECT_TRUE(stages[RuntimeStageBackend::kOpenGLES]); + EXPECT_TRUE(stages[RuntimeStageBackend::kMetal]); + EXPECT_TRUE(stages[RuntimeStageBackend::kVulkan]); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/shader_archive/BUILD.gn b/flutter/engine/src/flutter/impeller/shader_archive/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7e749b937222e0ec5d85c40b5f39332ca2ac0b48 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/third_party/flatbuffers/flatbuffers.gni") +import("../tools/impeller.gni") + +config("shader_archive_config") { + configs = [ "//flutter/impeller:impeller_public_config" ] + include_dirs = [ "$root_gen_dir/flutter" ] +} + +flatbuffers("shader_archive_flatbuffers") { + flatbuffers = [ "shader_archive.fbs" ] + public_configs = [ ":shader_archive_config" ] + public_deps = [ "//flutter/third_party/flatbuffers" ] +} + +impeller_component("shader_archive") { + sources = [ + "shader_archive.cc", + "shader_archive.h", + "shader_archive_types.h", + "shader_archive_writer.cc", + "shader_archive_writer.h", + ] + + public_deps = [ + ":shader_archive_flatbuffers", + "../base", + "//flutter/fml", + ] +} + +impeller_component("shader_archiver") { + target_type = "executable" + + sources = [ "shader_archive_main.cc" ] + + deps = [ + ":shader_archive", + "../base", + "//flutter/fml", + ] +} + +impeller_component("shader_archive_unittests") { + testonly = true + + sources = [ "shader_archive_unittests.cc" ] + + deps = [ + ":shader_archive", + "//flutter/fml", + "//flutter/testing", + ] +} diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.cc b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.cc new file mode 100644 index 0000000000000000000000000000000000000000..4cf2d3e1b564fae6740364a75c05620bedacf9b7 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/shader_archive/shader_archive.h" + +#include +#include +#include + +#include "impeller/base/validation.h" +#include "impeller/shader_archive/shader_archive_flatbuffers.h" + +namespace impeller { + +constexpr ArchiveShaderType ToShaderType(fb::Stage stage) { + switch (stage) { + case fb::Stage::kVertex: + return ArchiveShaderType::kVertex; + case fb::Stage::kFragment: + return ArchiveShaderType::kFragment; + case fb::Stage::kCompute: + return ArchiveShaderType::kCompute; + } + FML_UNREACHABLE(); +} + +ShaderArchive::ShaderArchive(std::shared_ptr payload) + : payload_(std::move(payload)) { + if (!payload_ || payload_->GetMapping() == nullptr) { + VALIDATION_LOG << "Shader mapping was absent."; + return; + } + + if (!fb::ShaderArchiveBufferHasIdentifier(payload_->GetMapping())) { + VALIDATION_LOG << "Invalid shader magic."; + return; + } + + auto shader_archive = fb::GetShaderArchive(payload_->GetMapping()); + if (!shader_archive) { + return; + } + + if (auto items = shader_archive->items()) { + for (auto i = items->begin(), end = items->end(); i != end; i++) { + ShaderKey key; + key.name = i->name()->str(); + key.type = ToShaderType(i->stage()); + shaders_[key] = std::make_shared( + i->mapping()->Data(), i->mapping()->size(), + [payload = payload_](auto, auto) { + // The pointers are into the base payload. Instead of copying the + // data, just hold onto the payload. + }); + } + } + + is_valid_ = true; +} + +ShaderArchive::ShaderArchive(ShaderArchive&&) = default; + +ShaderArchive::~ShaderArchive() = default; + +bool ShaderArchive::IsValid() const { + return is_valid_; +} + +size_t ShaderArchive::GetShaderCount() const { + return shaders_.size(); +} + +std::shared_ptr ShaderArchive::GetMapping( + ArchiveShaderType type, + std::string name) const { + ShaderKey key; + key.type = type; + key.name = std::move(name); + auto found = shaders_.find(key); + return found == shaders_.end() ? nullptr : found->second; +} + +size_t ShaderArchive::IterateAllShaders( + const std::function& mapping)>& + callback) const { + if (!IsValid() || !callback) { + return 0u; + } + size_t count = 0u; + for (const auto& shader : shaders_) { + count++; + if (!callback(shader.first.type, shader.first.name, shader.second)) { + break; + } + } + return count; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.fbs b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.fbs new file mode 100644 index 0000000000000000000000000000000000000000..0077f54a3535b520968c9b721e61516f9201f18a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.fbs @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +namespace impeller.fb; + +enum Stage:byte { + kVertex, + kFragment, + kCompute, +} + +table ShaderBlob { + stage: Stage; + name: string; + mapping: [ubyte]; +} + +table ShaderArchive { + items: [ShaderBlob]; +} + +root_type ShaderArchive; +file_identifier "SHAR"; diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.h b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.h new file mode 100644 index 0000000000000000000000000000000000000000..dc9c243785ca6552b1baf94c27585ecbcbd23b3a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_H_ +#define FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_H_ + +#include +#include +#include + +#include "flutter/fml/hash_combine.h" +#include "flutter/fml/mapping.h" +#include "impeller/shader_archive/shader_archive_types.h" + +namespace impeller { + +class ShaderArchive { + public: + explicit ShaderArchive(std::shared_ptr payload); + + ShaderArchive(ShaderArchive&&); + + ~ShaderArchive(); + + bool IsValid() const; + + size_t GetShaderCount() const; + + std::shared_ptr GetMapping(ArchiveShaderType type, + std::string name) const; + + size_t IterateAllShaders( + const std::function& mapping)>&) + const; + + private: + struct ShaderKey { + ArchiveShaderType type = ArchiveShaderType::kFragment; + std::string name; + + struct Hash { + size_t operator()(const ShaderKey& key) const { + return fml::HashCombine( + static_cast>(key.type), + key.name); + } + }; + + struct Equal { + bool operator()(const ShaderKey& lhs, const ShaderKey& rhs) const { + return lhs.type == rhs.type && lhs.name == rhs.name; + } + }; + }; + + using Shaders = std::unordered_map, + ShaderKey::Hash, + ShaderKey::Equal>; + + std::shared_ptr payload_; + Shaders shaders_; + bool is_valid_ = false; + + ShaderArchive(const ShaderArchive&) = delete; + + ShaderArchive& operator=(const ShaderArchive&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_H_ diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_main.cc b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..7220a8596021d3cb7e2be85305b80e1b91bcad7b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_main.cc @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "flutter/fml/command_line.h" +#include "impeller/shader_archive/shader_archive_writer.h" + +namespace impeller { + +bool Main(const fml::CommandLine& command_line) { + ShaderArchiveWriter writer; + + std::string output; + if (!command_line.GetOptionValue("output", &output)) { + std::cerr << "Output path not specified." << std::endl; + return false; + } + + for (const auto& input : command_line.GetOptionValues("input")) { + if (!writer.AddShaderAtPath(std::string{input})) { + std::cerr << "Could not add shader at path: " << input << std::endl; + return false; + } + } + + auto archive = writer.CreateMapping(); + if (!archive) { + std::cerr << "Could not create shader archive." << std::endl; + return false; + } + + auto current_directory = + fml::OpenDirectory(std::filesystem::current_path().string().c_str(), + false, fml::FilePermission::kReadWrite); + auto output_path = + std::filesystem::absolute(std::filesystem::current_path() / output); + if (!fml::WriteAtomically(current_directory, output_path.string().c_str(), + *archive)) { + std::cerr << "Could not write shader archive to path " << output + << std::endl; + return false; + } + + return true; +} + +} // namespace impeller + +int main(int argc, char const* argv[]) { + return impeller::Main(fml::CommandLineFromPlatformOrArgcArgv(argc, argv)) + ? EXIT_SUCCESS + : EXIT_FAILURE; +} diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_types.h b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_types.h new file mode 100644 index 0000000000000000000000000000000000000000..fb9273d82eb61d0bc00b4fc6401b7486cd0e9908 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_types.h @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_TYPES_H_ +#define FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_TYPES_H_ + +namespace impeller { + +enum class ArchiveShaderType { + kVertex, + kFragment, + kCompute, +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_TYPES_H_ diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_unittests.cc b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba4a3072c91b7afbaabe89cc8c551f82c2ab869b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_unittests.cc @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "flutter/fml/mapping.h" +#include "flutter/testing/testing.h" +#include "impeller/shader_archive/shader_archive.h" +#include "impeller/shader_archive/shader_archive_writer.h" + +namespace impeller { +namespace testing { + +static std::shared_ptr CreateMappingFromString( + std::string p_string) { + auto string = std::make_shared(std::move(p_string)); + return std::make_shared( + reinterpret_cast(string->data()), string->size(), + [string](auto, auto) {}); +} + +const std::string CreateStringFromMapping(const fml::Mapping& mapping) { + return std::string{reinterpret_cast(mapping.GetMapping()), + mapping.GetSize()}; +} + +TEST(ShaderArchiveTest, CanReadAndWriteBlobs) { + ShaderArchiveWriter writer; + ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Hello", + CreateMappingFromString("World"))); + ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kFragment, "Foo", + CreateMappingFromString("Bar"))); + ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Baz", + CreateMappingFromString("Bang"))); + ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kVertex, "Ping", + CreateMappingFromString("Pong"))); + ASSERT_TRUE(writer.AddShader(ArchiveShaderType::kFragment, "Pang", + CreateMappingFromString("World"))); + + auto mapping = writer.CreateMapping(); + ASSERT_NE(mapping, nullptr); + + ShaderArchive library(mapping); + ASSERT_TRUE(library.IsValid()); + ASSERT_EQ(library.GetShaderCount(), 5u); + + // Wrong type. + ASSERT_EQ(library.GetMapping(ArchiveShaderType::kFragment, "Hello"), nullptr); + + auto hello_vtx = library.GetMapping(ArchiveShaderType::kVertex, "Hello"); + ASSERT_NE(hello_vtx, nullptr); + ASSERT_EQ(CreateStringFromMapping(*hello_vtx), "World"); +} + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.cc b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.cc new file mode 100644 index 0000000000000000000000000000000000000000..83c0459f34ebe05a40939ebdb614b7349447ca07 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.cc @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/shader_archive/shader_archive_writer.h" + +#include +#include +#include + +#include "impeller/shader_archive/shader_archive_flatbuffers.h" + +namespace impeller { + +ShaderArchiveWriter::ShaderArchiveWriter() = default; + +ShaderArchiveWriter::~ShaderArchiveWriter() = default; + +std::optional InferShaderTypefromFileExtension( + const std::filesystem::path& path) { + if (path == ".vert") { + return ArchiveShaderType::kVertex; + } else if (path == ".frag") { + return ArchiveShaderType::kFragment; + } else if (path == ".comp") { + return ArchiveShaderType::kCompute; + } + return std::nullopt; +} + +bool ShaderArchiveWriter::AddShaderAtPath(const std::string& std_path) { + std::filesystem::path path(std_path); + + if (path.stem().empty()) { + FML_LOG(ERROR) << "File path stem was empty for " << path; + return false; + } + + if (path.extension() != ".gles" && path.extension() != ".vkspv") { + FML_LOG(ERROR) << "File path doesn't have a known shader extension " + << path; + return false; + } + + // Get rid of .gles + path = path.replace_extension(); + + auto shader_type = InferShaderTypefromFileExtension(path.extension()); + + if (!shader_type.has_value()) { + FML_LOG(ERROR) << "Could not infer shader type from file extension: " + << path.extension().string(); + return false; + } + + // Get rid of the shader type extension (.vert, .frag, etc..). + path = path.replace_extension(); + + const auto shader_name = path.stem().string(); + if (shader_name.empty()) { + FML_LOG(ERROR) << "Shader name was empty."; + return false; + } + + auto file_mapping = fml::FileMapping::CreateReadOnly(std_path); + if (!file_mapping) { + FML_LOG(ERROR) << "File doesn't exist at path: " << path; + return false; + } + + return AddShader(shader_type.value(), shader_name, std::move(file_mapping)); +} + +bool ShaderArchiveWriter::AddShader(ArchiveShaderType type, + std::string name, + std::shared_ptr mapping) { + if (name.empty() || !mapping || mapping->GetMapping() == nullptr) { + return false; + } + + shader_descriptions_.emplace_back( + ShaderDescription{type, std::move(name), std::move(mapping)}); + return true; +} + +constexpr fb::Stage ToStage(ArchiveShaderType type) { + switch (type) { + case ArchiveShaderType::kVertex: + return fb::Stage::kVertex; + case ArchiveShaderType::kFragment: + return fb::Stage::kFragment; + case ArchiveShaderType::kCompute: + return fb::Stage::kCompute; + } + FML_UNREACHABLE(); +} + +std::shared_ptr ShaderArchiveWriter::CreateMapping() const { + fb::ShaderArchiveT shader_archive; + for (const auto& shader_description : shader_descriptions_) { + auto mapping = shader_description.mapping; + if (!mapping) { + return nullptr; + } + auto desc = std::make_unique(); + desc->name = shader_description.name; + desc->stage = ToStage(shader_description.type); + desc->mapping = {mapping->GetMapping(), + mapping->GetMapping() + mapping->GetSize()}; + shader_archive.items.emplace_back(std::move(desc)); + } + auto builder = std::make_shared(); + builder->Finish(fb::ShaderArchive::Pack(*builder.get(), &shader_archive), + fb::ShaderArchiveIdentifier()); + return std::make_shared(builder->GetBufferPointer(), + builder->GetSize(), + [builder](auto, auto) {}); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.h b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..dd1dbf3234639e0679c701f54f4bd8cfce7eb0f9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_archive/shader_archive_writer.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_ +#define FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_ + +#include +#include +#include + +#include "flutter/fml/mapping.h" +#include "impeller/shader_archive/shader_archive_types.h" + +namespace impeller { + +class ShaderArchiveWriter { + public: + ShaderArchiveWriter(); + + ~ShaderArchiveWriter(); + + [[nodiscard]] bool AddShaderAtPath(const std::string& path); + + [[nodiscard]] bool AddShader(ArchiveShaderType type, + std::string name, + std::shared_ptr mapping); + + std::shared_ptr CreateMapping() const; + + private: + struct ShaderDescription { + ArchiveShaderType type; + std::string name; + std::shared_ptr mapping; + }; + + std::vector shader_descriptions_; + + ShaderArchiveWriter(const ShaderArchiveWriter&) = delete; + + ShaderArchiveWriter& operator=(const ShaderArchiveWriter&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_SHADER_ARCHIVE_SHADER_ARCHIVE_WRITER_H_ diff --git a/flutter/engine/src/flutter/impeller/shader_bundle/BUILD.gn b/flutter/engine/src/flutter/impeller/shader_bundle/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..14b6effb23d4f5f5c666416ef8bfb1b3ea9ab2aa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_bundle/BUILD.gn @@ -0,0 +1,12 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/third_party/flatbuffers/flatbuffers.gni") +import("../tools/impeller.gni") + +flatbuffers("shader_bundle_flatbuffers") { + flatbuffers = [ "shader_bundle.fbs" ] + public_configs = [ "//flutter/impeller:impeller_public_config" ] + public_deps = [ "//flutter/third_party/flatbuffers" ] +} diff --git a/flutter/engine/src/flutter/impeller/shader_bundle/shader_bundle.fbs b/flutter/engine/src/flutter/impeller/shader_bundle/shader_bundle.fbs new file mode 100644 index 0000000000000000000000000000000000000000..490312223d54cf462713c7dddf184a998adf6199 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/shader_bundle/shader_bundle.fbs @@ -0,0 +1,108 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +namespace impeller.fb.shaderbundle; + +enum ShaderStage:byte { + kVertex, + kFragment, + kCompute, +} + +// The subset of impeller::ShaderType that may be used for vertex attributes. +enum InputDataType:uint32 { + kBoolean, + kSignedByte, + kUnsignedByte, + kSignedShort, + kUnsignedShort, + kSignedInt, + kUnsignedInt, + kSignedInt64, + kUnsignedInt64, + kFloat, + kDouble, +} + +// The subset of impeller::ShaderType that may be used for uniform bindings. +enum UniformDataType:uint32 { + kBoolean, + kSignedByte, + kUnsignedByte, + kSignedShort, + kUnsignedShort, + kSignedInt, + kUnsignedInt, + kSignedInt64, + kUnsignedInt64, + kHalfFloat, + kFloat, + kDouble, + kSampledImage, +} + +// This contains the same attribute reflection data as +// impeller::ShaderStageIOSlot. +table ShaderInput { + name: string; + location: uint64; + set: uint64; + binding: uint64; + type: InputDataType; + bit_width: uint64; + vec_size: uint64; + columns: uint64; + offset: uint64; +} + +table ShaderUniformStructField { + name: string; + type: UniformDataType; + offset_in_bytes: uint64; + element_size_in_bytes: uint64; + total_size_in_bytes: uint64; + // Zero indicates that this field is not an array element. + array_elements: uint64; +} + +table ShaderUniformStruct { + name: string; + ext_res_0: uint64; + set: uint64; + binding: uint64; + size_in_bytes: uint64; // Includes all alignment padding. + fields: [ShaderUniformStructField]; +} + +table ShaderUniformTexture { + name: string; + ext_res_0: uint64; + set: uint64; + binding: uint64; +} + +table BackendShader { + stage: ShaderStage; + entrypoint: string; + inputs: [ShaderInput]; + uniform_structs: [ShaderUniformStruct]; + uniform_textures: [ShaderUniformTexture]; + shader: [ubyte]; +} + +table Shader { + name: string; + metal_ios: BackendShader; + metal_desktop: BackendShader; + opengl_es: BackendShader; + opengl_desktop: BackendShader; + vulkan: BackendShader; +} + +table ShaderBundle { + shaders: [Shader]; +} + +root_type ShaderBundle; +file_identifier "IPSB"; diff --git a/flutter/engine/src/flutter/impeller/tessellator/BUILD.gn b/flutter/engine/src/flutter/impeller/tessellator/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2a821e667b58395c6c8be7c24db23a32561f7294 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("tessellator") { + sources = [ + "tessellator.cc", + "tessellator.h", + ] + + public_deps = [ "../geometry" ] + + deps = [ + "../core", + "//flutter/fml", + ] +} + +impeller_component("tessellator_libtess") { + sources = [ + "tessellator_libtess.cc", + "tessellator_libtess.h", + ] + + public_deps = [ "../geometry" ] + + deps = [ + "../core", + "//flutter/fml", + "//third_party/libtess2", + ] +} + +impeller_component("tessellator_shared") { + target_type = "shared_library" + if (is_win) { + output_name = "libtessellator" + } else { + output_name = "tessellator" + } + + sources = [ + "c/tessellator.cc", + "c/tessellator.h", + ] + + deps = [ + ":tessellator_libtess", + "../core", + "../geometry", + "//flutter/fml", + "//third_party/libtess2", + ] + + metadata = { + entitlement_file_path = [ "libtessellator.dylib" ] + } +} + +impeller_component("tessellator_unittests") { + testonly = true + sources = [ "tessellator_unittests.cc" ] + deps = [ + ":tessellator_libtess", + "../geometry:geometry_asserts", + "//flutter/testing", + ] +} diff --git a/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.cc b/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe3587beb297bf7614088312f700cb9cc34c1a53 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.cc @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "tessellator.h" + +#include + +#include "impeller/tessellator/tessellator_libtess.h" + +namespace impeller { +PathBuilder* CreatePathBuilder() { + return new PathBuilder(); +} + +void DestroyPathBuilder(PathBuilder* builder) { + delete builder; +} + +void MoveTo(PathBuilder* builder, Scalar x, Scalar y) { + builder->MoveTo(Point(x, y)); +} + +void LineTo(PathBuilder* builder, Scalar x, Scalar y) { + builder->LineTo(Point(x, y)); +} + +void CubicTo(PathBuilder* builder, + Scalar x1, + Scalar y1, + Scalar x2, + Scalar y2, + Scalar x3, + Scalar y3) { + builder->CubicCurveTo(Point(x1, y1), Point(x2, y2), Point(x3, y3)); +} + +void Close(PathBuilder* builder) { + builder->Close(); +} + +struct Vertices* Tessellate(PathBuilder* builder, + int fill_type, + Scalar tolerance) { + auto path = builder->CopyPath(static_cast(fill_type)); + std::vector points; + if (TessellatorLibtess{}.Tessellate( + path, tolerance, + [&points](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { + // Results are expected to be re-duplicated. + std::vector raw_points; + for (auto i = 0u; i < vertices_count * 2; i += 2) { + raw_points.emplace_back(Point{vertices[i], vertices[i + 1]}); + } + for (auto i = 0u; i < indices_count; i++) { + auto point = raw_points[indices[i]]; + points.push_back(point.x); + points.push_back(point.y); + } + return true; + }) != TessellatorLibtess::Result::kSuccess) { + return nullptr; + } + + Vertices* vertices = new Vertices(); + vertices->points = new float[points.size()]; + if (!vertices->points) { + return nullptr; + } + vertices->length = points.size(); + std::copy(points.begin(), points.end(), vertices->points); + return vertices; +} + +void DestroyVertices(Vertices* vertices) { + delete vertices->points; + delete vertices; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.h b/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.h new file mode 100644 index 0000000000000000000000000000000000000000..c8e19b0e4f24806d4eae1e0e45d4086bdba07fab --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/c/tessellator.h @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TESSELLATOR_C_TESSELLATOR_H_ +#define FLUTTER_IMPELLER_TESSELLATOR_C_TESSELLATOR_H_ + +#include + +#include "impeller/geometry/path_builder.h" + +#ifdef _WIN32 +#define IMPELLER_API __declspec(dllexport) +#else +#define IMPELLER_API __attribute__((visibility("default"))) +#endif + +extern "C" { + +namespace impeller { + +struct IMPELLER_API Vertices { + float* points; + uint32_t length; +}; + +IMPELLER_API PathBuilder* CreatePathBuilder(); + +IMPELLER_API void DestroyPathBuilder(PathBuilder* builder); + +IMPELLER_API void MoveTo(PathBuilder* builder, Scalar x, Scalar y); + +IMPELLER_API void LineTo(PathBuilder* builder, Scalar x, Scalar y); + +IMPELLER_API void CubicTo(PathBuilder* builder, + Scalar x1, + Scalar y1, + Scalar x2, + Scalar y2, + Scalar x3, + Scalar y3); + +IMPELLER_API void Close(PathBuilder* builder); + +IMPELLER_API struct Vertices* Tessellate(PathBuilder* builder, + int fill_type, + Scalar tolerance); + +IMPELLER_API void DestroyVertices(Vertices* vertices); + +} // namespace impeller +} + +#endif // FLUTTER_IMPELLER_TESSELLATOR_C_TESSELLATOR_H_ diff --git a/flutter/engine/src/flutter/impeller/tessellator/dart/lib/tessellator.dart b/flutter/engine/src/flutter/impeller/tessellator/dart/lib/tessellator.dart new file mode 100644 index 0000000000000000000000000000000000000000..e228620fe9b7a8a6f5cb07311dc8422f96013743 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/dart/lib/tessellator.dart @@ -0,0 +1,210 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: camel_case_types +import 'dart:ffi' as ffi; +import 'dart:io'; +import 'dart:typed_data'; + +/// Determines the winding rule that decides how the interior of a Path is +/// calculated. +/// +/// This enum is used by the [VerticesBuilder.tessellate] method. +// must match ordering in geometry/path.h +enum FillType { + /// The interior is defined by a non-zero sum of signed edge crossings. + nonZero, + + /// The interior is defined by an odd number of edge crossings. + evenOdd, +} + +/// Information about how to approximate points on a curved path segment. +/// +/// In particular, the values in this object control how many vertices to +/// generate when approximating curves, and what tolerances to use when +/// calculating the sharpness of curves. +/// +/// Used by [VerticesBuilder.tessellate]. +class SmoothingApproximation { + /// Creates a new smoothing approximation instance with default values. + const SmoothingApproximation({this.scale = 1.0, this.angleTolerance = 0.0, this.cuspLimit = 0.0}); + + /// The scaling coefficient to use when translating to screen coordinates. + /// + /// Values approaching 0.0 will generate smoother looking curves with a + /// greater number of vertices, and will be more expensive to calculate. + final double scale; + + /// The tolerance value in radians for calculating sharp angles. + /// + /// Values approaching 0.0 will provide more accurate approximation of sharp + /// turns. A 0.0 value means angle conditions are not considered at all. + final double angleTolerance; + + /// An angle in radians at which to introduce bevel cuts. + /// + /// Values greater than zero will restirct the sharpness of bevel cuts on + /// turns. + final double cuspLimit; +} + +/// Creates vertices from path commands. +/// +/// First, build up the path contours with the [moveTo], [lineTo], [cubicTo], +/// and [close] methods. All methods expect absolute coordinates. +/// +/// Then, use the [tessellate] method to create a [Float32List] of vertex pairs. +/// +/// Finally, use the [dispose] method to clean up native resources. After +/// [dispose] has been called, this class must not be used again. +class VerticesBuilder { + /// Constructs a [VerticesBuilder] instance to which path commands can be + /// added. + VerticesBuilder() : _builder = _createPathFn(); + + ffi.Pointer<_PathBuilder>? _builder; + final List> _vertices = >[]; + + /// Adds a move verb to the absolute coordinates x,y. + void moveTo(double x, double y) { + assert(_builder != null); + _moveToFn(_builder!, x, y); + } + + /// Adds a line verb to the absolute coordinates x,y. + void lineTo(double x, double y) { + assert(_builder != null); + _lineToFn(_builder!, x, y); + } + + /// Adds a cubic Bezier curve with x1,y1 as the first control point, x2,y2 as + /// the second control point, and end point x3,y3. + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { + assert(_builder != null); + _cubicToFn(_builder!, x1, y1, x2, y2, x3, y3); + } + + /// Adds a close command to the start of the current contour. + void close() { + assert(_builder != null); + _closeFn(_builder!, true); + } + + /// Tessellates the path created by the previous method calls into a list of + /// vertices. + Float32List tessellate({ + FillType fillType = FillType.nonZero, + SmoothingApproximation smoothing = const SmoothingApproximation(), + }) { + assert(_vertices.isEmpty); + assert(_builder != null); + final ffi.Pointer<_Vertices> vertices = _tessellateFn( + _builder!, + fillType.index, + smoothing.scale, + smoothing.angleTolerance, + smoothing.cuspLimit, + ); + _vertices.add(vertices); + return vertices.ref.points.asTypedList(vertices.ref.size); + } + + /// Releases native resources. + /// + /// After calling dispose, this class must not be used again. + void dispose() { + assert(_builder != null); + _vertices.forEach(_destroyVerticesFn); + _destroyFn(_builder!); + _vertices.clear(); + _builder = null; + } +} + +// TODO(dnfield): Figure out where to put this. +// https://github.com/flutter/flutter/issues/99563 +final ffi.DynamicLibrary _dylib = () { + if (Platform.isWindows) { + return ffi.DynamicLibrary.open('tessellator.dll'); + } else if (Platform.isIOS || Platform.isMacOS) { + return ffi.DynamicLibrary.open('libtessellator.dylib'); + } else if (Platform.isAndroid || Platform.isLinux) { + return ffi.DynamicLibrary.open('libtessellator.so'); + } + throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}'); +}(); + +final class _Vertices extends ffi.Struct { + external ffi.Pointer points; + + @ffi.Uint32() + external int size; +} + +final class _PathBuilder extends ffi.Opaque {} + +typedef _CreatePathBuilderType = ffi.Pointer<_PathBuilder> Function(); +typedef _create_path_builder_type = ffi.Pointer<_PathBuilder> Function(); + +final _CreatePathBuilderType _createPathFn = _dylib + .lookupFunction<_create_path_builder_type, _CreatePathBuilderType>('CreatePathBuilder'); + +typedef _MoveToType = void Function(ffi.Pointer<_PathBuilder>, double, double); +typedef _move_to_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); + +final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>('MoveTo'); + +typedef _LineToType = void Function(ffi.Pointer<_PathBuilder>, double, double); +typedef _line_to_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); + +final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>('LineTo'); + +typedef _CubicToType = + void Function(ffi.Pointer<_PathBuilder>, double, double, double, double, double, double); +typedef _cubic_to_type = + ffi.Void Function( + ffi.Pointer<_PathBuilder>, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ); + +final _CubicToType _cubicToFn = _dylib.lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); + +typedef _CloseType = void Function(ffi.Pointer<_PathBuilder>, bool); +typedef _close_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Bool); + +final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>('Close'); + +typedef _TessellateType = + ffi.Pointer<_Vertices> Function(ffi.Pointer<_PathBuilder>, int, double, double, double); +typedef _tessellate_type = + ffi.Pointer<_Vertices> Function( + ffi.Pointer<_PathBuilder>, + ffi.Int, + ffi.Float, + ffi.Float, + ffi.Float, + ); + +final _TessellateType _tessellateFn = _dylib.lookupFunction<_tessellate_type, _TessellateType>( + 'Tessellate', +); + +typedef _DestroyType = void Function(ffi.Pointer<_PathBuilder>); +typedef _destroy_type = ffi.Void Function(ffi.Pointer<_PathBuilder>); + +final _DestroyType _destroyFn = _dylib.lookupFunction<_destroy_type, _DestroyType>( + 'DestroyPathBuilder', +); + +typedef _DestroyVerticesType = void Function(ffi.Pointer<_Vertices>); +typedef _destroy_vertices_type = ffi.Void Function(ffi.Pointer<_Vertices>); + +final _DestroyVerticesType _destroyVerticesFn = _dylib + .lookupFunction<_destroy_vertices_type, _DestroyVerticesType>('DestroyVertices'); diff --git a/flutter/engine/src/flutter/impeller/tessellator/dart/pubspec.yaml b/flutter/engine/src/flutter/impeller/tessellator/dart/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..618220c2e93e083f040069f236799b0ae5bb495d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/dart/pubspec.yaml @@ -0,0 +1,12 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +name: tessellator +publish_to: none + +# Required for workspace support. +environment: + sdk: ^3.7.0-0 + +# This package is managed as part of the engine workspace. +resolution: workspace diff --git a/flutter/engine/src/flutter/impeller/tessellator/tessellator.cc b/flutter/engine/src/flutter/impeller/tessellator/tessellator.cc new file mode 100644 index 0000000000000000000000000000000000000000..383440658cc7f5c55a1d771558714e5fb5bea548 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/tessellator.cc @@ -0,0 +1,626 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/tessellator/tessellator.h" +#include +#include + +#include "impeller/core/device_buffer.h" +#include "impeller/geometry/path_component.h" + +namespace impeller { + +Tessellator::Tessellator() + : point_buffer_(std::make_unique>()), + index_buffer_(std::make_unique>()), + stroke_points_(kPointArenaSize) { + point_buffer_->reserve(2048); + index_buffer_->reserve(2048); +} + +Tessellator::~Tessellator() = default; + +std::vector& Tessellator::GetStrokePointCache() { + return stroke_points_; +} + +Path::Polyline Tessellator::CreateTempPolyline(const Path& path, + Scalar tolerance) { + FML_DCHECK(point_buffer_); + point_buffer_->clear(); + auto polyline = + path.CreatePolyline(tolerance, std::move(point_buffer_), + [this](Path::Polyline::PointBufferPtr point_buffer) { + point_buffer_ = std::move(point_buffer); + }); + return polyline; +} + +VertexBuffer Tessellator::TessellateConvex(const Path& path, + HostBuffer& host_buffer, + Scalar tolerance, + bool supports_primitive_restart, + bool supports_triangle_fan) { + if (supports_primitive_restart) { + // Primitive Restart. + const auto [point_count, contour_count] = path.CountStorage(tolerance); + BufferView point_buffer = host_buffer.Emplace( + nullptr, sizeof(Point) * point_count, alignof(Point)); + BufferView index_buffer = host_buffer.Emplace( + nullptr, sizeof(uint16_t) * (point_count + contour_count), + alignof(uint16_t)); + + if (supports_triangle_fan) { + FanVertexWriter writer( + reinterpret_cast(point_buffer.GetBuffer()->OnGetContents() + + point_buffer.GetRange().offset), + reinterpret_cast( + index_buffer.GetBuffer()->OnGetContents() + + index_buffer.GetRange().offset)); + path.WritePolyline(tolerance, writer); + point_buffer.GetBuffer()->Flush(point_buffer.GetRange()); + index_buffer.GetBuffer()->Flush(index_buffer.GetRange()); + + return VertexBuffer{ + .vertex_buffer = std::move(point_buffer), + .index_buffer = std::move(index_buffer), + .vertex_count = writer.GetIndexCount(), + .index_type = IndexType::k16bit, + }; + } else { + StripVertexWriter writer( + reinterpret_cast(point_buffer.GetBuffer()->OnGetContents() + + point_buffer.GetRange().offset), + reinterpret_cast( + index_buffer.GetBuffer()->OnGetContents() + + index_buffer.GetRange().offset)); + path.WritePolyline(tolerance, writer); + point_buffer.GetBuffer()->Flush(point_buffer.GetRange()); + index_buffer.GetBuffer()->Flush(index_buffer.GetRange()); + + return VertexBuffer{ + .vertex_buffer = std::move(point_buffer), + .index_buffer = std::move(index_buffer), + .vertex_count = writer.GetIndexCount(), + .index_type = IndexType::k16bit, + }; + } + } + + FML_DCHECK(point_buffer_); + FML_DCHECK(index_buffer_); + TessellateConvexInternal(path, *point_buffer_, *index_buffer_, tolerance); + + if (point_buffer_->empty()) { + return VertexBuffer{ + .vertex_buffer = {}, + .index_buffer = {}, + .vertex_count = 0u, + .index_type = IndexType::k16bit, + }; + } + + BufferView vertex_buffer = host_buffer.Emplace( + point_buffer_->data(), sizeof(Point) * point_buffer_->size(), + alignof(Point)); + + BufferView index_buffer = host_buffer.Emplace( + index_buffer_->data(), sizeof(uint16_t) * index_buffer_->size(), + alignof(uint16_t)); + + return VertexBuffer{ + .vertex_buffer = std::move(vertex_buffer), + .index_buffer = std::move(index_buffer), + .vertex_count = index_buffer_->size(), + .index_type = IndexType::k16bit, + }; +} + +VertexBuffer Tessellator::GenerateLineStrip(const Path& path, + HostBuffer& host_buffer, + Scalar tolerance) { + LineStripVertexWriter writer(stroke_points_); + path.WritePolyline(tolerance, writer); + + const auto [arena_length, oversized_length] = writer.GetVertexCount(); + + if (oversized_length == 0) { + return VertexBuffer{ + .vertex_buffer = + host_buffer.Emplace(stroke_points_.data(), + arena_length * sizeof(Point), alignof(Point)), + .index_buffer = {}, + .vertex_count = arena_length, + .index_type = IndexType::kNone, + }; + } + const std::vector& oversized_data = writer.GetOversizedBuffer(); + BufferView buffer_view = host_buffer.Emplace( + /*buffer=*/nullptr, // + (arena_length + oversized_length) * sizeof(Point), // + alignof(Point) // + ); + memcpy(buffer_view.GetBuffer()->OnGetContents() + + buffer_view.GetRange().offset, // + stroke_points_.data(), // + arena_length * sizeof(Point) // + ); + memcpy(buffer_view.GetBuffer()->OnGetContents() + + buffer_view.GetRange().offset + arena_length * sizeof(Point), // + oversized_data.data(), // + oversized_data.size() * sizeof(Point) // + ); + buffer_view.GetBuffer()->Flush(buffer_view.GetRange()); + + return VertexBuffer{ + .vertex_buffer = buffer_view, + .index_buffer = {}, + .vertex_count = arena_length + oversized_length, + .index_type = IndexType::kNone, + }; +} + +void Tessellator::TessellateConvexInternal(const Path& path, + std::vector& point_buffer, + std::vector& index_buffer, + Scalar tolerance) { + point_buffer.clear(); + index_buffer.clear(); + + GLESVertexWriter writer(point_buffer, index_buffer); + + path.WritePolyline(tolerance, writer); +} + +static constexpr int kPrecomputedDivisionCount = 1024; +static int kPrecomputedDivisions[kPrecomputedDivisionCount] = { + // clang-format off + 1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, + 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, + 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, + 30, 30, 30, 30, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, + 31, 31, 31, 31, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, + 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, + 33, 33, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, + 34, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 35, 35, 35, + 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 36, + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, + 36, 36, 36, 36, 36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 38, 38, 38, 38, + 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, + 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, + 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, + 43, 43, 43, 43, 43, 43, 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, + 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, + 44, 44, 44, 44, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, + 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, + 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, + 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 47, + 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, + 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 48, 48, 48, + 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, + 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, + 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, + 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, + 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 54, + 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, + 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, + 54, 54, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, + 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, + 55, 55, 55, 55, 55, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, + 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, + 56, 56, 56, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, + // clang-format on +}; + +static size_t ComputeQuadrantDivisions(Scalar pixel_radius) { + if (pixel_radius <= 0.0) { + return 1; + } + int radius_index = ceil(pixel_radius); + if (radius_index < kPrecomputedDivisionCount) { + return kPrecomputedDivisions[radius_index]; + } + + // For a circle with N divisions per quadrant, the maximum deviation of + // the polgyon approximation from the true circle will be at the center + // of the base of each triangular pie slice. We can compute that distance + // by finding the midpoint of the line of the first slice and compare + // its distance from the center of the circle to the radius. We will aim + // to have the length of that bisector to be within |kCircleTolerance| + // from the radius in pixels. + // + // Each vertex will appear at an angle of: + // theta(i) = (kPi / 2) * (i / N) // for i in [0..N] + // with each point falling at: + // point(i) = r * (cos(theta), sin(theta)) + // If we consider the unit circle to simplify the calculations below then + // we need to scale the tolerance from its absolute quantity into a unit + // circle fraction: + // k = tolerance / radius + // Using this scaled tolerance below to avoid multiplying by the radius + // throughout all of the math, we have: + // first point = (1, 0) // theta(0) == 0 + // theta = kPi / 2 / N // theta(1) + // second point = (cos(theta), sin(theta)) = (c, s) + // midpoint = (first + second) * 0.5 = ((1 + c)/2, s/2) + // |midpoint| = sqrt((1 + c)*(1 + c)/4 + s*s/4) + // = sqrt((1 + c + c + c*c + s*s) / 4) + // = sqrt((1 + 2c + 1) / 4) + // = sqrt((2 + 2c) / 4) + // = sqrt((1 + c) / 2) + // = cos(theta / 2) // using half-angle cosine formula + // error = 1 - |midpoint| = 1 - cos(theta / 2) + // cos(theta/2) = 1 - error + // theta/2 = acos(1 - error) + // kPi / 2 / N / 2 = acos(1 - error) + // kPi / 4 / acos(1 - error) = N + // Since we need error <= k, we want divisions >= N, so we use: + // N = ceil(kPi / 4 / acos(1 - k)) + // + // Math is confirmed in https://math.stackexchange.com/a/4132095 + // (keeping in mind that we are computing quarter circle divisions here) + // which also points out a performance optimization that is accurate + // to within an over-estimation of 1 division would be: + // N = ceil(kPi / 4 / sqrt(2 * k)) + // Since we have precomputed the divisions for radii up to 1024, we can + // afford to be more accurate using the acos formula here for larger radii. + double k = Tessellator::kCircleTolerance / pixel_radius; + return ceil(kPiOver4 / std::acos(1 - k)); +} + +void Tessellator::Trigs::init(size_t divisions) { + if (!trigs_.empty()) { + return; + } + + // Either not cached yet, or we are using the temp storage... + trigs_.reserve(divisions + 1); + + double angle_scale = kPiOver2 / divisions; + + trigs_.emplace_back(1.0, 0.0); + for (size_t i = 1; i < divisions; i++) { + trigs_.emplace_back(Radians(i * angle_scale)); + } + trigs_.emplace_back(0.0, 1.0); +} + +Tessellator::Trigs Tessellator::GetTrigsForDivisions(size_t divisions) { + return divisions < Tessellator::kCachedTrigCount + ? Trigs(precomputed_trigs_[divisions], divisions) + : Trigs(divisions); +} + +using TessellatedVertexProc = Tessellator::TessellatedVertexProc; +using EllipticalVertexGenerator = Tessellator::EllipticalVertexGenerator; + +EllipticalVertexGenerator::EllipticalVertexGenerator( + EllipticalVertexGenerator::GeneratorProc& generator, + Trigs&& trigs, + PrimitiveType triangle_type, + size_t vertices_per_trig, + Data&& data) + : impl_(generator), + trigs_(std::move(trigs)), + data_(data), + vertices_per_trig_(vertices_per_trig) {} + +EllipticalVertexGenerator Tessellator::FilledCircle( + const Matrix& view_transform, + const Point& center, + Scalar radius) { + size_t divisions = + ComputeQuadrantDivisions(view_transform.GetMaxBasisLengthXY() * radius); + return EllipticalVertexGenerator(Tessellator::GenerateFilledCircle, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {center, center}, + .radii = {radius, radius}, + .half_width = -1.0f, + }); +} + +EllipticalVertexGenerator Tessellator::StrokedCircle( + const Matrix& view_transform, + const Point& center, + Scalar radius, + Scalar half_width) { + if (half_width > 0) { + auto divisions = ComputeQuadrantDivisions( + view_transform.GetMaxBasisLengthXY() * radius + half_width); + return EllipticalVertexGenerator(Tessellator::GenerateStrokedCircle, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 8, + { + .reference_centers = {center, center}, + .radii = {radius, radius}, + .half_width = half_width, + }); + } else { + return FilledCircle(view_transform, center, radius); + } +} + +EllipticalVertexGenerator Tessellator::RoundCapLine( + const Matrix& view_transform, + const Point& p0, + const Point& p1, + Scalar radius) { + auto along = p1 - p0; + auto length = along.GetLength(); + if (length > kEhCloseEnough) { + auto divisions = + ComputeQuadrantDivisions(view_transform.GetMaxBasisLengthXY() * radius); + return EllipticalVertexGenerator(Tessellator::GenerateRoundCapLine, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {p0, p1}, + .radii = {radius, radius}, + .half_width = -1.0f, + }); + } else { + return FilledCircle(view_transform, p0, radius); + } +} + +EllipticalVertexGenerator Tessellator::FilledEllipse( + const Matrix& view_transform, + const Rect& bounds) { + if (bounds.IsSquare()) { + return FilledCircle(view_transform, bounds.GetCenter(), + bounds.GetWidth() * 0.5f); + } + auto max_radius = bounds.GetSize().MaxDimension(); + auto divisions = ComputeQuadrantDivisions( + view_transform.GetMaxBasisLengthXY() * max_radius); + auto center = bounds.GetCenter(); + return EllipticalVertexGenerator(Tessellator::GenerateFilledEllipse, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = {center, center}, + .radii = bounds.GetSize() * 0.5f, + .half_width = -1.0f, + }); +} + +EllipticalVertexGenerator Tessellator::FilledRoundRect( + const Matrix& view_transform, + const Rect& bounds, + const Size& radii) { + if (radii.width * 2 < bounds.GetWidth() || + radii.height * 2 < bounds.GetHeight()) { + auto max_radius = radii.MaxDimension(); + auto divisions = ComputeQuadrantDivisions( + view_transform.GetMaxBasisLengthXY() * max_radius); + auto upper_left = bounds.GetLeftTop() + radii; + auto lower_right = bounds.GetRightBottom() - radii; + return EllipticalVertexGenerator(Tessellator::GenerateFilledRoundRect, + GetTrigsForDivisions(divisions), + PrimitiveType::kTriangleStrip, 4, + { + .reference_centers = + { + upper_left, + lower_right, + }, + .radii = radii, + .half_width = -1.0f, + }); + } else { + return FilledEllipse(view_transform, bounds); + } +} + +void Tessellator::GenerateFilledCircle( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + auto radius = data.radii.width; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(radius == data.radii.height); + FML_DCHECK(data.half_width < 0); + + // Quadrant 1 connecting with Quadrant 4: + for (auto& trig : trigs) { + auto offset = trig * radius; + proc({center.x - offset.x, center.y + offset.y}); + proc({center.x - offset.x, center.y - offset.y}); + } + + // The second half of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2 connecting with Quadrant 2: + for (auto& trig : trigs) { + auto offset = trig * radius; + proc({center.x + offset.y, center.y + offset.x}); + proc({center.x + offset.y, center.y - offset.x}); + } +} + +void Tessellator::GenerateStrokedCircle( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(data.radii.IsSquare()); + FML_DCHECK(data.half_width > 0 && data.half_width < data.radii.width); + + auto outer_radius = data.radii.width + data.half_width; + auto inner_radius = data.radii.width - data.half_width; + + // Zig-zag back and forth between points on the outer circle and the + // inner circle. Both circles are evaluated at the same number of + // quadrant divisions so the points for a given division should match + // 1 for 1 other than their applied radius. + + // Quadrant 1: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x - outer.x, center.y - outer.y}); + proc({center.x - inner.x, center.y - inner.y}); + } + + // The even quadrants of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x + outer.y, center.y - outer.x}); + proc({center.x + inner.y, center.y - inner.x}); + } + + // Quadrant 3: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x + outer.x, center.y + outer.y}); + proc({center.x + inner.x, center.y + inner.y}); + } + + // Quadrant 4: + for (auto& trig : trigs) { + auto outer = trig * outer_radius; + auto inner = trig * inner_radius; + proc({center.x - outer.y, center.y + outer.x}); + proc({center.x - inner.y, center.y + inner.x}); + } +} + +void Tessellator::GenerateRoundCapLine( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto p0 = data.reference_centers[0]; + auto p1 = data.reference_centers[1]; + auto radius = data.radii.width; + + FML_DCHECK(radius == data.radii.height); + FML_DCHECK(data.half_width < 0); + + auto along = p1 - p0; + along *= radius / along.GetLength(); + auto across = Point(-along.y, along.x); + + for (auto& trig : trigs) { + auto relative_along = along * trig.cos; + auto relative_across = across * trig.sin; + proc(p0 - relative_along + relative_across); + proc(p0 - relative_along - relative_across); + } + + // The second half of the round caps should be iterated in reverse, but + // we can instead iterate forward and swap the sin/cos values as they + // should be symmetric. + for (auto& trig : trigs) { + auto relative_along = along * trig.sin; + auto relative_across = across * trig.cos; + proc(p1 + relative_along + relative_across); + proc(p1 + relative_along - relative_across); + } +} + +void Tessellator::GenerateFilledEllipse( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + auto center = data.reference_centers[0]; + auto radii = data.radii; + + FML_DCHECK(center == data.reference_centers[1]); + FML_DCHECK(data.half_width < 0); + + // Quadrant 1 connecting with Quadrant 4: + for (auto& trig : trigs) { + auto offset = trig * radii; + proc({center.x - offset.x, center.y + offset.y}); + proc({center.x - offset.x, center.y - offset.y}); + } + + // The second half of the circle should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2 connecting with Quadrant 2: + for (auto& trig : trigs) { + auto offset = Point(trig.sin * radii.width, trig.cos * radii.height); + proc({center.x + offset.x, center.y + offset.y}); + proc({center.x + offset.x, center.y - offset.y}); + } +} + +void Tessellator::GenerateFilledRoundRect( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc) { + Scalar left = data.reference_centers[0].x; + Scalar top = data.reference_centers[0].y; + Scalar right = data.reference_centers[1].x; + Scalar bottom = data.reference_centers[1].y; + auto radii = data.radii; + + FML_DCHECK(data.half_width < 0); + + // Quadrant 1 connecting with Quadrant 4: + for (auto& trig : trigs) { + auto offset = trig * radii; + proc({left - offset.x, bottom + offset.y}); + proc({left - offset.x, top - offset.y}); + } + + // The second half of the round rect should be iterated in reverse, but + // we can instead iterate forward and swap the x/y values of the + // offset as the angles should be symmetric and thus should generate + // symmetrically reversed trig vectors. + // Quadrant 2 connecting with Quadrant 2: + for (auto& trig : trigs) { + auto offset = Point(trig.sin * radii.width, trig.cos * radii.height); + proc({right + offset.x, bottom + offset.y}); + proc({right + offset.x, top - offset.y}); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/tessellator/tessellator.h b/flutter/engine/src/flutter/impeller/tessellator/tessellator.h new file mode 100644 index 0000000000000000000000000000000000000000..604b7ce4a77dd6e7988b9fc8958309dfd479adbe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/tessellator.h @@ -0,0 +1,356 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_ +#define FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_ + +#include +#include +#include + +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/vertex_buffer.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/trig.h" + +namespace impeller { + +/// The size of the point arena buffer stored on the tessellator. +static constexpr size_t kPointArenaSize = 4096u; + +//------------------------------------------------------------------------------ +/// @brief A utility that generates triangles of the specified fill type +/// given a polyline. This happens on the CPU. +/// +/// Also contains functionality for optimized generation of circles +/// and ellipses. +/// +/// This object is not thread safe, and its methods must not be +/// called from multiple threads. +/// +class Tessellator { + private: + /// Essentially just a vector of Trig objects, but supports storing a + /// reference to either a cached vector or a locally generated vector. + /// The constructor will fill the vector with quarter circular samples + /// for the indicated number of equal divisions if the vector is new. + class Trigs { + public: + explicit Trigs(std::vector& trigs, size_t divisions) : trigs_(trigs) { + init(divisions); + FML_DCHECK(trigs_.size() == divisions + 1); + } + + explicit Trigs(size_t divisions) + : local_storage_(std::make_unique>()), + trigs_(*local_storage_) { + init(divisions); + FML_DCHECK(trigs_.size() == divisions + 1); + } + + // Utility forwards of the indicated vector methods. + auto inline size() const { return trigs_.size(); } + auto inline begin() const { return trigs_.begin(); } + auto inline end() const { return trigs_.end(); } + + private: + // nullptr if a cached vector is used, otherwise the actual storage + std::unique_ptr> local_storage_; + + // Whether or not a cached vector or the local storage is used, this + // this reference will always be valid + std::vector& trigs_; + + // Fill the vector with the indicated number of equal divisions of + // trigonometric values if it is empty. + void init(size_t divisions); + }; + + public: + enum class Result { + kSuccess, + kInputError, + kTessellationError, + }; + + /// @brief A callback function for a |VertexGenerator| to deliver + /// the vertices it computes as |Point| objects. + using TessellatedVertexProc = std::function; + + /// @brief An object which produces a list of vertices as |Point|s that + /// tessellate a previously provided shape and delivers the vertices + /// through a |TessellatedVertexProc| callback. + /// + /// The object can also provide advance information on how many + /// vertices it will generate. + /// + /// @see |Tessellator::FilledCircle| + /// @see |Tessellator::StrokedCircle| + /// @see |Tessellator::RoundCapLine| + /// @see |Tessellator::FilledEllipse| + class VertexGenerator { + public: + /// @brief Returns the |PrimitiveType| that describes the relationship + /// among the list of vertices produced by the |GenerateVertices| + /// method. + /// + /// Most generators will deliver |kTriangleStrip| triangles + virtual PrimitiveType GetTriangleType() const = 0; + + /// @brief Returns the number of vertices that the generator plans to + /// produce, if known. + /// + /// This value is advisory only and can be used to reserve space + /// where the vertices will be placed, but the count may be an + /// estimate. + /// + /// Implementations are encouraged to avoid overestimating + /// the count by too large a number and to provide a best + /// guess so as to minimize potential buffer reallocations + /// as the vertices are delivered. + virtual size_t GetVertexCount() const = 0; + + /// @brief Generate the vertices and deliver them in the necessary + /// order (as required by the PrimitiveType) to the given + /// callback function. + virtual void GenerateVertices(const TessellatedVertexProc& proc) const = 0; + }; + + /// @brief The |VertexGenerator| implementation common to all shapes + /// that are based on a polygonal representation of an ellipse. + class EllipticalVertexGenerator : public virtual VertexGenerator { + public: + /// |VertexGenerator| + PrimitiveType GetTriangleType() const override { + return PrimitiveType::kTriangleStrip; + } + + /// |VertexGenerator| + size_t GetVertexCount() const override { + return trigs_.size() * vertices_per_trig_; + } + + /// |VertexGenerator| + void GenerateVertices(const TessellatedVertexProc& proc) const override { + impl_(trigs_, data_, proc); + } + + private: + friend class Tessellator; + + struct Data { + // Circles and Ellipses only use one of these points. + // RoundCapLines use both as the endpoints of the unexpanded line. + // A round rect can specify its interior rectangle by using the + // 2 points as opposing corners. + const Point reference_centers[2]; + // Circular shapes have the same value in radii.width and radii.height + const Size radii; + // half_width is only used in cases where the generator will be + // generating 2 different outlines, such as StrokedCircle + const Scalar half_width; + }; + + typedef void GeneratorProc(const Trigs& trigs, + const Data& data, + const TessellatedVertexProc& proc); + + GeneratorProc& impl_; + const Trigs trigs_; + const Data data_; + const size_t vertices_per_trig_; + + EllipticalVertexGenerator(GeneratorProc& generator, + Trigs&& trigs, + PrimitiveType triangle_type, + size_t vertices_per_trig, + Data&& data); + }; + + Tessellator(); + + virtual ~Tessellator(); + + //---------------------------------------------------------------------------- + /// @brief Given a convex path, create a triangle fan structure. + /// + /// @param[in] path The path to tessellate. + /// @param[in] host_buffer The host buffer for allocation of vertices/index + /// data. + /// @param[in] tolerance The tolerance value for conversion of the path to + /// a polyline. This value is often derived from the + /// Matrix::GetMaxBasisLengthXY of the CTM applied to + /// the path for rendering. + /// + /// @return A vertex buffer containing all data from the provided curve. + VertexBuffer TessellateConvex(const Path& path, + HostBuffer& host_buffer, + Scalar tolerance, + bool supports_primitive_restart = false, + bool supports_triangle_fan = false); + + //---------------------------------------------------------------------------- + /// @brief Given a path, create a line strip primitive structure. + /// + /// A line strip is a series of vertices that draws a line + /// rendered at a specified width (in our case, always 1.0 + /// physical pixel) that is tessellated by the rasterizer. See + /// also PrimitiveType::kLineStrip. + /// + /// @param[in] path The path to tessellate. + /// @param[in] host_buffer The host buffer for allocation of vertices/index + /// data. + /// @param[in] tolerance The tolerance value for conversion of the path to + /// a polyline. This value is often derived from the + /// Matrix::GetMaxBasisLengthXY of the CTM applied to + /// the path for rendering. + /// + /// @return A vertex buffer containing all data from the provided curve. + VertexBuffer GenerateLineStrip(const Path& path, + HostBuffer& host_buffer, + Scalar tolerance); + + /// Visible for testing. + /// + /// This method only exists for the ease of benchmarking without using the + /// real allocator needed by the [host_buffer]. + static void TessellateConvexInternal(const Path& path, + std::vector& point_buffer, + std::vector& index_buffer, + Scalar tolerance); + + //---------------------------------------------------------------------------- + /// @brief Create a temporary polyline. Only one per-process can exist at + /// a time. + /// + /// The tessellator itself is not a thread safe class and should + /// only be used from the raster thread. + Path::Polyline CreateTempPolyline(const Path& path, Scalar tolerance); + + /// @brief The pixel tolerance used by the algorighm to determine how + /// many divisions to create for a circle. + /// + /// No point on the polygon of vertices should deviate from the + /// true circle by more than this tolerance. + static constexpr Scalar kCircleTolerance = 0.1f; + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a filled circle of the given radius around the given center + /// with enough polygon sub-divisions to provide reasonable + /// fidelity when viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the center point. + EllipticalVertexGenerator FilledCircle(const Matrix& view_transform, + const Point& center, + Scalar radius); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a stroked circle of the given radius and half_width around + /// the given shared center with enough polygon sub-divisions + /// to provide reasonable fidelity when viewed under the given + /// view transform. The outer edge of the stroked circle is + /// generated at (radius + half_width) and the inner edge is + /// generated at (radius - half_width). + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the center point. + EllipticalVertexGenerator StrokedCircle(const Matrix& view_transform, + const Point& center, + Scalar radius, + Scalar half_width); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a line with round end caps of the given radius with enough + /// polygon sub-divisions to provide reasonable fidelity when + /// viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the two points. + EllipticalVertexGenerator RoundCapLine(const Matrix& view_transform, + const Point& p0, + const Point& p1, + Scalar radius); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a filled ellipse inscribed within the given bounds with + /// enough polygon sub-divisions to provide reasonable + /// fidelity when viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the bounds. + EllipticalVertexGenerator FilledEllipse(const Matrix& view_transform, + const Rect& bounds); + + /// @brief Create a |VertexGenerator| that can produce vertices for + /// a filled round rect within the given bounds and corner radii + /// with enough polygon sub-divisions to provide reasonable + /// fidelity when viewed under the given view transform. + /// + /// Note that the view transform is only used to choose the + /// number of sample points to use per quarter circle and the + /// returned points are not transformed by it, instead they are + /// relative to the coordinate space of the bounds. + EllipticalVertexGenerator FilledRoundRect(const Matrix& view_transform, + const Rect& bounds, + const Size& radii); + + /// Retrieve a pre-allocated arena of kPointArenaSize points. + std::vector& GetStrokePointCache(); + + protected: + /// Used for polyline generation. + std::unique_ptr> point_buffer_; + std::unique_ptr> index_buffer_; + /// Used for stroke path generation. + std::vector stroke_points_; + + private: + // Data for various Circle/EllipseGenerator classes, cached per + // Tessellator instance which is usually the foreground life of an app + // if not longer. + static constexpr size_t kCachedTrigCount = 300; + std::vector precomputed_trigs_[kCachedTrigCount]; + + Trigs GetTrigsForDivisions(size_t divisions); + + static void GenerateFilledCircle(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateStrokedCircle(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateRoundCapLine(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateFilledEllipse(const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + static void GenerateFilledRoundRect( + const Trigs& trigs, + const EllipticalVertexGenerator::Data& data, + const TessellatedVertexProc& proc); + + Tessellator(const Tessellator&) = delete; + + Tessellator& operator=(const Tessellator&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_H_ diff --git a/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.cc b/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0b66aceab2a9f7674b87379cae3f1371a5a34d1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.cc @@ -0,0 +1,169 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/tessellator/tessellator_libtess.h" + +#include "third_party/libtess2/Include/tesselator.h" + +namespace impeller { + +static void* HeapAlloc(void* userData, unsigned int size) { + return malloc(size); +} + +static void* HeapRealloc(void* userData, void* ptr, unsigned int size) { + return realloc(ptr, size); +} + +static void HeapFree(void* userData, void* ptr) { + free(ptr); +} + +// Note: these units are "number of entities" for bucket size and not in KB. +static const TESSalloc kAlloc = { + HeapAlloc, HeapRealloc, HeapFree, 0, /* =userData */ + 16, /* =meshEdgeBucketSize */ + 16, /* =meshVertexBucketSize */ + 16, /* =meshFaceBucketSize */ + 16, /* =dictNodeBucketSize */ + 16, /* =regionBucketSize */ + 0 /* =extraVertices */ +}; + +TessellatorLibtess::TessellatorLibtess() + : c_tessellator_(nullptr, &DestroyTessellator) { + TESSalloc alloc = kAlloc; + { + // libTess2 copies the TESSalloc despite the non-const argument. + CTessellator tessellator(::tessNewTess(&alloc), &DestroyTessellator); + c_tessellator_ = std::move(tessellator); + } +} + +TessellatorLibtess::~TessellatorLibtess() = default; + +static int ToTessWindingRule(FillType fill_type) { + switch (fill_type) { + case FillType::kOdd: + return TESS_WINDING_ODD; + case FillType::kNonZero: + return TESS_WINDING_NONZERO; + } + return TESS_WINDING_ODD; +} + +TessellatorLibtess::Result TessellatorLibtess::Tessellate( + const Path& path, + Scalar tolerance, + const BuilderCallback& callback) { + if (!callback) { + return TessellatorLibtess::Result::kInputError; + } + + std::unique_ptr> point_buffer = + std::make_unique>(); + auto polyline = path.CreatePolyline(tolerance, std::move(point_buffer)); + + auto fill_type = path.GetFillType(); + + if (polyline.points->empty()) { + return TessellatorLibtess::Result::kInputError; + } + + auto tessellator = c_tessellator_.get(); + if (!tessellator) { + return TessellatorLibtess::Result::kTessellationError; + } + + constexpr int kVertexSize = 2; + constexpr int kPolygonSize = 3; + + //---------------------------------------------------------------------------- + /// Feed contour information to the tessellator. + /// + static_assert(sizeof(Point) == 2 * sizeof(float)); + for (size_t contour_i = 0; contour_i < polyline.contours.size(); + contour_i++) { + size_t start_point_index, end_point_index; + std::tie(start_point_index, end_point_index) = + polyline.GetContourPointBounds(contour_i); + + ::tessAddContour(tessellator, // the C tessellator + kVertexSize, // + polyline.points->data() + start_point_index, // + sizeof(Point), // + end_point_index - start_point_index // + ); + } + + //---------------------------------------------------------------------------- + /// Let's tessellate. + /// + auto result = ::tessTesselate(tessellator, // tessellator + ToTessWindingRule(fill_type), // winding + TESS_POLYGONS, // element type + kPolygonSize, // polygon size + kVertexSize, // vertex size + nullptr // normal (null is automatic) + ); + + if (result != 1) { + return TessellatorLibtess::Result::kTessellationError; + } + + int element_item_count = tessGetElementCount(tessellator) * kPolygonSize; + + // We default to using a 16bit index buffer, but in cases where we generate + // more tessellated data than this can contain we need to fall back to + // dropping the index buffer entirely. Instead code could instead switch to + // a uint32 index buffer, but this is done for simplicity with the other + // fast path above. + if (element_item_count < USHRT_MAX) { + int vertex_item_count = tessGetVertexCount(tessellator); + auto vertices = tessGetVertices(tessellator); + auto elements = tessGetElements(tessellator); + + // libtess uses an int index internally due to usage of -1 as a sentinel + // value. + std::vector indices(element_item_count); + for (int i = 0; i < element_item_count; i++) { + indices[i] = static_cast(elements[i]); + } + if (!callback(vertices, vertex_item_count, indices.data(), + element_item_count)) { + return TessellatorLibtess::Result::kInputError; + } + } else { + std::vector points; + std::vector data; + + int vertex_item_count = tessGetVertexCount(tessellator) * kVertexSize; + auto vertices = tessGetVertices(tessellator); + points.reserve(vertex_item_count); + for (int i = 0; i < vertex_item_count; i += 2) { + points.emplace_back(vertices[i], vertices[i + 1]); + } + + int element_item_count = tessGetElementCount(tessellator) * kPolygonSize; + auto elements = tessGetElements(tessellator); + data.reserve(element_item_count); + for (int i = 0; i < element_item_count; i++) { + data.emplace_back(points[elements[i]].x); + data.emplace_back(points[elements[i]].y); + } + if (!callback(data.data(), element_item_count, nullptr, 0u)) { + return TessellatorLibtess::Result::kInputError; + } + } + + return TessellatorLibtess::Result::kSuccess; +} + +void DestroyTessellator(TESStesselator* tessellator) { + if (tessellator != nullptr) { + ::tessDeleteTess(tessellator); + } +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.h b/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.h new file mode 100644 index 0000000000000000000000000000000000000000..d7fab33e458c5c5baa2ef754402daab8323d944f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/tessellator_libtess.h @@ -0,0 +1,77 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_LIBTESS_H_ +#define FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_LIBTESS_H_ + +#include +#include + +#include "impeller/geometry/path.h" + +struct TESStesselator; + +namespace impeller { + +void DestroyTessellator(TESStesselator* tessellator); + +using CTessellator = + std::unique_ptr; + +//------------------------------------------------------------------------------ +/// @brief An extended tessellator that offers arbitrary/concave +/// tessellation via the libtess2 library. +/// +/// This object is not thread safe, and its methods must not be +/// called from multiple threads. +/// +class TessellatorLibtess { + public: + TessellatorLibtess(); + + ~TessellatorLibtess(); + + enum class Result { + kSuccess, + kInputError, + kTessellationError, + }; + + /// @brief A callback that returns the results of the tessellation. + /// + /// The index buffer may not be populated, in which case [indices] will + /// be nullptr and indices_count will be 0. + using BuilderCallback = std::function; + + //---------------------------------------------------------------------------- + /// @brief Generates filled triangles from the path. A callback is + /// invoked once for the entire tessellation. + /// + /// @param[in] path The path to tessellate. + /// @param[in] tolerance The tolerance value for conversion of the path to + /// a polyline. This value is often derived from the + /// Matrix::GetMaxBasisLength of the CTM applied to the + /// path for rendering. + /// @param[in] callback The callback, return false to indicate failure. + /// + /// @return The result status of the tessellation. + /// + TessellatorLibtess::Result Tessellate(const Path& path, + Scalar tolerance, + const BuilderCallback& callback); + + private: + CTessellator c_tessellator_; + + TessellatorLibtess(const TessellatorLibtess&) = delete; + + TessellatorLibtess& operator=(const TessellatorLibtess&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TESSELLATOR_TESSELLATOR_LIBTESS_H_ diff --git a/flutter/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc b/flutter/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..cff81e9886e3dff5f5fc41839247a6f6bd0d966e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tessellator/tessellator_unittests.cc @@ -0,0 +1,528 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" + +#include "impeller/geometry/geometry_asserts.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/tessellator/tessellator.h" +#include "impeller/tessellator/tessellator_libtess.h" + +namespace impeller { +namespace testing { + +TEST(TessellatorTest, TessellatorBuilderReturnsCorrectResultStatus) { + // Zero points. + { + TessellatorLibtess t; + auto path = PathBuilder{}.TakePath(FillType::kOdd); + TessellatorLibtess::Result result = t.Tessellate( + path, 1.0f, + [](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { return true; }); + + ASSERT_EQ(result, TessellatorLibtess::Result::kInputError); + } + + // One point. + { + TessellatorLibtess t; + auto path = PathBuilder{}.LineTo({0, 0}).TakePath(FillType::kOdd); + TessellatorLibtess::Result result = t.Tessellate( + path, 1.0f, + [](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { return true; }); + + ASSERT_EQ(result, TessellatorLibtess::Result::kSuccess); + } + + // Two points. + { + TessellatorLibtess t; + auto path = PathBuilder{}.AddLine({0, 0}, {0, 1}).TakePath(FillType::kOdd); + TessellatorLibtess::Result result = t.Tessellate( + path, 1.0f, + [](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { return true; }); + + ASSERT_EQ(result, TessellatorLibtess::Result::kSuccess); + } + + // Many points. + { + TessellatorLibtess t; + PathBuilder builder; + for (int i = 0; i < 1000; i++) { + auto coord = i * 1.0f; + builder.AddLine({coord, coord}, {coord + 1, coord + 1}); + } + auto path = builder.TakePath(FillType::kOdd); + TessellatorLibtess::Result result = t.Tessellate( + path, 1.0f, + [](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { return true; }); + + ASSERT_EQ(result, TessellatorLibtess::Result::kSuccess); + } + + // Closure fails. + { + TessellatorLibtess t; + auto path = PathBuilder{}.AddLine({0, 0}, {0, 1}).TakePath(FillType::kOdd); + TessellatorLibtess::Result result = t.Tessellate( + path, 1.0f, + [](const float* vertices, size_t vertices_count, + const uint16_t* indices, size_t indices_count) { return false; }); + + ASSERT_EQ(result, TessellatorLibtess::Result::kInputError); + } +} + +TEST(TessellatorTest, TessellateConvex) { + { + std::vector points; + std::vector indices; + // Sanity check simple rectangle. + Tessellator::TessellateConvexInternal( + PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 10, 10)).TakePath(), points, + indices, 1.0); + + // Note: the origin point is repeated but not referenced in the indices + // below + std::vector expected = {{0, 0}, {10, 0}, {10, 10}, {0, 10}, {0, 0}}; + std::vector expected_indices = {0, 1, 3, 2}; + EXPECT_EQ(points, expected); + EXPECT_EQ(indices, expected_indices); + } + + { + std::vector points; + std::vector indices; + Tessellator::TessellateConvexInternal( + PathBuilder{} + .AddRect(Rect::MakeLTRB(0, 0, 10, 10)) + .AddRect(Rect::MakeLTRB(20, 20, 30, 30)) + .TakePath(), + points, indices, 1.0); + + std::vector expected = {{0, 0}, {10, 0}, {10, 10}, {0, 10}, + {0, 0}, {20, 20}, {30, 20}, {30, 30}, + {20, 30}, {20, 20}}; + std::vector expected_indices = {0, 1, 3, 2, 2, 5, 5, 6, 8, 7}; + EXPECT_EQ(points, expected); + EXPECT_EQ(indices, expected_indices); + } +} + +// Filled Paths without an explicit close should still be closed +TEST(TessellatorTest, TessellateConvexUnclosedPath) { + std::vector points; + std::vector indices; + + // Create a rectangle that lacks an explicit close. + Path path = PathBuilder{} + .LineTo({100, 0}) + .LineTo({100, 100}) + .LineTo({0, 100}) + .TakePath(); + Tessellator::TessellateConvexInternal(path, points, indices, 1.0); + + std::vector expected = {{0, 0}, {100, 0}, {100, 100}, {0, 100}}; + std::vector expected_indices = {0, 1, 3, 2}; + EXPECT_EQ(points, expected); + EXPECT_EQ(indices, expected_indices); +} + +TEST(TessellatorTest, CircleVertexCounts) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, Scalar radius) { + auto generator = tessellator->FilledCircle(transform, {}, radius); + size_t quadrant_divisions = generator.GetVertexCount() / 4; + + // Confirm the approximation error is within the currently accepted + // |kCircleTolerance| value advertised by |CircleTessellator|. + // (With an additional 1% tolerance for floating point rounding.) + double angle = kPiOver2 / quadrant_divisions; + Point first = {radius, 0}; + Point next = {static_cast(cos(angle) * radius), + static_cast(sin(angle) * radius)}; + Point midpoint = (first + next) * 0.5; + EXPECT_GE(midpoint.GetLength(), + radius - Tessellator::kCircleTolerance * 1.01) + << ", transform = " << transform << ", radius = " << radius + << ", divisions = " << quadrant_divisions; + }; + + test({}, 0.0); + test({}, 0.9); + test({}, 1.0); + test({}, 1.9); + test(Matrix::MakeScale(Vector2(2.0, 2.0)), 0.95); + test({}, 2.0); + test(Matrix::MakeScale(Vector2(2.0, 2.0)), 1.0); + test({}, 11.9); + test({}, 12.0); + test({}, 35.9); + for (int i = 36; i < 10000; i += 4) { + test({}, i); + } +} + +TEST(TessellatorTest, FilledCircleTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& center, + Scalar radius) { + auto generator = tessellator->FilledCircle(transform, center, radius); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * radius; + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + double rcos = (i == quadrant_count - 1) ? 0.0f : cos(angle) * radius; + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], + Point(center.x + rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + }; + + test({}, {}, 2.0); + test({}, {10, 10}, 2.0); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {}, 2.0); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {}, 1000.0); +} + +TEST(TessellatorTest, StrokedCircleTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& center, + Scalar radius, Scalar half_width) { + ASSERT_GT(radius, half_width); + auto generator = + tessellator->StrokedCircle(transform, center, radius, half_width); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 8; + + // Test outer points first + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * (radius + half_width); + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + double rcos = + (i == quadrant_count - 1) ? 0.0f : cos(angle) * (radius + half_width); + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2], + Point(center.x + rsin, center.y - rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2], + Point(center.x - rsin, center.y + rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + + // Then test innerer points + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + double rsin = sin(angle) * (radius - half_width); + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + double rcos = + (i == quadrant_count - 1) ? 0.0f : cos(angle) * (radius - half_width); + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 2 + i * 2 + 1], + Point(center.x + rsin, center.y - rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 4 + i * 2 + 1], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << std::endl; + EXPECT_POINT_NEAR(vertices[quadrant_count * 6 + i * 2 + 1], + Point(center.x - rsin, center.y + rcos)) + << "vertex " << i << ", angle = " << degrees << std::endl; + } + }; + + test({}, {}, 2.0, 1.0); + test({}, {}, 2.0, 0.5); + test({}, {10, 10}, 2.0, 1.0); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {}, 2.0, 1.0); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {}, 1000.0, 10.0); +} + +TEST(TessellatorTest, RoundCapLineTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Point& p0, + const Point& p1, Scalar radius) { + auto generator = tessellator->RoundCapLine(transform, p0, p1, radius); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + Point along = p1 - p0; + Scalar length = along.GetLength(); + if (length > 0) { + along *= radius / length; + } else { + along = {radius, 0}; + } + Point across = {-along.y, along.x}; + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + Point relative_along = + along * ((i == quadrant_count - 1) ? 0.0f : cos(angle)); + Point relative_across = across * sin(angle); + EXPECT_POINT_NEAR(vertices[i * 2], // + p0 - relative_along + relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], // + p0 - relative_along - relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], // + p1 + relative_along - relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], // + p1 + relative_along + relative_across) + << "vertex " << i << ", angle = " << degrees << ", " // + << "line = " << p0 << " => " << p1 << ", " // + << "radius = " << radius << std::endl; + } + }; + + // Empty line should actually use the circle generator, but its + // results should match the same math as the round cap generator. + test({}, {0, 0}, {0, 0}, 10); + + test({}, {0, 0}, {10, 0}, 2); + test({}, {10, 0}, {0, 0}, 2); + test({}, {0, 0}, {10, 10}, 2); + + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {0, 0}, {10, 0}, 2); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {10, 0}, {0, 0}, 2); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), {0, 0}, {10, 10}, 2); + + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {0, 0}, {10, 0}, 2); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {10, 0}, {0, 0}, 2); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), {0, 0}, {10, 10}, 2); +} + +TEST(TessellatorTest, FilledEllipseTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Rect& bounds) { + auto center = bounds.GetCenter(); + auto half_size = bounds.GetSize() * 0.5f; + + auto generator = tessellator->FilledEllipse(transform, bounds); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + double rcos = + (i == quadrant_count - 1) ? 0.0f : cos(angle) * half_size.width; + double rsin = sin(angle) * half_size.height; + EXPECT_POINT_NEAR(vertices[i * 2], + Point(center.x - rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(center.x - rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], + Point(center.x + rcos, center.y - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], + Point(center.x + rcos, center.y + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + } + }; + + // Square bounds should actually use the circle generator, but its + // results should match the same math as the ellipse generator. + test({}, Rect::MakeXYWH(0, 0, 2, 2)); + + test({}, Rect::MakeXYWH(0, 0, 2, 3)); + test({}, Rect::MakeXYWH(0, 0, 3, 2)); + test({}, Rect::MakeXYWH(5, 10, 2, 3)); + test({}, Rect::MakeXYWH(16, 7, 3, 2)); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeXYWH(5, 10, 3, 2)); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeXYWH(5, 10, 2, 3)); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeXYWH(5000, 10000, 3000, 2000)); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeXYWH(5000, 10000, 2000, 3000)); +} + +TEST(TessellatorTest, FilledRoundRectTessellationVertices) { + auto tessellator = std::make_shared(); + + auto test = [&tessellator](const Matrix& transform, const Rect& bounds, + const Size& radii) { + FML_DCHECK(radii.width * 2 <= bounds.GetWidth()) << radii << bounds; + FML_DCHECK(radii.height * 2 <= bounds.GetHeight()) << radii << bounds; + + Scalar middle_left = bounds.GetX() + radii.width; + Scalar middle_top = bounds.GetY() + radii.height; + Scalar middle_right = bounds.GetX() + bounds.GetWidth() - radii.width; + Scalar middle_bottom = bounds.GetY() + bounds.GetHeight() - radii.height; + + auto generator = tessellator->FilledRoundRect(transform, bounds, radii); + EXPECT_EQ(generator.GetTriangleType(), PrimitiveType::kTriangleStrip); + + auto vertex_count = generator.GetVertexCount(); + auto vertices = std::vector(); + generator.GenerateVertices([&vertices](const Point& p) { // + vertices.push_back(p); + }); + EXPECT_EQ(vertices.size(), vertex_count); + ASSERT_EQ(vertex_count % 4, 0u); + + auto quadrant_count = vertex_count / 4; + for (size_t i = 0; i < quadrant_count; i++) { + double angle = kPiOver2 * i / (quadrant_count - 1); + double degrees = angle * 180.0 / kPi; + // Note that cos(radians(90 degrees)) isn't exactly 0.0 like it should be + double rcos = (i == quadrant_count - 1) ? 0.0f : cos(angle) * radii.width; + double rsin = sin(angle) * radii.height; + EXPECT_POINT_NEAR(vertices[i * 2], + Point(middle_left - rcos, middle_bottom + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[i * 2 + 1], + Point(middle_left - rcos, middle_top - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 1], + Point(middle_right + rcos, middle_top - rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + EXPECT_POINT_NEAR(vertices[vertex_count - i * 2 - 2], + Point(middle_right + rcos, middle_bottom + rsin)) + << "vertex " << i << ", angle = " << degrees << ", " // + << "bounds = " << bounds << std::endl; + } + }; + + // Both radii spanning the bounds should actually use the circle/ellipse + // generator, but their results should match the same math as the round + // rect generator. + test({}, Rect::MakeXYWH(0, 0, 20, 20), {10, 10}); + + // One radius spanning the bounds, but not the other will not match the + // round rect math if the generator transfers to circle/ellipse + test({}, Rect::MakeXYWH(0, 0, 20, 20), {10, 5}); + test({}, Rect::MakeXYWH(0, 0, 20, 20), {5, 10}); + + test({}, Rect::MakeXYWH(0, 0, 20, 30), {2, 2}); + test({}, Rect::MakeXYWH(0, 0, 30, 20), {2, 2}); + test({}, Rect::MakeXYWH(5, 10, 20, 30), {2, 3}); + test({}, Rect::MakeXYWH(16, 7, 30, 20), {2, 3}); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeXYWH(5, 10, 30, 20), + {2, 3}); + test(Matrix::MakeScale({500.0, 500.0, 0.0}), Rect::MakeXYWH(5, 10, 20, 30), + {2, 3}); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeXYWH(5000, 10000, 3000, 2000), {50, 70}); + test(Matrix::MakeScale({0.002, 0.002, 0.0}), + Rect::MakeXYWH(5000, 10000, 2000, 3000), {50, 70}); +} + +TEST(TessellatorTest, EarlyReturnEmptyConvexShape) { + // This path is not technically empty (it has a size in one dimension), + // but is otherwise completely flat. + PathBuilder builder; + builder.MoveTo({0, 0}); + builder.MoveTo({10, 10}, /*relative=*/true); + + std::vector points; + std::vector indices; + Tessellator::TessellateConvexInternal(builder.TakePath(), points, indices, + 3.0); + + EXPECT_TRUE(points.empty()); +} + +#if !NDEBUG +TEST(TessellatorTest, ChecksConcurrentPolylineUsage) { + auto tessellator = std::make_shared(); + PathBuilder builder; + builder.AddLine({0, 0}, {100, 100}); + auto path = builder.TakePath(); + + auto polyline = tessellator->CreateTempPolyline(path, 0.1); + EXPECT_DEBUG_DEATH(tessellator->CreateTempPolyline(path, 0.1), + "point_buffer_"); +} +#endif // NDEBUG + +} // namespace testing +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/android/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0e0b30337f64e6d08aeca169637406bca3504f2e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/testing/android/native_activity/native_activity.gni") +import("../../tools/impeller.gni") + +config("public_android_config") { + defines = [ "__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__" ] +} + +impeller_component("android") { + sources = [ + "choreographer.cc", + "choreographer.h", + "hardware_buffer.cc", + "hardware_buffer.h", + "native_window.cc", + "native_window.h", + "proc_table.cc", + "proc_table.h", + "surface_control.cc", + "surface_control.h", + "surface_transaction.cc", + "surface_transaction.h", + "surface_transaction_stats.cc", + "surface_transaction_stats.h", + ] + + public_deps = [ + "../../base", + "../../geometry", + "//flutter/fml", + ] + + public_configs = [ ":public_android_config" ] +} + +test_fixtures("unittests_fixtures") { + fixtures = [] +} + +source_set("unittests_lib") { + visibility = [ ":*" ] + + testonly = true + + sources = [ "toolkit_android_unittests.cc" ] + + deps = [ + ":android", + ":unittests_fixtures", + "//flutter/testing", + ] + + defines = [ "TESTING" ] +} + +executable("unittests") { + assert(is_android) + + testonly = true + + output_name = "impeller_toolkit_android_unittests" + + deps = [ ":unittests_lib" ] +} + +native_activity_apk("apk_unittests") { + apk_name = "impeller_toolkit_android_unittests" + + testonly = true + + deps = [ + ":unittests_lib", + "//flutter/testing/android/native_activity:gtest_activity", + ] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/README.md b/flutter/engine/src/flutter/impeller/toolkit/android/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b52d8f6ea8f7f02bb153d50cbf9af1af4697c453 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/README.md @@ -0,0 +1,7 @@ +Android Toolkit +=============== + +Type-safe managed wrappers around Android objects vended by the NDK. Does not +require linking to libandroid.so. The symbols are resolved via dynamic runtime +lookup so that the toolkit can be built with an older NDK but still run on +modern Android versions and use the latest features. diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.cc b/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.cc new file mode 100644 index 0000000000000000000000000000000000000000..89a852ae8ff339c053a07e216003b0c634d9d1a3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.cc @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/toolkit/android/choreographer.h" + +#include "flutter/fml/message_loop.h" + +namespace impeller::android { + +Choreographer& Choreographer::GetInstance() { + static thread_local Choreographer tChoreographer; + return tChoreographer; +} + +Choreographer::Choreographer() { + if (!IsAvailableOnPlatform()) { + return; + } + + // We need a message loop on the current thread for the choreographer to + // schedule callbacks for us on. + fml::MessageLoop::EnsureInitializedForCurrentThread(); + instance_ = GetProcTable().AChoreographer_getInstance(); +} + +Choreographer::~Choreographer() = default; + +bool Choreographer::IsValid() const { + return !!instance_; +} + +static Choreographer::FrameTimePoint ClockMonotonicNanosToFrameTimePoint( + int64_t p_nanos) { + return Choreographer::FrameTimePoint{std::chrono::nanoseconds(p_nanos)}; +} + +bool Choreographer::PostFrameCallback(FrameCallback callback) const { + if (!callback || !IsValid()) { + return false; + } + + struct InFlightData { + FrameCallback callback; + }; + + auto data = std::make_unique(); + data->callback = std::move(callback); + + const auto& table = GetProcTable(); + if (table.AChoreographer_postFrameCallback64) { + table.AChoreographer_postFrameCallback64( + const_cast(instance_), + [](int64_t nanos, void* p_data) { + auto data = reinterpret_cast(p_data); + data->callback(ClockMonotonicNanosToFrameTimePoint(nanos)); + delete data; + }, + data.release()); + return true; + } else if (table.AChoreographer_postFrameCallback) { + table.AChoreographer_postFrameCallback( + const_cast(instance_), + [](long /*NOLINT*/ nanos, void* p_data) { + auto data = reinterpret_cast(p_data); + data->callback(ClockMonotonicNanosToFrameTimePoint(nanos)); + delete data; + }, + data.release()); + return true; + } + + // The validity check should have tripped by now. + FML_UNREACHABLE(); + return false; +} + +bool Choreographer::IsAvailableOnPlatform() { + return GetProcTable().AChoreographer_getInstance && + (GetProcTable().AChoreographer_postFrameCallback64 || + GetProcTable().AChoreographer_postFrameCallback); +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.h b/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.h new file mode 100644 index 0000000000000000000000000000000000000000..a4b781df8535f6943f644796cfd3bb38941c0997 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/choreographer.h @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_CHOREOGRAPHER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_CHOREOGRAPHER_H_ + +#include "impeller/toolkit/android/proc_table.h" + +#include +#include + +namespace impeller::android { + +//------------------------------------------------------------------------------ +/// @brief This class describes access to the choreographer instance for +/// the current thread. Choreographers are only available on API +/// levels above 24. On levels below 24, an invalid choreographer +/// will be returned. +/// +/// Since choreographer need an event loop on the current thread, +/// one will be setup if it doesn't already exist. +/// +class Choreographer { + public: + static bool IsAvailableOnPlatform(); + + //---------------------------------------------------------------------------- + /// @brief Create or get the thread local instance of a choreographer. A + /// message loop will be setup on the calling thread if none + /// exists. + /// + /// @warning Choreographers are only available on API levels 24 and above. + /// Below this level, this will return an invalid instance. + /// Availability can also be checked via the + /// `IsAvailableOnPlatform` call. + /// + /// @return The thread local choreographer instance. If none can be setup, + /// an invalid object reference will be returned. See `IsValid`. + /// + static Choreographer& GetInstance(); + + ~Choreographer(); + + Choreographer(const Choreographer&) = delete; + + Choreographer& operator=(const Choreographer&) = delete; + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// A monotonic system clock. + /// + using FrameClock = std::chrono::steady_clock; + + //---------------------------------------------------------------------------- + /// A timepoint on a monotonic system clock. + /// + using FrameTimePoint = std::chrono::time_point; + using FrameCallback = std::function; + + //---------------------------------------------------------------------------- + /// @brief Posts a frame callback. The time that the frame is being + /// rendered will be available in the callback as an argument. + /// Multiple frame callbacks within the same frame interval will + /// receive the same argument. + /// + /// @param[in] callback The callback + /// + /// @return `true` if the frame callback could be posted. This may return + /// `false` if choreographers are not available on the platform. + /// See `IsAvailableOnPlatform`. + /// + bool PostFrameCallback(FrameCallback callback) const; + + private: + AChoreographer* instance_ = nullptr; + + explicit Choreographer(); +}; + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_CHOREOGRAPHER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.cc b/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..57137f305593c6c98d394d67d34eaa66d124ebce --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.cc @@ -0,0 +1,170 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/android/hardware_buffer.h" + +#include "impeller/base/validation.h" + +namespace impeller::android { + +static AHardwareBuffer_Format ToAHardwareBufferFormat( + HardwareBufferFormat format) { + switch (format) { + case HardwareBufferFormat::kR8G8B8A8UNormInt: + return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; + } + FML_UNREACHABLE(); +} + +static AHardwareBuffer_Desc ToAHardwareBufferDesc( + const HardwareBufferDescriptor& desc) { + AHardwareBuffer_Desc ahb_desc = {}; + ahb_desc.width = desc.size.width; + ahb_desc.height = desc.size.height; + ahb_desc.format = ToAHardwareBufferFormat(desc.format); + ahb_desc.layers = 1u; + if (desc.usage & HardwareBufferUsageFlags::kFrameBufferAttachment) { + ahb_desc.usage |= (AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER | + AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT); + } + if (desc.usage & HardwareBufferUsageFlags::kCompositorOverlay) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY; + } + if (desc.usage & HardwareBufferUsageFlags::kSampledImage) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE; + } + if (desc.usage & HardwareBufferUsageFlags::kCPUReadRarely) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_CPU_READ_RARELY; + } + if (desc.usage & HardwareBufferUsageFlags::kCPUReadOften) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN; + } + if (desc.usage & HardwareBufferUsageFlags::kCPUWriteRarely) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY; + } + if (desc.usage & HardwareBufferUsageFlags::kCPUWriteOften) { + ahb_desc.usage |= AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN; + } + return ahb_desc; +} + +bool HardwareBufferDescriptor::IsAllocatable() const { + const auto desc = ToAHardwareBufferDesc(*this); + return GetProcTable().AHardwareBuffer_isSupported(&desc) != 0u; +} + +HardwareBuffer::HardwareBuffer(HardwareBufferDescriptor descriptor) + : descriptor_(descriptor), + android_descriptor_(ToAHardwareBufferDesc(descriptor_)) { + if (!descriptor_.IsAllocatable()) { + VALIDATION_LOG << "The hardware buffer descriptor is not allocatable."; + return; + } + const auto& proc_table = GetProcTable(); + + AHardwareBuffer* buffer = nullptr; + if (auto result = + proc_table.AHardwareBuffer_allocate(&android_descriptor_, &buffer); + result != 0 || buffer == nullptr) { + VALIDATION_LOG << "Could not allocate hardware buffer. Error: " << result; + return; + } + buffer_.reset(buffer); + is_valid_ = true; +} + +HardwareBuffer::~HardwareBuffer() = default; + +bool HardwareBuffer::IsValid() const { + return is_valid_; +} + +AHardwareBuffer* HardwareBuffer::GetHandle() const { + return buffer_.get(); +} + +HardwareBufferDescriptor HardwareBufferDescriptor::MakeForSwapchainImage( + const ISize& size) { + HardwareBufferDescriptor desc; + desc.format = HardwareBufferFormat::kR8G8B8A8UNormInt; + // Zero sized hardware buffers cannot be allocated. + desc.size = size.Max(ISize{1u, 1u}); + desc.usage = HardwareBufferUsageFlags::kFrameBufferAttachment | + HardwareBufferUsageFlags::kCompositorOverlay | + HardwareBufferUsageFlags::kSampledImage; + return desc; +} + +const HardwareBufferDescriptor& HardwareBuffer::GetDescriptor() const { + return descriptor_; +} + +const AHardwareBuffer_Desc& HardwareBuffer::GetAndroidDescriptor() const { + return android_descriptor_; +} + +bool HardwareBuffer::IsAvailableOnPlatform() { + return GetProcTable().IsValid() && GetProcTable().AHardwareBuffer_isSupported; +} + +std::optional HardwareBuffer::GetSystemUniqueID() const { + return GetSystemUniqueID(GetHandle()); +} + +std::optional HardwareBuffer::GetSystemUniqueID( + AHardwareBuffer* buffer) { + if (!GetProcTable().AHardwareBuffer_getId) { + return std::nullopt; + } + uint64_t out_id = 0u; + if (GetProcTable().AHardwareBuffer_getId(buffer, &out_id) != 0) { + return std::nullopt; + } + return out_id; +} + +std::optional HardwareBuffer::Describe( + AHardwareBuffer* buffer) { + if (!buffer || !GetProcTable().AHardwareBuffer_describe) { + return std::nullopt; + } + AHardwareBuffer_Desc desc = {}; + GetProcTable().AHardwareBuffer_describe(buffer, &desc); + return desc; +} + +void* HardwareBuffer::Lock(CPUAccessType type) const { + if (!is_valid_ || !GetProcTable().AHardwareBuffer_lock) { + return nullptr; + } + uint64_t usage = 0; + switch (type) { + case CPUAccessType::kRead: + usage |= AHARDWAREBUFFER_USAGE_CPU_READ_MASK; + break; + case CPUAccessType::kWrite: + usage |= AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK; + break; + } + void* buffer = nullptr; + const auto result = GetProcTable().AHardwareBuffer_lock( // + buffer_.get(), // buffer + usage, // usage + -1, // fence + nullptr, // rect + &buffer // out-addr + ); + return result == 0 ? buffer : nullptr; +} + +bool HardwareBuffer::Unlock() const { + if (!is_valid_ || !GetProcTable().AHardwareBuffer_unlock) { + return false; + } + const auto result = + GetProcTable().AHardwareBuffer_unlock(buffer_.get(), nullptr); + return result == 0; +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.h b/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..bce356da7604bb7efc32f29773bf1a22e260fe55 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/hardware_buffer.h @@ -0,0 +1,185 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_ + +#include + +#include "flutter/fml/unique_fd.h" +#include "flutter/fml/unique_object.h" +#include "impeller/base/mask.h" +#include "impeller/geometry/size.h" +#include "impeller/toolkit/android/proc_table.h" + +namespace impeller::android { + +enum class HardwareBufferFormat { + //---------------------------------------------------------------------------- + /// This format is guaranteed to be supported on all versions of Android. This + /// format can also be converted to an Impeller and Vulkan format. + /// + /// @see Vulkan Format: VK_FORMAT_R8G8B8A8_UNORM + /// @see OpenGL ES Format: GL_RGBA8 + /// + /// Why have many format when one format do trick? + /// + kR8G8B8A8UNormInt, +}; + +enum class HardwareBufferUsageFlags { + kNone = 0u, + kFrameBufferAttachment = 1u << 0u, + kCompositorOverlay = 1u << 1u, + kSampledImage = 1u << 2u, + kCPUReadRarely = 1u << 3u, + kCPUReadOften = 1u << 4u, + kCPUWriteRarely = 1u << 5u, + kCPUWriteOften = 1u << 6u, +}; + +using HardwareBufferUsage = Mask; + +//------------------------------------------------------------------------------ +/// @brief A descriptor use to specify hardware buffer allocations. +/// +struct HardwareBufferDescriptor { + HardwareBufferFormat format = HardwareBufferFormat::kR8G8B8A8UNormInt; + ISize size; + HardwareBufferUsage usage = HardwareBufferUsageFlags::kNone; + + //---------------------------------------------------------------------------- + /// @brief Create a descriptor of the given size that is suitable for use + /// as a swapchain image. + /// + /// @warning Descriptors of zero size are not allocatable. The next best + /// valid size is picked. So make sure to check the actual size of + /// the descriptor after this call is made to determine the size + /// of the allocated hardware buffer. + /// + /// @param[in] size The size. See the restrictions about valid sizes above. + /// + /// @return The hardware buffer descriptor. + /// + static HardwareBufferDescriptor MakeForSwapchainImage(const ISize& size); + + //---------------------------------------------------------------------------- + /// @brief If hardware buffers can be created using this descriptor. + /// Allocatable descriptors may still cause failing allocations in + /// case of resource exhaustion. + /// + /// @return `true` if allocatable (unless resource exhaustion). + /// + bool IsAllocatable() const; + + constexpr bool operator==(const HardwareBufferDescriptor& o) const { + return format == o.format && size == o.size && usage == o.usage; + } + + constexpr bool operator!=(const HardwareBufferDescriptor& o) const { + return !(*this == o); + } +}; + +//------------------------------------------------------------------------------ +/// @brief A wrapper for AHardwareBuffer +/// https://developer.android.com/ndk/reference/group/a-hardware-buffer +/// +/// This wrapper creates and owns a handle to a managed hardware +/// buffer. That is, there is no ability to take a reference to an +/// externally created hardware buffer. +/// +/// This wrapper is only available on Android API 29 and above. +/// +class HardwareBuffer { + public: + static bool IsAvailableOnPlatform(); + + explicit HardwareBuffer(HardwareBufferDescriptor descriptor); + + ~HardwareBuffer(); + + HardwareBuffer(const HardwareBuffer&) = delete; + + HardwareBuffer& operator=(const HardwareBuffer&) = delete; + + bool IsValid() const; + + AHardwareBuffer* GetHandle() const; + + const HardwareBufferDescriptor& GetDescriptor() const; + + const AHardwareBuffer_Desc& GetAndroidDescriptor() const; + + static std::optional Describe(AHardwareBuffer* buffer); + + //---------------------------------------------------------------------------- + /// @brief Get the system wide unique ID of the hardware buffer if + /// possible. This is only available on Android API 31 and above. + /// Within the process, the handle are unique. + /// + /// @return The system unique id if one can be obtained. + /// + std::optional GetSystemUniqueID() const; + + //---------------------------------------------------------------------------- + /// @brief Get the system wide unique ID of the hardware buffer if + /// possible. This is only available on Android API 31 and above. + /// Within the process, the handle are unique. + /// + /// @return The system unique id if one can be obtained. + /// + static std::optional GetSystemUniqueID(AHardwareBuffer* buffer); + + enum class CPUAccessType { + kRead, + kWrite, + }; + //---------------------------------------------------------------------------- + /// @brief Lock the buffer for CPU access. This call may fail if the + /// buffer was not created with one the usages that allow for CPU + /// access. + /// + /// @param[in] type The type + /// + /// @return A host-accessible buffer if there was no error related to + /// usage or buffer validity. + /// + void* Lock(CPUAccessType type) const; + + //---------------------------------------------------------------------------- + /// @brief Unlock a mapping previously locked for CPU access. + /// + /// @return If the unlock was successful. + /// + bool Unlock() const; + + private: + struct UniqueAHardwareBufferTraits { + static AHardwareBuffer* InvalidValue() { return nullptr; } + + static bool IsValid(AHardwareBuffer* value) { + return value != InvalidValue(); + } + + static void Free(AHardwareBuffer* value) { + GetProcTable().AHardwareBuffer_release(value); + } + }; + + const HardwareBufferDescriptor descriptor_; + const AHardwareBuffer_Desc android_descriptor_; + fml::UniqueObject buffer_; + bool is_valid_ = false; +}; + +} // namespace impeller::android + +namespace impeller { + +IMPELLER_ENUM_IS_MASK(android::HardwareBufferUsageFlags); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_HARDWARE_BUFFER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/native_window.cc b/flutter/engine/src/flutter/impeller/toolkit/android/native_window.cc new file mode 100644 index 0000000000000000000000000000000000000000..663a482f624a389b275e84923ba981576eddd9aa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/native_window.cc @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/android/native_window.h" + +namespace impeller::android { + +NativeWindow::NativeWindow(ANativeWindow* window) : window_(window) { + if (window_.get()) { + GetProcTable().ANativeWindow_acquire(window_.get()); + } +} + +NativeWindow::~NativeWindow() = default; + +bool NativeWindow::IsValid() const { + return window_.is_valid(); +} + +ISize NativeWindow::GetSize() const { + if (!IsValid()) { + return {}; + } + const int32_t width = ANativeWindow_getWidth(window_.get()); + const int32_t height = ANativeWindow_getHeight(window_.get()); + return ISize::MakeWH(std::max(width, 0), std::max(height, 0)); +} + +ANativeWindow* NativeWindow::GetHandle() const { + return window_.get(); +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/native_window.h b/flutter/engine/src/flutter/impeller/toolkit/android/native_window.h new file mode 100644 index 0000000000000000000000000000000000000000..8af6cfb4ba5a6c7eeff023eebec22dfec48f3d93 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/native_window.h @@ -0,0 +1,57 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_ + +#include "flutter/fml/unique_object.h" +#include "impeller/geometry/size.h" +#include "impeller/toolkit/android/proc_table.h" + +namespace impeller::android { + +//------------------------------------------------------------------------------ +/// @brief A wrapper for ANativeWindow +/// https://developer.android.com/ndk/reference/group/a-native-window +/// +/// This wrapper is only available on Android. +/// +class NativeWindow { + public: + explicit NativeWindow(ANativeWindow* window); + + ~NativeWindow(); + + NativeWindow(const NativeWindow&) = delete; + + NativeWindow& operator=(const NativeWindow&) = delete; + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @return The current size of the native window. + /// + ISize GetSize() const; + + ANativeWindow* GetHandle() const; + + private: + struct UniqueANativeWindowTraits { + static ANativeWindow* InvalidValue() { return nullptr; } + + static bool IsValid(ANativeWindow* value) { + return value != InvalidValue(); + } + + static void Free(ANativeWindow* value) { + GetProcTable().ANativeWindow_release(value); + } + }; + + fml::UniqueObject window_; +}; + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_NATIVE_WINDOW_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.cc b/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.cc new file mode 100644 index 0000000000000000000000000000000000000000..24f9f99008a3dcdebf31f1f9cb064f452fae6be1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.cc @@ -0,0 +1,73 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/toolkit/android/proc_table.h" + +#include "flutter/fml/build_config.h" +#include "impeller/base/validation.h" + +namespace impeller::android { + +const ProcTable& GetProcTable() { + static ProcTable gProcTable; + return gProcTable; +} + +// Only used by tests. +ProcTable& GetMutableProcTable() { + return const_cast(GetProcTable()); +} + +template +void ResolveAndroidProc( + AndroidProc& proc, + const std::vector>& libs) { + for (const auto& lib : libs) { + proc.proc = lib->ResolveFunction(proc.proc_name).value_or(nullptr); + if (proc.proc) { + break; + } + } +} + +ProcTable::ProcTable() { + auto lib_android = fml::NativeLibrary::Create("libandroid.so"); + auto lib_egl = fml::NativeLibrary::Create("libEGL.so"); + + if (!lib_android || !lib_egl) { + VALIDATION_LOG << "Could not open Android libraries."; + return; + } + + libraries_.push_back(std::move(lib_android)); + libraries_.push_back(std::move(lib_egl)); + +#define RESOLVE_PROC(proc, api) ResolveAndroidProc(proc, libraries_); + FOR_EACH_ANDROID_PROC(RESOLVE_PROC); +#undef RESOLVE_PROC + + if (AChoreographer_postFrameCallback64) { + AChoreographer_postFrameCallback.Reset(); + } + +#if FML_ARCH_CPU_32_BITS + // On 32-bit platforms, the nanosecond resolution timestamp causes overflow on + // the argument in the callback. Don't use it on those platforms. + AChoreographer_postFrameCallback.Reset(); +#endif // FML_ARCH_CPU_32_BITS + + is_valid_ = true; +} + +ProcTable::~ProcTable() = default; + +bool ProcTable::IsValid() const { + return is_valid_; +} + +bool ProcTable::TraceIsEnabled() const { + return this->ATrace_isEnabled ? this->ATrace_isEnabled() : false; +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.h b/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.h new file mode 100644 index 0000000000000000000000000000000000000000..6e90b7fe86926b1232c0d7cbd88c1648f7d15032 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/proc_table.h @@ -0,0 +1,140 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_ + +#include +#define EGL_EGLEXT_PROTOTYPES +#include +#include +#include +#include +#include +#include + +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/native_library.h" + +namespace impeller::android { + +ASurfaceTransaction* ASurfaceTransaction_fromJava(JNIEnv* env, + jobject transaction); + +//------------------------------------------------------------------------------ +/// @brief The Android procs along with the device API level on which these +/// will be available. There is no checking of the actual API level +/// however (because getting the API level is itself only possible +/// on API levels 29 and above). +/// +/// Take care to explicitly check for the availability of these APIs +/// at runtime before invoking them. +/// +/// Typically, you'll never have to deal with the proc. table +/// directly. Instead, rely on the handle wrappers (`Choreographer`, +/// `HardwareBuffer`, etc..). +/// +#define FOR_EACH_ANDROID_PROC(INVOKE) \ + INVOKE(AChoreographer_getInstance, 24) \ + INVOKE(AChoreographer_postFrameCallback, 24) \ + INVOKE(AChoreographer_postFrameCallback64, 29) \ + INVOKE(AHardwareBuffer_acquire, 26) \ + INVOKE(AHardwareBuffer_allocate, 26) \ + INVOKE(AHardwareBuffer_describe, 26) \ + INVOKE(AHardwareBuffer_fromHardwareBuffer, 26) \ + INVOKE(AHardwareBuffer_getId, 31) \ + INVOKE(AHardwareBuffer_isSupported, 29) \ + INVOKE(AHardwareBuffer_lock, 26) \ + INVOKE(AHardwareBuffer_release, 26) \ + INVOKE(AHardwareBuffer_unlock, 26) \ + INVOKE(ANativeWindow_acquire, 0) \ + INVOKE(ANativeWindow_getHeight, 0) \ + INVOKE(ANativeWindow_getWidth, 0) \ + INVOKE(ANativeWindow_release, 0) \ + INVOKE(ASurfaceControl_createFromWindow, 29) \ + INVOKE(ASurfaceControl_release, 29) \ + INVOKE(ASurfaceTransaction_apply, 29) \ + INVOKE(ASurfaceTransaction_create, 29) \ + INVOKE(ASurfaceTransaction_delete, 29) \ + INVOKE(ASurfaceTransaction_reparent, 29) \ + INVOKE(ASurfaceTransaction_setBuffer, 29) \ + INVOKE(ASurfaceTransaction_setColor, 29) \ + INVOKE(ASurfaceTransaction_setOnComplete, 29) \ + INVOKE(ASurfaceTransactionStats_getPreviousReleaseFenceFd, 29) \ + INVOKE(ASurfaceTransaction_fromJava, 34) \ + INVOKE(ATrace_isEnabled, 23) \ + INVOKE(eglGetNativeClientBufferANDROID, 0) + +template +struct AndroidProc { + using AndroidProcType = T; + + const char* proc_name = nullptr; + + AndroidProcType* proc = nullptr; + + constexpr bool IsAvailable() const { return proc != nullptr; } + + explicit constexpr operator bool() const { return IsAvailable(); } + + template + auto operator()(Args&&... args) const { + FML_DCHECK(IsAvailable()) + << "Android method " << proc_name + << " is not available on this device. Missing check."; + return proc(std::forward(args)...); + } + + void Reset() { proc = nullptr; } +}; + +//------------------------------------------------------------------------------ +/// @brief The table of Android procs that are resolved dynamically. +/// +struct ProcTable { + ProcTable(); + + ~ProcTable(); + + ProcTable(const ProcTable&) = delete; + + ProcTable& operator=(const ProcTable&) = delete; + + //---------------------------------------------------------------------------- + /// @brief If a valid proc table could be setup. This may fail in case of + /// setup on non-Android platforms. + /// + /// @return `true` if valid. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Check if tracing in enabled in the process. This call can be + /// made at any API level. + /// + /// @return If tracing is enabled. + /// + bool TraceIsEnabled() const; + +#define DEFINE_PROC(name, api) \ + AndroidProc name = {.proc_name = #name}; + FOR_EACH_ANDROID_PROC(DEFINE_PROC); +#undef DEFINE_PROC + + private: + std::vector> libraries_; + bool is_valid_ = false; +}; + +const ProcTable& GetProcTable(); + +#ifdef TESTING +ProcTable& GetMutableProcTable(); +#endif + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_PROC_TABLE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.cc b/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f0400cf972d3e1658b6129d2538b0c9cd4892ad --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.cc @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/android/surface_control.h" + +#include "impeller/base/validation.h" +#include "impeller/toolkit/android/surface_transaction.h" + +namespace impeller::android { + +SurfaceControl::SurfaceControl(ANativeWindow* window, const char* debug_name) { + if (window == nullptr) { + VALIDATION_LOG << "Parent window of surface was null."; + return; + } + if (debug_name == nullptr) { + debug_name = "Impeller Layer"; + } + control_.reset( + GetProcTable().ASurfaceControl_createFromWindow(window, debug_name)); +} + +SurfaceControl::~SurfaceControl() { + if (IsValid() && !RemoveFromParent()) { + VALIDATION_LOG << "Surface control could not be removed from its parent. " + "Expect a leak."; + } +} + +bool SurfaceControl::IsValid() const { + return control_.is_valid(); +} + +ASurfaceControl* SurfaceControl::GetHandle() const { + return control_.get(); +} + +bool SurfaceControl::RemoveFromParent() const { + if (!IsValid()) { + return false; + } + SurfaceTransaction transaction; + if (!transaction.SetParent(*this, nullptr)) { + return false; + } + return transaction.Apply(); +} + +bool SurfaceControl::IsAvailableOnPlatform() { + auto api_level = android_get_device_api_level(); + + // Technically SurfaceControl is supported on API 29 but I've observed + // enough reported bugs that I'm bumping the constraint to 30. If + // we had more time to test all of these older devices maybe we could + // figure out what the problem is. + // https://github.com/flutter/flutter/issues/155877 + return api_level >= 29 && GetProcTable().IsValid() && + GetProcTable().ASurfaceControl_createFromWindow.IsAvailable(); +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.h b/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.h new file mode 100644 index 0000000000000000000000000000000000000000..b853ed488040aaa5ce2dfe391492d56993cfadbe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_control.h @@ -0,0 +1,89 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_CONTROL_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_CONTROL_H_ + +#include "flutter/fml/unique_object.h" +#include "impeller/toolkit/android/proc_table.h" + +namespace impeller::android { + +//------------------------------------------------------------------------------ +/// @brief A wrapper for ASurfaceControl. +/// https://developer.android.com/ndk/reference/group/native-activity#asurfacecontrol +/// +/// Instances of this class represent a node in the hierarchy of +/// surfaces sent to the system compositor for final composition. +/// +/// This wrapper is only available on Android API 29 and above. +/// +class SurfaceControl { + public: + //---------------------------------------------------------------------------- + /// @return `true` if any surface controls can be created on this + /// platform. + /// + static bool IsAvailableOnPlatform(); + + //---------------------------------------------------------------------------- + /// @brief Creates a new surface control and adds it as a child of the + /// given window. + /// + /// @param window The window + /// @param[in] debug_name A debug name. See it using + /// `adb shell dumpsys SurfaceFlinger` along with + /// other control properties. If no debug name is + /// specified, the value "Impeller Layer" is used. + /// + explicit SurfaceControl(ANativeWindow* window, + const char* debug_name = nullptr); + + //---------------------------------------------------------------------------- + /// @brief Removes the surface control from the presentation hierarchy + /// managed by the system compositor and release the client side + /// reference to the control. At this point, it may be collected + /// when the compositor is also done using it. + /// + ~SurfaceControl(); + + SurfaceControl(const SurfaceControl&) = delete; + + SurfaceControl& operator=(const SurfaceControl&) = delete; + + bool IsValid() const; + + ASurfaceControl* GetHandle() const; + + //---------------------------------------------------------------------------- + /// @brief Remove the surface control from the hierarchy of nodes + /// presented by the system compositor. + /// + /// This is called implicitly when the surface control is + /// collected. + /// + /// @return `true` If the control will be removed from the hierarchy of + /// nodes presented by the system compositor. + /// + bool RemoveFromParent() const; + + private: + struct UniqueASurfaceControlTraits { + static ASurfaceControl* InvalidValue() { return nullptr; } + + static bool IsValid(ASurfaceControl* value) { + return value != InvalidValue(); + } + + static void Free(ASurfaceControl* value) { + GetProcTable().ASurfaceControl_release(value); + } + }; + + fml::UniqueObject control_; +}; + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_CONTROL_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.cc b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e1b0352964d4ddd08ccd7fc09de357877c11c83 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.cc @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/toolkit/android/surface_transaction.h" + +#include "flutter/impeller/toolkit/android/hardware_buffer.h" +#include "flutter/impeller/toolkit/android/surface_control.h" +#include "impeller/base/validation.h" + +namespace impeller::android { + +SurfaceTransaction::SurfaceTransaction() + : transaction_( + WrappedSurfaceTransaction{GetProcTable().ASurfaceTransaction_create(), + /*owned=*/true}) {} + +SurfaceTransaction::SurfaceTransaction(ASurfaceTransaction* transaction) + : transaction_(WrappedSurfaceTransaction{transaction, /*owned=*/false}) {} + +SurfaceTransaction::~SurfaceTransaction() = default; + +bool SurfaceTransaction::IsValid() const { + return transaction_.is_valid(); +} + +struct TransactionInFlightData { + SurfaceTransaction::OnCompleteCallback callback; +}; + +bool SurfaceTransaction::Apply(OnCompleteCallback callback) { + if (!IsValid()) { + return false; + } + + if (!callback) { + callback = [](auto) {}; + } + + const auto& proc_table = GetProcTable(); + + auto data = std::make_unique(); + data->callback = callback; + proc_table.ASurfaceTransaction_setOnComplete( + transaction_.get().tx, // + data.release(), // + [](void* context, ASurfaceTransactionStats* stats) -> void { + auto data = reinterpret_cast(context); + data->callback(stats); + delete data; + }); + // If the transaction was created in Java, then it must be applied in + // the Java PlatformViewController and not as a part of the engine render + // loop. + if (!transaction_.get().owned) { + transaction_.reset(); + return true; + } + + proc_table.ASurfaceTransaction_apply(transaction_.get().tx); + + // Transactions may not be applied over and over. + transaction_.reset(); + return true; +} + +bool SurfaceTransaction::SetContents(const SurfaceControl* control, + const HardwareBuffer* buffer, + fml::UniqueFD acquire_fence) { + if (control == nullptr || buffer == nullptr) { + VALIDATION_LOG << "Invalid control or buffer."; + return false; + } + GetProcTable().ASurfaceTransaction_setBuffer( + transaction_.get().tx, // + control->GetHandle(), // + buffer->GetHandle(), // + acquire_fence.is_valid() ? acquire_fence.release() : -1 // + ); + return true; +} + +bool SurfaceTransaction::SetBackgroundColor(const SurfaceControl& control, + const Color& color) { + if (!IsValid() || !control.IsValid()) { + return false; + } + GetProcTable().ASurfaceTransaction_setColor(transaction_.get().tx, // + control.GetHandle(), // + color.red, // + color.green, // + color.blue, // + color.alpha, // + ADATASPACE_SRGB_LINEAR // + ); + return true; +} + +bool SurfaceTransaction::SetParent(const SurfaceControl& control, + const SurfaceControl* new_parent) { + if (!IsValid() || !control.IsValid()) { + return false; + } + if (new_parent && !new_parent->IsValid()) { + return false; + } + GetProcTable().ASurfaceTransaction_reparent( + transaction_.get().tx, // + control.GetHandle(), // + new_parent == nullptr ? nullptr : new_parent->GetHandle() // + ); + return true; +} + +bool SurfaceTransaction::IsAvailableOnPlatform() { + return GetProcTable().IsValid() && + GetProcTable().ASurfaceTransaction_create.IsAvailable(); +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.h b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.h new file mode 100644 index 0000000000000000000000000000000000000000..85fcdcfacdabcd05da0f25e89ac6179df374b242 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction.h @@ -0,0 +1,162 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_ + +#include +#include + +#include "flutter/fml/unique_fd.h" +#include "flutter/fml/unique_object.h" +#include "impeller/geometry/color.h" +#include "impeller/toolkit/android/proc_table.h" + +namespace impeller::android { + +class SurfaceControl; +class HardwareBuffer; + +/// @brief A wrapper class that indicates whether a SurfaceTransaction was +/// created by the flutter engine or was borrowed from Java for platform +/// interop. +struct WrappedSurfaceTransaction { + ASurfaceTransaction* tx = nullptr; + + /// Whether this SurfaceTransaction was created by the engine or imported from + /// Java. + bool owned = true; + + constexpr bool operator==(const WrappedSurfaceTransaction& other) const { + return other.tx == tx; + } + + constexpr bool operator!=(const WrappedSurfaceTransaction& other) const { + return !(*this == other); + } +}; + +//------------------------------------------------------------------------------ +/// @brief A wrapper for ASurfaceTransaction. +/// https://developer.android.com/ndk/reference/group/native-activity#asurfacetransaction +/// +/// A surface transaction is a collection of updates to the +/// hierarchy of surfaces (represented by `ASurfaceControl` +/// instances) that are applied atomically in the compositor. +/// +/// This wrapper is only available on Android API 29 and above. +/// +/// @note Transactions should be short lived objects (create, apply, +/// collect). But, if these are used on multiple threads, they must +/// be externally synchronized. +/// +class SurfaceTransaction { + public: + //---------------------------------------------------------------------------- + /// @return `true` if any surface transactions can be created on this + /// platform. + /// + static bool IsAvailableOnPlatform(); + + SurfaceTransaction(); + + ~SurfaceTransaction(); + + SurfaceTransaction(const SurfaceTransaction&) = delete; + + SurfaceTransaction& operator=(const SurfaceTransaction&) = delete; + + explicit SurfaceTransaction(ASurfaceTransaction* transaction); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Encodes that the updated contents of a surface control are + /// specified by the given hardware buffer. The update will not be + /// committed till the call to `Apply` however. + /// + /// @see `SurfaceTransaction::Apply`. + /// + /// @param[in] control The control. + /// @param[in] buffer The hardware buffer. + /// @param[in] acquire_fence The fence to wait on before setting the + /// contents. + /// + /// @return If the update was encoded in the transaction. + /// + [[nodiscard]] bool SetContents(const SurfaceControl* control, + const HardwareBuffer* buffer, + fml::UniqueFD acquire_fence = {}); + + //---------------------------------------------------------------------------- + /// @brief Encodes the updated background color of the surface control. + /// The update will not be committed till the call to `Apply` + /// however. + /// + /// @see `SurfaceTransaction::Apply`. + /// + /// @param[in] control The control + /// @param[in] color The color + /// + /// @return `true` if the background control will be set when transaction + /// is applied. + /// + [[nodiscard]] bool SetBackgroundColor(const SurfaceControl& control, + const Color& color); + + using OnCompleteCallback = std::function; + + //---------------------------------------------------------------------------- + /// @brief Applies the updated encoded in the transaction and invokes the + /// callback when the updated are complete. + /// + /// @warning The callback will be invoked on a system managed thread. + /// + /// @note It is fine to immediately destroy the transaction after the + /// call to apply. It is not necessary to wait for transaction + /// completion to collect the transaction handle. + /// + /// @param[in] callback The callback + /// + /// @return `true` if the surface transaction was applied. `true` does not + /// indicate the application was completed however. Only the + /// invocation of the callback denotes transaction completion. + /// + [[nodiscard]] bool Apply(OnCompleteCallback callback = nullptr); + + //---------------------------------------------------------------------------- + /// @brief Set the new parent control of the given control. If the new + /// parent is null, it is removed from the control hierarchy. + /// + /// @param[in] control The control + /// @param[in] new_parent The new parent + /// + /// @return `true` if the control will be re-parented when the transaction + /// is applied. + /// + [[nodiscard]] bool SetParent(const SurfaceControl& control, + const SurfaceControl* new_parent = nullptr); + + private: + struct UniqueASurfaceTransactionTraits { + static WrappedSurfaceTransaction InvalidValue() { return {}; } + + static bool IsValid(const WrappedSurfaceTransaction& value) { + return value.tx != nullptr; + } + + static void Free(const WrappedSurfaceTransaction& value) { + if (value.owned && value.tx) { + GetProcTable().ASurfaceTransaction_delete(value.tx); + } + } + }; + + fml::UniqueObject + transaction_; +}; + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.cc b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.cc new file mode 100644 index 0000000000000000000000000000000000000000..d2d4e3e7ade3908e52ca343f23a8398a93f95453 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.cc @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/android/surface_transaction_stats.h" + +#include "impeller/toolkit/android/proc_table.h" + +namespace impeller::android { + +fml::UniqueFD CreatePreviousReleaseFence(const SurfaceControl& control, + ASurfaceTransactionStats* stats) { + const auto fd = + GetProcTable().ASurfaceTransactionStats_getPreviousReleaseFenceFd( + stats, control.GetHandle()); + if (fd == -1) { + // The previous buffer has already been released. This is not an error. + return {}; + } + return fml::UniqueFD{fd}; +} + +} // namespace impeller::android diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.h b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..2ddda8fdfd317981148e6ee1cfe815e247d5a542 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/surface_transaction_stats.h @@ -0,0 +1,18 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_STATS_H_ +#define FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_STATS_H_ + +#include "flutter/fml/unique_fd.h" +#include "impeller/toolkit/android/surface_control.h" + +namespace impeller::android { + +fml::UniqueFD CreatePreviousReleaseFence(const SurfaceControl& control, + ASurfaceTransactionStats* stats); + +} // namespace impeller::android + +#endif // FLUTTER_IMPELLER_TOOLKIT_ANDROID_SURFACE_TRANSACTION_STATS_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/android/toolkit_android_unittests.cc b/flutter/engine/src/flutter/impeller/toolkit/android/toolkit_android_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c6218fa879627f7cccffd302b66f457f22ad17e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/android/toolkit_android_unittests.cc @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/waitable_event.h" +#include "flutter/testing/testing.h" +#include "impeller/toolkit/android/choreographer.h" +#include "impeller/toolkit/android/hardware_buffer.h" +#include "impeller/toolkit/android/proc_table.h" +#include "impeller/toolkit/android/surface_control.h" +#include "impeller/toolkit/android/surface_transaction.h" + +namespace impeller::android::testing { + +#define DISABLE_ANDROID_PROC(name) \ + struct Disable##name { \ + Disable##name() { \ + real_proc = GetMutableProcTable().name.proc; \ + GetMutableProcTable().name.proc = nullptr; \ + } \ + ~Disable##name() { \ + GetMutableProcTable().name.proc = real_proc; \ + } \ + decltype(name)* real_proc; \ + } disable##name; + +TEST(ToolkitAndroidTest, CanCreateProcTable) { + ProcTable proc_table; + ASSERT_TRUE(proc_table.IsValid()); +} + +TEST(ToolkitAndroidTest, GuardsAgainstZeroSizedDescriptors) { + auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({0, 0}); + ASSERT_GT(desc.size.width, 0u); + ASSERT_GT(desc.size.height, 0u); +} + +TEST(ToolkitAndroidTest, CanCreateHardwareBuffer) { + if (!HardwareBuffer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Hardware buffers are not supported on this platform."; + } + ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); + auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); + ASSERT_TRUE(desc.IsAllocatable()); + HardwareBuffer buffer(desc); + ASSERT_TRUE(buffer.IsValid()); +} + +TEST(ToolkitAndroidTest, CanGetHardwareBufferIDs) { + if (!HardwareBuffer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Hardware buffers are not supported on this platform."; + } + ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); + if (!GetProcTable().AHardwareBuffer_getId.IsAvailable()) { + GTEST_SKIP() << "Hardware buffer IDs are not available on this platform."; + } + auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); + ASSERT_TRUE(desc.IsAllocatable()); + HardwareBuffer buffer(desc); + ASSERT_TRUE(buffer.IsValid()); + ASSERT_TRUE(buffer.GetSystemUniqueID().has_value()); +} + +TEST(ToolkitAndroidTest, HardwareBufferNullIDIfAPIUnavailable) { + DISABLE_ANDROID_PROC(AHardwareBuffer_getId); + ASSERT_FALSE(HardwareBuffer::GetSystemUniqueID(nullptr).has_value()); +} + +TEST(ToolkitAndroidTest, CanDescribeHardwareBufferHandles) { + if (!HardwareBuffer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Hardware buffers are not supported on this platform."; + } + ASSERT_TRUE(HardwareBuffer::IsAvailableOnPlatform()); + auto desc = HardwareBufferDescriptor::MakeForSwapchainImage({100, 100}); + ASSERT_TRUE(desc.IsAllocatable()); + HardwareBuffer buffer(desc); + ASSERT_TRUE(buffer.IsValid()); + auto a_desc = HardwareBuffer::Describe(buffer.GetHandle()); + ASSERT_TRUE(a_desc.has_value()); + ASSERT_EQ(a_desc->width, 100u); // NOLINT + ASSERT_EQ(a_desc->height, 100u); // NOLINT +} + +TEST(ToolkitAndroidTest, CanApplySurfaceTransaction) { + if (!SurfaceTransaction::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Surface controls are not supported on this platform."; + } + ASSERT_TRUE(SurfaceTransaction::IsAvailableOnPlatform()); + SurfaceTransaction transaction; + ASSERT_TRUE(transaction.IsValid()); + fml::AutoResetWaitableEvent event; + ASSERT_TRUE(transaction.Apply([&event](auto) { event.Signal(); })); + event.Wait(); +} + +TEST(ToolkitAndroidTest, SurfacControlsAreAvailable) { + if (!SurfaceControl::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Surface controls are not supported on this platform."; + } + ASSERT_TRUE(SurfaceControl::IsAvailableOnPlatform()); +} + +TEST(ToolkitAndroidTest, ChoreographerIsAvailable) { + if (!Choreographer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Choreographer is not supported on this platform."; + } + ASSERT_TRUE(Choreographer::IsAvailableOnPlatform()); +} + +TEST(ToolkitAndroidTest, CanPostAndNotWaitForFrameCallbacks) { + if (!Choreographer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Choreographer is not supported on this platform."; + } + const auto& choreographer = Choreographer::GetInstance(); + ASSERT_TRUE(choreographer.IsValid()); + ASSERT_TRUE(choreographer.PostFrameCallback([](auto) {})); +} + +TEST(ToolkitAndroidTest, CanPostAndWaitForFrameCallbacks) { + if (!Choreographer::IsAvailableOnPlatform()) { + GTEST_SKIP() << "Choreographer is not supported on this platform."; + } + if ((true)) { + GTEST_SKIP() + << "Disabled till the test harness is in an Android activity. " + "Running it without one will hang because the choreographer " + "frame callback will never execute."; + } + const auto& choreographer = Choreographer::GetInstance(); + ASSERT_TRUE(choreographer.IsValid()); + fml::AutoResetWaitableEvent event; + ASSERT_TRUE(choreographer.PostFrameCallback( + [&event](auto point) { event.Signal(); })); + event.Wait(); +} + +} // namespace impeller::android::testing diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/egl/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..82d10a14d195ebd7c8720cc8a0febdb50c18b73c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../../tools/impeller.gni") + +impeller_component("egl") { + sources = [ + "config.cc", + "config.h", + "context.cc", + "context.h", + "display.cc", + "display.h", + "egl.cc", + "egl.h", + "image.cc", + "image.h", + "surface.cc", + "surface.h", + ] + + deps = [ + "../../base", + "//flutter/fml", + ] + + libs = [] + if (is_android) { + libs = [ "EGL" ] + } +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/config.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/config.cc new file mode 100644 index 0000000000000000000000000000000000000000..be42642bc446bbab04aecc39bdf866a01c798fcb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/config.cc @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/egl/config.h" + +#include + +namespace impeller { +namespace egl { + +Config::Config(ConfigDescriptor descriptor, EGLConfig config) + : desc_(descriptor), config_(config) {} + +Config::~Config() = default; + +const ConfigDescriptor& Config::GetDescriptor() const { + return desc_; +} + +const EGLConfig& Config::GetHandle() const { + return config_; +} + +bool Config::IsValid() const { + return config_ != nullptr; +} + +} // namespace egl +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/config.h b/flutter/engine/src/flutter/impeller/toolkit/egl/config.h new file mode 100644 index 0000000000000000000000000000000000000000..6690ee2db6f678b4beb0d58afacbc4e447c038a1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/config.h @@ -0,0 +1,89 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_ + +#include "impeller/toolkit/egl/egl.h" + +namespace impeller { +namespace egl { + +enum class API { + kOpenGL, + kOpenGLES2, + kOpenGLES3, +}; + +enum class Samples { + kOne = 1, + kTwo = 2, + kFour = 4, +}; + +enum class ColorFormat { + kRGBA8888, + kRGB565, +}; + +enum class StencilBits { + kZero = 0, + kEight = 8, +}; + +enum class DepthBits { + kZero = 0, + kEight = 8, + kTwentyFour = 24, +}; + +enum class SurfaceType { + kWindow, + kPBuffer, +}; + +struct ConfigDescriptor { + API api = API::kOpenGLES2; + Samples samples = Samples::kOne; + ColorFormat color_format = ColorFormat::kRGB565; + StencilBits stencil_bits = StencilBits::kZero; + DepthBits depth_bits = DepthBits::kZero; + SurfaceType surface_type = SurfaceType::kPBuffer; +}; + +class Display; + +//------------------------------------------------------------------------------ +/// @brief An EGL config. These are returned by the display to indicate +/// support for a specific config descriptor. +/// +/// There is no ability to construct these manually except for +/// testing. +/// +class Config { + public: + ~Config(); + + bool IsValid() const; + + const ConfigDescriptor& GetDescriptor() const; + + const EGLConfig& GetHandle() const; + + // Do not use. Only for testing. + Config(ConfigDescriptor descriptor, EGLConfig config); + + private: + const ConfigDescriptor desc_; + EGLConfig config_ = nullptr; + + Config(const Config&) = delete; + + Config& operator=(const Config&) = delete; +}; + +} // namespace egl +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_CONFIG_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/context.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/context.cc new file mode 100644 index 0000000000000000000000000000000000000000..715516a8f8652da85a073906ac44e2d2c853f9c9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/context.cc @@ -0,0 +1,107 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/egl/context.h" + +#include "impeller/toolkit/egl/surface.h" + +namespace impeller { +namespace egl { + +Context::Context(EGLDisplay display, EGLContext context) + : display_(display), context_(context) {} + +Context::~Context() { + if (context_ != EGL_NO_CONTEXT) { + if (::eglDestroyContext(display_, context_) != EGL_TRUE) { + IMPELLER_LOG_EGL_ERROR; + } + } +} + +bool Context::IsValid() const { + return context_ != EGL_NO_CONTEXT; +} + +const EGLContext& Context::GetHandle() const { + return context_; +} + +static EGLBoolean EGLMakeCurrentIfNecessary(EGLDisplay display, + EGLSurface draw, + EGLSurface read, + EGLContext context) { + if (display != ::eglGetCurrentDisplay() || + draw != ::eglGetCurrentSurface(EGL_DRAW) || + read != ::eglGetCurrentSurface(EGL_READ) || + context != ::eglGetCurrentContext()) { + return ::eglMakeCurrent(display, draw, read, context); + } + // The specified context configuration is already current. + return EGL_TRUE; +} + +bool Context::MakeCurrent(const Surface& surface) const { + if (context_ == EGL_NO_CONTEXT) { + return false; + } + const auto result = EGLMakeCurrentIfNecessary(display_, // + surface.GetHandle(), // + surface.GetHandle(), // + context_ // + ) == EGL_TRUE; + if (!result) { + IMPELLER_LOG_EGL_ERROR; + } + DispatchLifecyleEvent(LifecycleEvent::kDidMakeCurrent); + return result; +} + +bool Context::ClearCurrent() const { + DispatchLifecyleEvent(LifecycleEvent::kWillClearCurrent); + const auto result = EGLMakeCurrentIfNecessary(display_, // + EGL_NO_SURFACE, // + EGL_NO_SURFACE, // + EGL_NO_CONTEXT // + ) == EGL_TRUE; + if (!result) { + IMPELLER_LOG_EGL_ERROR; + } + return result; +} + +std::optional Context::AddLifecycleListener( + const LifecycleListener& listener) { + if (!listener) { + return std::nullopt; + } + WriterLock lock(listeners_mutex_); + UniqueID id; + listeners_[id] = listener; + return id; +} + +bool Context::RemoveLifecycleListener(UniqueID id) { + WriterLock lock(listeners_mutex_); + auto found = listeners_.find(id); + if (found == listeners_.end()) { + return false; + } + listeners_.erase(found); + return true; +} + +void Context::DispatchLifecyleEvent(LifecycleEvent event) const { + ReaderLock lock(listeners_mutex_); + for (const auto& listener : listeners_) { + listener.second(event); + } +} + +bool Context::IsCurrent() const { + return ::eglGetCurrentContext() == context_; +} + +} // namespace egl +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/context.h b/flutter/engine/src/flutter/impeller/toolkit/egl/context.h new file mode 100644 index 0000000000000000000000000000000000000000..74bc8195d4d7afdfd10baa2568f686bdb4ece2bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/context.h @@ -0,0 +1,129 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_CONTEXT_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_CONTEXT_H_ + +#include + +#include "impeller/base/comparable.h" +#include "impeller/base/thread.h" +#include "impeller/toolkit/egl/egl.h" + +namespace impeller { +namespace egl { + +class Surface; +class Display; + +//------------------------------------------------------------------------------ +/// @brief An instance of an EGL context. +/// +/// An EGL context can only be used on a single thread at a given +/// time. A thread can only have a single context current at any +/// given time. +/// +/// Context cannot be created directly. Only a valid instance of an +/// egl::Display can create a context. +/// +class Context { + public: + ~Context(); + + //---------------------------------------------------------------------------- + /// @brief Determines if a valid context could be created. The context + /// still needs to be made current on the thread for it to be + /// useful. + /// + /// @return True if valid, False otherwise. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Get the underlying handle to the EGL context. + /// + /// @return The handle. + /// + const EGLContext& GetHandle() const; + + //---------------------------------------------------------------------------- + /// @brief Make the context current on the calling thread. It is the + /// caller responsibility to ensure that any context previously + /// current on the thread must be cleared via `ClearCurrent`. + /// + /// @important The config used to create the surface must match the config + /// used to create this context instance. + /// + /// @param[in] surface The surface to use to make the context current. + /// + /// @return If the context could be made current on the callers thread. + /// + bool MakeCurrent(const Surface& surface) const; + + //---------------------------------------------------------------------------- + /// @brief Clear the thread association of this context. + /// + /// @return If the thread association could be cleared. + /// + bool ClearCurrent() const; + + enum class LifecycleEvent { + kDidMakeCurrent, + kWillClearCurrent, + }; + using LifecycleListener = std::function; + //---------------------------------------------------------------------------- + /// @brief Add a listener that gets invoked when the context is made and + /// cleared current from the thread. Applications typically use + /// this to manage workers that schedule OpenGL API calls that + /// need to be careful about the context being current when + /// called. + /// + /// @param[in] listener The listener + /// + /// @return A unique ID for the listener that can used used in + /// `RemoveLifecycleListener` to remove a previously added + /// listener. + /// + std::optional AddLifecycleListener( + const LifecycleListener& listener); + + //---------------------------------------------------------------------------- + /// @brief Remove a previously added context listener. + /// + /// @param[in] id The identifier obtained via a previous call to + /// `AddLifecycleListener`. + /// + /// @return True if the listener could be removed. + /// + bool RemoveLifecycleListener(UniqueID id); + + //---------------------------------------------------------------------------- + /// @return True if the context is current and attached to any surface, + /// False otherwise. + /// + bool IsCurrent() const; + + private: + friend class Display; + + EGLDisplay display_ = EGL_NO_DISPLAY; + EGLContext context_ = EGL_NO_CONTEXT; + mutable RWMutex listeners_mutex_; + std::map listeners_ IPLR_GUARDED_BY( + listeners_mutex_); + + Context(EGLDisplay display, EGLContext context); + + void DispatchLifecyleEvent(LifecycleEvent event) const; + + Context(const Context&) = delete; + + Context& operator=(const Context&) = delete; +}; + +} // namespace egl +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/display.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/display.cc new file mode 100644 index 0000000000000000000000000000000000000000..86cc72045daa368a0417b88e4d5ce03daf1d7ccc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/display.cc @@ -0,0 +1,214 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/egl/display.h" + +#include + +#include "flutter/fml/logging.h" +#include "impeller/toolkit/egl/context.h" +#include "impeller/toolkit/egl/surface.h" + +namespace impeller { +namespace egl { + +Display::Display() { + EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + + if (::eglInitialize(display, nullptr, nullptr) != EGL_TRUE) { + IMPELLER_LOG_EGL_ERROR; + return; + } + display_ = display; +} + +Display::~Display() { + if (display_ != EGL_NO_DISPLAY) { + if (::eglTerminate(display_) != EGL_TRUE) { + IMPELLER_LOG_EGL_ERROR; + } + } +} + +bool Display::IsValid() const { + return display_ != EGL_NO_DISPLAY; +} + +std::unique_ptr Display::CreateContext(const Config& config, + const Context* share_context) { + const auto& desc = config.GetDescriptor(); + + std::vector attributes; + switch (desc.api) { + case API::kOpenGL: + break; + case API::kOpenGLES2: + attributes.push_back(EGL_CONTEXT_CLIENT_VERSION); + attributes.push_back(2); + break; + case API::kOpenGLES3: + attributes.push_back(EGL_CONTEXT_CLIENT_VERSION); + attributes.push_back(3); + break; + } + // Termination sentinel must be present. + attributes.push_back(EGL_NONE); + + auto context = ::eglCreateContext( + display_, // display + config.GetHandle(), // config + share_context != nullptr ? share_context->GetHandle() : nullptr, // share + attributes.data() // attributes + ); + + if (context == EGL_NO_CONTEXT) { + IMPELLER_LOG_EGL_ERROR; + return nullptr; + } + + return std::unique_ptr(new Context(display_, context)); +} + +std::unique_ptr Display::ChooseConfig(ConfigDescriptor config) const { + if (!display_) { + return nullptr; + } + + std::vector attributes; + + { + attributes.push_back(EGL_RENDERABLE_TYPE); + switch (config.api) { + case API::kOpenGL: + attributes.push_back(EGL_OPENGL_BIT); + break; + case API::kOpenGLES2: + attributes.push_back(EGL_OPENGL_ES2_BIT); + break; + case API::kOpenGLES3: + attributes.push_back(EGL_OPENGL_ES3_BIT); + break; + } + } + + { + attributes.push_back(EGL_SURFACE_TYPE); + switch (config.surface_type) { + case SurfaceType::kWindow: + attributes.push_back(EGL_WINDOW_BIT); + break; + case SurfaceType::kPBuffer: + attributes.push_back(EGL_PBUFFER_BIT); + break; + } + } + + { + switch (config.color_format) { + case ColorFormat::kRGBA8888: + attributes.push_back(EGL_RED_SIZE); + attributes.push_back(8); + attributes.push_back(EGL_GREEN_SIZE); + attributes.push_back(8); + attributes.push_back(EGL_BLUE_SIZE); + attributes.push_back(8); + attributes.push_back(EGL_ALPHA_SIZE); + attributes.push_back(8); + break; + case ColorFormat::kRGB565: + attributes.push_back(EGL_RED_SIZE); + attributes.push_back(5); + attributes.push_back(EGL_GREEN_SIZE); + attributes.push_back(6); + attributes.push_back(EGL_BLUE_SIZE); + attributes.push_back(5); + break; + } + } + + { + attributes.push_back(EGL_DEPTH_SIZE); + attributes.push_back(static_cast(config.depth_bits)); + } + + { + attributes.push_back(EGL_STENCIL_SIZE); + attributes.push_back(static_cast(config.stencil_bits)); + } + + { + const auto sample_count = static_cast(config.samples); + if (sample_count > 1) { + attributes.push_back(EGL_SAMPLE_BUFFERS); + attributes.push_back(1); + attributes.push_back(EGL_SAMPLES); + attributes.push_back(sample_count); + } + } + + // termination sentinel must be present. + attributes.push_back(EGL_NONE); + + EGLConfig config_out = nullptr; + EGLint config_count_out = 0; + if (::eglChooseConfig(display_, // display + attributes.data(), // attributes (null terminated) + &config_out, // matched configs + 1, // configs array size + &config_count_out // match configs count + ) != EGL_TRUE) { + IMPELLER_LOG_EGL_ERROR; + return nullptr; + } + + if (config_count_out < 1) { + return nullptr; + } + + return std::make_unique(config, config_out); +} + +std::unique_ptr Display::CreateWindowSurface( + const Config& config, + EGLNativeWindowType window) { + const EGLint attribs[] = {EGL_NONE}; + auto surface = ::eglCreateWindowSurface(display_, // display + config.GetHandle(), // config + window, // window + attribs // attrib_list + ); + if (surface == EGL_NO_SURFACE) { + IMPELLER_LOG_EGL_ERROR; + return nullptr; + } + return std::unique_ptr(new Surface(display_, surface)); +} + +std::unique_ptr Display::CreatePixelBufferSurface(const Config& config, + size_t width, + size_t height) { + // clang-format off + const EGLint attribs[] = { + EGL_WIDTH, static_cast(width), + EGL_HEIGHT, static_cast(height), + EGL_NONE + }; + // clang-format on + auto surface = ::eglCreatePbufferSurface(display_, // display + config.GetHandle(), // config + attribs // attrib_list + ); + if (surface == EGL_NO_SURFACE) { + IMPELLER_LOG_EGL_ERROR; + return nullptr; + } + return std::unique_ptr(new Surface(display_, surface)); +} + +const EGLDisplay& Display::GetHandle() const { + return display_; +} + +} // namespace egl +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/display.h b/flutter/engine/src/flutter/impeller/toolkit/egl/display.h new file mode 100644 index 0000000000000000000000000000000000000000..715de1d5663f1242ada73afbc099a4d084562708 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/display.h @@ -0,0 +1,112 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_DISPLAY_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_DISPLAY_H_ + +#include + +#include "impeller/toolkit/egl/config.h" +#include "impeller/toolkit/egl/egl.h" + +namespace impeller { +namespace egl { + +class Context; +class Surface; + +//------------------------------------------------------------------------------ +/// @brief A connection to an EGL display. Only one connection per +/// application instance is sufficient. +/// +/// The display connection is used to first choose a config from +/// among the available, create a context from that config, and then +/// use that context with a surface on one (and only one) thread at +/// a time. +/// +class Display { + public: + Display(); + + virtual ~Display(); + + //---------------------------------------------------------------------------- + /// @return True if the display connection is valid. + /// + virtual bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Choose a config that most closely matches a given descriptor. + /// If there are no matches, this method returns `nullptr`. + /// + /// @param[in] config The configuration + /// + /// @return A config that matches a descriptor if one is available. + /// `nullptr` otherwise. + /// + virtual std::unique_ptr ChooseConfig(ConfigDescriptor config) const; + + //---------------------------------------------------------------------------- + /// @brief Create a context with a supported config. The supported config + /// can be obtained via a successful call to `ChooseConfig`. + /// + /// @param[in] config The configuration. + /// @param[in] share_context The share context. Context within the same + /// share-group use the same handle table. The + /// contexts should still only be used exclusively + /// on each thread however. + /// + /// @return A context if one can be created. `nullptr` otherwise. + /// + virtual std::unique_ptr CreateContext(const Config& config, + const Context* share_context); + + //---------------------------------------------------------------------------- + /// @brief Create a window surface. The window is an opaque pointer whose + /// value value is platform specific. For instance, ANativeWindow + /// on Android. + /// + /// @param[in] config A valid configuration. One can be obtained via + /// `ChooseConfig`. + /// @param[in] window An opaque pointer to a platform specific window + /// handle. + /// + /// @return A valid window surface if one can be created. `nullptr` + /// otherwise. + /// + virtual std::unique_ptr CreateWindowSurface( + const Config& config, + EGLNativeWindowType window); + + //---------------------------------------------------------------------------- + /// @brief Create an offscreen pixelbuffer surface. These are of limited + /// use except in the context where applications need to render to + /// a texture in an offscreen context. In such cases, a 1x1 pixel + /// buffer surface is created to obtain a surface that can be used + /// to make the context current on the background thread. + /// + /// @param[in] config The configuration + /// @param[in] width The width + /// @param[in] height The height + /// + /// @return A valid pixel buffer surface if one can be created. `nullptr` + /// otherwise. + /// + virtual std::unique_ptr + CreatePixelBufferSurface(const Config& config, size_t width, size_t height); + + const EGLDisplay& GetHandle() const; + + private: + EGLDisplay display_ = EGL_NO_DISPLAY; + + Display(const Display&) = delete; + + Display& operator=(const Display&) = delete; +}; + +} // namespace egl +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_DISPLAY_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/egl.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/egl.cc new file mode 100644 index 0000000000000000000000000000000000000000..54abfecee244a202d8c5507a0a48f82f8fefc99c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/egl.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/egl/egl.h" + +#include "flutter/fml/logging.h" + +namespace impeller { +namespace egl { + +std::function CreateProcAddressResolver() { + return [](const char* name) -> void* { + return reinterpret_cast(::eglGetProcAddress(name)); + }; +} + +static const char* EGLErrorToString(EGLint error) { + switch (error) { + case EGL_SUCCESS: + return "Success"; + case EGL_NOT_INITIALIZED: + return "Not Initialized"; + case EGL_BAD_ACCESS: + return "Bad Access"; + case EGL_BAD_ALLOC: + return "Bad Alloc"; + case EGL_BAD_ATTRIBUTE: + return "Bad Attribute"; + case EGL_BAD_CONTEXT: + return "Bad Context"; + case EGL_BAD_CONFIG: + return "Bad Config"; + case EGL_BAD_CURRENT_SURFACE: + return "Bad Current Surface"; + case EGL_BAD_DISPLAY: + return "Bad Display"; + case EGL_BAD_SURFACE: + return "Bad Surface"; + case EGL_BAD_MATCH: + return "Bad Match"; + case EGL_BAD_PARAMETER: + return "Bad Parameter"; + case EGL_BAD_NATIVE_PIXMAP: + return "Bad Native Pixmap"; + case EGL_BAD_NATIVE_WINDOW: + return "Bad Native Window"; + case EGL_CONTEXT_LOST: + return "Context Lost"; + } + return "Unknown"; +} + +void LogEGLError(const char* file, int line) { + const auto error = ::eglGetError(); + FML_LOG(ERROR) << "EGL Error: " << EGLErrorToString(error) << " (" << error + << ") in " << file << ":" << line; +} + +} // namespace egl +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/egl.h b/flutter/engine/src/flutter/impeller/toolkit/egl/egl.h new file mode 100644 index 0000000000000000000000000000000000000000..fd388113a5a90fb0f57e07c05439f238f4bc8b3a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/egl.h @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_ + +#include +#define EGL_EGLEXT_PROTOTYPES +#include + +#include + +namespace impeller { +namespace egl { + +//------------------------------------------------------------------------------ +/// @brief Creates a proc address resolver that resolves function pointers +/// to EGL and OpenGL (ES) procs. +/// +/// @return The resolver if one can be created. +/// +std::function CreateProcAddressResolver(); + +#define IMPELLER_LOG_EGL_ERROR LogEGLError(__FILE__, __LINE__); + +void LogEGLError(const char* file, int line); + +} // namespace egl +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_EGL_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/image.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/image.cc new file mode 100644 index 0000000000000000000000000000000000000000..c1f17ebddc960b180c9d02044c9d8a02fc49c405 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/image.cc @@ -0,0 +1,3 @@ +#include "flutter/impeller/toolkit/egl/image.h" + +namespace impeller {} diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/image.h b/flutter/engine/src/flutter/impeller/toolkit/egl/image.h new file mode 100644 index 0000000000000000000000000000000000000000..51e3330065c40907767229aa3a9a6b8caa5c7820 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/image.h @@ -0,0 +1,77 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_IMAGE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_IMAGE_H_ + +#include "flutter/fml/unique_object.h" +#include "flutter/impeller/toolkit/egl/egl.h" + +namespace impeller { + +// Simple holder of an EGLImage and the owning EGLDisplay. +struct EGLImageWithDisplay { + EGLImage image = EGL_NO_IMAGE; + EGLDisplay display = EGL_NO_DISPLAY; + + constexpr bool operator==(const EGLImageWithDisplay& other) const { + return image == other.image && display == other.display; + } + + constexpr bool operator!=(const EGLImageWithDisplay& other) const { + return !(*this == other); + } +}; + +struct EGLImageWithDisplayTraits { + static EGLImageWithDisplay InvalidValue() { + return {EGL_NO_IMAGE, EGL_NO_DISPLAY}; + } + + static bool IsValid(const EGLImageWithDisplay& value) { + return value != InvalidValue(); + } + + static void Free(EGLImageWithDisplay image) { + eglDestroyImage(image.display, image.image); + } +}; + +using UniqueEGLImage = + fml::UniqueObject; + +// Simple holder of an EGLImageKHR and the owning EGLDisplay. +struct EGLImageKHRWithDisplay { + EGLImageKHR image = EGL_NO_IMAGE_KHR; + EGLDisplay display = EGL_NO_DISPLAY; + + constexpr bool operator==(const EGLImageKHRWithDisplay& other) const { + return image == other.image && display == other.display; + } + + constexpr bool operator!=(const EGLImageKHRWithDisplay& other) const { + return !(*this == other); + } +}; + +struct EGLImageKHRWithDisplayTraits { + static EGLImageKHRWithDisplay InvalidValue() { + return {EGL_NO_IMAGE_KHR, EGL_NO_DISPLAY}; + } + + static bool IsValid(const EGLImageKHRWithDisplay& value) { + return value != InvalidValue(); + } + + static void Free(EGLImageKHRWithDisplay image) { + eglDestroyImageKHR(image.display, image.image); + } +}; + +using UniqueEGLImageKHR = + fml::UniqueObject; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_IMAGE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/surface.cc b/flutter/engine/src/flutter/impeller/toolkit/egl/surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..54fc614cd1140aedf1d4a2a716308d1adcbf3fd8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/surface.cc @@ -0,0 +1,38 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/egl/surface.h" + +namespace impeller { +namespace egl { + +Surface::Surface(EGLDisplay display, EGLSurface surface) + : display_(display), surface_(surface) {} + +Surface::~Surface() { + if (surface_ != EGL_NO_SURFACE) { + if (::eglDestroySurface(display_, surface_) != EGL_TRUE) { + IMPELLER_LOG_EGL_ERROR; + } + } +} + +const EGLSurface& Surface::GetHandle() const { + return surface_; +} + +bool Surface::IsValid() const { + return surface_ != EGL_NO_SURFACE; +} + +bool Surface::Present() const { + const auto result = ::eglSwapBuffers(display_, surface_) == EGL_TRUE; + if (!result) { + IMPELLER_LOG_EGL_ERROR; + } + return result; +} + +} // namespace egl +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/toolkit/egl/surface.h b/flutter/engine/src/flutter/impeller/toolkit/egl/surface.h new file mode 100644 index 0000000000000000000000000000000000000000..c82fc23a60547821c3ecf36958b546dc81b0c57f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/egl/surface.h @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_EGL_SURFACE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_EGL_SURFACE_H_ + +#include "impeller/toolkit/egl/egl.h" + +namespace impeller { +namespace egl { + +//------------------------------------------------------------------------------ +/// @brief An instance of an EGL surface. There is no ability to create +/// surfaces directly. Instead, one must be created using a Display +/// connection. +/// +class Surface { + public: + ~Surface(); + + //---------------------------------------------------------------------------- + /// @return True if this is a valid surface. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @return Get the handle to the underlying surface. + /// + const EGLSurface& GetHandle() const; + + //---------------------------------------------------------------------------- + /// @brief Present the surface. For an offscreen pixel buffer surface, + /// this is a no-op. + /// + /// @return True if the surface could be presented. + /// + bool Present() const; + + private: + friend class Display; + + EGLDisplay display_ = EGL_NO_DISPLAY; + EGLSurface surface_ = EGL_NO_SURFACE; + + Surface(EGLDisplay display, EGLSurface surface); + + Surface(const Surface&) = delete; + + Surface& operator=(const Surface&) = delete; +}; + +} // namespace egl +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_EGL_SURFACE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/gles/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/gles/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..06a16f95bf3540054a5bba013733c1a4b4619d08 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/gles/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../../tools/impeller.gni") + +impeller_component("gles") { + sources = [ + "gles.h", + "texture.cc", + "texture.h", + ] + + deps = [ + "../../base", + "//flutter/fml", + ] + + libs = [] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/gles/gles.h b/flutter/engine/src/flutter/impeller/toolkit/gles/gles.h new file mode 100644 index 0000000000000000000000000000000000000000..9cb1609fd5c2712e733fcbc99707c0e4b1c60c10 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/gles/gles.h @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_GLES_GLES_H_ +#define FLUTTER_IMPELLER_TOOLKIT_GLES_GLES_H_ + +#include "GLES3/gl3.h" +#define GL_GLEXT_PROTOTYPES +#include "GLES2/gl2ext.h" + +#endif // FLUTTER_IMPELLER_TOOLKIT_GLES_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/gles/texture.cc b/flutter/engine/src/flutter/impeller/toolkit/gles/texture.cc new file mode 100644 index 0000000000000000000000000000000000000000..56f3d5b7b746f9b2a5492eee206f3c13b3e395de --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/gles/texture.cc @@ -0,0 +1,3 @@ +#include "flutter/impeller/toolkit/gles/texture.h" + +namespace impeller {} diff --git a/flutter/engine/src/flutter/impeller/toolkit/gles/texture.h b/flutter/engine/src/flutter/impeller/toolkit/gles/texture.h new file mode 100644 index 0000000000000000000000000000000000000000..cebef02e61a258b811b5419023f6272713afb0af --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/gles/texture.h @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_GLES_TEXTURE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_GLES_TEXTURE_H_ + +#include "flutter/fml/unique_object.h" +#include "flutter/impeller/toolkit/gles/gles.h" + +namespace impeller { + +// Simple holder of an GLTexture and the owning EGLDisplay. +struct GLTexture { + GLuint texture_name; + + constexpr bool operator==(const GLTexture& other) const { + return texture_name == other.texture_name; + } + + constexpr bool operator!=(const GLTexture& other) const { + return !(*this == other); + } +}; + +struct GLTextureTraits { + static GLTexture InvalidValue() { return {0}; } + + static bool IsValid(const GLTexture& value) { + return value != InvalidValue(); + } + + static void Free(GLTexture image) { + glDeleteTextures(1, &image.texture_name); + } +}; + +using UniqueGLTexture = fml::UniqueObject; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TOOLKIT_GLES_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/glvk/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..061b52bf070cbd7f6eb6670e760bae5602ea1fc9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("../../tools/impeller.gni") + +impeller_component("glvk") { + sources = [ + "proc_table.cc", + "proc_table.h", + "trampoline.cc", + "trampoline.h", + ] + + public_deps = [ + "../../renderer", + "../../renderer/backend/gles", + "../../renderer/backend/vulkan", + "../../toolkit/egl", + "../../toolkit/gles", + "//flutter/fml", + ] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/README.md b/flutter/engine/src/flutter/impeller/toolkit/glvk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7dce6a5f3b35252b45edc86042c6016391ae666 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/README.md @@ -0,0 +1,3 @@ +# GLVK Toolkit + +A toolkit for inter-operating between OpenGL and Vulkan. diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.cc b/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.cc new file mode 100644 index 0000000000000000000000000000000000000000..d7d6c8252083a4a40f53a637d206f6fdc9ede9bd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.cc @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/glvk/proc_table.h" + +#include "impeller/base/validation.h" + +namespace impeller::glvk { + +ProcTable::ProcTable(const Resolver& resolver) { + if (!resolver) { + return; + } + + auto error_fn = reinterpret_cast(resolver("glGetError")); + if (!error_fn) { + VALIDATION_LOG << "Could not resolve " << "glGetError"; + return; + } + +#define GLVK_PROC(proc_ivar) \ + if (auto fn_ptr = resolver(proc_ivar.name)) { \ + proc_ivar.function = \ + reinterpret_cast(fn_ptr); \ + proc_ivar.error_fn = error_fn; \ + } else { \ + VALIDATION_LOG << "Could not resolve " << proc_ivar.name; \ + return; \ + } + + FOR_EACH_GLVK_PROC(GLVK_PROC); + +#undef GLVK_PROC + + is_valid_ = true; +} + +ProcTable::~ProcTable() = default; + +bool ProcTable::IsValid() const { + return is_valid_; +} + +} // namespace impeller::glvk diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.h b/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.h new file mode 100644 index 0000000000000000000000000000000000000000..9a2b8035c1af559ae745a42a9374b7c0e3abf125 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/proc_table.h @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_GLVK_PROC_TABLE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_GLVK_PROC_TABLE_H_ + +#include "impeller/renderer/backend/gles/proc_table_gles.h" +#include "impeller/toolkit/gles/gles.h" + +namespace impeller::glvk { + +#define FOR_EACH_GLVK_PROC(PROC) \ + PROC(ActiveTexture) \ + PROC(AttachShader) \ + PROC(BindAttribLocation) \ + PROC(BindBuffer) \ + PROC(BindFramebuffer) \ + PROC(BindTexture) \ + PROC(BufferData) \ + PROC(CheckFramebufferStatus) \ + PROC(Clear) \ + PROC(ClearColor) \ + PROC(ColorMask) \ + PROC(CompileShader) \ + PROC(CreateProgram) \ + PROC(CreateShader) \ + PROC(DeleteBuffers) \ + PROC(DeleteFramebuffers) \ + PROC(DeleteProgram) \ + PROC(DeleteShader) \ + PROC(DeleteTextures) \ + PROC(Disable) \ + PROC(DrawArrays) \ + PROC(EGLImageTargetTexture2DOES) \ + PROC(Enable) \ + PROC(EnableVertexAttribArray) \ + PROC(Flush) \ + PROC(FramebufferTexture2D) \ + PROC(GenBuffers) \ + PROC(GenFramebuffers) \ + PROC(GenTextures) \ + PROC(GetProgramiv) \ + PROC(GetShaderiv) \ + PROC(GetUniformLocation) \ + PROC(LinkProgram) \ + PROC(ShaderSource) \ + PROC(TexParameteri) \ + PROC(Uniform1i) \ + PROC(UniformMatrix4fv) \ + PROC(UseProgram) \ + PROC(VertexAttribPointer) \ + PROC(Viewport) + +//------------------------------------------------------------------------------ +/// @brief A proc. table consisting of methods that are useful when +/// interoperating between OpenGL and Vulkan. This is different from +/// the OpenGL proc. table since it may contain more interop +/// extension related methods. +/// +class ProcTable { + public: + using Resolver = std::function; + + //---------------------------------------------------------------------------- + /// @brief Create a proc table using a resolver to resolve OpenGL + /// methods. + /// + /// @param[in] resolver The resolver + /// + explicit ProcTable(const Resolver& resolver); + + ~ProcTable(); + + ProcTable(const ProcTable&) = delete; + + ProcTable& operator=(const ProcTable&) = delete; + + //---------------------------------------------------------------------------- + /// @brief Determines if a proc. table is suitable for interop purposes. + /// The absence of optional extension methods that have fallbacks + /// don't result in an invalid proc. table. But an invalid proc + /// table must always be discarded as there can be no error + /// recovery. + /// + /// @return True if valid, False otherwise. + /// + bool IsValid() const; + +#define GLVK_PROC(name) GLProc name = {"gl" #name, nullptr}; + + FOR_EACH_GLVK_PROC(GLVK_PROC); + +#undef GLVK_PROC + + private: + bool is_valid_ = false; +}; + +} // namespace impeller::glvk + +#endif // FLUTTER_IMPELLER_TOOLKIT_GLVK_PROC_TABLE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.cc b/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.cc new file mode 100644 index 0000000000000000000000000000000000000000..eda8595a0c5e14ac939c18d3d36ace4d8577f454 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.cc @@ -0,0 +1,332 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/glvk/trampoline.h" + +#include + +#include "flutter/fml/closure.h" +#include "flutter/fml/trace_event.h" +#include "impeller/base/timing.h" +#include "impeller/base/validation.h" +#include "impeller/geometry/point.h" +#include "impeller/renderer/backend/gles/formats_gles.h" +#include "impeller/toolkit/android/proc_table.h" +#include "impeller/toolkit/egl/image.h" + +namespace impeller::glvk { + +static GLuint kAttributeIndexPosition = 0u; +static GLuint kAttributeIndexTexCoord = 1u; + +static constexpr const char* kVertShader = R"IMPELLER_SHADER(#version 100 + +precision mediump float; + +attribute vec2 aPosition; +attribute vec2 aTexCoord; + +varying vec2 vTexCoord; + +void main() { + gl_Position = vec4(aPosition, 0.0, 1.0); + vTexCoord = aTexCoord; + +} +)IMPELLER_SHADER"; + +static constexpr const char* kFragShader = R"IMPELLER_SHADER(#version 100 + +#extension GL_OES_EGL_image_external : require + +precision mediump float; + +uniform samplerExternalOES uTexture; +uniform mat4 uUVTransformation; + +varying vec2 vTexCoord; + +void main() { + vec2 texture_coords = (uUVTransformation * vec4(vTexCoord, 0, 1)).xy; + gl_FragColor = texture2D(uTexture, texture_coords); +} + +)IMPELLER_SHADER"; + +Trampoline::Trampoline() { + auto egl_display = std::make_unique(); + if (!egl_display->IsValid()) { + VALIDATION_LOG + << "Could not create EGL display for external texture interop."; + return; + } + + egl::ConfigDescriptor egl_config_desc; + egl_config_desc.api = egl::API::kOpenGLES2; + egl_config_desc.samples = egl::Samples::kOne; + egl_config_desc.color_format = egl::ColorFormat::kRGBA8888; + egl_config_desc.stencil_bits = egl::StencilBits::kZero; + egl_config_desc.depth_bits = egl::DepthBits::kZero; + egl_config_desc.surface_type = egl::SurfaceType::kPBuffer; + auto egl_config = egl_display->ChooseConfig(egl_config_desc); + if (!egl_config) { + VALIDATION_LOG + << "Could not choose EGL config for external texture interop."; + return; + } + + auto egl_surface = egl_display->CreatePixelBufferSurface(*egl_config, 1u, 1u); + auto egl_context = egl_display->CreateContext(*egl_config, nullptr); + + if (!egl_surface || !egl_context) { + VALIDATION_LOG << "Could not create EGL surface and/or context for " + "external texture interop."; + return; + } + + // Make the context current so the proc addresses can be resolved. + if (!egl_context->MakeCurrent(*egl_surface)) { + VALIDATION_LOG << "Could not make the context current."; + return; + } + + auto gl = std::make_unique(egl::CreateProcAddressResolver()); + + if (!gl->IsValid()) { + egl_context->ClearCurrent(); + VALIDATION_LOG << "Could not setup trampoline proc table."; + return; + } + + // Generate program object. + auto vert_shader = gl->CreateShader(GL_VERTEX_SHADER); + auto frag_shader = gl->CreateShader(GL_FRAGMENT_SHADER); + + GLint vert_shader_size = strlen(kVertShader); + GLint frag_shader_size = strlen(kFragShader); + + gl->ShaderSource(vert_shader, 1u, &kVertShader, &vert_shader_size); + gl->ShaderSource(frag_shader, 1u, &kFragShader, &frag_shader_size); + + gl->CompileShader(vert_shader); + gl->CompileShader(frag_shader); + + GLint vert_status = GL_FALSE; + GLint frag_status = GL_FALSE; + + gl->GetShaderiv(vert_shader, GL_COMPILE_STATUS, &vert_status); + gl->GetShaderiv(frag_shader, GL_COMPILE_STATUS, &frag_status); + + FML_CHECK(vert_status == GL_TRUE); + FML_CHECK(frag_status == GL_TRUE); + + program_ = gl->CreateProgram(); + gl->AttachShader(program_, vert_shader); + gl->AttachShader(program_, frag_shader); + + gl->BindAttribLocation(program_, kAttributeIndexPosition, "aPosition"); + gl->BindAttribLocation(program_, kAttributeIndexTexCoord, "aTexCoord"); + + gl->LinkProgram(program_); + + GLint link_status = GL_FALSE; + gl->GetProgramiv(program_, GL_LINK_STATUS, &link_status); + FML_CHECK(link_status == GL_TRUE); + + texture_uniform_location_ = gl->GetUniformLocation(program_, "uTexture"); + uv_transformation_location_ = + gl->GetUniformLocation(program_, "uUVTransformation"); + + gl->DeleteShader(vert_shader); + gl->DeleteShader(frag_shader); + + egl_context->ClearCurrent(); + + gl_ = std::move(gl); + egl_display_ = std::move(egl_display); + egl_context_ = std::move(egl_context); + egl_surface_ = std::move(egl_surface); + is_valid_ = true; +} + +Trampoline::~Trampoline() { + if (!is_valid_) { + return; + } + auto context = MakeCurrentContext(); + gl_->DeleteProgram(program_); +} + +bool Trampoline::IsValid() const { + return is_valid_; +} + +static UniqueEGLImageKHR CreateEGLImageFromAHBTexture( + const EGLDisplay& display, + const AHBTextureSourceVK& to_texture) { + if (!android::GetProcTable().eglGetNativeClientBufferANDROID.IsAvailable()) { + VALIDATION_LOG << "Could not get native client buffer."; + return {}; + } + + EGLClientBuffer client_buffer = + android::GetProcTable().eglGetNativeClientBufferANDROID( + to_texture.GetBackingStore()->GetHandle()); + + if (!client_buffer) { + VALIDATION_LOG + << "Could not get client buffer from Android hardware buffer."; + return {}; + } + + auto image = ::eglCreateImageKHR(display, // + EGL_NO_CONTEXT, // + EGL_NATIVE_BUFFER_ANDROID, // + client_buffer, // + nullptr // + ); + if (image == NULL) { + VALIDATION_LOG << "Could not create EGL Image."; + return {}; + } + + return UniqueEGLImageKHR(EGLImageKHRWithDisplay{image, display}); +} + +bool Trampoline::BlitTextureOpenGLToVulkan( + const GLTextureInfo& src_texture, + const AHBTextureSourceVK& dst_texture) const { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!is_valid_) { + return false; + } + + FML_DCHECK(egl_context_->IsCurrent()); + + auto dst_egl_image = + CreateEGLImageFromAHBTexture(egl_display_->GetHandle(), dst_texture); + if (!dst_egl_image.is_valid()) { + VALIDATION_LOG << "Could not create EGL image from AHB texture."; + return false; + } + + const auto& gl = *gl_; + + GLuint dst_gl_texture = GL_NONE; + gl.GenTextures(1u, &dst_gl_texture); + gl.BindTexture(GL_TEXTURE_2D, dst_gl_texture); + gl.EGLImageTargetTexture2DOES(GL_TEXTURE_2D, dst_egl_image.get().image); + + GLuint offscreen_fbo = GL_NONE; + gl.GenFramebuffers(1u, &offscreen_fbo); + gl.BindFramebuffer(GL_FRAMEBUFFER, offscreen_fbo); + gl.FramebufferTexture2D(GL_FRAMEBUFFER, // + GL_COLOR_ATTACHMENT0, // + GL_TEXTURE_2D, // + dst_gl_texture, // + 0 // + ); + + FML_CHECK(gl.CheckFramebufferStatus(GL_FRAMEBUFFER) == + GL_FRAMEBUFFER_COMPLETE); + + gl.Disable(GL_BLEND); + gl.Disable(GL_SCISSOR_TEST); + gl.Disable(GL_DITHER); + gl.Disable(GL_CULL_FACE); + gl.ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + + gl.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); + gl.Clear(GL_COLOR_BUFFER_BIT); + + const auto& fb_size = dst_texture.GetTextureDescriptor().size; + gl.Viewport(0, 0, fb_size.width, fb_size.height); + + gl.UseProgram(program_); + + struct VertexData { + Point position; + Point tex_coord; + }; + + // The vertex coordinates assume OpenGL NDC because that's the API we are + // using to draw the quad. But the texture will be sampled in Vulkan so the + // texture coordinate system assumes Vulkan convention. + // + // See the following help link for an overview of the different coordinate + // systems: + // https://github.com/flutter/engine/blob/5810b3fc791f4bb82b9a454014310990eddc1181/impeller/docs/coordinate_system.md + static constexpr const VertexData kVertData[] = { + {{-1, -1}, {0, 1}}, // bottom left + {{-1, +1}, {0, 0}}, // top left + {{+1, +1}, {1, 0}}, // top right + {{+1, -1}, {1, 1}}, // bottom right + }; + + // This is tedious but we assume no vertex array objects (VAO) are available + // because of ES 2 versioning constraints. + GLuint vertex_buffer = GL_NONE; + gl.GenBuffers(1u, &vertex_buffer); + gl.BindBuffer(GL_ARRAY_BUFFER, vertex_buffer); + gl.BufferData(GL_ARRAY_BUFFER, sizeof(kVertData), kVertData, GL_STATIC_DRAW); + gl.EnableVertexAttribArray(kAttributeIndexPosition); + gl.EnableVertexAttribArray(kAttributeIndexTexCoord); + gl.VertexAttribPointer( + kAttributeIndexPosition, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), + reinterpret_cast(offsetof(VertexData, position))); + gl.VertexAttribPointer( + kAttributeIndexTexCoord, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), + reinterpret_cast(offsetof(VertexData, tex_coord))); + + gl.ActiveTexture(GL_TEXTURE0); + gl.BindTexture(src_texture.target, src_texture.texture); + gl.TexParameteri(src_texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + gl.TexParameteri(src_texture.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + gl.TexParameteri(src_texture.target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + gl.TexParameteri(src_texture.target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + gl.Uniform1i(texture_uniform_location_, 0u); + + auto gl_uv_transformation = src_texture.uv_transformation; + + gl.UniformMatrix4fv(uv_transformation_location_, 1u, GL_FALSE, + reinterpret_cast(&gl_uv_transformation)); + + gl.DrawArrays(GL_TRIANGLE_FAN, 0, 4); + + gl.UseProgram(GL_NONE); + + gl.Flush(); + + gl.DeleteFramebuffers(1u, &offscreen_fbo); + gl.DeleteTextures(1u, &dst_gl_texture); + gl.DeleteBuffers(1u, &vertex_buffer); + + // Theoretically, this does nothing because the surface is a 1x1 pbuffer + // surface. But frame capture tools use this to denote a frame boundary in + // OpenGL. So add this as a debugging aid anyway. + eglSwapBuffers(egl_display_->GetHandle(), egl_surface_->GetHandle()); + + return true; +} + +AutoTrampolineContext Trampoline::MakeCurrentContext() const { + FML_DCHECK(is_valid_); + return AutoTrampolineContext{*this}; +} + +AutoTrampolineContext::AutoTrampolineContext(const Trampoline& trampoline) + : context_(trampoline.egl_context_.get()), + surface_(trampoline.egl_surface_.get()) { + if (!context_->IsCurrent() && !context_->MakeCurrent(*surface_)) { + VALIDATION_LOG << "Could not make context current."; + } +}; + +AutoTrampolineContext::~AutoTrampolineContext() { + if (!context_->ClearCurrent()) { + VALIDATION_LOG << "Could not clear current context."; + } +} + +} // namespace impeller::glvk diff --git a/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.h b/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.h new file mode 100644 index 0000000000000000000000000000000000000000..4bb078807bc9ca3b91fb3fcee7c3aaa3caeb220d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/glvk/trampoline.h @@ -0,0 +1,153 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_GLVK_TRAMPOLINE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_GLVK_TRAMPOLINE_H_ + +#include "impeller/base/thread_safety.h" +#include "impeller/renderer/backend/vulkan/android/ahb_texture_source_vk.h" +#include "impeller/toolkit/egl/context.h" +#include "impeller/toolkit/egl/display.h" +#include "impeller/toolkit/egl/surface.h" +#include "impeller/toolkit/glvk/proc_table.h" + +namespace impeller::glvk { + +class AutoTrampolineContext; + +//------------------------------------------------------------------------------ +/// @brief An object used to interoperate between OpenGL and Vulkan. +/// +/// While these are not super expensive to create, they do manage an +/// internal EGL context as well as some OpenGL state. For this +/// reason, it is recommended that callers cache these for the +/// duration of the lifecycle of main rendering context. +/// +class Trampoline { + public: + //---------------------------------------------------------------------------- + /// @brief Constructs a new trampoline. It is recommended that these + /// objects be cached and reused for all conversion operations. + /// + /// EGL contexts on already bound to the callers thread may become + /// unbound after a call to this method. + /// + Trampoline(); + + //---------------------------------------------------------------------------- + /// @brief Destroys the trampoline. There are no threading restrictions. + /// EGL contexts on already bound to the callers thread may become + /// unbound after a call to this method. + /// + ~Trampoline(); + + Trampoline(const Trampoline&) = delete; + + Trampoline& operator=(const Trampoline&) = delete; + + //---------------------------------------------------------------------------- + /// @brief Determines if this is a valid trampoline. There is no error + /// recovery mechanism if a trampoline cannot be constructed and + /// an invalid trampoline must be immediately discarded. + /// + /// @return True if valid, False otherwise. + /// + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Describes an OpenGL texture along with information on how to + /// sample from it. + /// + struct GLTextureInfo { + //-------------------------------------------------------------------------- + /// The OpenGL texture handle. + /// + GLuint texture = 0; + //-------------------------------------------------------------------------- + /// The OpenGL texture target enum. For instance, GL_TEXTURE_2D or + /// GL_TEXTURE_EXTERNAL_OES. + /// + GLenum target = 0; + //-------------------------------------------------------------------------- + /// A transformation applied to the texture coordinates in the form of (u, + /// v, 0, 1) when sampling from the texture. + /// + Matrix uv_transformation; + }; + + //---------------------------------------------------------------------------- + /// @brief Perform a blit operation from the source OpenGL texture to a + /// target Vulkan texture. + /// + /// It is the callers responsibility to ensure that the EGL + /// context associated with the trampoline is already current + /// before making this call. + /// + /// It is also the responsibility of the caller to ensure that the + /// destination texture is the color-attachment-optimal layout. + /// Failure to ensure this will lead to validation error. + /// + /// @see `MakeCurrentContext` + /// + /// @param[in] src_texture The source OpenGL texture. + /// @param[in] dst_texture The destination Vulkan texture. + /// + /// @return True if the blit was successful, False otherwise. + /// + bool BlitTextureOpenGLToVulkan(const GLTextureInfo& src_texture, + const AHBTextureSourceVK& dst_texture) const; + + //---------------------------------------------------------------------------- + /// @brief Make the EGL context associated with this trampoline current + /// on the calling thread. + /// + /// @return The automatic trampoline context. The collection of this + /// context clears the threads EGL binding. + /// + [[nodiscard]] AutoTrampolineContext MakeCurrentContext() const; + + private: + friend class AutoTrampolineContext; + + std::unique_ptr egl_display_; + std::unique_ptr egl_context_; + std::unique_ptr egl_surface_; + std::unique_ptr gl_; + GLuint program_ = GL_NONE; + GLint texture_uniform_location_ = 0; + GLint uv_transformation_location_ = 0; + bool is_valid_ = false; +}; + +//------------------------------------------------------------------------------ +/// @brief An RAII object that makes the trampolines EGL context current +/// when constructed and clears the EGL binding on destruction. +/// +class AutoTrampolineContext final { + public: + //---------------------------------------------------------------------------- + /// @brief Constructs a new instance and makes the trampolines EGL + /// context current on the calling thread. + /// + /// @param[in] trampoline The trampoline. + /// + explicit AutoTrampolineContext(const Trampoline& trampoline); + + //---------------------------------------------------------------------------- + /// @brief Destroys the object and clears the previous EGL binding. + /// + ~AutoTrampolineContext(); + + AutoTrampolineContext(const AutoTrampolineContext&) = delete; + + AutoTrampolineContext& operator=(const AutoTrampolineContext&) = delete; + + private: + const egl::Context* context_ = nullptr; + const egl::Surface* surface_ = nullptr; +}; + +} // namespace impeller::glvk + +#endif // FLUTTER_IMPELLER_TOOLKIT_GLVK_TRAMPOLINE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/interop/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..19622807ed94f79d32e4dcd7d5a00eb2d3c17ebc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/BUILD.gn @@ -0,0 +1,241 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/build/zip_bundle.gni") +import("//flutter/impeller/tools/impeller.gni") + +embed_blob("embedded_icu_data") { + symbol_name = "embedded_icu_data" + blob = "//flutter/third_party/icu/flutter/icudtl.dat" + hdr = "$target_gen_dir/embedded_icu_data.h" + cc = "$target_gen_dir/embedded_icu_data.cc" + deps = [] +} + +# The public C/C++ Impeller API. +impeller_component("interop_api") { + public = [ + "impeller.h", + "impeller.hpp", + ] + + sources = [ + "impeller_c.c", + "impeller_cc.cc", + ] +} + +# The common base used by all interop backends. +impeller_component("interop_base") { + sources = [ + "color_filter.cc", + "color_filter.h", + "color_source.cc", + "color_source.h", + "context.cc", + "context.h", + "dl.cc", + "dl.h", + "dl_builder.cc", + "dl_builder.h", + "formats.cc", + "formats.h", + "glyph_info.cc", + "glyph_info.h", + "image_filter.cc", + "image_filter.h", + "line_metrics.cc", + "line_metrics.h", + "mask_filter.cc", + "mask_filter.h", + "object.cc", + "object.h", + "paint.cc", + "paint.h", + "paragraph.cc", + "paragraph.h", + "paragraph_builder.cc", + "paragraph_builder.h", + "paragraph_style.cc", + "paragraph_style.h", + "path.cc", + "path.h", + "path_builder.cc", + "path_builder.h", + "surface.cc", + "surface.h", + "texture.cc", + "texture.h", + "typography_context.cc", + "typography_context.h", + ] + + public_deps = [ + ":embedded_icu_data", + ":interop_api", + "../../base", + "../../display_list", + "../../entity", + "../../renderer/backend", + "//flutter/display_list", + "//flutter/fml", + "//flutter/txt", + ] +} + +# Wires up the public API entrypoints to the appropriate backends. +impeller_component("interop") { + sources = [ "impeller.cc" ] + public_deps = [ + ":interop_base", + "backend", + ] +} + +impeller_component("library") { + target_type = "shared_library" + + output_name = "impeller" + + deps = [ ":interop" ] +} + +impeller_component("example_gl") { + target_type = "executable" + + output_name = "impeller_interop_example_gl" + + sources = [ "example_gl.c" ] + + deps = [ + ":interop", + "//flutter/third_party/glfw", + ] +} + +impeller_component("example_mtl") { + target_type = "executable" + + output_name = "impeller_interop_example_mtl" + + sources = [ "example_mtl.m" ] + + deps = [ + ":interop", + "//flutter/third_party/glfw", + ] + + frameworks = [ "QuartzCore.framework" ] +} + +impeller_component("example_vk") { + target_type = "executable" + + output_name = "impeller_interop_example_vk" + + sources = [ "example_vk.c" ] + + deps = [ + ":interop", + "//flutter/third_party/glfw", + ] +} + +group("example") { + deps = [] + if (impeller_enable_opengles) { + deps += [ ":example_gl" ] + } + + if (impeller_enable_metal) { + deps += [ ":example_mtl" ] + } + + if (impeller_enable_vulkan) { + deps += [ ":example_vk" ] + } +} + +impeller_component("interop_unittests") { + testonly = true + + sources = [ + "impeller_unittests.cc", + "object_unittests.cc", + "playground_test.cc", + "playground_test.h", + ] + + deps = [ + ":interop", + "../../fixtures", + "../../playground:playground_test", + "//flutter/testing:testing_lib", + ] +} + +zip_bundle("sdk") { + if (is_mac) { + zip_out_dir = "darwin-${target_cpu}" + } else { + zip_out_dir = "${full_target_platform_name}" + } + + output = "${zip_out_dir}/impeller_sdk.zip" + deps = [ ":library" ] + + files = [ + { + source = "README.md" + destination = "README.md" + }, + { + source = "impeller.h" + destination = "include/impeller.h" + }, + { + source = "impeller.hpp" + destination = "include/impeller.hpp" + }, + { + source = "example_gl.c" + destination = "examples/example_gl.c" + }, + { + source = "example_vk.c" + destination = "examples/example_vk.c" + }, + { + source = "example_mtl.m" + destination = "examples/example_mtl.m" + }, + ] + + if (is_mac) { + files += [ + { + source = "$root_build_dir/libimpeller.dylib" + destination = "lib/libimpeller.dylib" + }, + ] + } else if (is_linux || is_android) { + files += [ + { + source = "$root_build_dir/libimpeller.so" + destination = "lib/libimpeller.so" + }, + ] + } else if (is_win) { + files += [ + { + source = "$root_build_dir/impeller.dll" + destination = "lib/impeller.dll" + }, + { + source = "$root_build_dir/impeller.dll.lib" + destination = "lib/impeller.dll.lib" + }, + ] + } +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/README.md b/flutter/engine/src/flutter/impeller/toolkit/interop/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6e75a53a11775093cec4f68f56a38803c4915bdb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/README.md @@ -0,0 +1,129 @@ +# Impeller Standalone SDK + +A single-header C API for 2D graphics and text rendering. [Impeller](../../README.md) is used by Flutter for rendering but can be consumed by non-Flutter applications and projects. + +* **Full-featured** + * The library supports all rendering operations supported by Flutter with few exceptions. + * An optional text-layout and shaping engine is included by default. +* **Easy to Embed** + * The entire library is distributed as a single library with a C API. + * The C API is single-header with no platform dependencies. + * For the common platforms, [prebuilt artifacts](#prebuilt-artifacts) are generated per Flutter Engine commit. +* **Easy Interoperability** + * The C API allows for explicit management of object lifecycle and is well suited for the generation of automated bindings to languages like Rust, Dart, Lua, etc… +* **Lightweight** + * The core rendering engine is less than 200 KB compressed. + * The text layout and shaping engine along with the bundled ICU data tables brings the size up to ~2.5 MB. + * If the application does not need text layout and shaping, or can interface with an existing library on the target platform, it is recommended to generate the SDK without built-in support for typography. +* **Performant** + * Built to perform the best when using a modern graphics API like Metal or Vulkan and when running on mobile tiler GPUs like the ones found in smartphones and AppleSilicon/ARM desktops. + * Impeller does need a GPU. Performance will likely be inadequate for interactive use cases when using software rendering. Software rendering can be enabled using projects like SwiftShader, Angle, LLVMPipe, etc… If you are using software rendering in your projects, restrict its use to testing on CI. Impeller will likely never have a dedicated software renderer. + +# Prebuilt Artifacts + +> [!IMPORTANT] +> Users of these prebuilt artifacts should strip the binaries before deployment as these contain debug symbols. + +Users may plug in a custom toolchain into the Flutter Engine build system to build the `libimpeller.so` dynamic library. However, for the common platforms, the CI bots upload a tarball containing the library and headers. This URL for the SDK tarball for a particular platform can be constructed as follows: + +```sh +https://storage.googleapis.com/flutter_infra_release/flutter/$FLUTTER_SHA/$PLATFORM_ARCH/impeller_sdk.zip +``` + +The `$FLUTTER_SHA` is the Git hash in the [Flutter repository](https://github.com/flutter/flutter). The `$PLATFORM_ARCH` can be determined from the table below. + +| | macOS | Linux | Android | Windows | +|:-----:|:------------:|:-----------:|:--------------:|:-------------:| +| armv7 | | | android-arm | | +| arm64 | darwin-arm64 | linux-arm64 | android-arm64 | windows-arm64 | +| x86 | | | android-x86 | | +| x64 | darwin-x64 | linux-x64 | android-x64 | windows-x64 | + + +_For example, the SDK for `Linux x64` at Flutter SHA `cda35151265f00fab84d8128b086d5534f690c1b` would be [this link](https://storage.googleapis.com/flutter_infra_release/flutter/cda35151265f00fab84d8128b086d5534f690c1b/linux-x64/impeller_sdk.zip)_ + +# Examples + +A quick peek at the API that shows rendering different shapes using the provided [C++ wrapper to the C API](#c-wrapper) is as follows: + +```c++ +DisplayListBuilder builder; + +Paint red_paint; +red_paint.SetColor({1.0, 0.0, 0.0, 1.0}); +red_paint.SetStrokeWidth(10.0); + +builder.Translate(10, 10); +builder.DrawRect({0, 0, 100, 100}, red_paint); +builder.Translate(100, 100); +builder.DrawOval({0, 0, 100, 100}, red_paint); +builder.Translate(100, 100); +builder.DrawLine({0, 0}, {100, 100}, red_paint); + +builder.Translate(100, 100); +ImpellerRoundingRadii radii = {}; +radii.top_left = {10, 10}; +radii.bottom_right = {10, 10}; +builder.DrawRoundedRect({0, 0, 100, 100}, radii, red_paint); + +builder.Translate(100, 100); +builder.DrawPath(hpp::PathBuilder{}.AddOval({0, 0, 100, 100}).Build(), + red_paint); + +auto dl = builder.Build(); + +// Per frame +hpp::Surface window(surface); +window.Draw(dl); +``` + +### Standalone + +A fully functional example of using Impeller to draw using GLFW is available in [`example_gl.c`](example_gl.c), [`example_vk.c`](example_vk.c) and [`example_mtl.c`](example_mtl.c). This example is also present in the `impeller_sdk.zip` [prebuilts](#prebuilt-artifacts) along with necessary artifacts. + +### CMake + +A demo of using CMake to fetch prebuilt artifacts and build the demo is [available here](https://github.com/chinmaygarde/impeller_cmake_demo). + +## C++ Wrapper + +For users of the library using C++, a single-header-only C++ 17 library is provided that wraps the single-header C API ([`impeller.h`](impeller.h)). This headers ([`impeller.hpp`](impeller.hpp)) is distributed as part of the [prebuilt artifacts](#prebuilt-artifacts) as well. + +# API Fundamentals + +## Versioning + +The current version of the API is denoted by the `IMPELLER_VERSION` macro. This version must be passed to APIs that create top-level objects like graphics contexts. Construction of the context may fail if the API version expected by the caller is not supported by the library. + +The version currently supported by the library is returned by a call to `ImpellerGetVersion()` + +Since there are no API stability guarantees today, passing a version that is different to the one returned by `ImpellerGetVersion` will always fail. + +## Object Model + +Users interact with Impeller objects using opaque handles. Impeller objects can be identified by their definition using `IMPELLER_DEFINE_HANDLE` in the SDK. + +All Impeller objects are thread-safe reference-counted. + +## Reference Management + +Methods in the Impeller API follow a very strict convention. This makes it easy to write automated bindings generators that handle object lifecycles to various degrees: + +* Methods that end with `Retain` increment the reference count of the object by 1. +* Methods that end with `Release` decrement the reference count of the object by 1. When the reference count of the object reaches 0, the object is collected. +* Methods that end with `New` create a new object with a reference count of 1. + * This reference must be relinquished by the appropriate call to `Release`. +* The framework may hold strong references to objects internally. When the user releases their last reference, it is not guaranteed that the object will be immediately destructed. +* Reference counts can be incremented and decremented in a thread-safe manner. But, not all objects can be used safely from multiple thread concurrently. The thread safety attributes of the object should be documented in the header. + +## Null Safety + +The Impeller API passes [nullability completeness](https://clang.llvm.org/docs/DiagnosticsReference.html#wnullability-completeness) checks. All pointer arguments and return values are decorated with `IMPELLER_NULLABLE` and `IMPELLER_NONNULL`. Passing a null pointer to an argument decorated with `IMPELLER_NONNULL` will very likely result in a null pointer dereference. When generating automated bindings to other languages, it is recommended that these decorations be used to inform the API and perform additional checks. + +## API Stability + +Unlike the [Flutter Embedder API]([url](https://docs.flutter.dev/embedded)) which has a stable API as well as ABI, the Impeller API does **not** currently have stability guarantees. + +However, the API does look similar to the one used by Flutter in Dart. So major overhauls are not realistically on the horizon. + +The API is also versioned and there may be stability guarantees between specific versions in the future. diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2ce918dc07dd0862e6409426c9b814f559a80e3d --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +group("backend") { + public_deps = [] + + if (impeller_enable_metal) { + public_deps += [ "metal" ] + } + + if (impeller_enable_opengles) { + public_deps += [ "gles" ] + } + + if (impeller_enable_vulkan) { + public_deps += [ "vulkan" ] + } +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..236b129ca8da26dd3130fefae745a81430064953 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/BUILD.gn @@ -0,0 +1,17 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("gles") { + public_deps = [ "../../:interop_base" ] + sources = [ + "context_gles.cc", + "context_gles.h", + "reactor_worker_gles.cc", + "reactor_worker_gles.h", + "surface_gles.cc", + "surface_gles.h", + ] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..cbdfc78cdc6d6ebafbebc56a25d280bafbb2e4c0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.cc @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/gles/context_gles.h" + +#include "impeller/base/validation.h" +#include "impeller/entity/gles/entity_shaders_gles.h" +#include "impeller/entity/gles/framebuffer_blend_shaders_gles.h" +#include "impeller/renderer/backend/gles/context_gles.h" + +namespace impeller::interop { + +ScopedObject ContextGLES::Create( + std::function proc_address_callback) { + auto proc_table = std::make_unique( + impeller::ProcTableGLES(std::move(proc_address_callback))); + if (!proc_table || !proc_table->IsValid()) { + VALIDATION_LOG << "Could not create valid OpenGL ES proc. table."; + return {}; + } + std::vector> shader_mappings = { + std::make_shared( + impeller_entity_shaders_gles_data, + impeller_entity_shaders_gles_length), + std::make_shared( + impeller_framebuffer_blend_shaders_gles_data, + impeller_framebuffer_blend_shaders_gles_length), + }; + auto impeller_context = impeller::ContextGLES::Create( + Flags{}, std::move(proc_table), shader_mappings, false); + if (!impeller_context) { + VALIDATION_LOG << "Could not create Impeller context."; + return {}; + } + auto reactor_worker = std::make_shared(); + auto worker_id = impeller_context->AddReactorWorker(reactor_worker); + if (!worker_id.has_value()) { + VALIDATION_LOG << "Could not add reactor worker."; + return {}; + } + return Create(std::move(impeller_context), std::move(reactor_worker)); +} + +ScopedObject ContextGLES::Create( + std::shared_ptr impeller_context, + std::shared_ptr worker) { + // Can't call Create because of private constructor. Adopt the raw pointer + // instead. + auto context = Adopt( + new ContextGLES(std::move(impeller_context), std::move(worker))); + + if (!context->IsValid()) { + VALIDATION_LOG << "Could not create valid context."; + return {}; + } + return context; +} + +ContextGLES::ContextGLES(std::shared_ptr context, + std::shared_ptr worker) + : Context(std::move(context)), worker_(std::move(worker)) {} + +ContextGLES::~ContextGLES() = default; + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..baaf08cf866a58467d536a78128067aa390616f1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/context_gles.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_CONTEXT_GLES_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_CONTEXT_GLES_H_ + +#include +#include + +#include "impeller/toolkit/interop/backend/gles/reactor_worker_gles.h" +#include "impeller/toolkit/interop/context.h" + +namespace impeller::interop { + +class ContextGLES final : public Context { + public: + static ScopedObject Create( + std::function proc_address_callback); + + static ScopedObject Create( + std::shared_ptr context, + std::shared_ptr worker = nullptr); + + ContextGLES(); + + // |Context| + ~ContextGLES() override; + + ContextGLES(const ContextGLES&) = delete; + + ContextGLES& operator=(const ContextGLES&) = delete; + + private: + std::shared_ptr worker_; + + ContextGLES(std::shared_ptr context, + std::shared_ptr worker); +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_CONTEXT_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4c7bba3a5ed9bbae58e2c98bdae893929c34be2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.cc @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/gles/reactor_worker_gles.h" + +namespace impeller::interop { + +ReactorWorkerGLES::ReactorWorkerGLES() + : thread_id_(std::this_thread::get_id()) {} + +ReactorWorkerGLES::~ReactorWorkerGLES() = default; + +bool ReactorWorkerGLES::CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const { + return thread_id_ == std::this_thread::get_id(); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..676c0a2b00457cada9fdfda4ee1a37bc9e165ac5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/reactor_worker_gles.h @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_REACTOR_WORKER_GLES_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_REACTOR_WORKER_GLES_H_ + +#include "impeller/renderer/backend/gles/reactor_gles.h" + +namespace impeller::interop { + +class ReactorWorkerGLES final : public ReactorGLES::Worker { + public: + ReactorWorkerGLES(); + + // |ReactorGLES::Worker| + ~ReactorWorkerGLES() override; + + // |ReactorGLES::Worker| + bool CanReactorReactOnCurrentThreadNow( + const ReactorGLES& reactor) const override; + + private: + std::thread::id thread_id_; + + ReactorWorkerGLES(const ReactorWorkerGLES&) = delete; + + ReactorWorkerGLES& operator=(const ReactorWorkerGLES&) = delete; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_REACTOR_WORKER_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.cc new file mode 100644 index 0000000000000000000000000000000000000000..6860b1611531225f960d4a447e34a7b0d6f3f074 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.cc @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/gles/surface_gles.h" + +#include "impeller/renderer/backend/gles/surface_gles.h" + +namespace impeller::interop { + +SurfaceGLES::SurfaceGLES(Context& context, + uint64_t fbo, + PixelFormat color_format, + ISize size) + : SurfaceGLES(context, + impeller::SurfaceGLES::WrapFBO( + context.GetContext(), + []() { return true; }, + fbo, + color_format, + size)) {} + +SurfaceGLES::SurfaceGLES(Context& context, + std::shared_ptr surface) + : Surface(context, std::move(surface)) {} + +SurfaceGLES::~SurfaceGLES() = default; + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.h new file mode 100644 index 0000000000000000000000000000000000000000..06c351d3fa1491a76403a46ae781e79ca82b2dda --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/gles/surface_gles.h @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_SURFACE_GLES_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_SURFACE_GLES_H_ + +#include "impeller/toolkit/interop/surface.h" + +namespace impeller::interop { + +class SurfaceGLES final : public Surface { + public: + SurfaceGLES(Context& context, + uint64_t fbo, + PixelFormat color_format, + ISize size); + + SurfaceGLES(Context& context, std::shared_ptr surface); + + // |Surface| + ~SurfaceGLES(); + + SurfaceGLES(const SurfaceGLES&) = delete; + + SurfaceGLES& operator=(const SurfaceGLES&) = delete; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_GLES_SURFACE_GLES_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..55f443c974b8cbd05b6f10d13e3f84c98829d3fd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/BUILD.gn @@ -0,0 +1,15 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("metal") { + public_deps = [ "../../:interop_base" ] + sources = [ + "context_mtl.h", + "context_mtl.mm", + "surface_mtl.h", + "surface_mtl.mm", + ] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..4ff2f7baabd79517dd4f4caf9298fb34fc2ecd12 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.h @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_CONTEXT_MTL_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_CONTEXT_MTL_H_ + +#include "impeller/renderer/backend/metal/swapchain_transients_mtl.h" +#include "impeller/toolkit/interop/context.h" + +namespace impeller::interop { + +class ContextMTL final : public Context { + public: + static ScopedObject Create(); + + static ScopedObject Create( + const std::shared_ptr& context); + + // |Context| + ~ContextMTL() override; + + ContextMTL(const ContextMTL&) = delete; + + ContextMTL& operator=(const ContextMTL&) = delete; + + const std::shared_ptr& GetSwapchainTransients() const; + + private: + std::shared_ptr swapchain_transients_; + + explicit ContextMTL(const std::shared_ptr& context); +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_CONTEXT_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.mm b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..755beca4829a2d308ce06d0ffca57275878185fd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/context_mtl.mm @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/metal/context_mtl.h" + +#include "impeller/base/validation.h" +#include "impeller/entity/mtl/entity_shaders.h" +#include "impeller/entity/mtl/framebuffer_blend_shaders.h" +#include "impeller/entity/mtl/modern_shaders.h" +#include "impeller/renderer/backend/metal/context_mtl.h" +#include "impeller/renderer/mtl/compute_shaders.h" + +namespace impeller::interop { + +static std::vector> +CreateShaderLibraryMappings() { + return {std::make_shared( + impeller_entity_shaders_data, impeller_entity_shaders_length), + std::make_shared( + impeller_modern_shaders_data, impeller_modern_shaders_length), + std::make_shared( + impeller_framebuffer_blend_shaders_data, + impeller_framebuffer_blend_shaders_length), + std::make_shared( + impeller_compute_shaders_data, impeller_compute_shaders_length)}; +} + +ScopedObject ContextMTL::Create() { + auto impeller_context = + impeller::ContextMTL::Create(Flags{}, CreateShaderLibraryMappings(), // + std::make_shared(), // + "Impeller" // + ); + if (!impeller_context) { + VALIDATION_LOG << "Could not create Impeller context."; + return {}; + } + return Create(std::move(impeller_context)); +} + +ScopedObject ContextMTL::Create( + const std::shared_ptr& impeller_context) { + // Can't call Create because of private constructor. Adopt the raw pointer + // instead. + auto context = Adopt(new ContextMTL(impeller_context)); + if (!context->IsValid()) { + VALIDATION_LOG << " Could not create valid context."; + return {}; + } + return context; +} + +ContextMTL::ContextMTL(const std::shared_ptr& context) + : Context(context), + swapchain_transients_(std::make_shared( + context->GetResourceAllocator())) {} + +ContextMTL::~ContextMTL() = default; + +const std::shared_ptr& +ContextMTL::GetSwapchainTransients() const { + return swapchain_transients_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.h new file mode 100644 index 0000000000000000000000000000000000000000..2178038466f2600f689e12c004c3b8ece9f2a3cf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.h @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_SURFACE_MTL_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_SURFACE_MTL_H_ + +#include "impeller/toolkit/interop/surface.h" + +namespace impeller::interop { + +class SurfaceMTL final : public Surface { + public: + SurfaceMTL(Context& context, void* metal_drawable); + + SurfaceMTL(Context& context, std::shared_ptr surface); + + ~SurfaceMTL(); + + SurfaceMTL(const SurfaceMTL&) = delete; + + SurfaceMTL& operator=(const SurfaceMTL&) = delete; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_METAL_SURFACE_MTL_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.mm b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.mm new file mode 100644 index 0000000000000000000000000000000000000000..9a08f0d686b5da7508068791741aa876ef4109df --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/metal/surface_mtl.mm @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/metal/surface_mtl.h" + +#include "impeller/renderer/backend/metal/surface_mtl.h" +#include "impeller/toolkit/interop/backend/metal/context_mtl.h" + +namespace impeller::interop { + +SurfaceMTL::SurfaceMTL(Context& context, void* metal_drawable) + : SurfaceMTL(context, + impeller::SurfaceMTL::MakeFromMetalLayerDrawable( + context.GetContext(), + (__bridge id)metal_drawable, + reinterpret_cast(&context) + ->GetSwapchainTransients())) {} + +SurfaceMTL::SurfaceMTL(Context& context, + std::shared_ptr surface) + : Surface(context, std::move(surface)) {} + +SurfaceMTL::~SurfaceMTL() = default; + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/BUILD.gn b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..585df81f1d586b18242e446b907331739462a27f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/BUILD.gn @@ -0,0 +1,17 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("vulkan") { + public_deps = [ "../../:interop_base" ] + sources = [ + "context_vk.cc", + "context_vk.h", + "surface_vk.cc", + "surface_vk.h", + "swapchain_vk.cc", + "swapchain_vk.h", + ] +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..131d75e1284f72f53fa7037a13df18fecc62b59e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.cc @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/vulkan/context_vk.h" + +#include "flutter/fml/paths.h" +#include "impeller/entity/vk/entity_shaders_vk.h" +#include "impeller/entity/vk/framebuffer_blend_shaders_vk.h" +#include "impeller/entity/vk/modern_shaders_vk.h" +#include "impeller/renderer/backend/vulkan/context_vk.h" +#include "impeller/renderer/vk/compute_shaders_vk.h" + +namespace impeller::interop { + +static std::vector> +CreateShaderLibraryMappings() { + return { + std::make_shared(impeller_entity_shaders_vk_data, + impeller_entity_shaders_vk_length), + std::make_shared(impeller_modern_shaders_vk_data, + impeller_modern_shaders_vk_length), + std::make_shared( + impeller_framebuffer_blend_shaders_vk_data, + impeller_framebuffer_blend_shaders_vk_length), + std::make_shared( + impeller_compute_shaders_vk_data, impeller_compute_shaders_vk_length), + }; +} +// This bit is complicated by the fact that impeller::ContextVK::Settings takes +// a raw function pointer to the callback. +thread_local std::function + sContextVKProcAddressCallback; + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL ContextVKGetInstanceProcAddress( + VkInstance instance, + const char* proc_name) { + if (sContextVKProcAddressCallback) { + return sContextVKProcAddressCallback(instance, proc_name); + } + return nullptr; +} + +ScopedObject ContextVK::Create(const Settings& settings) { + if (!settings.IsValid()) { + VALIDATION_LOG << "Invalid settings for Vulkan context creation."; + return {}; + } + impeller::ContextVK::Settings impeller_settings; + impeller_settings.shader_libraries_data = CreateShaderLibraryMappings(); + impeller_settings.cache_directory = fml::paths::GetCachesDirectory(); + impeller_settings.enable_validation = true; + sContextVKProcAddressCallback = settings.instance_proc_address_callback; + impeller_settings.proc_address_callback = ContextVKGetInstanceProcAddress; + impeller_settings.flags = impeller::Flags{}; + auto impeller_context = + impeller::ContextVK::Create(std::move(impeller_settings)); + sContextVKProcAddressCallback = nullptr; + if (!impeller_context) { + VALIDATION_LOG << "Could not create Impeller context."; + return {}; + } + return Create(std::move(impeller_context)); +} + +ScopedObject ContextVK::Create( + std::shared_ptr impeller_context) { + // Can't call Create because of private constructor. Adopt the raw pointer + // instead. + auto context = Adopt(new ContextVK(std::move(impeller_context))); + if (!context->IsValid()) { + VALIDATION_LOG << " Could not create valid context."; + return {}; + } + return context; +} + +ContextVK::ContextVK(std::shared_ptr context) + : Context(std::move(context)) {} + +ContextVK::~ContextVK() = default; + +ContextVK::Settings::Settings(const ImpellerContextVulkanSettings& settings) + : enable_validation(settings.enable_vulkan_validation) { + instance_proc_address_callback = + [&settings](VkInstance instance, + const char* proc_name) -> PFN_vkVoidFunction { + if (settings.proc_address_callback) { + return reinterpret_cast( + settings.proc_address_callback(instance, proc_name, + settings.user_data)); + } + return nullptr; + }; +} + +bool ContextVK::GetInfo(ImpellerContextVulkanInfo& info) const { + if (!IsValid()) { + return false; + } + const auto& context = impeller::ContextVK::Cast(*GetContext()); + // NOLINTBEGIN(google-readability-casting) + info.vk_instance = reinterpret_cast(VkInstance(context.GetInstance())); + info.vk_physical_device = + reinterpret_cast(VkPhysicalDevice(context.GetPhysicalDevice())); + info.vk_logical_device = + reinterpret_cast(VkDevice(context.GetDevice())); + // NOLINTEND(google-readability-casting) + info.graphics_queue_family_index = + context.GetGraphicsQueue()->GetIndex().family; + info.graphics_queue_index = context.GetGraphicsQueue()->GetIndex().index; + return true; +} + +bool ContextVK::Settings::IsValid() const { + return !!instance_proc_address_callback; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..7964c23ba06f03ea68d8d14d676fb31d2a1a22b6 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/context_vk.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_CONTEXT_VK_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_CONTEXT_VK_H_ + +#include "impeller/renderer/backend/vulkan/vk.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/impeller.h" + +namespace impeller::interop { + +class ContextVK final : public Context { + public: + struct Settings { + std::function + instance_proc_address_callback; + bool enable_validation = false; + + explicit Settings(const ImpellerContextVulkanSettings& settings); + + bool IsValid() const; + }; + + static ScopedObject Create(const Settings& settings); + + static ScopedObject Create( + std::shared_ptr context); + + // |Context| + ~ContextVK() override; + + ContextVK(const ContextVK&) = delete; + + ContextVK& operator=(const ContextVK&) = delete; + + bool GetInfo(ImpellerContextVulkanInfo& info) const; + + private: + explicit ContextVK(std::shared_ptr context); +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_CONTEXT_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..735e387057465b5228f0ec7f3a2d9e2cbb581ef4 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.cc @@ -0,0 +1,15 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/vulkan/surface_vk.h" + +namespace impeller::interop { + +SurfaceVK::SurfaceVK(Context& context, + std::shared_ptr surface) + : Surface(context, std::move(surface)) {} + +SurfaceVK::~SurfaceVK() = default; + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..057e5527e38db06db0e60cbb434c425f94e8b405 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/surface_vk.h @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SURFACE_VK_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SURFACE_VK_H_ + +#include "impeller/toolkit/interop/surface.h" + +namespace impeller::interop { + +class SurfaceVK final : public Surface { + public: + SurfaceVK(Context& context, std::shared_ptr surface); + + ~SurfaceVK(); + + SurfaceVK(const SurfaceVK&) = delete; + + SurfaceVK& operator=(const SurfaceVK&) = delete; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SURFACE_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.cc new file mode 100644 index 0000000000000000000000000000000000000000..ae55da72640933cedaf57745c889c1dd9dd919b9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.cc @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/backend/vulkan/swapchain_vk.h" + +#include "impeller/renderer/backend/vulkan/context_vk.h" + +namespace impeller::interop { + +SwapchainVK::SwapchainVK(Context& context, VkSurfaceKHR c_surface) + : context_(Ref(&context)) { + if (!context.IsVulkan()) { + VALIDATION_LOG << "Context is not Vulkan."; + return; + } + + if (!c_surface) { + VALIDATION_LOG << "Invalid surface."; + return; + } + + // Creating a unique object from a raw handle requires fetching the owner + // manually. + auto surface = vk::UniqueSurfaceKHR( + vk::SurfaceKHR{c_surface}, + impeller::ContextVK::Cast(*context_->GetContext()).GetInstance()); + auto swapchain = impeller::SwapchainVK::Create(context.GetContext(), // + std::move(surface), // + ISize::MakeWH(1, 1) // + ); + if (!swapchain) { + VALIDATION_LOG << "Could not create Vulkan swapchain."; + return; + } + swapchain_ = std::move(swapchain); +} + +SwapchainVK::~SwapchainVK() = default; + +bool SwapchainVK::IsValid() const { + return swapchain_ && swapchain_->IsValid(); +} + +ScopedObject SwapchainVK::AcquireNextSurface() { + if (!IsValid()) { + return nullptr; + } + + auto impeller_surface = swapchain_->AcquireNextDrawable(); + if (!impeller_surface) { + VALIDATION_LOG << "Could not acquire next drawable."; + return nullptr; + } + + auto surface = Create(*context_, std::move(impeller_surface)); + if (!surface || !surface->IsValid()) { + VALIDATION_LOG << "Could not create valid surface."; + return nullptr; + } + + return surface; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.h b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.h new file mode 100644 index 0000000000000000000000000000000000000000..610af596836318c4f2b2337f9cbac82101857606 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/backend/vulkan/swapchain_vk.h @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SWAPCHAIN_VK_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SWAPCHAIN_VK_H_ + +#include "impeller/renderer/backend/vulkan/swapchain/swapchain_vk.h" +#include "impeller/toolkit/interop/backend/vulkan/surface_vk.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class SwapchainVK final + : public Object { + public: + SwapchainVK(Context& context, VkSurfaceKHR surface); + + ~SwapchainVK(); + + bool IsValid() const; + + SwapchainVK(const SwapchainVK&) = delete; + + SwapchainVK& operator=(const SwapchainVK&) = delete; + + ScopedObject AcquireNextSurface(); + + private: + ScopedObject context_; + std::shared_ptr swapchain_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_BACKEND_VULKAN_SWAPCHAIN_VK_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..01825aa266137af3818561213f3363cca24e58fa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.cc @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/color_filter.h" + +namespace impeller::interop { + +ScopedObject ColorFilter::MakeBlend(Color color, BlendMode mode) { + auto filter = flutter::DlColorFilter::MakeBlend(ToDisplayListType(color), + ToDisplayListType(mode)); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ScopedObject ColorFilter::MakeMatrix(const float matrix[20]) { + auto filter = flutter::DlColorFilter::MakeMatrix(matrix); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ColorFilter::ColorFilter(std::shared_ptr filter) + : filter_(std::move(filter)) {} + +ColorFilter::~ColorFilter() = default; + +const std::shared_ptr& +ColorFilter::GetColorFilter() const { + return filter_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.h b/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..2f0b066a98b3e7c2846aa81bff80b42c515546a1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/color_filter.h @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_FILTER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_FILTER_H_ + +#include "flutter/display_list/effects/dl_color_filter.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class ColorFilter final + : public Object { + public: + static ScopedObject MakeBlend(Color color, BlendMode mode); + + static ScopedObject MakeMatrix(const float matrix[20]); + + explicit ColorFilter(std::shared_ptr filter); + + ~ColorFilter() override; + + ColorFilter(const ColorFilter&) = delete; + + ColorFilter& operator=(const ColorFilter&) = delete; + + const std::shared_ptr& GetColorFilter() const; + + private: + std::shared_ptr filter_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_FILTER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.cc new file mode 100644 index 0000000000000000000000000000000000000000..8fff4c16cb42fccc95d4f090500df4cbc7d199ea --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.cc @@ -0,0 +1,128 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/color_source.h" + +namespace impeller::interop { + +ScopedObject ColorSource::MakeLinearGradient( + const Point& start_point, + const Point& end_point, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation) { + auto dl_filter = flutter::DlColorSource::MakeLinear(start_point, // + end_point, // + stops.size(), // + colors.data(), // + stops.data(), // + tile_mode, // + &transformation // + ); + if (!dl_filter) { + return nullptr; + } + return Create(std::move(dl_filter)); +} + +ScopedObject ColorSource::MakeRadialGradient( + const Point& center, + Scalar radius, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation) { + auto dl_filter = flutter::DlColorSource::MakeRadial(center, // + radius, // + stops.size(), // + colors.data(), // + stops.data(), // + tile_mode, // + &transformation // + ); + if (!dl_filter) { + return nullptr; + } + return Create(std::move(dl_filter)); +} + +ScopedObject ColorSource::MakeConicalGradient( + const Point& start_center, + Scalar start_radius, + const Point& end_center, + Scalar end_radius, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation) { + auto dl_filter = flutter::DlColorSource::MakeConical(start_center, // + start_radius, // + end_center, // + end_radius, // + stops.size(), // + colors.data(), // + stops.data(), // + tile_mode, // + &transformation // + ); + if (!dl_filter) { + return nullptr; + } + return Create(std::move(dl_filter)); +} + +ScopedObject ColorSource::MakeSweepGradient( + const Point& center, + Scalar start, + Scalar end, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation) { + auto dl_filter = flutter::DlColorSource::MakeSweep(center, // + start, // + end, // + stops.size(), // + colors.data(), // + stops.data(), // + tile_mode, // + &transformation // + ); + if (!dl_filter) { + return nullptr; + } + return Create(std::move(dl_filter)); +} + +ScopedObject ColorSource::MakeImage( + const Texture& image, + flutter::DlTileMode horizontal_tile_mode, + flutter::DlTileMode vertical_tile_mode, + flutter::DlImageSampling sampling, + const Matrix& transformation) { + auto dl_filter = flutter::DlColorSource::MakeImage(image.MakeImage(), // + horizontal_tile_mode, // + vertical_tile_mode, // + sampling, // + &transformation // + ); + return Create(std::move(dl_filter)); +} + +ColorSource::ColorSource(std::shared_ptr source) + : color_source_(std::move(source)) {} + +ColorSource::~ColorSource() = default; + +bool ColorSource::IsValid() const { + return !!color_source_; +} + +const std::shared_ptr& ColorSource::GetColorSource() + const { + return color_source_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.h b/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.h new file mode 100644 index 0000000000000000000000000000000000000000..4b2f96e51f1c9bdb878b2d748362448f3aec5ca9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/color_source.h @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_SOURCE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_SOURCE_H_ + +#include + +#include "flutter/display_list/effects/dl_color_source.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/point.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/texture.h" + +namespace impeller::interop { + +class ColorSource final + : public Object { + public: + static ScopedObject MakeLinearGradient( + const Point& start_point, + const Point& end_point, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation); + + static ScopedObject MakeRadialGradient( + const Point& center, + Scalar radius, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation); + + static ScopedObject MakeConicalGradient( + const Point& start_center, + Scalar start_radius, + const Point& end_center, + Scalar end_radius, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation); + + static ScopedObject MakeSweepGradient( + const Point& center, + Scalar start, + Scalar end, + const std::vector& colors, + const std::vector& stops, + flutter::DlTileMode tile_mode, + const Matrix& transformation); + + static ScopedObject MakeImage( + const Texture& image, + flutter::DlTileMode horizontal_tile_mode, + flutter::DlTileMode vertical_tile_mode, + flutter::DlImageSampling sampling, + const Matrix& transformation); + + explicit ColorSource(std::shared_ptr source); + + ~ColorSource() override; + + ColorSource(const ColorSource&) = delete; + + ColorSource& operator=(const ColorSource&) = delete; + + bool IsValid() const; + + const std::shared_ptr& GetColorSource() const; + + private: + std::shared_ptr color_source_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_COLOR_SOURCE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/context.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/context.cc new file mode 100644 index 0000000000000000000000000000000000000000..117d15eb32ac9035022ea9dadb20d5564d6f19cf --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/context.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/context.h" + +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +namespace impeller::interop { + +Context::Context(std::shared_ptr context) + : context_(std::move(context), TypographerContextSkia::Make()) {} + +Context::~Context() = default; + +bool Context::IsValid() const { + return context_.IsValid(); +} + +std::shared_ptr Context::GetContext() const { + return context_.GetContext(); +} + +AiksContext& Context::GetAiksContext() { + return context_; +} + +bool Context::IsBackend(impeller::Context::BackendType type) const { + if (!IsValid()) { + return false; + } + return GetContext()->GetBackendType() == type; +} + +bool Context::IsGL() const { + return IsBackend(impeller::Context::BackendType::kOpenGLES); +} + +bool Context::IsMetal() const { + return IsBackend(impeller::Context::BackendType::kMetal); +} + +bool Context::IsVulkan() const { + return IsBackend(impeller::Context::BackendType::kVulkan); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/context.h b/flutter/engine/src/flutter/impeller/toolkit/interop/context.h new file mode 100644 index 0000000000000000000000000000000000000000..b41b743b01d512acdb95ee7a58e4dc892907e496 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/context.h @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_CONTEXT_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_CONTEXT_H_ + +#include "impeller/display_list/aiks_context.h" +#include "impeller/renderer/context.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class Context + : public Object { + public: + ~Context() override; + + Context(const Context&) = delete; + + Context& operator=(const Context&) = delete; + + bool IsValid() const; + + std::shared_ptr GetContext() const; + + AiksContext& GetAiksContext(); + + bool IsBackend(impeller::Context::BackendType type) const; + + bool IsGL() const; + + bool IsMetal() const; + + bool IsVulkan() const; + + protected: + explicit Context(std::shared_ptr context); + + private: + impeller::AiksContext context_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/dl.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/dl.cc new file mode 100644 index 0000000000000000000000000000000000000000..cceee49e30e32d3fdf416206ea6e17b243a04065 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/dl.cc @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/dl.h" + +namespace impeller::interop { + +DisplayList::DisplayList(sk_sp display_list) + : display_list_(std::move(display_list)) {} + +DisplayList::~DisplayList() = default; + +bool DisplayList::IsValid() const { + return !!display_list_; +} + +const sk_sp DisplayList::GetDisplayList() const { + return display_list_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/dl.h b/flutter/engine/src/flutter/impeller/toolkit/interop/dl.h new file mode 100644 index 0000000000000000000000000000000000000000..710a0223c75b480a629deb53ca3dc9d0c4f562fa --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/dl.h @@ -0,0 +1,36 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_H_ + +#include "flutter/display_list/display_list.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class DisplayList final + : public Object { + public: + explicit DisplayList(sk_sp display_list); + + ~DisplayList() override; + + DisplayList(const DisplayList&) = delete; + + DisplayList& operator=(const DisplayList&) = delete; + + bool IsValid() const; + + const sk_sp GetDisplayList() const; + + private: + sk_sp display_list_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a24b567103bdd9de16d9f33d5dea7bf1af07d70 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.cc @@ -0,0 +1,197 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/dl_builder.h" + +#include "impeller/toolkit/interop/formats.h" + +namespace impeller::interop { + +DisplayListBuilder::DisplayListBuilder(const ImpellerRect* rect) + : builder_(rect) {} + +DisplayListBuilder::~DisplayListBuilder() = default; + +void DisplayListBuilder::Save() { + builder_.Save(); +} + +void DisplayListBuilder::SaveLayer(const Rect& bounds, + const Paint* paint, + const ImageFilter* backdrop) { + builder_.SaveLayer( + bounds, // + paint == nullptr ? nullptr : &paint->GetPaint(), // + backdrop == nullptr ? nullptr : backdrop->GetImageFilter().get()); +} + +void DisplayListBuilder::Restore() { + builder_.Restore(); +} + +void DisplayListBuilder::Scale(Size scale) { + builder_.Scale(scale.width, scale.height); +} + +void DisplayListBuilder::Rotate(Degrees angle) { + builder_.Rotate(angle.degrees); +} + +void DisplayListBuilder::Translate(Point translation) { + builder_.Translate(translation.x, translation.y); +} + +Matrix DisplayListBuilder::GetTransform() const { + return builder_.GetMatrix(); +} + +void DisplayListBuilder::SetTransform(const Matrix& matrix) { + builder_.SetTransform(matrix); +} + +void DisplayListBuilder::Transform(const Matrix& matrix) { + builder_.Transform(matrix); +} + +void DisplayListBuilder::ResetTransform() { + builder_.TransformReset(); +} + +uint32_t DisplayListBuilder::GetSaveCount() const { + return builder_.GetSaveCount(); +} + +void DisplayListBuilder::RestoreToCount(uint32_t count) { + builder_.RestoreToCount(count); +} + +void DisplayListBuilder::ClipRect(const Rect& rect, flutter::DlClipOp op) { + builder_.ClipRect(rect, op); +} + +void DisplayListBuilder::ClipOval(const Rect& rect, flutter::DlClipOp op) { + builder_.ClipOval(rect, op); +} + +void DisplayListBuilder::ClipRoundedRect(const Rect& rect, + const RoundingRadii& radii, + flutter::DlClipOp op) { + builder_.ClipRoundRect(RoundRect::MakeRectRadii(rect, radii), op); +} + +void DisplayListBuilder::ClipPath(const Path& path, flutter::DlClipOp op) { + builder_.ClipPath(flutter::DlPath(path.GetPath()), op); +} + +void DisplayListBuilder::DrawRect(const Rect& rect, const Paint& paint) { + builder_.DrawRect(rect, paint.GetPaint()); +} + +void DisplayListBuilder::DrawOval(const Rect& oval_bounds, const Paint& paint) { + builder_.DrawOval(oval_bounds, paint.GetPaint()); +} + +void DisplayListBuilder::DrawRoundedRect(const Rect& rect, + const RoundingRadii& radii, + const Paint& paint) { + builder_.DrawRoundRect(RoundRect::MakeRectRadii(rect, radii), + paint.GetPaint()); +} + +void DisplayListBuilder::DrawRoundedRectDifference( + const Rect& outer_rect, + const RoundingRadii& outer_radii, + const Rect& inner_rect, + const RoundingRadii& inner_radii, + const Paint& paint) { + builder_.DrawDiffRoundRect( + RoundRect::MakeRectRadii(outer_rect, outer_radii), // + RoundRect::MakeRectRadii(inner_rect, inner_radii), // + paint.GetPaint() // + ); +} + +void DisplayListBuilder::DrawPath(const Path& path, const Paint& paint) { + builder_.DrawPath(flutter::DlPath(path.GetPath()), paint.GetPaint()); +} + +void DisplayListBuilder::DrawPaint(const Paint& paint) { + builder_.DrawPaint(paint.GetPaint()); +} + +void DisplayListBuilder::DrawLine(const Point& from, + const Point& to, + const Paint& paint) { + builder_.DrawLine(from, to, paint.GetPaint()); +} + +void DisplayListBuilder::DrawDashedLine(const Point& from, + const Point& to, + Scalar on_length, + Scalar off_length, + const Paint& paint) { + builder_.DrawDashedLine(from, // + to, // + on_length, // + off_length, // + paint.GetPaint() // + ); +} + +ScopedObject DisplayListBuilder::Build() { + return Create(builder_.Build()); +} + +void DisplayListBuilder::DrawDisplayList(const DisplayList& dl, + Scalar opacity) { + builder_.DrawDisplayList(dl.GetDisplayList(), opacity); +} + +void DisplayListBuilder::DrawTexture(const Texture& texture, + const Point& point, + flutter::DlImageSampling sampling, + const Paint* paint) { + builder_.DrawImage(texture.MakeImage(), // + point, // + sampling, // + paint == nullptr ? nullptr : &paint->GetPaint() // + ); +} + +void DisplayListBuilder::DrawTextureRect(const Texture& texture, + const Rect& src_rect, + const Rect& dst_rect, + flutter::DlImageSampling sampling, + const Paint* paint) { + builder_.DrawImageRect(texture.MakeImage(), // + src_rect, // + dst_rect, // + sampling, // + paint == nullptr ? nullptr : &paint->GetPaint() // + ); +} + +void DisplayListBuilder::DrawParagraph(const Paragraph& paragraph, + Point point) { + const auto& handle = paragraph.GetHandle(); + if (!handle) { + return; + } + handle->Paint(&builder_, point.x, point.y); +} + +void DisplayListBuilder::DrawShadow(const Path& path, + const flutter::DlColor& color, + float elevation, + bool occluder_is_transparent, + float device_pixel_ratio) { + builder_.DrawShadow(flutter::DlPath(path.GetPath()), // path + color, // shadow color + elevation, // elevation + occluder_is_transparent, // occluder transparency + device_pixel_ratio // dpr + ); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.h b/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..a41172383830d5fa3bfa04a4e310cdb9f48377fe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/dl_builder.h @@ -0,0 +1,127 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_BUILDER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_BUILDER_H_ + +#include "flutter/display_list/dl_builder.h" +#include "flutter/display_list/dl_canvas.h" +#include "impeller/geometry/scalar.h" +#include "impeller/geometry/size.h" +#include "impeller/toolkit/interop/dl.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/image_filter.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/paint.h" +#include "impeller/toolkit/interop/paragraph.h" +#include "impeller/toolkit/interop/path.h" +#include "impeller/toolkit/interop/texture.h" + +namespace impeller::interop { + +class DisplayListBuilder final + : public Object { + public: + explicit DisplayListBuilder(const ImpellerRect* rect); + + ~DisplayListBuilder() override; + + DisplayListBuilder(const DisplayListBuilder&) = delete; + + DisplayListBuilder& operator=(const DisplayListBuilder&) = delete; + + void Save(); + + void SaveLayer(const Rect& bounds, + const Paint* paint, + const ImageFilter* backdrop); + + void Restore(); + + void Scale(Size scale); + + void Rotate(Degrees angle); + + void Translate(Point translation); + + Matrix GetTransform() const; + + void SetTransform(const Matrix& matrix); + + void Transform(const Matrix& matrix); + + void ResetTransform(); + + uint32_t GetSaveCount() const; + + void RestoreToCount(uint32_t count); + + void ClipRect(const Rect& rect, flutter::DlClipOp op); + + void ClipOval(const Rect& rect, flutter::DlClipOp op); + + void ClipRoundedRect(const Rect& rect, + const RoundingRadii& radii, + flutter::DlClipOp op); + + void ClipPath(const Path& path, flutter::DlClipOp op); + + void DrawPaint(const Paint& paint); + + void DrawLine(const Point& from, const Point& to, const Paint& paint); + + void DrawDashedLine(const Point& from, + const Point& to, + Scalar on_length, + Scalar off_length, + const Paint& paint); + + void DrawRect(const Rect& rect, const Paint& paint); + + void DrawOval(const Rect& oval_bounds, const Paint& paint); + + void DrawRoundedRect(const Rect& rect, + const RoundingRadii& radii, + const Paint& paint); + + void DrawRoundedRectDifference(const Rect& outer_rect, + const RoundingRadii& outer_radii, + const Rect& inner_rect, + const RoundingRadii& inner_radii, + const Paint& paint); + + void DrawPath(const Path& path, const Paint& paint); + + void DrawTexture(const Texture& texture, + const Point& point, + flutter::DlImageSampling sampling, + const Paint* paint); + + void DrawTextureRect(const Texture& texture, + const Rect& src_rect, + const Rect& dst_rect, + flutter::DlImageSampling sampling, + const Paint* paint); + + void DrawDisplayList(const DisplayList& dl, Scalar opacity); + + void DrawParagraph(const Paragraph& paragraph, Point point); + + void DrawShadow(const Path& path, + const flutter::DlColor& color, + float elevation, + bool occluder_is_transparent, + float device_pixel_ratio); + + ScopedObject Build(); + + private: + flutter::DisplayListBuilder builder_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_DL_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/example_gl.c b/flutter/engine/src/flutter/impeller/toolkit/interop/example_gl.c new file mode 100644 index 0000000000000000000000000000000000000000..4516d94402d87cfd3c79efaddc2499e4f605ab7a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/example_gl.c @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "GLFW/glfw3.h" +#include "impeller.h" + +void GLFWErrorCallback(int error, const char* description) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "GLFW Error (%d): %s\n", error, description); + fflush(stderr); +} + +void* ProcAddressCallback(const char* proc_name, void* user_data) { + return glfwGetProcAddress(proc_name); +} + +int main(int argc, char const* argv[]) { + glfwSetErrorCallback(GLFWErrorCallback); + [[maybe_unused]] int result = glfwInit(); + assert(result == GLFW_TRUE); + + if (glfwGetPlatform() == GLFW_PLATFORM_COCOA) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, + "OpenGL(ES) is not available on macOS. Please use Metal or Vulkan " + "instead.\n"); + fflush(stderr); + return -1; + } + + glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); + + GLFWwindow* window = + glfwCreateWindow(800, 600, "Impeller Example (OpenGL)", NULL, NULL); + assert(window != NULL); + + int framebuffer_width, framebuffer_height; + glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); + + // The GL context must be current on the calling thread. + glfwMakeContextCurrent(window); + + ImpellerContext context = ImpellerContextCreateOpenGLESNew( + IMPELLER_VERSION, ProcAddressCallback, NULL); + assert(context != NULL); + + ImpellerISize surface_size = {}; + surface_size.width = framebuffer_width; + surface_size.height = framebuffer_height; + + ImpellerSurface surface = ImpellerSurfaceCreateWrappedFBONew( + context, 0u, kImpellerPixelFormatRGBA8888, &surface_size); + assert(surface != NULL); + + ImpellerDisplayList dl = NULL; + + { + ImpellerDisplayListBuilder builder = ImpellerDisplayListBuilderNew(NULL); + ImpellerPaint paint = ImpellerPaintNew(); + + // Clear the background to a white color. + ImpellerColor clear_color = {1.0, 1.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint, &clear_color); + ImpellerDisplayListBuilderDrawPaint(builder, paint); + + // Draw a red box. + ImpellerColor box_color = {1.0, 0.0, 0.0, 1.0}; + ImpellerPaintSetColor(paint, &box_color); + ImpellerRect box_rect = {10, 10, 100, 100}; + ImpellerDisplayListBuilderDrawRect(builder, &box_rect, paint); + + dl = ImpellerDisplayListBuilderCreateDisplayListNew(builder); + + ImpellerPaintRelease(paint); + ImpellerDisplayListBuilderRelease(builder); + } + + assert(dl != NULL); + + while (!glfwWindowShouldClose(window)) { + glfwWaitEvents(); + ImpellerSurfaceDrawDisplayList(surface, dl); + glfwSwapBuffers(window); + } + + ImpellerDisplayListRelease(dl); + ImpellerSurfaceRelease(surface); + ImpellerContextRelease(context); + + glfwMakeContextCurrent(NULL); + + glfwDestroyWindow(window); + + glfwTerminate(); + return 0; +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/example_mtl.m b/flutter/engine/src/flutter/impeller/toolkit/interop/example_mtl.m new file mode 100644 index 0000000000000000000000000000000000000000..31624a9736f348057e2401b7f021fbc5eecfcfe2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/example_mtl.m @@ -0,0 +1,110 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#define GLFW_INCLUDE_NONE +#include "GLFW/glfw3.h" +#define GLFW_EXPOSE_NATIVE_COCOA +#import "GLFW/glfw3native.h" + +#include "impeller.h" + +#include +#include +#include + +void GLFWErrorCallback(int error, const char* description) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "GLFW Error (%d): %s\n", error, description); + fflush(stderr); +} + +int main(int argc, char const* argv[]) { + glfwSetErrorCallback(GLFWErrorCallback); + [[maybe_unused]] int result = glfwInit(); + assert(result == GLFW_TRUE); + + if (glfwGetPlatform() != GLFW_PLATFORM_COCOA) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, + "Metal is only available on macOS. Please try either Vulkan or " + "OpenGL (ES).\n"); + fflush(stderr); + return -1; + } + + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + + GLFWwindow* window = + glfwCreateWindow(800, 600, "Impeller Example (Metal)", NULL, NULL); + assert(window != NULL); + + int framebuffer_width, framebuffer_height; + glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); + + ImpellerContext context = ImpellerContextCreateMetalNew(IMPELLER_VERSION); + assert(context != NULL); + + // This example assumes Automatic Reference Counting (ARC) in Objective-C is + // enabled. + NSWindow* cocoa_window = glfwGetCocoaWindow(window); + assert(cocoa_window != NULL); + CAMetalLayer* layer = [CAMetalLayer layer]; + layer.framebufferOnly = NO; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + layer.device = MTLCreateSystemDefaultDevice(); + cocoa_window.contentView.layer = layer; + cocoa_window.contentView.wantsLayer = YES; + + ImpellerDisplayList dl = NULL; + + { + ImpellerDisplayListBuilder builder = ImpellerDisplayListBuilderNew(NULL); + ImpellerPaint paint = ImpellerPaintNew(); + + // Clear the background to a white color. + ImpellerColor clear_color = {1.0, 1.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint, &clear_color); + ImpellerDisplayListBuilderDrawPaint(builder, paint); + + // Draw a red box. + ImpellerColor box_color = {1.0, 0.0, 0.0, 1.0}; + ImpellerPaintSetColor(paint, &box_color); + ImpellerRect box_rect = {10, 10, 100, 100}; + ImpellerDisplayListBuilderDrawRect(builder, &box_rect, paint); + + dl = ImpellerDisplayListBuilderCreateDisplayListNew(builder); + + ImpellerPaintRelease(paint); + ImpellerDisplayListBuilderRelease(builder); + } + + assert(dl != NULL); + + while (!glfwWindowShouldClose(window)) { + glfwWaitEvents(); + + // React to window resizes. + layer.drawableSize = layer.bounds.size; + + ImpellerSurface surface = ImpellerSurfaceCreateWrappedMetalDrawableNew( + context, (__bridge void*)layer.nextDrawable); + assert(surface != NULL); + ImpellerSurfaceDrawDisplayList(surface, dl); + ImpellerSurfacePresent(surface); + ImpellerSurfaceRelease(surface); + } + + ImpellerDisplayListRelease(dl); + ImpellerContextRelease(context); + + glfwMakeContextCurrent(NULL); + + glfwDestroyWindow(window); + + glfwTerminate(); + return 0; +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/example_vk.c b/flutter/engine/src/flutter/impeller/toolkit/interop/example_vk.c new file mode 100644 index 0000000000000000000000000000000000000000..c2661194a2df7b85e15c5c32c3f57d0575bfdf97 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/example_vk.c @@ -0,0 +1,125 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#define GLFW_INCLUDE_VULKAN +#include "GLFW/glfw3.h" +#include "impeller.h" + +void GLFWErrorCallback(int error, const char* description) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "GLFW Error (%d): %s\n", error, description); + fflush(stderr); +} + +void* ProcAddressCallback(void* vulkan_instance, + const char* vulkan_proc_name, + void* user_data) { + return glfwGetInstanceProcAddress(vulkan_instance, vulkan_proc_name); +} + +int main(int argc, char const* argv[]) { + glfwSetErrorCallback(GLFWErrorCallback); + [[maybe_unused]] int result = glfwInit(); + assert(result == GLFW_TRUE); + + if (!glfwVulkanSupported()) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "Vulkan is not supported on this platform.\n"); + fflush(stderr); + return -1; + } + + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + + GLFWwindow* window = + glfwCreateWindow(800, 600, "Impeller Example (Vulkan)", NULL, NULL); + assert(window != NULL); + + ImpellerContextVulkanSettings vulkan_settings = {}; + vulkan_settings.proc_address_callback = &ProcAddressCallback; + vulkan_settings.enable_vulkan_validation = true; + ImpellerContext context = + ImpellerContextCreateVulkanNew(IMPELLER_VERSION, &vulkan_settings); + assert(context != NULL); + + ImpellerContextVulkanInfo info = {}; + [[maybe_unused]] bool info_result = + ImpellerContextGetVulkanInfo(context, &info); + assert(!!info_result); + + if (glfwGetPhysicalDevicePresentationSupport( + info.vk_instance, info.vk_physical_device, + info.graphics_queue_family_index) != GLFW_TRUE) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "Queue does not support presentation.\n"); + fflush(stderr); + return -1; + } + + VkSurfaceKHR vulkan_surface_khr; + VkResult error = glfwCreateWindowSurface(info.vk_instance, window, NULL, + &vulkan_surface_khr); + if (error) { + // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling) + fprintf(stderr, "Could not create Vulkan surface for presentation.\n"); + fflush(stderr); + return -1; + } + + int framebuffer_width, framebuffer_height; + glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); + ImpellerVulkanSwapchain swapchain = + ImpellerVulkanSwapchainCreateNew(context, vulkan_surface_khr); + assert(swapchain != NULL); + + ImpellerDisplayList dl = NULL; + + { + ImpellerDisplayListBuilder builder = ImpellerDisplayListBuilderNew(NULL); + ImpellerPaint paint = ImpellerPaintNew(); + + // Clear the background to a white color. + ImpellerColor clear_color = {1.0, 1.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint, &clear_color); + ImpellerDisplayListBuilderDrawPaint(builder, paint); + + // Draw a red box. + ImpellerColor box_color = {1.0, 0.0, 0.0, 1.0}; + ImpellerPaintSetColor(paint, &box_color); + ImpellerRect box_rect = {10, 10, 100, 100}; + ImpellerDisplayListBuilderDrawRect(builder, &box_rect, paint); + + dl = ImpellerDisplayListBuilderCreateDisplayListNew(builder); + + ImpellerPaintRelease(paint); + ImpellerDisplayListBuilderRelease(builder); + } + + assert(dl != NULL); + + while (!glfwWindowShouldClose(window)) { + glfwWaitEvents(); + + ImpellerSurface surface = + ImpellerVulkanSwapchainAcquireNextSurfaceNew(swapchain); + assert(surface != NULL); + ImpellerSurfaceDrawDisplayList(surface, dl); + ImpellerSurfacePresent(surface); + ImpellerSurfaceRelease(surface); + } + + ImpellerDisplayListRelease(dl); + ImpellerVulkanSwapchainRelease(swapchain); + ImpellerContextRelease(context); + + glfwMakeContextCurrent(NULL); + + glfwDestroyWindow(window); + + glfwTerminate(); + return 0; +} diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/formats.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/formats.cc new file mode 100644 index 0000000000000000000000000000000000000000..29b213405da38365ac07cf50546a885a3d6a485e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/formats.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/formats.h" + +namespace impeller::interop { + +// + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/formats.h b/flutter/engine/src/flutter/impeller/toolkit/interop/formats.h new file mode 100644 index 0000000000000000000000000000000000000000..e90dd92e270a6744ec97999fa30072f480827e85 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/formats.h @@ -0,0 +1,494 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_FORMATS_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_FORMATS_H_ + +#include + +#include "flutter/display_list/dl_builder.h" +#include "flutter/display_list/dl_color.h" +#include "flutter/txt/src/txt/font_style.h" +#include "flutter/txt/src/txt/font_weight.h" +#include "flutter/txt/src/txt/paragraph_style.h" +#include "impeller/entity/entity.h" +#include "impeller/geometry/color.h" +#include "impeller/geometry/matrix.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/size.h" +#include "impeller/toolkit/interop/impeller.h" + +namespace impeller::interop { + +constexpr std::optional ToSkiaType(const ImpellerRect* rect) { + if (!rect) { + return std::nullopt; + } + return SkRect::MakeXYWH(rect->x, rect->y, rect->width, rect->height); +} + +constexpr SkPoint ToSkiaType(const Point& point) { + return SkPoint::Make(point.x, point.y); +} + +constexpr SkVector ToSkiaVector(const Size& point) { + return SkVector::Make(point.width, point.height); +} + +constexpr SkRect ToSkiaType(const Rect& rect) { + return SkRect::MakeXYWH(rect.GetX(), // + rect.GetY(), // + rect.GetWidth(), // + rect.GetHeight() // + ); +} + +constexpr SkPathFillType ToSkiaType(FillType type) { + switch (type) { + case FillType::kNonZero: + return SkPathFillType::kWinding; + case FillType::kOdd: + return SkPathFillType::kEvenOdd; + } + return SkPathFillType::kWinding; +} + +constexpr SkIRect ToSkiaType(IRect rect) { + return SkIRect::MakeXYWH(rect.GetX(), // + rect.GetY(), // + rect.GetWidth(), // + rect.GetHeight() // + ); +} + +template +std::vector ToSkiaType(const std::vector& other_vec) { + std::vector skia_vec; + skia_vec.reserve(other_vec.size()); + for (const auto& other : other_vec) { + skia_vec.emplace_back(ToSkiaType(other)); + } + return skia_vec; +} + +constexpr flutter::DlColor ToDisplayListType(Color color) { + return flutter::DlColor::RGBA(color.red, // + color.green, // + color.blue, // + color.alpha // + ); +} + +constexpr SkMatrix ToSkMatrix(const Matrix& matrix) { + return SkM44::ColMajor(matrix.m).asM33(); +} + +template +std::vector ToDisplayListType(const std::vector& other_vec) { + std::vector dl_vec; + dl_vec.reserve(other_vec.size()); + for (const auto& other : other_vec) { + dl_vec.emplace_back(ToDisplayListType(other)); + } + return dl_vec; +} + +constexpr flutter::DlImageSampling ToDisplayListType( + ImpellerTextureSampling sampling) { + switch (sampling) { + case kImpellerTextureSamplingNearestNeighbor: + return flutter::DlImageSampling::kNearestNeighbor; + case kImpellerTextureSamplingLinear: + return flutter::DlImageSampling::kLinear; + } + return flutter::DlImageSampling::kLinear; +} + +constexpr flutter::DlBlurStyle ToDisplayListType(ImpellerBlurStyle style) { + switch (style) { + case kImpellerBlurStyleNormal: + return flutter::DlBlurStyle::kNormal; + case kImpellerBlurStyleSolid: + return flutter::DlBlurStyle::kSolid; + case kImpellerBlurStyleOuter: + return flutter::DlBlurStyle::kOuter; + case kImpellerBlurStyleInner: + return flutter::DlBlurStyle::kInner; + } + return flutter::DlBlurStyle::kNormal; +} + +constexpr flutter::DlBlendMode ToDisplayListType(BlendMode mode) { + using Mode = flutter::DlBlendMode; + switch (mode) { + case BlendMode::kClear: + return Mode::kClear; + case BlendMode::kSrc: + return Mode::kSrc; + case BlendMode::kDst: + return Mode::kDst; + case BlendMode::kSrcOver: + return Mode::kSrcOver; + case BlendMode::kDstOver: + return Mode::kDstOver; + case BlendMode::kSrcIn: + return Mode::kSrcIn; + case BlendMode::kDstIn: + return Mode::kDstIn; + case BlendMode::kSrcOut: + return Mode::kSrcOut; + case BlendMode::kDstOut: + return Mode::kDstOut; + case BlendMode::kSrcATop: + return Mode::kSrcATop; + case BlendMode::kDstATop: + return Mode::kDstATop; + case BlendMode::kXor: + return Mode::kXor; + case BlendMode::kPlus: + return Mode::kPlus; + case BlendMode::kModulate: + return Mode::kModulate; + case BlendMode::kScreen: + return Mode::kScreen; + case BlendMode::kOverlay: + return Mode::kOverlay; + case BlendMode::kDarken: + return Mode::kDarken; + case BlendMode::kLighten: + return Mode::kLighten; + case BlendMode::kColorDodge: + return Mode::kColorDodge; + case BlendMode::kColorBurn: + return Mode::kColorBurn; + case BlendMode::kHardLight: + return Mode::kHardLight; + case BlendMode::kSoftLight: + return Mode::kSoftLight; + case BlendMode::kDifference: + return Mode::kDifference; + case BlendMode::kExclusion: + return Mode::kExclusion; + case BlendMode::kMultiply: + return Mode::kMultiply; + case BlendMode::kHue: + return Mode::kHue; + case BlendMode::kSaturation: + return Mode::kSaturation; + case BlendMode::kColor: + return Mode::kColor; + case BlendMode::kLuminosity: + return Mode::kLuminosity; + } + return Mode::kSrcOver; +} + +inline SkRRect ToSkiaType(const Rect& rect, const RoundingRadii& radii) { + using Corner = SkRRect::Corner; + SkVector sk_radii[4]; + sk_radii[Corner::kUpperLeft_Corner] = ToSkiaVector(radii.top_left); + sk_radii[Corner::kUpperRight_Corner] = ToSkiaVector(radii.top_right); + sk_radii[Corner::kLowerRight_Corner] = ToSkiaVector(radii.bottom_right); + sk_radii[Corner::kLowerLeft_Corner] = ToSkiaVector(radii.bottom_left); + SkRRect result; + result.setRectRadii(ToSkiaType(rect), sk_radii); + return result; +} + +constexpr Matrix ToImpellerType(const ImpellerMatrix& m) { + return Matrix(m.m[0], m.m[1], m.m[2], m.m[3], // + m.m[4], m.m[5], m.m[6], m.m[7], // + m.m[8], m.m[9], m.m[10], m.m[11], // + m.m[12], m.m[13], m.m[14], m.m[15] // + ); +} + +constexpr void FromImpellerType(const Matrix& from, ImpellerMatrix& to) { + to.m[0] = from.m[0]; + to.m[1] = from.m[1]; + to.m[2] = from.m[2]; + to.m[3] = from.m[3]; + to.m[4] = from.m[4]; + to.m[5] = from.m[5]; + to.m[6] = from.m[6]; + to.m[7] = from.m[7]; + to.m[8] = from.m[8]; + to.m[9] = from.m[9]; + to.m[10] = from.m[10]; + to.m[11] = from.m[11]; + to.m[12] = from.m[12]; + to.m[13] = from.m[13]; + to.m[14] = from.m[14]; + to.m[15] = from.m[15]; +} + +constexpr Size ToImpellerType(const ImpellerSize& size) { + return Size{size.width, size.height}; +} + +constexpr Point ToImpellerType(const ImpellerPoint& point) { + return Point{point.x, point.y}; +} + +constexpr Size ToImpellerSize(const ImpellerPoint& point) { + return Size{point.x, point.y}; +} + +constexpr Rect ToImpellerType(const ImpellerRect& rect) { + return Rect::MakeXYWH(rect.x, rect.y, rect.width, rect.height); +} + +constexpr flutter::DlTileMode ToDisplayListType(ImpellerTileMode mode) { + switch (mode) { + case kImpellerTileModeClamp: + return flutter::DlTileMode::kClamp; + case kImpellerTileModeRepeat: + return flutter::DlTileMode::kRepeat; + case kImpellerTileModeMirror: + return flutter::DlTileMode::kMirror; + case kImpellerTileModeDecal: + return flutter::DlTileMode::kDecal; + } + return flutter::DlTileMode::kClamp; +} + +constexpr RoundingRadii ToImpellerType(const ImpellerRoundingRadii& radii) { + auto result = RoundingRadii{}; + result.top_left = ToImpellerSize(radii.top_left); + result.bottom_left = ToImpellerSize(radii.bottom_left); + result.top_right = ToImpellerSize(radii.top_right); + result.bottom_right = ToImpellerSize(radii.bottom_right); + return result; +} + +constexpr FillType ToImpellerType(ImpellerFillType type) { + switch (type) { + case kImpellerFillTypeNonZero: + return FillType::kNonZero; + case kImpellerFillTypeOdd: + return FillType::kOdd; + } + return FillType::kNonZero; +} + +constexpr flutter::DlClipOp ToImpellerType(ImpellerClipOperation op) { + switch (op) { + case kImpellerClipOperationDifference: + return flutter::DlClipOp::kDifference; + case kImpellerClipOperationIntersect: + return flutter::DlClipOp::kIntersect; + } + return flutter::DlClipOp::kDifference; +} + +constexpr Color ToImpellerType(const ImpellerColor& color) { + Color result; + result.red = color.red; + result.green = color.green; + result.blue = color.blue; + result.alpha = color.alpha; + return result; +} + +constexpr BlendMode ToImpellerType(ImpellerBlendMode mode) { + switch (mode) { + case kImpellerBlendModeClear: + return BlendMode::kClear; + case kImpellerBlendModeSource: + return BlendMode::kSrc; + case kImpellerBlendModeDestination: + return BlendMode::kDst; + case kImpellerBlendModeSourceOver: + return BlendMode::kSrcOver; + case kImpellerBlendModeDestinationOver: + return BlendMode::kDstOver; + case kImpellerBlendModeSourceIn: + return BlendMode::kSrcIn; + case kImpellerBlendModeDestinationIn: + return BlendMode::kDstIn; + case kImpellerBlendModeSourceOut: + return BlendMode::kSrcOut; + case kImpellerBlendModeDestinationOut: + return BlendMode::kDstOut; + case kImpellerBlendModeSourceATop: + return BlendMode::kSrcATop; + case kImpellerBlendModeDestinationATop: + return BlendMode::kDstATop; + case kImpellerBlendModeXor: + return BlendMode::kXor; + case kImpellerBlendModePlus: + return BlendMode::kPlus; + case kImpellerBlendModeModulate: + return BlendMode::kModulate; + case kImpellerBlendModeScreen: + return BlendMode::kScreen; + case kImpellerBlendModeOverlay: + return BlendMode::kOverlay; + case kImpellerBlendModeDarken: + return BlendMode::kDarken; + case kImpellerBlendModeLighten: + return BlendMode::kLighten; + case kImpellerBlendModeColorDodge: + return BlendMode::kColorDodge; + case kImpellerBlendModeColorBurn: + return BlendMode::kColorBurn; + case kImpellerBlendModeHardLight: + return BlendMode::kHardLight; + case kImpellerBlendModeSoftLight: + return BlendMode::kSoftLight; + case kImpellerBlendModeDifference: + return BlendMode::kDifference; + case kImpellerBlendModeExclusion: + return BlendMode::kExclusion; + case kImpellerBlendModeMultiply: + return BlendMode::kMultiply; + case kImpellerBlendModeHue: + return BlendMode::kHue; + case kImpellerBlendModeSaturation: + return BlendMode::kSaturation; + case kImpellerBlendModeColor: + return BlendMode::kColor; + case kImpellerBlendModeLuminosity: + return BlendMode::kLuminosity; + } + return BlendMode::kSrcOver; +} + +constexpr flutter::DlDrawStyle ToDisplayListType(ImpellerDrawStyle style) { + switch (style) { + case kImpellerDrawStyleFill: + return flutter::DlDrawStyle::kFill; + case kImpellerDrawStyleStroke: + return flutter::DlDrawStyle::kStroke; + case kImpellerDrawStyleStrokeAndFill: + return flutter::DlDrawStyle::kStrokeAndFill; + } + return flutter::DlDrawStyle::kFill; +} + +constexpr flutter::DlStrokeCap ToDisplayListType(ImpellerStrokeCap cap) { + switch (cap) { + case kImpellerStrokeCapButt: + return flutter::DlStrokeCap::kButt; + case kImpellerStrokeCapRound: + return flutter::DlStrokeCap::kRound; + case kImpellerStrokeCapSquare: + return flutter::DlStrokeCap::kSquare; + } + return flutter::DlStrokeCap::kButt; +} + +constexpr flutter::DlStrokeJoin ToDisplayListType(ImpellerStrokeJoin join) { + switch (join) { + case kImpellerStrokeJoinMiter: + return flutter::DlStrokeJoin::kMiter; + case kImpellerStrokeJoinRound: + return flutter::DlStrokeJoin::kRound; + case kImpellerStrokeJoinBevel: + return flutter::DlStrokeJoin::kBevel; + } + return flutter::DlStrokeJoin::kMiter; +} + +constexpr PixelFormat ToImpellerType(ImpellerPixelFormat format) { + switch (format) { + case kImpellerPixelFormatRGBA8888: + return PixelFormat::kR8G8B8A8UNormInt; + } + return PixelFormat::kR8G8B8A8UNormInt; +} + +constexpr ISize ToImpellerType(const ImpellerISize& size) { + return ISize::MakeWH(size.width, size.height); +} + +constexpr flutter::DlColorSpace ToDisplayListType( + ImpellerColorSpace color_space) { + switch (color_space) { + case kImpellerColorSpaceSRGB: + return flutter::DlColorSpace::kSRGB; + case kImpellerColorSpaceExtendedSRGB: + return flutter::DlColorSpace::kExtendedSRGB; + case kImpellerColorSpaceDisplayP3: + return flutter::DlColorSpace::kDisplayP3; + } + return flutter::DlColorSpace::kSRGB; +} + +constexpr flutter::DlColor ToDisplayListType(ImpellerColor color) { + return flutter::DlColor(color.alpha, // + color.red, // + color.green, // + color.blue, // + ToDisplayListType(color.color_space) // + ); +} + +constexpr txt::FontWeight ToTxtType(ImpellerFontWeight weight) { + switch (weight) { + case kImpellerFontWeight100: + return txt::FontWeight::w100; + case kImpellerFontWeight200: + return txt::FontWeight::w200; + case kImpellerFontWeight300: + return txt::FontWeight::w300; + case kImpellerFontWeight400: + return txt::FontWeight::w400; + case kImpellerFontWeight500: + return txt::FontWeight::w500; + case kImpellerFontWeight600: + return txt::FontWeight::w600; + case kImpellerFontWeight700: + return txt::FontWeight::w700; + case kImpellerFontWeight800: + return txt::FontWeight::w800; + case kImpellerFontWeight900: + return txt::FontWeight::w900; + } + return txt::FontWeight::w400; +} + +constexpr txt::FontStyle ToTxtType(ImpellerFontStyle style) { + switch (style) { + case kImpellerFontStyleNormal: + return txt::FontStyle::normal; + case kImpellerFontStyleItalic: + return txt::FontStyle::italic; + } + return txt::FontStyle::normal; +} + +constexpr txt::TextAlign ToTxtType(ImpellerTextAlignment align) { + switch (align) { + case kImpellerTextAlignmentLeft: + return txt::TextAlign::left; + case kImpellerTextAlignmentRight: + return txt::TextAlign::right; + case kImpellerTextAlignmentCenter: + return txt::TextAlign::center; + case kImpellerTextAlignmentJustify: + return txt::TextAlign::justify; + case kImpellerTextAlignmentStart: + return txt::TextAlign::start; + case kImpellerTextAlignmentEnd: + return txt::TextAlign::end; + } + return txt::TextAlign::left; +} + +constexpr txt::TextDirection ToTxtType(ImpellerTextDirection direction) { + switch (direction) { + case kImpellerTextDirectionRTL: + return txt::TextDirection::rtl; + case kImpellerTextDirectionLTR: + return txt::TextDirection::ltr; + } + return txt::TextDirection::ltr; +} + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_FORMATS_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.cc new file mode 100644 index 0000000000000000000000000000000000000000..93eb41ff430da1aa41cf443e6c1dd81adb4de374 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.cc @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/glyph_info.h" + +namespace impeller::interop { + +GlyphInfo::~GlyphInfo() = default; + +size_t GlyphInfo::GetGraphemeClusterCodeUnitRangeBegin() const { + return info_.fGraphemeClusterTextRange.start; +} + +size_t GlyphInfo::GetGraphemeClusterCodeUnitRangeEnd() const { + return info_.fGraphemeClusterTextRange.end; +} + +ImpellerRect GlyphInfo::GetGraphemeClusterBounds() const { + return ImpellerRect{ + info_.fGraphemeLayoutBounds.y(), + info_.fGraphemeLayoutBounds.x(), + info_.fGraphemeLayoutBounds.width(), + info_.fGraphemeLayoutBounds.height(), + }; +} + +bool GlyphInfo::IsEllipsis() const { + return info_.fIsEllipsis; +} + +ImpellerTextDirection GlyphInfo::GetTextDirection() const { + switch (info_.fDirection) { + case skia::textlayout::TextDirection::kRtl: + return kImpellerTextDirectionRTL; + case skia::textlayout::TextDirection::kLtr: + return kImpellerTextDirectionLTR; + } + return kImpellerTextDirectionLTR; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.h b/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.h new file mode 100644 index 0000000000000000000000000000000000000000..0b40e61fcee2e7992f5623e1e39181ffbcc1b991 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/glyph_info.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_GLYPH_INFO_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_GLYPH_INFO_H_ + +#include "flutter/third_party/skia/modules/skparagraph/include/Paragraph.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +//------------------------------------------------------------------------------ +/// @brief Internal C++ peer of ImpellerGlyphInfo. For detailed +/// documentation, refer to the headerdocs in the public API in +/// impeller.h. +/// +class GlyphInfo final + : public Object { + public: + explicit GlyphInfo(skia::textlayout::Paragraph::GlyphInfo info) + : info_(info) {} + + ~GlyphInfo(); + + GlyphInfo(const GlyphInfo&) = delete; + + GlyphInfo& operator=(const GlyphInfo&) = delete; + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin. + /// + size_t GetGraphemeClusterCodeUnitRangeBegin() const; + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd. + /// + size_t GetGraphemeClusterCodeUnitRangeEnd() const; + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterBounds. + /// + ImpellerRect GetGraphemeClusterBounds() const; + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoIsEllipsis. + /// + bool IsEllipsis() const; + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetTextDirection. + /// + ImpellerTextDirection GetTextDirection() const; + + private: + const skia::textlayout::Paragraph::GlyphInfo info_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_GLYPH_INFO_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..4929200483f5af937c12854730b5667389acc9d1 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.cc @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/image_filter.h" + +#include "flutter/display_list/effects/dl_image_filters.h" + +namespace impeller::interop { + +ImageFilter::ImageFilter(std::shared_ptr filter) + : filter_(std::move(filter)) {} + +ImageFilter::~ImageFilter() = default; + +ScopedObject ImageFilter::MakeBlur(Scalar x_sigma, + Scalar y_sigma, + flutter::DlTileMode tile_mode) { + auto filter = flutter::DlBlurImageFilter::Make(x_sigma, y_sigma, tile_mode); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ScopedObject ImageFilter::MakeDilate(Scalar x_radius, + Scalar y_radius) { + auto filter = flutter::DlDilateImageFilter::Make(x_radius, y_radius); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ScopedObject ImageFilter::MakeErode(Scalar x_radius, + Scalar y_radius) { + auto filter = flutter::DlErodeImageFilter::Make(x_radius, y_radius); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ScopedObject ImageFilter::MakeMatrix( + const Matrix& matrix, + flutter::DlImageSampling sampling) { + auto filter = flutter::DlMatrixImageFilter::Make(matrix, sampling); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +ScopedObject ImageFilter::MakeCompose(const ImageFilter& outer, + const ImageFilter& inner) { + auto filter = flutter::DlComposeImageFilter::Make(outer.GetImageFilter(), + inner.GetImageFilter()); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +const std::shared_ptr& ImageFilter::GetImageFilter() + const { + return filter_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.h b/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..4db52f98eb99f25d9b5cef0c97030706d0849b4b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/image_filter.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMAGE_FILTER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMAGE_FILTER_H_ + +#include "flutter/display_list/effects/dl_image_filter.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class ImageFilter final + : public Object { + public: + static ScopedObject MakeBlur(Scalar x_sigma, + Scalar y_sigma, + flutter::DlTileMode tile_mode); + + static ScopedObject MakeDilate(Scalar x_radius, Scalar y_radius); + + static ScopedObject MakeErode(Scalar x_radius, Scalar y_radius); + + static ScopedObject MakeMatrix( + const Matrix& matrix, + flutter::DlImageSampling sampling); + + static ScopedObject MakeCompose(const ImageFilter& outer, + const ImageFilter& inner); + + explicit ImageFilter(std::shared_ptr filter); + + ~ImageFilter() override; + + ImageFilter(const ImageFilter&) = delete; + + ImageFilter& operator=(const ImageFilter&) = delete; + + const std::shared_ptr& GetImageFilter() const; + + private: + std::shared_ptr filter_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMAGE_FILTER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.cc new file mode 100644 index 0000000000000000000000000000000000000000..9913cc1fd17344f74208cbddc9de903a67f35868 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.cc @@ -0,0 +1,1472 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/impeller.h" + +#include + +#include "flutter/fml/mapping.h" +#include "impeller/base/validation.h" +#include "impeller/geometry/scalar.h" +#include "impeller/renderer/backend/gles/context_gles.h" +#include "impeller/renderer/backend/gles/texture_gles.h" +#include "impeller/renderer/context.h" +#include "impeller/toolkit/interop/color_filter.h" +#include "impeller/toolkit/interop/color_source.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/dl_builder.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/glyph_info.h" +#include "impeller/toolkit/interop/image_filter.h" +#include "impeller/toolkit/interop/line_metrics.h" +#include "impeller/toolkit/interop/mask_filter.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/paint.h" +#include "impeller/toolkit/interop/paragraph.h" +#include "impeller/toolkit/interop/paragraph_builder.h" +#include "impeller/toolkit/interop/paragraph_style.h" +#include "impeller/toolkit/interop/path.h" +#include "impeller/toolkit/interop/path_builder.h" +#include "impeller/toolkit/interop/surface.h" +#include "impeller/toolkit/interop/texture.h" +#include "impeller/toolkit/interop/typography_context.h" + +#if IMPELLER_ENABLE_OPENGLES +#include "impeller/toolkit/interop/backend/gles/context_gles.h" +#include "impeller/toolkit/interop/backend/gles/surface_gles.h" +#endif // IMPELLER_ENABLE_OPENGLES + +#if IMPELLER_ENABLE_METAL +#include "impeller/toolkit/interop/backend/metal/context_mtl.h" +#include "impeller/toolkit/interop/backend/metal/surface_mtl.h" +#endif // IMPELLER_ENABLE_METAL + +#if IMPELLER_ENABLE_VULKAN +#include "impeller/toolkit/interop/backend/vulkan/context_vk.h" +#include "impeller/toolkit/interop/backend/vulkan/surface_vk.h" +#include "impeller/toolkit/interop/backend/vulkan/swapchain_vk.h" +#endif // IMPELLER_ENABLE_VULKAN + +namespace impeller::interop { + +#define DEFINE_PEER_GETTER(cxx_type, c_type) \ + cxx_type* GetPeer(c_type object) { \ + return reinterpret_cast(object); \ + } + +DEFINE_PEER_GETTER(ColorFilter, ImpellerColorFilter); +DEFINE_PEER_GETTER(ColorSource, ImpellerColorSource); +DEFINE_PEER_GETTER(Context, ImpellerContext); +DEFINE_PEER_GETTER(DisplayList, ImpellerDisplayList); +DEFINE_PEER_GETTER(DisplayListBuilder, ImpellerDisplayListBuilder); +DEFINE_PEER_GETTER(GlyphInfo, ImpellerGlyphInfo); +DEFINE_PEER_GETTER(ImageFilter, ImpellerImageFilter); +DEFINE_PEER_GETTER(LineMetrics, ImpellerLineMetrics); +DEFINE_PEER_GETTER(MaskFilter, ImpellerMaskFilter); +DEFINE_PEER_GETTER(Paint, ImpellerPaint); +DEFINE_PEER_GETTER(Paragraph, ImpellerParagraph); +DEFINE_PEER_GETTER(ParagraphBuilder, ImpellerParagraphBuilder); +DEFINE_PEER_GETTER(ParagraphStyle, ImpellerParagraphStyle); +DEFINE_PEER_GETTER(Path, ImpellerPath); +DEFINE_PEER_GETTER(PathBuilder, ImpellerPathBuilder); +DEFINE_PEER_GETTER(Surface, ImpellerSurface); +DEFINE_PEER_GETTER(SwapchainVK, ImpellerVulkanSwapchain); +DEFINE_PEER_GETTER(Texture, ImpellerTexture); +DEFINE_PEER_GETTER(TypographyContext, ImpellerTypographyContext); + +static std::string GetVersionAsString(uint32_t version) { + std::stringstream stream; + stream << IMPELLER_VERSION_GET_VARIANT(version) << "." + << IMPELLER_VERSION_GET_MAJOR(version) << "." + << IMPELLER_VERSION_GET_MINOR(version) << "." + << IMPELLER_VERSION_GET_PATCH(version); + return stream.str(); +} + +IMPELLER_EXTERN_C +uint32_t ImpellerGetVersion() { + return IMPELLER_VERSION; +} + +static bool CheckVersion(uint32_t version) { + if (version != IMPELLER_VERSION) { + VALIDATION_LOG << "This version of Impeller (" + << GetVersionAsString(ImpellerGetVersion()) << ") " + << "doesn't match the version the user expects (" + << GetVersionAsString(version) << ")."; + return false; + } + return true; +} + +IMPELLER_EXTERN_C +ImpellerContext ImpellerContextCreateOpenGLESNew( + uint32_t version, + ImpellerProcAddressCallback gl_proc_address_callback, + void* gl_proc_address_callback_user_data) { + if (!CheckVersion(version)) { + return nullptr; + } +#if IMPELLER_ENABLE_OPENGLES + auto context = ContextGLES::Create( + [gl_proc_address_callback, + gl_proc_address_callback_user_data](const char* proc_name) -> void* { + return gl_proc_address_callback(proc_name, + gl_proc_address_callback_user_data); + }); + if (!context || !context->IsValid()) { + VALIDATION_LOG << "Could not create valid context."; + return nullptr; + } + return context.Leak(); +#else // IMPELLER_ENABLE_OPENGLES + VALIDATION_LOG << "OpenGLES not available."; + return nullptr; +#endif // IMPELLER_ENABLE_OPENGLES +} + +IMPELLER_EXTERN_C ImpellerContext ImpellerContextCreateMetalNew( + uint32_t version) { + if (!CheckVersion(version)) { + return nullptr; + } +#if IMPELLER_ENABLE_METAL + auto context = ContextMTL::Create(); + if (!context || !context->IsValid()) { + VALIDATION_LOG << "Could not create valid context."; + return nullptr; + } + return context.Leak(); +#else // IMPELLER_ENABLE_METAL + VALIDATION_LOG << "Metal not available."; + return nullptr; +#endif // IMPELLER_ENABLE_METAL +} + +IMPELLER_EXTERN_C ImpellerContext ImpellerContextCreateVulkanNew( + uint32_t version, + const ImpellerContextVulkanSettings* settings) { + if (!CheckVersion(version)) { + return nullptr; + } +#if IMPELLER_ENABLE_VULKAN + auto context = ContextVK::Create(ContextVK::Settings(*settings)); + if (!context || !context->IsValid()) { + VALIDATION_LOG << "Could not create valid context."; + return nullptr; + } + return context.Leak(); +#else // IMPELLER_ENABLE_VULKAN + VALIDATION_LOG << "Vulkan not available."; + return nullptr; +#endif // IMPELLER_ENABLE_VULKAN +} + +IMPELLER_EXTERN_C +void ImpellerContextRetain(ImpellerContext context) { + ObjectBase::SafeRetain(context); +} + +IMPELLER_EXTERN_C +void ImpellerContextRelease(ImpellerContext context) { + ObjectBase::SafeRelease(context); +} + +IMPELLER_EXTERN_C +bool ImpellerContextGetVulkanInfo(ImpellerContext IMPELLER_NONNULL context, + ImpellerContextVulkanInfo* out_vulkan_info) { +#if IMPELLER_ENABLE_VULKAN + if (!GetPeer(context)->IsVulkan()) { + VALIDATION_LOG << "Not a Vulkan context."; + return false; + } + return reinterpret_cast(GetPeer(context)) + ->GetInfo(*out_vulkan_info); +#else // IMPELLER_ENABLE_VULKAN + VALIDATION_LOG << "Vulkan not available."; + return nullptr; +#endif // IMPELLER_ENABLE_VULKAN +} + +IMPELLER_EXTERN_C +ImpellerVulkanSwapchain ImpellerVulkanSwapchainCreateNew( + ImpellerContext context, + void* vulkan_surface_khr) { +#if IMPELLER_ENABLE_VULKAN + return Create( + *GetPeer(context), // + reinterpret_cast(vulkan_surface_khr) // + ) + .Leak(); +#else // IMPELLER_ENABLE_VULKAN + VALIDATION_LOG << "Vulkan not available."; + return nullptr; +#endif // IMPELLER_ENABLE_VULKAN +} + +IMPELLER_EXTERN_C +void ImpellerVulkanSwapchainRetain(ImpellerVulkanSwapchain swapchain) { + ObjectBase::SafeRetain(swapchain); +} + +IMPELLER_EXTERN_C +void ImpellerVulkanSwapchainRelease(ImpellerVulkanSwapchain swapchain) { + ObjectBase::SafeRelease(swapchain); +} + +IMPELLER_EXTERN_C +ImpellerSurface ImpellerVulkanSwapchainAcquireNextSurfaceNew( + ImpellerVulkanSwapchain swapchain) { + return GetPeer(swapchain)->AcquireNextSurface().Leak(); +} + +IMPELLER_EXTERN_C ImpellerDisplayListBuilder ImpellerDisplayListBuilderNew( + const ImpellerRect* cull_rect) { + return Create(cull_rect).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderRetain(ImpellerDisplayListBuilder builder) { + ObjectBase::SafeRetain(builder); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderRelease(ImpellerDisplayListBuilder builder) { + ObjectBase::SafeRelease(builder); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderSave(ImpellerDisplayListBuilder builder) { + GetPeer(builder)->Save(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderSaveLayer(ImpellerDisplayListBuilder builder, + const ImpellerRect* bounds, + ImpellerPaint paint, + ImpellerImageFilter backdrop) { + GetPeer(builder)->SaveLayer(ToImpellerType(*bounds), // + GetPeer(paint), // + GetPeer(backdrop) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderRestore(ImpellerDisplayListBuilder builder) { + GetPeer(builder)->Restore(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderScale(ImpellerDisplayListBuilder builder, + float x_scale, + float y_scale) { + GetPeer(builder)->Scale(Size{x_scale, y_scale}); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderRotate(ImpellerDisplayListBuilder builder, + float angle_degrees) { + GetPeer(builder)->Rotate(Degrees{angle_degrees}); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderTranslate(ImpellerDisplayListBuilder builder, + float x_translation, + float y_translation) { + GetPeer(builder)->Translate(Point{x_translation, y_translation}); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderSetTransform(ImpellerDisplayListBuilder builder, + const ImpellerMatrix* transform) { + GetPeer(builder)->SetTransform(ToImpellerType(*transform)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderTransform(ImpellerDisplayListBuilder builder, + const ImpellerMatrix* transform) { + GetPeer(builder)->Transform(ToImpellerType(*transform)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderGetTransform(ImpellerDisplayListBuilder builder, + ImpellerMatrix* out_transform) { + FromImpellerType(GetPeer(builder)->GetTransform(), *out_transform); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderResetTransform( + ImpellerDisplayListBuilder builder) { + GetPeer(builder)->ResetTransform(); +} + +IMPELLER_EXTERN_C +uint32_t ImpellerDisplayListBuilderGetSaveCount( + ImpellerDisplayListBuilder builder) { + return GetPeer(builder)->GetSaveCount(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderRestoreToCount( + ImpellerDisplayListBuilder builder, + uint32_t count) { + GetPeer(builder)->RestoreToCount(count); +} + +IMPELLER_EXTERN_C +void ImpellerPathRetain(ImpellerPath path) { + ObjectBase::SafeRetain(path); +} + +IMPELLER_EXTERN_C +void ImpellerPathRelease(ImpellerPath path) { + ObjectBase::SafeRelease(path); +} + +IMPELLER_EXTERN_C +ImpellerPathBuilder ImpellerPathBuilderNew() { + return Create().Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderRetain(ImpellerPathBuilder builder) { + ObjectBase::SafeRetain(builder); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderRelease(ImpellerPathBuilder builder) { + ObjectBase::SafeRelease(builder); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderMoveTo(ImpellerPathBuilder builder, + const ImpellerPoint* location) { + GetPeer(builder)->MoveTo(ToImpellerType(*location)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderLineTo(ImpellerPathBuilder builder, + const ImpellerPoint* location) { + GetPeer(builder)->LineTo(ToImpellerType(*location)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderQuadraticCurveTo(ImpellerPathBuilder builder, + const ImpellerPoint* control_point, + const ImpellerPoint* end_point) { + GetPeer(builder)->QuadraticCurveTo(ToImpellerType(*control_point), + ToImpellerType(*end_point)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderCubicCurveTo(ImpellerPathBuilder builder, + const ImpellerPoint* control_point_1, + const ImpellerPoint* control_point_2, + const ImpellerPoint* end_point) { + GetPeer(builder)->CubicCurveTo(ToImpellerType(*control_point_1), // + ToImpellerType(*control_point_2), // + ToImpellerType(*end_point) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderAddRect(ImpellerPathBuilder builder, + const ImpellerRect* rect) { + GetPeer(builder)->AddRect(ToImpellerType(*rect)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderAddArc(ImpellerPathBuilder builder, + const ImpellerRect* oval_bounds, + float start_angle_degrees, + float end_angle_degrees) { + GetPeer(builder)->AddArc(ToImpellerType(*oval_bounds), // + Degrees{start_angle_degrees}, // + Degrees{end_angle_degrees} // + ); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderAddOval(ImpellerPathBuilder builder, + const ImpellerRect* oval_bounds) { + GetPeer(builder)->AddOval(ToImpellerType(*oval_bounds)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderAddRoundedRect( + ImpellerPathBuilder builder, + const ImpellerRect* rect, + const ImpellerRoundingRadii* rounding_radii) { + GetPeer(builder)->AddRoundedRect(ToImpellerType(*rect), + ToImpellerType(*rounding_radii)); +} + +IMPELLER_EXTERN_C +void ImpellerPathBuilderClose(ImpellerPathBuilder builder) { + GetPeer(builder)->Close(); +} + +IMPELLER_EXTERN_C +ImpellerPath ImpellerPathBuilderCopyPathNew(ImpellerPathBuilder builder, + ImpellerFillType fill) { + return GetPeer(builder)->CopyPath(ToImpellerType(fill)).Leak(); +} + +IMPELLER_EXTERN_C +ImpellerPath ImpellerPathBuilderTakePathNew(ImpellerPathBuilder builder, + ImpellerFillType fill) { + return GetPeer(builder)->TakePath(ToImpellerType(fill)).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderClipRect(ImpellerDisplayListBuilder builder, + const ImpellerRect* rect, + ImpellerClipOperation op) { + GetPeer(builder)->ClipRect(ToImpellerType(*rect), ToImpellerType(op)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderClipOval(ImpellerDisplayListBuilder builder, + const ImpellerRect* oval_bounds, + ImpellerClipOperation op) { + GetPeer(builder)->ClipOval(ToImpellerType(*oval_bounds), ToImpellerType(op)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderClipRoundedRect( + ImpellerDisplayListBuilder builder, + const ImpellerRect* rect, + const ImpellerRoundingRadii* radii, + ImpellerClipOperation op) { + GetPeer(builder)->ClipRoundedRect(ToImpellerType(*rect), // + ToImpellerType(*radii), // + ToImpellerType(op) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderClipPath(ImpellerDisplayListBuilder builder, + ImpellerPath path, + ImpellerClipOperation op) { + GetPeer(builder)->ClipPath(*GetPeer(path), ToImpellerType(op)); +} + +IMPELLER_EXTERN_C +ImpellerPaint ImpellerPaintNew() { + return Create().Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerPaintRetain(ImpellerPaint paint) { + ObjectBase::SafeRetain(paint); +} + +IMPELLER_EXTERN_C +void ImpellerPaintRelease(ImpellerPaint paint) { + ObjectBase::SafeRelease(paint); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetColor(ImpellerPaint paint, const ImpellerColor* color) { + GetPeer(paint)->SetColor(ToDisplayListType(*color)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetBlendMode(ImpellerPaint paint, ImpellerBlendMode mode) { + GetPeer(paint)->SetBlendMode(ToImpellerType(mode)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetDrawStyle(ImpellerPaint paint, ImpellerDrawStyle style) { + GetPeer(paint)->SetDrawStyle(ToDisplayListType(style)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetStrokeCap(ImpellerPaint paint, ImpellerStrokeCap cap) { + GetPeer(paint)->SetStrokeCap(ToDisplayListType(cap)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetStrokeJoin(ImpellerPaint paint, ImpellerStrokeJoin join) { + GetPeer(paint)->SetStrokeJoin(ToDisplayListType(join)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetStrokeWidth(ImpellerPaint paint, float width) { + GetPeer(paint)->SetStrokeWidth(width); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetStrokeMiter(ImpellerPaint paint, float miter) { + GetPeer(paint)->SetStrokeMiter(miter); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawPaint(ImpellerDisplayListBuilder builder, + ImpellerPaint paint) { + GetPeer(builder)->DrawPaint(*GetPeer(paint)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawLine(ImpellerDisplayListBuilder builder, + const ImpellerPoint* from, + const ImpellerPoint* to, + ImpellerPaint paint) { + GetPeer(builder)->DrawLine(ToImpellerType(*from), // + ToImpellerType(*to), // + *GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawDashedLine( + ImpellerDisplayListBuilder builder, + const ImpellerPoint* from, + const ImpellerPoint* to, + float on_length, + float off_length, + ImpellerPaint paint) { + GetPeer(builder)->DrawDashedLine(ToImpellerType(*from), // + ToImpellerType(*to), // + on_length, // + off_length, // + *GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawRect(ImpellerDisplayListBuilder builder, + const ImpellerRect* rect, + ImpellerPaint paint) { + GetPeer(builder)->DrawRect(ToImpellerType(*rect), *GetPeer(paint)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawOval(ImpellerDisplayListBuilder builder, + const ImpellerRect* oval_bounds, + ImpellerPaint paint) { + GetPeer(builder)->DrawOval(ToImpellerType(*oval_bounds), *GetPeer(paint)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawRoundedRect( + ImpellerDisplayListBuilder builder, + const ImpellerRect* rect, + const ImpellerRoundingRadii* radii, + ImpellerPaint paint) { + GetPeer(builder)->DrawRoundedRect(ToImpellerType(*rect), // + ToImpellerType(*radii), // + *GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawRoundedRectDifference( + ImpellerDisplayListBuilder builder, + const ImpellerRect* outer_rect, + const ImpellerRoundingRadii* outer_radii, + const ImpellerRect* inner_rect, + const ImpellerRoundingRadii* inner_radii, + ImpellerPaint paint) { + GetPeer(builder)->DrawRoundedRectDifference(ToImpellerType(*outer_rect), // + ToImpellerType(*outer_radii), // + ToImpellerType(*inner_rect), // + ToImpellerType(*inner_radii), // + *GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawPath(ImpellerDisplayListBuilder builder, + ImpellerPath path, + ImpellerPaint paint) { + GetPeer(builder)->DrawPath(*GetPeer(path), *GetPeer(paint)); +} + +IMPELLER_EXTERN_C +ImpellerTexture ImpellerTextureCreateWithContentsNew( + ImpellerContext context, + const ImpellerTextureDescriptor* descriptor, + const ImpellerMapping* contents, + void* contents_on_release_user_data) { + TextureDescriptor desc; + desc.storage_mode = StorageMode::kHostVisible; + desc.type = TextureType::kTexture2D; + desc.format = ToImpellerType(descriptor->pixel_format); + desc.size = ToImpellerType(descriptor->size); + desc.mip_count = std::min(descriptor->mip_count, 1u); + desc.usage = TextureUsage::kShaderRead; + desc.compression_type = CompressionType::kLossless; + auto texture = Create(*GetPeer(context), desc); + if (!texture->IsValid()) { + VALIDATION_LOG << "Could not create texture."; + return nullptr; + } + // Depending on whether the de-allocation can be delayed, it may be possible + // to avoid a data copy. + if (contents->on_release) { + // Avoids data copy. + auto wrapped_contents = std::make_shared( + contents->data, // data ptr + contents->length, // data length + [on_release = contents->on_release, contents_on_release_user_data]( + auto, auto) { + on_release(contents_on_release_user_data); + } // release callback + ); + if (!texture->SetContents(std::move(wrapped_contents))) { + VALIDATION_LOG << "Could not set texture contents."; + return nullptr; + } + } else { + // May copy. + if (!texture->SetContents(contents->data, contents->length)) { + VALIDATION_LOG << "Could not set texture contents."; + return nullptr; + } + } + return texture.Leak(); +} + +IMPELLER_EXTERN_C +ImpellerTexture ImpellerTextureCreateWithOpenGLTextureHandleNew( + ImpellerContext context, + const ImpellerTextureDescriptor* descriptor, + uint64_t external_gl_handle) { + auto impeller_context = GetPeer(context)->GetContext(); + if (impeller_context->GetBackendType() != + impeller::Context::BackendType::kOpenGLES) { + VALIDATION_LOG << "Context is not OpenGL."; + return nullptr; + } + + const auto& impeller_context_gl = + impeller::ContextGLES::Cast(*impeller_context); + const auto& reactor = impeller_context_gl.GetReactor(); + + TextureDescriptor desc; + desc.storage_mode = StorageMode::kDevicePrivate; + desc.type = TextureType::kTexture2D; + desc.format = ToImpellerType(descriptor->pixel_format); + desc.size = ToImpellerType(descriptor->size); + desc.mip_count = std::min(descriptor->mip_count, 1u); + desc.usage = TextureUsage::kShaderRead; + desc.compression_type = CompressionType::kLossless; + + auto texture = TextureGLES::WrapTexture( + reactor, // + desc, // + reactor->CreateHandle(HandleType::kTexture, external_gl_handle) // + ); + if (!texture || !texture->IsValid()) { + VALIDATION_LOG << "Could not wrap external texture."; + return nullptr; + } + texture->SetCoordinateSystem(TextureCoordinateSystem::kUploadFromHost); + return Create(impeller::Context::BackendType::kOpenGLES, + std::move(texture)) + .Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerTextureRetain(ImpellerTexture texture) { + ObjectBase::SafeRetain(texture); +} + +IMPELLER_EXTERN_C +void ImpellerTextureRelease(ImpellerTexture texture) { + ObjectBase::SafeRelease(texture); +} + +IMPELLER_EXTERN_C +uint64_t ImpellerTextureGetOpenGLHandle(ImpellerTexture texture) { + auto interop_texture = GetPeer(texture); + if (interop_texture->GetBackendType() != + impeller::Context::BackendType::kOpenGLES) { + VALIDATION_LOG << "Can only fetch the texture handle of an OpenGL texture."; + return 0u; + } + return TextureGLES::Cast(*interop_texture->GetTexture()) + .GetGLHandle() + .value_or(0u); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListRetain(ImpellerDisplayList display_list) { + ObjectBase::SafeRetain(display_list); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListRelease(ImpellerDisplayList display_list) { + ObjectBase::SafeRelease(display_list); +} + +IMPELLER_EXTERN_C +ImpellerDisplayList ImpellerDisplayListBuilderCreateDisplayListNew( + ImpellerDisplayListBuilder builder) { + auto dl = GetPeer(builder)->Build(); + if (!dl->IsValid()) { + return nullptr; + } + return dl.Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawDisplayList( + ImpellerDisplayListBuilder builder, + ImpellerDisplayList display_list, + float opacity) { + GetPeer(builder)->DrawDisplayList(*GetPeer(display_list), opacity); +} + +IMPELLER_EXTERN_C +ImpellerSurface ImpellerSurfaceCreateWrappedFBONew(ImpellerContext context, + uint64_t fbo, + ImpellerPixelFormat format, + const ImpellerISize* size) { +#if IMPELLER_ENABLE_OPENGLES + if (!GetPeer(context)->IsGL()) { + VALIDATION_LOG << "Context is not OpenGL."; + return nullptr; + } + return Create(*GetPeer(context), // + fbo, // + ToImpellerType(format), // + ToImpellerType(*size)) // + .Leak(); +#else // IMPELLER_ENABLE_OPENGLES + VALIDATION_LOG << "OpenGL unavailable."; + return nullptr; +#endif // IMPELLER_ENABLE_OPENGLES +} + +IMPELLER_EXTERN_C +ImpellerSurface ImpellerSurfaceCreateWrappedMetalDrawableNew( + ImpellerContext context, + void* metal_drawable) { +#if IMPELLER_ENABLE_METAL + if (!GetPeer(context)->IsMetal()) { + VALIDATION_LOG << "Context is not Metal."; + return nullptr; + } + return Create(*GetPeer(context), metal_drawable).Leak(); +#else // IMPELLER_ENABLE_METAL + VALIDATION_LOG << "Metal unavailable."; + return nullptr; +#endif // IMPELLER_ENABLE_METAL +} + +IMPELLER_EXTERN_C void ImpellerSurfaceRetain(ImpellerSurface surface) { + ObjectBase::SafeRetain(surface); +} + +IMPELLER_EXTERN_C +void ImpellerSurfaceRelease(ImpellerSurface surface) { + ObjectBase::SafeRelease(surface); +} + +IMPELLER_EXTERN_C +bool ImpellerSurfaceDrawDisplayList(ImpellerSurface surface, + ImpellerDisplayList display_list) { + return GetPeer(surface)->DrawDisplayList(*GetPeer(display_list)); +} + +IMPELLER_EXTERN_C +bool ImpellerSurfacePresent(ImpellerSurface surface) { + return GetPeer(surface)->Present(); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawTexture(ImpellerDisplayListBuilder builder, + ImpellerTexture texture, + const ImpellerPoint* point, + ImpellerTextureSampling sampling, + ImpellerPaint paint) { + GetPeer(builder)->DrawTexture(*GetPeer(texture), // + ToImpellerType(*point), // + ToDisplayListType(sampling), // + GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawTextureRect( + ImpellerDisplayListBuilder builder, + ImpellerTexture texture, + const ImpellerRect* src_rect, + const ImpellerRect* dst_rect, + ImpellerTextureSampling sampling, + ImpellerPaint paint) { + GetPeer(builder)->DrawTextureRect(*GetPeer(texture), // + ToImpellerType(*src_rect), // + ToImpellerType(*dst_rect), // + ToDisplayListType(sampling), // + GetPeer(paint) // + ); +} + +IMPELLER_EXTERN_C +void ImpellerColorSourceRetain(ImpellerColorSource color_source) { + ObjectBase::SafeRetain(color_source); +} + +IMPELLER_EXTERN_C +void ImpellerColorSourceRelease(ImpellerColorSource color_source) { + ObjectBase::SafeRelease(color_source); +} + +static std::pair, std::vector> +ParseColorsAndStops(uint32_t stop_count, + const ImpellerColor* colors, + const float* stops) { + if (stop_count == 0) { + return {}; + } + std::pair, std::vector> result; + result.first.reserve(stop_count); + result.second.reserve(stop_count); + for (size_t i = 0; i < stop_count; i++) { + result.first.emplace_back(ToDisplayListType(colors[i])); + result.second.emplace_back(stops[i]); + } + return result; +} + +IMPELLER_EXTERN_C +ImpellerColorSource ImpellerColorSourceCreateLinearGradientNew( + const ImpellerPoint* start_point, + const ImpellerPoint* end_point, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation) { + const auto colors_and_stops = ParseColorsAndStops(stop_count, colors, stops); + return ColorSource::MakeLinearGradient( + ToImpellerType(*start_point), // + ToImpellerType(*end_point), // + colors_and_stops.first, // + colors_and_stops.second, // + ToDisplayListType(tile_mode), // + transformation == nullptr ? Matrix{} + : ToImpellerType(*transformation) // + ) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerColorSource ImpellerColorSourceCreateRadialGradientNew( + const ImpellerPoint* center, + float radius, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation) { + const auto colors_and_stops = ParseColorsAndStops(stop_count, colors, stops); + return ColorSource::MakeRadialGradient( + ToImpellerType(*center), // + radius, // + colors_and_stops.first, // + colors_and_stops.second, // + ToDisplayListType(tile_mode), // + transformation == nullptr ? Matrix{} + : ToImpellerType(*transformation) // + ) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerColorSource ImpellerColorSourceCreateConicalGradientNew( + const ImpellerPoint* start_center, + float start_radius, + const ImpellerPoint* end_center, + float end_radius, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation) { + const auto colors_and_stops = ParseColorsAndStops(stop_count, colors, stops); + return ColorSource::MakeConicalGradient( + ToImpellerType(*start_center), // + start_radius, // + ToImpellerType(*end_center), // + end_radius, // + colors_and_stops.first, // + colors_and_stops.second, // + ToDisplayListType(tile_mode), // + transformation == nullptr ? Matrix{} + : ToImpellerType(*transformation) // + ) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerColorSource ImpellerColorSourceCreateSweepGradientNew( + const ImpellerPoint* center, + float start, + float end, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation) { + const auto colors_and_stops = ParseColorsAndStops(stop_count, colors, stops); + return ColorSource::MakeSweepGradient( + ToImpellerType(*center), // + start, // + end, // + colors_and_stops.first, // + colors_and_stops.second, // + ToDisplayListType(tile_mode), // + transformation == nullptr ? Matrix{} + : ToImpellerType(*transformation) // + ) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerColorSource ImpellerColorSourceCreateImageNew( + ImpellerTexture image, + ImpellerTileMode horizontal_tile_mode, + ImpellerTileMode vertical_tile_mode, + ImpellerTextureSampling sampling, + const ImpellerMatrix* transformation) { + return ColorSource::MakeImage( + *GetPeer(image), // + ToDisplayListType(horizontal_tile_mode), // + ToDisplayListType(vertical_tile_mode), // + ToDisplayListType(sampling), // + transformation == nullptr ? Matrix{} + : ToImpellerType(*transformation) // + ) + .Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerColorFilterRetain(ImpellerColorFilter color_filter) { + ObjectBase::SafeRetain(color_filter); +} + +IMPELLER_EXTERN_C +void ImpellerColorFilterRelease(ImpellerColorFilter color_filter) { + ObjectBase::SafeRelease(color_filter); +} + +IMPELLER_EXTERN_C +ImpellerColorFilter ImpellerColorFilterCreateBlendNew( + const ImpellerColor* color, + ImpellerBlendMode blend_mode) { + return ColorFilter::MakeBlend(ToImpellerType(*color), + ToImpellerType(blend_mode)) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerColorFilter ImpellerColorFilterCreateColorMatrixNew( + const ImpellerColorMatrix* color_matrix) { + return ColorFilter::MakeMatrix(color_matrix->m).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerMaskFilterRetain(ImpellerMaskFilter mask_filter) { + ObjectBase::SafeRetain(mask_filter); +} + +IMPELLER_EXTERN_C +void ImpellerMaskFilterRelease(ImpellerMaskFilter mask_filter) { + ObjectBase::SafeRelease(mask_filter); +} + +IMPELLER_EXTERN_C +ImpellerMaskFilter ImpellerMaskFilterCreateBlurNew(ImpellerBlurStyle style, + float sigma) { + return MaskFilter::MakeBlur(ToDisplayListType(style), sigma).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerImageFilterRetain(ImpellerImageFilter image_filter) { + ObjectBase::SafeRetain(image_filter); +} + +IMPELLER_EXTERN_C +void ImpellerImageFilterRelease(ImpellerImageFilter image_filter) { + ObjectBase::SafeRelease(image_filter); +} + +IMPELLER_EXTERN_C +ImpellerImageFilter ImpellerImageFilterCreateBlurNew( + float x_sigma, + float y_sigma, + ImpellerTileMode tile_mode) { + return ImageFilter::MakeBlur(x_sigma, y_sigma, ToDisplayListType(tile_mode)) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerImageFilter ImpellerImageFilterCreateDilateNew(float x_radius, + float y_radius) { + return ImageFilter::MakeDilate(x_radius, y_radius).Leak(); +} + +IMPELLER_EXTERN_C +ImpellerImageFilter ImpellerImageFilterCreateErodeNew(float x_radius, + float y_radius) { + return ImageFilter::MakeErode(x_radius, y_radius).Leak(); +} + +IMPELLER_EXTERN_C +ImpellerImageFilter ImpellerImageFilterCreateMatrixNew( + const ImpellerMatrix* matrix, + ImpellerTextureSampling sampling) { + return ImageFilter::MakeMatrix(ToImpellerType(*matrix), + ToDisplayListType(sampling)) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerImageFilter ImpellerImageFilterCreateComposeNew( + ImpellerImageFilter outer, + ImpellerImageFilter inner) { + return ImageFilter::MakeCompose(*GetPeer(outer), *GetPeer(inner)).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetColorFilter(ImpellerPaint paint, + ImpellerColorFilter color_filter) { + GetPeer(paint)->SetColorFilter(*GetPeer(color_filter)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetColorSource(ImpellerPaint paint, + ImpellerColorSource color_source) { + GetPeer(paint)->SetColorSource(*GetPeer(color_source)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetImageFilter(ImpellerPaint paint, + ImpellerImageFilter image_filter) { + GetPeer(paint)->SetImageFilter(*GetPeer(image_filter)); +} + +IMPELLER_EXTERN_C +void ImpellerPaintSetMaskFilter(ImpellerPaint paint, + ImpellerMaskFilter mask_filter) { + GetPeer(paint)->SetMaskFilter(*GetPeer(mask_filter)); +} + +IMPELLER_EXTERN_C +ImpellerParagraphStyle ImpellerParagraphStyleNew() { + return Create().Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleRetain(ImpellerParagraphStyle paragraph_style) { + ObjectBase::SafeRetain(paragraph_style); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleRelease(ImpellerParagraphStyle paragraph_style) { + ObjectBase::SafeRelease(paragraph_style); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetForeground(ImpellerParagraphStyle paragraph_style, + ImpellerPaint paint) { + GetPeer(paragraph_style)->SetForeground(Ref(GetPeer(paint))); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetBackground(ImpellerParagraphStyle paragraph_style, + ImpellerPaint paint) { + GetPeer(paragraph_style)->SetBackground(Ref(GetPeer(paint))); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetFontWeight(ImpellerParagraphStyle paragraph_style, + ImpellerFontWeight weight) { + GetPeer(paragraph_style)->SetFontWeight(ToTxtType(weight)); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetFontStyle(ImpellerParagraphStyle paragraph_style, + ImpellerFontStyle style) { + GetPeer(paragraph_style)->SetFontStyle(ToTxtType(style)); +} + +static std::string ReadString(const char* string) { + if (string == nullptr) { + return ""; + } + return std::string{string}; +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetFontFamily(ImpellerParagraphStyle paragraph_style, + const char* family_name) { + GetPeer(paragraph_style)->SetFontFamily(ReadString(family_name)); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetFontSize(ImpellerParagraphStyle paragraph_style, + float size) { + GetPeer(paragraph_style)->SetFontSize(size); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetHeight(ImpellerParagraphStyle paragraph_style, + float height) { + GetPeer(paragraph_style)->SetHeight(height); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetTextAlignment( + ImpellerParagraphStyle paragraph_style, + ImpellerTextAlignment align) { + GetPeer(paragraph_style)->SetTextAlignment(ToTxtType(align)); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetTextDirection( + ImpellerParagraphStyle paragraph_style, + ImpellerTextDirection direction) { + GetPeer(paragraph_style)->SetTextDirection(ToTxtType(direction)); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetMaxLines(ImpellerParagraphStyle paragraph_style, + uint32_t max_lines) { + GetPeer(paragraph_style)->SetMaxLines(max_lines); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphStyleSetLocale(ImpellerParagraphStyle paragraph_style, + const char* locale) { + GetPeer(paragraph_style)->SetLocale(ReadString(locale)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawParagraph(ImpellerDisplayListBuilder builder, + ImpellerParagraph paragraph, + const ImpellerPoint* point) { + GetPeer(builder)->DrawParagraph(*GetPeer(paragraph), ToImpellerType(*point)); +} + +IMPELLER_EXTERN_C +void ImpellerDisplayListBuilderDrawShadow(ImpellerDisplayListBuilder builder, + ImpellerPath path, + const ImpellerColor* color, + float elevation, + bool occluder_is_transparent, + float device_pixel_ratio) { + GetPeer(builder)->DrawShadow(*GetPeer(path), // + ToDisplayListType(*color), // + elevation, // + occluder_is_transparent, // + device_pixel_ratio // + ); +} + +IMPELLER_EXTERN_C +ImpellerParagraphBuilder ImpellerParagraphBuilderNew( + ImpellerTypographyContext context) { + auto builder = + Create(Ref(GetPeer(context))); + if (!builder->IsValid()) { + VALIDATION_LOG << "Could not create valid paragraph builder."; + return nullptr; + } + return builder.Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphBuilderRetain( + ImpellerParagraphBuilder paragraph_builder) { + ObjectBase::SafeRetain(paragraph_builder); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphBuilderRelease( + ImpellerParagraphBuilder paragraph_builder) { + ObjectBase::SafeRelease(paragraph_builder); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphBuilderPushStyle( + ImpellerParagraphBuilder paragraph_builder, + ImpellerParagraphStyle style) { + GetPeer(paragraph_builder)->PushStyle(*GetPeer(style)); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphBuilderPopStyle( + ImpellerParagraphBuilder paragraph_builder) { + GetPeer(paragraph_builder)->PopStyle(); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphBuilderAddText(ImpellerParagraphBuilder paragraph_builder, + const uint8_t* data, + uint32_t length) { + if (data == nullptr) { + length = 0; + } + if (length == 0) { + return; + } + GetPeer(paragraph_builder)->AddText(data, length); +} + +IMPELLER_EXTERN_C +ImpellerParagraph ImpellerParagraphBuilderBuildParagraphNew( + ImpellerParagraphBuilder paragraph_builder, + float width) { + return GetPeer(paragraph_builder)->Build(width).Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphRetain(ImpellerParagraph paragraph) { + ObjectBase::SafeRetain(paragraph); +} + +IMPELLER_EXTERN_C +void ImpellerParagraphRelease(ImpellerParagraph paragraph) { + ObjectBase::SafeRelease(paragraph); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetMaxWidth(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetMaxWidth(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetHeight(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetHeight(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetLongestLineWidth(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetLongestLineWidth(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetMinIntrinsicWidth(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetMinIntrinsicWidth(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetMaxIntrinsicWidth(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetMaxIntrinsicWidth(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetIdeographicBaseline(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetIdeographicBaseline(); +} + +IMPELLER_EXTERN_C +float ImpellerParagraphGetAlphabeticBaseline(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetAlphabeticBaseline(); +} + +IMPELLER_EXTERN_C +uint32_t ImpellerParagraphGetLineCount(ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetLineCount(); +} + +IMPELLER_EXTERN_C +ImpellerRange ImpellerParagraphGetWordBoundary(ImpellerParagraph paragraph, + size_t code_unit_index) { + return GetPeer(paragraph)->GetWordBoundary(code_unit_index); +} + +IMPELLER_EXTERN_C +ImpellerTypographyContext ImpellerTypographyContextNew() { + auto context = Create(); + if (!context->IsValid()) { + VALIDATION_LOG << "Could not create typography context."; + return nullptr; + } + return context.Leak(); +} + +IMPELLER_EXTERN_C +void ImpellerTypographyContextRetain(ImpellerTypographyContext context) { + ObjectBase::SafeRetain(context); +} + +IMPELLER_EXTERN_C +void ImpellerTypographyContextRelease(ImpellerTypographyContext context) { + ObjectBase::SafeRelease(context); +} + +IMPELLER_EXTERN_C +bool ImpellerTypographyContextRegisterFont(ImpellerTypographyContext context, + const ImpellerMapping* contents, + void* contents_on_release_user_data, + const char* family_name_alias) { + auto wrapped_contents = std::make_unique( + contents->data, // data ptr + contents->length, // data length + [on_release = contents->on_release, contents_on_release_user_data](auto, + auto) { + on_release(contents_on_release_user_data); + } // release callback + ); + return GetPeer(context)->RegisterFont(std::move(wrapped_contents), + family_name_alias); +} + +IMPELLER_EXTERN_C +ImpellerLineMetrics ImpellerParagraphGetLineMetrics( + ImpellerParagraph paragraph) { + return GetPeer(paragraph)->GetLineMetrics().GetC(); +} + +IMPELLER_EXTERN_C +ImpellerGlyphInfo ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew( + ImpellerParagraph paragraph, + size_t code_unit_index) { + return GetPeer(paragraph) + ->GetGlyphInfoAtCodeUnitIndex(code_unit_index) + .Leak(); +} + +IMPELLER_EXTERN_C +ImpellerGlyphInfo ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew( + ImpellerParagraph paragraph, + double x, + double y) { + return GetPeer(paragraph) + ->GetClosestGlyphInfoAtParagraphCoordinates(x, y) + .Leak(); +} + +//------------------------------------------------------------------------------ +// Line Metrics +//------------------------------------------------------------------------------ + +IMPELLER_EXTERN_C +void ImpellerLineMetricsRetain(ImpellerLineMetrics line_metrics) { + ObjectBase::SafeRetain(line_metrics); +} + +IMPELLER_EXTERN_C +void ImpellerLineMetricsRelease(ImpellerLineMetrics line_metrics) { + ObjectBase::SafeRelease(line_metrics); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetUnscaledAscent(ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetUnscaledAscent(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetAscent(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->GetAscent(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetDescent(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->GetDescent(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetBaseline(ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetBaseline(line); +} + +IMPELLER_EXTERN_C +bool ImpellerLineMetricsIsHardbreak(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->IsHardbreak(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetWidth(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->GetWidth(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetHeight(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->GetHeight(line); +} + +IMPELLER_EXTERN_C +double ImpellerLineMetricsGetLeft(ImpellerLineMetrics metrics, size_t line) { + return GetPeer(metrics)->GetLeft(line); +} + +IMPELLER_EXTERN_C +size_t ImpellerLineMetricsGetCodeUnitStartIndex(ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetCodeUnitStartIndex(line); +} + +IMPELLER_EXTERN_C +size_t ImpellerLineMetricsGetCodeUnitEndIndex(ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetCodeUnitEndIndex(line); +} + +IMPELLER_EXTERN_C +size_t ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace( + ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetCodeUnitEndIndexExcludingWhitespace(line); +} + +IMPELLER_EXTERN_C +size_t ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline( + ImpellerLineMetrics metrics, + size_t line) { + return GetPeer(metrics)->GetCodeUnitEndIndexIncludingNewline(line); +} + +//------------------------------------------------------------------------------ +// Glyph Info +//------------------------------------------------------------------------------ + +IMPELLER_EXTERN_C +void ImpellerGlyphInfoRetain(ImpellerGlyphInfo glyph_info) { + ObjectBase::SafeRetain(glyph_info); +} + +IMPELLER_EXTERN_C +void ImpellerGlyphInfoRelease(ImpellerGlyphInfo glyph_info) { + ObjectBase::SafeRelease(glyph_info); +} + +IMPELLER_EXTERN_C +size_t ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin( + ImpellerGlyphInfo glyph_info) { + return GetPeer(glyph_info)->GetGraphemeClusterCodeUnitRangeBegin(); +} + +IMPELLER_EXTERN_C +size_t ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd( + ImpellerGlyphInfo glyph_info) { + return GetPeer(glyph_info)->GetGraphemeClusterCodeUnitRangeEnd(); +} + +IMPELLER_EXTERN_C +ImpellerRect ImpellerGlyphInfoGetGraphemeClusterBounds( + ImpellerGlyphInfo glyph_info) { + return GetPeer(glyph_info)->GetGraphemeClusterBounds(); +} + +IMPELLER_EXTERN_C +bool ImpellerGlyphInfoIsEllipsis(ImpellerGlyphInfo glyph_info) { + return GetPeer(glyph_info)->IsEllipsis(); +} + +IMPELLER_EXTERN_C +ImpellerTextDirection ImpellerGlyphInfoGetTextDirection( + ImpellerGlyphInfo glyph_info) { + return GetPeer(glyph_info)->GetTextDirection(); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.h b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.h new file mode 100644 index 0000000000000000000000000000000000000000..5f1b4589abc7aca46d1d2034163665462df9459c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.h @@ -0,0 +1,2965 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_H_ + +// NOLINTBEGIN(google-objc-function-naming) + +#include +#include +#include + +///----------------------------------------------------------------------------- +///----------------------------------------------------------------------------- +/// ------- ___ _ _ _ ____ ___ -------- +/// ------- |_ _|_ __ ___ _ __ ___| | | ___ _ __ / \ | _ \_ _| -------- +/// ------- | || '_ ` _ \| '_ \ / _ \ | |/ _ \ '__| / _ \ | |_) | | -------- +/// ------- | || | | | | | |_) | __/ | | __/ | / ___ \| __/| | -------- +/// ------- |___|_| |_| |_| .__/ \___|_|_|\___|_| /_/ \_\_| |___| -------- +/// ------- |_| -------- +///----------------------------------------------------------------------------- +///----------------------------------------------------------------------------- +/// +/// This file describes a high-level, single-header, dependency-free, 2D +/// graphics API. +/// +/// The API fundamentals that include details about the object model, reference +/// counting, and null-safety are described in the README. +/// +#if defined(__cplusplus) +#define IMPELLER_EXTERN_C extern "C" +#define IMPELLER_EXTERN_C_BEGIN IMPELLER_EXTERN_C { +#define IMPELLER_EXTERN_C_END } +#else // defined(__cplusplus) +#define IMPELLER_EXTERN_C +#define IMPELLER_EXTERN_C_BEGIN +#define IMPELLER_EXTERN_C_END +#endif // defined(__cplusplus) + +#ifdef _WIN32 +#define IMPELLER_EXPORT_DECORATION __declspec(dllexport) +#else +#define IMPELLER_EXPORT_DECORATION __attribute__((visibility("default"))) +#endif + +#ifndef IMPELLER_NO_EXPORT +#define IMPELLER_EXPORT IMPELLER_EXPORT_DECORATION +#else // IMPELLER_NO_EXPORT +#define IMPELLER_EXPORT +#endif // IMPELLER_NO_EXPORT + +#ifdef __clang__ +#define IMPELLER_NULLABLE _Nullable +#define IMPELLER_NONNULL _Nonnull +#else // __clang__ +#define IMPELLER_NULLABLE +#define IMPELLER_NONNULL +#endif // __clang__ + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202000L) +#define IMPELLER_NODISCARD [[nodiscard]] +#else // defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202000L) +#define IMPELLER_NODISCARD +#endif // defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202000L) + +IMPELLER_EXTERN_C_BEGIN + +//------------------------------------------------------------------------------ +/// @brief Pack a version in a uint32_t. +/// +/// @param[in] variant The version variant. +/// @param[in] major The major version. +/// @param[in] minor The minor version. +/// @param[in] patch The patch version. +/// +/// @return The packed version number. +/// +#define IMPELLER_MAKE_VERSION(variant, major, minor, patch) \ + ((((uint32_t)(variant)) << 29U) | (((uint32_t)(major)) << 22U) | \ + (((uint32_t)(minor)) << 12U) | ((uint32_t)(patch))) + +#define IMPELLER_VERSION_VARIANT 1 +#define IMPELLER_VERSION_MAJOR 1 +#define IMPELLER_VERSION_MINOR 3 +#define IMPELLER_VERSION_PATCH 0 + +//------------------------------------------------------------------------------ +/// The current Impeller API version. +/// +/// This version must be passed to APIs that create top-level objects like +/// graphics contexts. Construction of the context may fail if the API version +/// expected by the caller is not supported by the library. +/// +/// The version currently supported by the library is returned by a call to +/// `ImpellerGetVersion` +/// +/// Since there are no API stability guarantees today, passing a version that is +/// different to the one returned by `ImpellerGetVersion` will always fail. +/// +/// @see `ImpellerGetVersion` +/// +#define IMPELLER_VERSION \ + IMPELLER_MAKE_VERSION(IMPELLER_VERSION_VARIANT, IMPELLER_VERSION_MAJOR, \ + IMPELLER_VERSION_MINOR, IMPELLER_VERSION_PATCH) + +//------------------------------------------------------------------------------ +/// @param[in] version The packed version. +/// +/// @return The version variant. +/// +#define IMPELLER_VERSION_GET_VARIANT(version) ((uint32_t)(version) >> 29U) + +//------------------------------------------------------------------------------ +/// @param[in] version The packed version. +/// +/// @return The major version. +/// +#define IMPELLER_VERSION_GET_MAJOR(version) \ + (((uint32_t)(version) >> 22U) & 0x7FU) + +//------------------------------------------------------------------------------ +/// @param[in] version The packed version. +/// +/// @return The minor version. +/// +#define IMPELLER_VERSION_GET_MINOR(version) \ + (((uint32_t)(version) >> 12U) & 0x3FFU) + +//------------------------------------------------------------------------------ +/// @param[in] version The packed version. +/// +/// @return The patch version. +/// +#define IMPELLER_VERSION_GET_PATCH(version) ((uint32_t)(version) & 0xFFFU) + +//------------------------------------------------------------------------------ +// Handles +//------------------------------------------------------------------------------ + +#define IMPELLER_INTERNAL_HANDLE_NAME(handle) handle##_ +#define IMPELLER_DEFINE_HANDLE(handle) \ + typedef struct IMPELLER_INTERNAL_HANDLE_NAME(handle) * handle; + +//------------------------------------------------------------------------------ +/// An Impeller graphics context. Contexts are platform and client-rendering-API +/// specific. +/// +/// Contexts are thread-safe objects that are expensive to create. Most +/// applications will only ever create a single context during their lifetimes. +/// Once setup, Impeller is ready to render frames as performantly as possible. +/// +/// During setup, context create the underlying graphics pipelines, allocators, +/// worker threads, etc... +/// +/// The general guidance is to create as few contexts as possible (typically +/// just one) and share them as much as possible. +/// +IMPELLER_DEFINE_HANDLE(ImpellerContext); + +//------------------------------------------------------------------------------ +/// Display lists represent encoded rendering intent. These objects are +/// immutable, reusable, thread-safe, and context-agnostic. +/// +/// While it is perfectly fine to create new display lists per frame, there may +/// be opportunities for optimization when display lists are reused multiple +/// times. +/// +IMPELLER_DEFINE_HANDLE(ImpellerDisplayList); + +//------------------------------------------------------------------------------ +/// Display list builders allow for the incremental creation of display lists. +/// +/// Display list builders are context-agnostic. +/// +IMPELLER_DEFINE_HANDLE(ImpellerDisplayListBuilder); + +//------------------------------------------------------------------------------ +/// Paints control the behavior of draw calls encoded in a display list. +/// +/// Like display lists, paints are context-agnostic. +/// +IMPELLER_DEFINE_HANDLE(ImpellerPaint); + +//------------------------------------------------------------------------------ +/// Color filters are functions that take two colors and mix them to produce a +/// single color. This color is then merged with the destination during +/// blending. +/// +IMPELLER_DEFINE_HANDLE(ImpellerColorFilter); + +//------------------------------------------------------------------------------ +/// Color sources are functions that generate colors for each texture element +/// covered by a draw call. The colors for each element can be generated using a +/// mathematical function (to produce gradients for example) or sampled from a +/// texture. +/// +IMPELLER_DEFINE_HANDLE(ImpellerColorSource); + +//------------------------------------------------------------------------------ +/// Image filters are functions that are applied regions of a texture to produce +/// a single color. Contrast this with color filters that operate independently +/// on a per-pixel basis. The generated color is then merged with the +/// destination during blending. +/// +IMPELLER_DEFINE_HANDLE(ImpellerImageFilter); + +//------------------------------------------------------------------------------ +/// Mask filters are functions that are applied over a shape after it has been +/// drawn but before it has been blended into the final image. +/// +IMPELLER_DEFINE_HANDLE(ImpellerMaskFilter); + +//------------------------------------------------------------------------------ +/// Typography contexts allow for the layout and rendering of text. +/// +/// These are typically expensive to create and applications will only ever need +/// to create a single one of these during their lifetimes. +/// +/// Unlike graphics context, typograhy contexts are not thread-safe. These must +/// be created, used, and collected on a single thread. +/// +IMPELLER_DEFINE_HANDLE(ImpellerTypographyContext); + +//------------------------------------------------------------------------------ +/// An immutable, fully laid out paragraph. +/// +IMPELLER_DEFINE_HANDLE(ImpellerParagraph); + +//------------------------------------------------------------------------------ +/// Paragraph builders allow for the creation of fully laid out paragraphs +/// (which themselves are immutable). +/// +/// To build a paragraph, users push/pop paragraph styles onto a stack then add +/// UTF-8 encoded text. The properties on the top of paragraph style stack when +/// the text is added are used to layout and shape that subset of the paragraph. +/// +/// @see `ImpellerParagraphStyle` +/// +IMPELLER_DEFINE_HANDLE(ImpellerParagraphBuilder); + +//------------------------------------------------------------------------------ +/// Specified when building a paragraph, paragraph styles are managed in a stack +/// with specify text properties to apply to text that is added to the paragraph +/// builder. +/// +IMPELLER_DEFINE_HANDLE(ImpellerParagraphStyle); + +//------------------------------------------------------------------------------ +/// Describes the metrics of lines in a fully laid out paragraph. +/// +/// Regardless of how the string of text is specified to the paragraph builder, +/// offsets into buffers that are returned by line metrics are always assumed to +/// be into buffers of UTF-16 code units. +/// +IMPELLER_DEFINE_HANDLE(ImpellerLineMetrics); + +//------------------------------------------------------------------------------ +/// Describes the metrics of glyphs in a paragraph line. +/// +IMPELLER_DEFINE_HANDLE(ImpellerGlyphInfo); + +//------------------------------------------------------------------------------ +/// Represents a two-dimensional path that is immutable and graphics context +/// agnostic. +/// +/// Paths in Impeller consist of linear, cubic Bézier curve, and quadratic +/// Bézier curve segments. All other shapes are approximations using these +/// building blocks. +/// +/// Paths are created using path builder that allow for the configuration of the +/// path segments, how they are filled, and/or stroked. +/// +IMPELLER_DEFINE_HANDLE(ImpellerPath); + +//------------------------------------------------------------------------------ +/// Path builders allow for the incremental building up of paths. +/// +IMPELLER_DEFINE_HANDLE(ImpellerPathBuilder); + +//------------------------------------------------------------------------------ +/// A surface represents a render target for Impeller to direct the rendering +/// intent specified the form of display lists to. +/// +/// Render targets are how Impeller API users perform Window System Integration +/// (WSI). Users wrap swapchain images as surfaces and draw display lists onto +/// these surfaces to present content. +/// +/// Creating surfaces is typically platform and client-rendering-API specific. +/// +IMPELLER_DEFINE_HANDLE(ImpellerSurface); + +//------------------------------------------------------------------------------ +/// A reference to a texture whose data is resident on the GPU. These can be +/// referenced in draw calls and paints. +/// +/// Creating textures is extremely expensive. Creating a single one can +/// typically comfortably blow the frame budget of an application. Textures +/// should be created on background threads. +/// +/// @warning While textures themselves are thread safe, some context types +/// (like OpenGL) may need extra configuration to be able to operate +/// from multiple threads. +/// +IMPELLER_DEFINE_HANDLE(ImpellerTexture); + +//------------------------------------------------------------------------------ +/// The primary form of WSI when using a Vulkan context, these swapchains use +/// the `VK_KHR_surface` Vulkan extension. +/// +/// Creating a swapchain is extremely expensive. One must be created at +/// application startup and re-used throughout the application lifecycle. +/// +/// Swapchains are resilient to the underlying surfaces being resized. The +/// swapchain images will be re-created as necessary on-demand. +/// +IMPELLER_DEFINE_HANDLE(ImpellerVulkanSwapchain); + +//------------------------------------------------------------------------------ +// Signatures +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// A callback invoked by Impeller that passes a user supplied baton back to the +/// user. Impeller does not interpret the baton in any way. The way the baton is +/// specified and the thread on which the callback is invoked depends on how the +/// user supplies the callback to Impeller. +/// +typedef void (*ImpellerCallback)(void* IMPELLER_NULLABLE user_data); + +//------------------------------------------------------------------------------ +/// A callback used by Impeller to allow the user to resolve function pointers. +/// A user supplied baton that is uninterpreted by Impeller is passed back to +/// the user in the callback. How the baton is specified to Impeller and the +/// thread on which the callback is invoked depends on how the callback is +/// specified to Impeller. +/// +typedef void* IMPELLER_NULLABLE (*ImpellerProcAddressCallback)( + const char* IMPELLER_NONNULL proc_name, + void* IMPELLER_NULLABLE user_data); + +//------------------------------------------------------------------------------ +/// A callback used by Impeller to allow the user to resolve Vulkan function +/// pointers. A user supplied baton that is uninterpreted by Impeller is passed +/// back to the user in the callback. +/// +typedef void* IMPELLER_NULLABLE (*ImpellerVulkanProcAddressCallback)( + void* IMPELLER_NULLABLE vulkan_instance, + const char* IMPELLER_NONNULL vulkan_proc_name, + void* IMPELLER_NULLABLE user_data); + +//------------------------------------------------------------------------------ +// Enumerations +// ----------------------------------------------------------------------------- +typedef enum ImpellerFillType { + kImpellerFillTypeNonZero, + kImpellerFillTypeOdd, +} ImpellerFillType; + +typedef enum ImpellerClipOperation { + kImpellerClipOperationDifference, + kImpellerClipOperationIntersect, +} ImpellerClipOperation; + +typedef enum ImpellerBlendMode { + kImpellerBlendModeClear, + kImpellerBlendModeSource, + kImpellerBlendModeDestination, + kImpellerBlendModeSourceOver, + kImpellerBlendModeDestinationOver, + kImpellerBlendModeSourceIn, + kImpellerBlendModeDestinationIn, + kImpellerBlendModeSourceOut, + kImpellerBlendModeDestinationOut, + kImpellerBlendModeSourceATop, + kImpellerBlendModeDestinationATop, + kImpellerBlendModeXor, + kImpellerBlendModePlus, + kImpellerBlendModeModulate, + kImpellerBlendModeScreen, + kImpellerBlendModeOverlay, + kImpellerBlendModeDarken, + kImpellerBlendModeLighten, + kImpellerBlendModeColorDodge, + kImpellerBlendModeColorBurn, + kImpellerBlendModeHardLight, + kImpellerBlendModeSoftLight, + kImpellerBlendModeDifference, + kImpellerBlendModeExclusion, + kImpellerBlendModeMultiply, + kImpellerBlendModeHue, + kImpellerBlendModeSaturation, + kImpellerBlendModeColor, + kImpellerBlendModeLuminosity, +} ImpellerBlendMode; + +typedef enum ImpellerDrawStyle { + kImpellerDrawStyleFill, + kImpellerDrawStyleStroke, + kImpellerDrawStyleStrokeAndFill, +} ImpellerDrawStyle; + +typedef enum ImpellerStrokeCap { + kImpellerStrokeCapButt, + kImpellerStrokeCapRound, + kImpellerStrokeCapSquare, +} ImpellerStrokeCap; + +typedef enum ImpellerStrokeJoin { + kImpellerStrokeJoinMiter, + kImpellerStrokeJoinRound, + kImpellerStrokeJoinBevel, +} ImpellerStrokeJoin; + +typedef enum ImpellerPixelFormat { + kImpellerPixelFormatRGBA8888, +} ImpellerPixelFormat; + +typedef enum ImpellerTextureSampling { + kImpellerTextureSamplingNearestNeighbor, + kImpellerTextureSamplingLinear, +} ImpellerTextureSampling; + +typedef enum ImpellerTileMode { + kImpellerTileModeClamp, + kImpellerTileModeRepeat, + kImpellerTileModeMirror, + kImpellerTileModeDecal, +} ImpellerTileMode; + +typedef enum ImpellerBlurStyle { + kImpellerBlurStyleNormal, + kImpellerBlurStyleSolid, + kImpellerBlurStyleOuter, + kImpellerBlurStyleInner, +} ImpellerBlurStyle; + +typedef enum ImpellerColorSpace { + kImpellerColorSpaceSRGB, + kImpellerColorSpaceExtendedSRGB, + kImpellerColorSpaceDisplayP3, +} ImpellerColorSpace; + +typedef enum ImpellerFontWeight { + kImpellerFontWeight100, // Thin + kImpellerFontWeight200, // Extra-Light + kImpellerFontWeight300, // Light + kImpellerFontWeight400, // Normal/Regular + kImpellerFontWeight500, // Medium + kImpellerFontWeight600, // Semi-bold + kImpellerFontWeight700, // Bold + kImpellerFontWeight800, // Extra-Bold + kImpellerFontWeight900, // Black +} ImpellerFontWeight; + +typedef enum ImpellerFontStyle { + kImpellerFontStyleNormal, + kImpellerFontStyleItalic, +} ImpellerFontStyle; + +typedef enum ImpellerTextAlignment { + kImpellerTextAlignmentLeft, + kImpellerTextAlignmentRight, + kImpellerTextAlignmentCenter, + kImpellerTextAlignmentJustify, + kImpellerTextAlignmentStart, + kImpellerTextAlignmentEnd, +} ImpellerTextAlignment; + +typedef enum ImpellerTextDirection { + kImpellerTextDirectionRTL, + kImpellerTextDirectionLTR, +} ImpellerTextDirection; + +//------------------------------------------------------------------------------ +// Non-opaque structs +// ----------------------------------------------------------------------------- +typedef struct ImpellerRect { + float x; + float y; + float width; + float height; +} ImpellerRect; + +typedef struct ImpellerPoint { + float x; + float y; +} ImpellerPoint; + +typedef struct ImpellerSize { + float width; + float height; +} ImpellerSize; + +typedef struct ImpellerISize { + int64_t width; + int64_t height; +} ImpellerISize; + +typedef struct ImpellerRange { + uint64_t start; + uint64_t end; +} ImpellerRange; + +//------------------------------------------------------------------------------ +/// A 4x4 transformation matrix using column-major storage. +/// +/// ``` +/// | m[0] m[4] m[8] m[12] | +/// | m[1] m[5] m[9] m[13] | +/// | m[2] m[6] m[10] m[14] | +/// | m[3] m[7] m[11] m[15] | +/// ``` +/// +typedef struct ImpellerMatrix { + float m[16]; +} ImpellerMatrix; + +//------------------------------------------------------------------------------ +/// A 4x5 matrix using row-major storage used for transforming color values. +/// +/// To transform color values, a 5x5 matrix is constructed with the 5th row +/// being identity. Then the following transformation is performed: +/// +/// ``` +/// | R' | | m[0] m[1] m[2] m[3] m[4] | | R | +/// | G' | | m[5] m[6] m[7] m[8] m[9] | | G | +/// | B' | = | m[10] m[11] m[12] m[13] m[14] | * | B | +/// | A' | | m[15] m[16] m[17] m[18] m[19] | | A | +/// | 1 | | 0 0 0 0 1 | | 1 | +/// ``` +/// +/// The translation column (m[4], m[9], m[14], m[19]) must be specified in +/// non-normalized 8-bit unsigned integer space (0 to 255). Values outside this +/// range will produce undefined results. +/// +/// The identity transformation is thus: +/// +/// ``` +/// 1, 0, 0, 0, 0, +/// 0, 1, 0, 0, 0, +/// 0, 0, 1, 0, 0, +/// 0, 0, 0, 1, 0, +/// ``` +/// +/// Some examples: +/// +/// To invert all colors: +/// +/// ``` +/// -1, 0, 0, 0, 255, +/// 0, -1, 0, 0, 255, +/// 0, 0, -1, 0, 255, +/// 0, 0, 0, 1, 0, +/// ``` +/// +/// To apply a sepia filter: +/// +/// ``` +/// 0.393, 0.769, 0.189, 0, 0, +/// 0.349, 0.686, 0.168, 0, 0, +/// 0.272, 0.534, 0.131, 0, 0, +/// 0, 0, 0, 1, 0, +/// ``` +/// +/// To apply a grayscale conversion filter: +/// +/// ``` +/// 0.2126, 0.7152, 0.0722, 0, 0, +/// 0.2126, 0.7152, 0.0722, 0, 0, +/// 0.2126, 0.7152, 0.0722, 0, 0, +/// 0, 0, 0, 1, 0, +/// ``` +/// +/// @see ImpellerColorFilter +/// +typedef struct ImpellerColorMatrix { + float m[20]; +} ImpellerColorMatrix; + +typedef struct ImpellerRoundingRadii { + ImpellerPoint top_left; + ImpellerPoint bottom_left; + ImpellerPoint top_right; + ImpellerPoint bottom_right; +} ImpellerRoundingRadii; + +typedef struct ImpellerColor { + float red; + float green; + float blue; + float alpha; + ImpellerColorSpace color_space; +} ImpellerColor; + +typedef struct ImpellerTextureDescriptor { + ImpellerPixelFormat pixel_format; + ImpellerISize size; + uint32_t mip_count; +} ImpellerTextureDescriptor; + +typedef struct ImpellerMapping { + const uint8_t* IMPELLER_NONNULL data; + uint64_t length; + ImpellerCallback IMPELLER_NULLABLE on_release; +} ImpellerMapping; + +typedef struct ImpellerContextVulkanSettings { + void* IMPELLER_NULLABLE user_data; + ImpellerVulkanProcAddressCallback IMPELLER_NONNULL proc_address_callback; + bool enable_vulkan_validation; +} ImpellerContextVulkanSettings; + +typedef struct ImpellerContextVulkanInfo { + void* IMPELLER_NULLABLE vk_instance; + void* IMPELLER_NULLABLE vk_physical_device; + void* IMPELLER_NULLABLE vk_logical_device; + uint32_t graphics_queue_family_index; + uint32_t graphics_queue_index; +} ImpellerContextVulkanInfo; + +//------------------------------------------------------------------------------ +// Version +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Get the version of Impeller standalone API. This is the API that +/// will be accepted for validity checks when provided to the +/// context creation methods. +/// +/// The current version of the API is denoted by the +/// `IMPELLER_VERSION` macro. This version must be passed to APIs +/// that create top-level objects like graphics contexts. +/// Construction of the context may fail if the API version expected +/// by the caller is not supported by the library. +/// +/// Since there are no API stability guarantees today, passing a +/// version that is different to the one returned by +/// `ImpellerGetVersion` will always fail. +/// +/// @see `ImpellerContextCreateOpenGLESNew` +/// +/// @return The version of the standalone API. +/// +IMPELLER_EXPORT +uint32_t ImpellerGetVersion(); + +//------------------------------------------------------------------------------ +// Context +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create an OpenGL(ES) Impeller context. +/// +/// @warning Unlike other context types, the OpenGL ES context can only be +/// created, used, and collected on the calling thread. This +/// restriction may be lifted in the future once reactor workers are +/// exposed in the API. No other context types have threading +/// restrictions. Till reactor workers can be used, using the +/// context on a background thread will cause a stall of OpenGL +/// operations. +/// +/// @param[in] version The version of the Impeller +/// standalone API. See `ImpellerGetVersion`. If the +/// specified here is not compatible with the version +/// of the library, context creation will fail and NULL +/// context returned from this call. +/// @param[in] gl_proc_address_callback +/// The gl proc address callback. For instance, +/// `eglGetProcAddress`. +/// @param[in] gl_proc_address_callback_user_data +/// The gl proc address callback user data baton. This +/// pointer is not interpreted by Impeller and will be +/// returned as user data in the proc address callback. +/// user data. +/// +/// @return The context or NULL if one cannot be created. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerContext IMPELLER_NULLABLE +ImpellerContextCreateOpenGLESNew( + uint32_t version, + ImpellerProcAddressCallback IMPELLER_NONNULL gl_proc_address_callback, + void* IMPELLER_NULLABLE gl_proc_address_callback_user_data); + +//------------------------------------------------------------------------------ +/// @brief Create a Metal context using the system default Metal device. +/// +/// @param[in] version The version specified in the IMPELLER_VERSION macro. +/// +/// @return The Metal context or NULL if one cannot be created. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerContext IMPELLER_NULLABLE +ImpellerContextCreateMetalNew(uint32_t version); + +//------------------------------------------------------------------------------ +/// @brief Create a Vulkan context using the provided Vulkan Settings. +/// +/// @param[in] version The version specified in the IMPELLER_VERSION macro. +/// @param[in] settings The Vulkan settings. +/// +/// @return The Vulkan context or NULL if one cannot be created. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerContext IMPELLER_NULLABLE +ImpellerContextCreateVulkanNew( + uint32_t version, + const ImpellerContextVulkanSettings* IMPELLER_NONNULL settings); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] context The context. +/// +IMPELLER_EXPORT +void ImpellerContextRetain(ImpellerContext IMPELLER_NULLABLE context); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] context The context. +/// +IMPELLER_EXPORT +void ImpellerContextRelease(ImpellerContext IMPELLER_NULLABLE context); + +//------------------------------------------------------------------------------ +/// @brief Get internal Vulkan handles managed by the given Vulkan context. +/// Ownership of the handles is still maintained by Impeller. This +/// accessor is just available so embedders can create resources +/// using the same device and instance as Impeller for interop. +/// +/// @warning If the context is not a Vulkan context, False is returned with +/// the [out] argument unaffected. +/// +/// @param[in] context The context +/// @param[out] out_vulkan_info The out vulkan information +/// +/// @return If the Vulkan info could be fetched from the context. +/// +IMPELLER_EXPORT +bool ImpellerContextGetVulkanInfo( + ImpellerContext IMPELLER_NONNULL context, + ImpellerContextVulkanInfo* IMPELLER_NONNULL out_vulkan_info); + +//------------------------------------------------------------------------------ +// Vulkan Swapchain +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new Vulkan swapchain using a VkSurfaceKHR instance. +/// Ownership of the surface is transferred over to Impeller. The +/// Vulkan instance the surface is created from must the same as the +/// context provided. +/// +/// @param[in] context The context. Must be a Vulkan context whose +/// instance is the same used to create the +/// surface passed into the next argument. +/// @param vulkan_surface_khr The vulkan surface. +/// +/// @return The vulkan swapchain. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerVulkanSwapchain IMPELLER_NULLABLE +ImpellerVulkanSwapchainCreateNew(ImpellerContext IMPELLER_NONNULL context, + void* IMPELLER_NONNULL vulkan_surface_khr); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] swapchain The swapchain. +/// +IMPELLER_EXPORT +void ImpellerVulkanSwapchainRetain( + ImpellerVulkanSwapchain IMPELLER_NULLABLE swapchain); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] swapchain The swapchain. +/// +IMPELLER_EXPORT +void ImpellerVulkanSwapchainRelease( + ImpellerVulkanSwapchain IMPELLER_NULLABLE swapchain); + +//------------------------------------------------------------------------------ +/// @brief A potentially blocking operation, acquires the next surface to +/// render to. Since this may block, surface acquisition must be +/// delayed for as long as possible to avoid an idle wait on the +/// CPU. +/// +/// @param[in] swapchain The swapchain. +/// +/// @return The surface if one could be obtained, NULL otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerSurface IMPELLER_NULLABLE +ImpellerVulkanSwapchainAcquireNextSurfaceNew( + ImpellerVulkanSwapchain IMPELLER_NONNULL swapchain); + +//------------------------------------------------------------------------------ +// Surface +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new surface by wrapping an existing framebuffer object. +/// The framebuffer must be complete as determined by +/// `glCheckFramebufferStatus`. The framebuffer is still owned by +/// the caller and it must be collected once the surface is +/// collected. +/// +/// @param[in] context The context. +/// @param[in] fbo The framebuffer object handle. +/// @param[in] format The format of the framebuffer. +/// @param[in] size The size of the framebuffer is texels. +/// +/// @return The surface if once can be created, NULL otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerSurface IMPELLER_NULLABLE +ImpellerSurfaceCreateWrappedFBONew(ImpellerContext IMPELLER_NONNULL context, + uint64_t fbo, + ImpellerPixelFormat format, + const ImpellerISize* IMPELLER_NONNULL size); + +//------------------------------------------------------------------------------ +/// @brief Create a surface by wrapping a Metal drawable. This is useful +/// during WSI when the drawable is the backing store of the Metal +/// layer being drawn to. +/// +/// The Metal layer must be using the same device managed by the +/// underlying context. +/// +/// @param[in] context The context. The Metal device managed by this +/// context must be the same used to create the +/// drawable that is being wrapped. +/// @param metal_drawable The drawable to wrap as a surface. +/// +/// @return The surface if one could be wrapped, NULL otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerSurface IMPELLER_NULLABLE +ImpellerSurfaceCreateWrappedMetalDrawableNew( + ImpellerContext IMPELLER_NONNULL context, + void* IMPELLER_NONNULL metal_drawable); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] surface The surface. +/// +IMPELLER_EXPORT +void ImpellerSurfaceRetain(ImpellerSurface IMPELLER_NULLABLE surface); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] surface The surface. +/// +IMPELLER_EXPORT +void ImpellerSurfaceRelease(ImpellerSurface IMPELLER_NULLABLE surface); + +//------------------------------------------------------------------------------ +/// @brief Draw a display list onto the surface. The same display list can +/// be drawn multiple times to different surfaces. +/// +/// @warning In the OpenGL backend, Impeller will not make an effort to +/// preserve the OpenGL state that is current in the context. +/// Embedders that perform additional OpenGL operations in the +/// context should expect the reset state after control transitions +/// back to them. Key state to watch out for would be the viewports, +/// stencil rects, test toggles, resource (texture, framebuffer, +/// buffer) bindings, etc... +/// +/// @param[in] surface The surface to draw the display list to. +/// @param[in] display_list The display list to draw onto the surface. +/// +/// @return If the display list could be drawn onto the surface. +/// +IMPELLER_EXPORT +bool ImpellerSurfaceDrawDisplayList( + ImpellerSurface IMPELLER_NONNULL surface, + ImpellerDisplayList IMPELLER_NONNULL display_list); + +//------------------------------------------------------------------------------ +/// @brief Present the surface to the underlying window system. +/// +/// @param[in] surface The surface to present. +/// +/// @return True if the surface could be presented. +/// +IMPELLER_EXPORT +bool ImpellerSurfacePresent(ImpellerSurface IMPELLER_NONNULL surface); + +//------------------------------------------------------------------------------ +// Path +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] path The path. +/// +IMPELLER_EXPORT +void ImpellerPathRetain(ImpellerPath IMPELLER_NULLABLE path); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] path The path. +/// +IMPELLER_EXPORT +void ImpellerPathRelease(ImpellerPath IMPELLER_NULLABLE path); + +//------------------------------------------------------------------------------ +// Path Builder +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new path builder. Paths themselves are immutable. +/// A builder builds these immutable paths. +/// +/// @return The path builder. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerPathBuilder IMPELLER_NULLABLE +ImpellerPathBuilderNew(); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderRetain(ImpellerPathBuilder IMPELLER_NULLABLE builder); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderRelease(ImpellerPathBuilder IMPELLER_NULLABLE builder); + +//------------------------------------------------------------------------------ +/// @brief Move the cursor to the specified location. +/// +/// @param[in] builder The builder. +/// @param[in] location The location. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderMoveTo(ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL location); + +//------------------------------------------------------------------------------ +/// @brief Add a line segment from the current cursor location to the given +/// location. The cursor location is updated to be at the endpoint. +/// +/// @param[in] builder The builder. +/// @param[in] location The location. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderLineTo(ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL location); + +//------------------------------------------------------------------------------ +/// @brief Add a quadratic curve from whose start point is the cursor to +/// the specified end point using the a single control point. +/// +/// The new location of the cursor after this call is the end point. +/// +/// @param[in] builder The builder. +/// @param[in] control_point The control point. +/// @param[in] end_point The end point. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderQuadraticCurveTo( + ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL control_point, + const ImpellerPoint* IMPELLER_NONNULL end_point); + +//------------------------------------------------------------------------------ +/// @brief Add a cubic curve whose start point is current cursor location +/// to the specified end point using the two specified control +/// points. +/// +/// The new location of the cursor after this call is the end point +/// supplied. +/// +/// @param[in] builder The builder +/// @param[in] control_point_1 The control point 1 +/// @param[in] control_point_2 The control point 2 +/// @param[in] end_point The end point +/// +IMPELLER_EXPORT +void ImpellerPathBuilderCubicCurveTo( + ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL control_point_1, + const ImpellerPoint* IMPELLER_NONNULL control_point_2, + const ImpellerPoint* IMPELLER_NONNULL end_point); + +//------------------------------------------------------------------------------ +/// @brief Adds a rectangle to the path. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderAddRect(ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect); + +//------------------------------------------------------------------------------ +/// @brief Add an arc to the path. +/// +/// @param[in] builder The builder. +/// @param[in] oval_bounds The oval bounds. +/// @param[in] start_angle_degrees The start angle in degrees. +/// @param[in] end_angle_degrees The end angle in degrees. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderAddArc(ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL oval_bounds, + float start_angle_degrees, + float end_angle_degrees); + +//------------------------------------------------------------------------------ +/// @brief Add an oval to the path. +/// +/// @param[in] builder The builder. +/// @param[in] oval_bounds The oval bounds. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderAddOval( + ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL oval_bounds); + +//------------------------------------------------------------------------------ +/// @brief Add a rounded rect with potentially non-uniform radii to the +/// path. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// @param[in] rounding_radii The rounding radii. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderAddRoundedRect( + ImpellerPathBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect, + const ImpellerRoundingRadii* IMPELLER_NONNULL rounding_radii); + +//------------------------------------------------------------------------------ +/// @brief Close the path. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerPathBuilderClose(ImpellerPathBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +/// @brief Create a new path by copying the existing built-up path. The +/// existing path can continue being added to. +/// +/// @param[in] builder The builder. +/// @param[in] fill The fill. +/// +/// @return The impeller path. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerPath IMPELLER_NULLABLE +ImpellerPathBuilderCopyPathNew(ImpellerPathBuilder IMPELLER_NONNULL builder, + ImpellerFillType fill); + +//------------------------------------------------------------------------------ +/// @brief Create a new path using the existing built-up path. The existing +/// path builder now contains an empty path. +/// +/// @param[in] builder The builder. +/// @param[in] fill The fill. +/// +/// @return The impeller path. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerPath IMPELLER_NULLABLE +ImpellerPathBuilderTakePathNew(ImpellerPathBuilder IMPELLER_NONNULL builder, + ImpellerFillType fill); + +//------------------------------------------------------------------------------ +// Paint +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new paint with default values. +/// +/// @return The impeller paint. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerPaint IMPELLER_NULLABLE +ImpellerPaintNew(); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerPaintRetain(ImpellerPaint IMPELLER_NULLABLE paint); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerPaintRelease(ImpellerPaint IMPELLER_NULLABLE paint); + +//------------------------------------------------------------------------------ +/// @brief Set the paint color. +/// +/// @param[in] paint The paint. +/// @param[in] color The color. +/// +IMPELLER_EXPORT +void ImpellerPaintSetColor(ImpellerPaint IMPELLER_NONNULL paint, + const ImpellerColor* IMPELLER_NONNULL color); + +//------------------------------------------------------------------------------ +/// @brief Set the paint blend mode. The blend mode controls how the new +/// paints contents are mixed with the values already drawn using +/// previous draw calls. +/// +/// @param[in] paint The paint. +/// @param[in] mode The mode. +/// +IMPELLER_EXPORT +void ImpellerPaintSetBlendMode(ImpellerPaint IMPELLER_NONNULL paint, + ImpellerBlendMode mode); + +//------------------------------------------------------------------------------ +/// @brief Set the paint draw style. The style controls if the closed +/// shapes are filled and/or stroked. +/// +/// @param[in] paint The paint. +/// @param[in] style The style. +/// +IMPELLER_EXPORT +void ImpellerPaintSetDrawStyle(ImpellerPaint IMPELLER_NONNULL paint, + ImpellerDrawStyle style); + +//------------------------------------------------------------------------------ +/// @brief Sets how strokes rendered using this paint are capped. +/// +/// @param[in] paint The paint. +/// @param[in] cap The stroke cap style. +/// +IMPELLER_EXPORT +void ImpellerPaintSetStrokeCap(ImpellerPaint IMPELLER_NONNULL paint, + ImpellerStrokeCap cap); + +//------------------------------------------------------------------------------ +/// @brief Sets how strokes rendered using this paint are joined. +/// +/// @param[in] paint The paint. +/// @param[in] join The join. +/// +IMPELLER_EXPORT +void ImpellerPaintSetStrokeJoin(ImpellerPaint IMPELLER_NONNULL paint, + ImpellerStrokeJoin join); + +//------------------------------------------------------------------------------ +/// @brief Set the width of the strokes rendered using this paint. +/// +/// @param[in] paint The paint. +/// @param[in] width The width. +/// +IMPELLER_EXPORT +void ImpellerPaintSetStrokeWidth(ImpellerPaint IMPELLER_NONNULL paint, + float width); + +//------------------------------------------------------------------------------ +/// @brief Set the miter limit of the strokes rendered using this paint. +/// +/// @param[in] paint The paint. +/// @param[in] miter The miter limit. +/// +IMPELLER_EXPORT +void ImpellerPaintSetStrokeMiter(ImpellerPaint IMPELLER_NONNULL paint, + float miter); + +//------------------------------------------------------------------------------ +/// @brief Set the color filter of the paint. +/// +/// Color filters are functions that take two colors and mix them to +/// produce a single color. This color is then usually merged with +/// the destination during blending. +/// +/// @param[in] paint The paint. +/// @param[in] color_filter The color filter. +/// +IMPELLER_EXPORT +void ImpellerPaintSetColorFilter( + ImpellerPaint IMPELLER_NONNULL paint, + ImpellerColorFilter IMPELLER_NONNULL color_filter); + +//------------------------------------------------------------------------------ +/// @brief Set the color source of the paint. +/// +/// Color sources are functions that generate colors for each +/// texture element covered by a draw call. +/// +/// @param[in] paint The paint. +/// @param[in] color_source The color source. +/// +IMPELLER_EXPORT +void ImpellerPaintSetColorSource( + ImpellerPaint IMPELLER_NONNULL paint, + ImpellerColorSource IMPELLER_NONNULL color_source); + +//------------------------------------------------------------------------------ +/// @brief Set the image filter of a paint. +/// +/// Image filters are functions that are applied to regions of a +/// texture to produce a single color. +/// +/// @param[in] paint The paint. +/// @param[in] image_filter The image filter. +/// +IMPELLER_EXPORT +void ImpellerPaintSetImageFilter( + ImpellerPaint IMPELLER_NONNULL paint, + ImpellerImageFilter IMPELLER_NONNULL image_filter); + +//------------------------------------------------------------------------------ +/// @brief Set the mask filter of a paint. +/// +/// @param[in] paint The paint. +/// @param[in] mask_filter The mask filter. +/// +IMPELLER_EXPORT +void ImpellerPaintSetMaskFilter( + ImpellerPaint IMPELLER_NONNULL paint, + ImpellerMaskFilter IMPELLER_NONNULL mask_filter); + +//------------------------------------------------------------------------------ +// Texture +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a texture with decompressed bytes. +/// +/// Impeller will do its best to perform the transfer of this data +/// to GPU memory with a minimal number of copies. Towards this +/// end, it may need to send this data to a different thread for +/// preparation and transfer. To facilitate this transfer, it is +/// recommended that the content mapping have a release callback +/// attach to it. When there is a release callback, Impeller assumes +/// that collection of the data can be deferred till texture upload +/// is done and can happen on a background thread. When there is no +/// release callback, Impeller may try to perform an eager copy of +/// the data if it needs to perform data preparation and transfer on +/// a background thread. +/// +/// Whether an extra data copy actually occurs will always depend on +/// the rendering backend in use. But it is best practice to provide +/// a release callback and be resilient to the data being released +/// in a deferred manner on a background thread. +/// +/// @warning Do **not** supply compressed image data directly (PNG, JPEG, +/// etc...). This function only works with tightly packed +/// decompressed data. +/// +/// @param[in] context The context. +/// @param[in] descriptor The texture descriptor. +/// @param[in] contents The contents. +/// @param[in] contents_on_release_user_data The baton passes to the contents +/// release callback if one exists. +/// +/// @return The texture if one can be created using the provided data, NULL +/// otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerTexture IMPELLER_NULLABLE +ImpellerTextureCreateWithContentsNew( + ImpellerContext IMPELLER_NONNULL context, + const ImpellerTextureDescriptor* IMPELLER_NONNULL descriptor, + const ImpellerMapping* IMPELLER_NONNULL contents, + void* IMPELLER_NULLABLE contents_on_release_user_data); + +//------------------------------------------------------------------------------ +/// @brief Create a texture with an externally created OpenGL texture +/// handle. +/// +/// Ownership of the handle is transferred over to Impeller after a +/// successful call to this method. Impeller is responsible for +/// calling glDeleteTextures on this handle. Do **not** collect this +/// handle yourself as this will lead to a double-free. +/// +/// The handle must be created in the same context as the one used +/// by Impeller. If a different context is used, that context must +/// be in the same sharegroup as Impellers OpenGL context and all +/// synchronization of texture contents must already be complete. +/// +/// If the context is not an OpenGL context, this call will always +/// fail. +/// +/// @param[in] context The context +/// @param[in] descriptor The descriptor +/// @param[in] handle The handle +/// +/// @return The texture if one could be created by adopting the supplied +/// texture handle, NULL otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerTexture IMPELLER_NULLABLE +ImpellerTextureCreateWithOpenGLTextureHandleNew( + ImpellerContext IMPELLER_NONNULL context, + const ImpellerTextureDescriptor* IMPELLER_NONNULL descriptor, + uint64_t handle // transfer-in ownership +); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] texture The texture. +/// +IMPELLER_EXPORT +void ImpellerTextureRetain(ImpellerTexture IMPELLER_NULLABLE texture); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] texture The texture. +/// +IMPELLER_EXPORT +void ImpellerTextureRelease(ImpellerTexture IMPELLER_NULLABLE texture); + +//------------------------------------------------------------------------------ +/// @brief Get the OpenGL handle associated with this texture. If this is +/// not an OpenGL texture, this method will always return 0. +/// +/// OpenGL handles are lazily created, this method will return +/// GL_NONE is no OpenGL handle is available. To ensure that this +/// call eagerly creates an OpenGL texture, call this on a thread +/// where Impeller knows there is an OpenGL context available. +/// +/// @param[in] texture The texture. +/// +/// @return The OpenGL handle if one is available, GL_NONE otherwise. +/// +IMPELLER_EXPORT +uint64_t ImpellerTextureGetOpenGLHandle( + ImpellerTexture IMPELLER_NONNULL texture); + +//------------------------------------------------------------------------------ +// Color Sources +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] color_source The color source. +/// + +IMPELLER_EXPORT +void ImpellerColorSourceRetain( + ImpellerColorSource IMPELLER_NULLABLE color_source); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] color_source The color source. +/// +IMPELLER_EXPORT +void ImpellerColorSourceRelease( + ImpellerColorSource IMPELLER_NULLABLE color_source); + +//------------------------------------------------------------------------------ +/// @brief Create a color source that forms a linear gradient. +/// +/// @param[in] start_point The start point. +/// @param[in] end_point The end point. +/// @param[in] stop_count The stop count. +/// @param[in] colors The colors. +/// @param[in] stops The stops. +/// @param[in] tile_mode The tile mode. +/// @param[in] transformation The transformation. +/// +/// @return The color source. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorSource IMPELLER_NULLABLE +ImpellerColorSourceCreateLinearGradientNew( + const ImpellerPoint* IMPELLER_NONNULL start_point, + const ImpellerPoint* IMPELLER_NONNULL end_point, + uint32_t stop_count, + const ImpellerColor* IMPELLER_NONNULL colors, + const float* IMPELLER_NONNULL stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* IMPELLER_NULLABLE transformation); + +//------------------------------------------------------------------------------ +/// @brief Create a color source that forms a radial gradient. +/// +/// @param[in] center The center. +/// @param[in] radius The radius. +/// @param[in] stop_count The stop count. +/// @param[in] colors The colors. +/// @param[in] stops The stops. +/// @param[in] tile_mode The tile mode. +/// @param[in] transformation The transformation. +/// +/// @return The color source. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorSource IMPELLER_NULLABLE +ImpellerColorSourceCreateRadialGradientNew( + const ImpellerPoint* IMPELLER_NONNULL center, + float radius, + uint32_t stop_count, + const ImpellerColor* IMPELLER_NONNULL colors, + const float* IMPELLER_NONNULL stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* IMPELLER_NULLABLE transformation); + +//------------------------------------------------------------------------------ +/// @brief Create a color source that forms a conical gradient. +/// +/// @param[in] start_center The start center. +/// @param[in] start_radius The start radius. +/// @param[in] end_center The end center. +/// @param[in] end_radius The end radius. +/// @param[in] stop_count The stop count. +/// @param[in] colors The colors. +/// @param[in] stops The stops. +/// @param[in] tile_mode The tile mode. +/// @param[in] transformation The transformation. +/// +/// @return The color source. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorSource IMPELLER_NULLABLE +ImpellerColorSourceCreateConicalGradientNew( + const ImpellerPoint* IMPELLER_NONNULL start_center, + float start_radius, + const ImpellerPoint* IMPELLER_NONNULL end_center, + float end_radius, + uint32_t stop_count, + const ImpellerColor* IMPELLER_NONNULL colors, + const float* IMPELLER_NONNULL stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* IMPELLER_NULLABLE transformation); + +//------------------------------------------------------------------------------ +/// @brief Create a color source that forms a sweep gradient. +/// +/// @param[in] center The center. +/// @param[in] start The start. +/// @param[in] end The end. +/// @param[in] stop_count The stop count. +/// @param[in] colors The colors. +/// @param[in] stops The stops. +/// @param[in] tile_mode The tile mode. +/// @param[in] transformation The transformation. +/// +/// @return The color source. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorSource IMPELLER_NULLABLE +ImpellerColorSourceCreateSweepGradientNew( + const ImpellerPoint* IMPELLER_NONNULL center, + float start, + float end, + uint32_t stop_count, + const ImpellerColor* IMPELLER_NONNULL colors, + const float* IMPELLER_NONNULL stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* IMPELLER_NULLABLE transformation); + +//------------------------------------------------------------------------------ +/// @brief Create a color source that samples from an image. +/// +/// @param[in] image The image. +/// @param[in] horizontal_tile_mode The horizontal tile mode. +/// @param[in] vertical_tile_mode The vertical tile mode. +/// @param[in] sampling The sampling. +/// @param[in] transformation The transformation. +/// +/// @return The color source. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorSource IMPELLER_NULLABLE +ImpellerColorSourceCreateImageNew( + ImpellerTexture IMPELLER_NONNULL image, + ImpellerTileMode horizontal_tile_mode, + ImpellerTileMode vertical_tile_mode, + ImpellerTextureSampling sampling, + const ImpellerMatrix* IMPELLER_NULLABLE transformation); + +//------------------------------------------------------------------------------ +// Color Filters +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] color_filter The color filter. +/// +IMPELLER_EXPORT +void ImpellerColorFilterRetain( + ImpellerColorFilter IMPELLER_NULLABLE color_filter); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] color_filter The color filter. +/// +IMPELLER_EXPORT +void ImpellerColorFilterRelease( + ImpellerColorFilter IMPELLER_NULLABLE color_filter); + +//------------------------------------------------------------------------------ +/// @brief Create a color filter that performs blending of pixel values +/// independently. +/// +/// @param[in] color The color. +/// @param[in] blend_mode The blend mode. +/// +/// @return The color filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorFilter IMPELLER_NULLABLE +ImpellerColorFilterCreateBlendNew(const ImpellerColor* IMPELLER_NONNULL color, + ImpellerBlendMode blend_mode); + +//------------------------------------------------------------------------------ +/// @brief Create a color filter that transforms pixel color values +/// independently. +/// +/// @param[in] color_matrix The color matrix. +/// +/// @return The color filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerColorFilter IMPELLER_NULLABLE +ImpellerColorFilterCreateColorMatrixNew( + const ImpellerColorMatrix* IMPELLER_NONNULL color_matrix); + +//------------------------------------------------------------------------------ +// Mask Filters +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] mask_filter The mask filter. +/// +IMPELLER_EXPORT +void ImpellerMaskFilterRetain(ImpellerMaskFilter IMPELLER_NULLABLE mask_filter); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] mask_filter The mask filter. +/// +IMPELLER_EXPORT +void ImpellerMaskFilterRelease( + ImpellerMaskFilter IMPELLER_NULLABLE mask_filter); + +//------------------------------------------------------------------------------ +/// @brief Create a mask filter that blurs contents in the masked shape. +/// +/// @param[in] style The style. +/// @param[in] sigma The sigma. +/// +/// @return The mask filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerMaskFilter IMPELLER_NULLABLE +ImpellerMaskFilterCreateBlurNew(ImpellerBlurStyle style, float sigma); + +//------------------------------------------------------------------------------ +// Image Filters +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] image_filter The image filter. +/// +IMPELLER_EXPORT +void ImpellerImageFilterRetain( + ImpellerImageFilter IMPELLER_NULLABLE image_filter); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] image_filter The image filter. +/// +IMPELLER_EXPORT +void ImpellerImageFilterRelease( + ImpellerImageFilter IMPELLER_NULLABLE image_filter); + +//------------------------------------------------------------------------------ +/// @brief Creates an image filter that applies a Gaussian blur. +/// +/// The Gaussian blur applied may be an approximation for +/// performance. +/// +/// +/// @param[in] x_sigma The x sigma. +/// @param[in] y_sigma The y sigma. +/// @param[in] tile_mode The tile mode. +/// +/// @return The image filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerImageFilter IMPELLER_NULLABLE +ImpellerImageFilterCreateBlurNew(float x_sigma, + float y_sigma, + ImpellerTileMode tile_mode); + +//------------------------------------------------------------------------------ +/// @brief Creates an image filter that enhances the per-channel pixel +/// values to the maximum value in a circle around the pixel. +/// +/// @param[in] x_radius The x radius. +/// @param[in] y_radius The y radius. +/// +/// @return The image filter. +/// + +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerImageFilter IMPELLER_NULLABLE +ImpellerImageFilterCreateDilateNew(float x_radius, float y_radius); + +//------------------------------------------------------------------------------ +/// @brief Creates an image filter that dampens the per-channel pixel +/// values to the minimum value in a circle around the pixel. +/// +/// @param[in] x_radius The x radius. +/// @param[in] y_radius The y radius. +/// +/// @return The image filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerImageFilter IMPELLER_NULLABLE +ImpellerImageFilterCreateErodeNew(float x_radius, float y_radius); + +//------------------------------------------------------------------------------ +/// @brief Creates an image filter that applies a transformation matrix to +/// the underlying image. +/// +/// @param[in] matrix The transformation matrix. +/// @param[in] sampling The image sampling mode. +/// +/// @return The image filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerImageFilter IMPELLER_NULLABLE +ImpellerImageFilterCreateMatrixNew( + const ImpellerMatrix* IMPELLER_NONNULL matrix, + ImpellerTextureSampling sampling); + +//------------------------------------------------------------------------------ +/// @brief Creates a composed filter that when applied is identical to +/// subsequently applying the inner and then the outer filters. +/// +/// ``` +/// destination = outer_filter(inner_filter(source)) +/// ``` +/// +/// @param[in] outer The outer image filter. +/// @param[in] inner The inner image filter. +/// +/// @return The combined image filter. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerImageFilter IMPELLER_NULLABLE +ImpellerImageFilterCreateComposeNew(ImpellerImageFilter IMPELLER_NONNULL outer, + ImpellerImageFilter IMPELLER_NONNULL inner); + +//------------------------------------------------------------------------------ +// Display List +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] display_list The display list. +/// +IMPELLER_EXPORT +void ImpellerDisplayListRetain( + ImpellerDisplayList IMPELLER_NULLABLE display_list); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] display_list The display list. +/// +IMPELLER_EXPORT +void ImpellerDisplayListRelease( + ImpellerDisplayList IMPELLER_NULLABLE display_list); + +//------------------------------------------------------------------------------ +// Display List Builder +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new display list builder. +/// +/// An optional cull rectangle may be specified. Impeller is allowed +/// to treat the contents outside this rectangle as being undefined. +/// This may aid performance optimizations. +/// +/// @param[in] cull_rect The cull rectangle or NULL. +/// +/// @return The display list builder. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerDisplayListBuilder IMPELLER_NULLABLE +ImpellerDisplayListBuilderNew(const ImpellerRect* IMPELLER_NULLABLE cull_rect); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] builder The display list builder. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderRetain( + ImpellerDisplayListBuilder IMPELLER_NULLABLE builder); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] builder The display list builder. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderRelease( + ImpellerDisplayListBuilder IMPELLER_NULLABLE builder); + +//------------------------------------------------------------------------------ +/// @brief Create a new display list using the rendering intent already +/// encoded in the builder. The builder is reset after this call. +/// +/// @param[in] builder The builder. +/// +/// @return The display list. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerDisplayList IMPELLER_NULLABLE +ImpellerDisplayListBuilderCreateDisplayListNew( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +// Display List Builder: Managing the transformation stack. +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Stashes the current transformation and clip state onto a save +/// stack. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderSave( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +/// @brief Stashes the current transformation and clip state onto a save +/// stack and creates and creates an offscreen layer onto which +/// subsequent rendering intent will be directed to. +/// +/// On the balancing call to restore, the supplied paints filters +/// and blend modes will be used to composite the offscreen contents +/// back onto the display display list. +/// +/// @param[in] builder The builder. +/// @param[in] bounds The bounds. +/// @param[in] paint The paint. +/// @param[in] backdrop The backdrop. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderSaveLayer( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL bounds, + ImpellerPaint IMPELLER_NULLABLE paint, + ImpellerImageFilter IMPELLER_NULLABLE backdrop); + +//------------------------------------------------------------------------------ +/// @brief Pops the last entry pushed onto the save stack using a call to +/// `ImpellerDisplayListBuilderSave` or +/// `ImpellerDisplayListBuilderSaveLayer`. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderRestore( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +/// @brief Apply a scale to the transformation matrix currently on top of +/// the save stack. +/// +/// @param[in] builder The builder. +/// @param[in] x_scale The x scale. +/// @param[in] y_scale The y scale. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderScale( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + float x_scale, + float y_scale); + +//------------------------------------------------------------------------------ +/// @brief Apply a clockwise rotation to the transformation matrix +/// currently on top of the save stack. +/// +/// @param[in] builder The builder. +/// @param[in] angle_degrees The angle in degrees. +/// + +IMPELLER_EXPORT +void ImpellerDisplayListBuilderRotate( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + float angle_degrees); + +//------------------------------------------------------------------------------ +/// @brief Apply a translation to the transformation matrix currently on +/// top of the save stack. +/// +/// @param[in] builder The builder. +/// @param[in] x_translation The x translation. +/// @param[in] y_translation The y translation. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderTranslate( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + float x_translation, + float y_translation); + +//------------------------------------------------------------------------------ +/// @brief Appends the the provided transformation to the transformation +/// already on the save stack. +/// +/// @param[in] builder The builder. +/// @param[in] transform The transform to append. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderTransform( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerMatrix* IMPELLER_NONNULL transform); + +//------------------------------------------------------------------------------ +/// @brief Clear the transformation on top of the save stack and replace it +/// with a new value. +/// +/// @param[in] builder The builder. +/// @param[in] transform The new transform. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderSetTransform( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerMatrix* IMPELLER_NONNULL transform); + +//------------------------------------------------------------------------------ +/// @brief Get the transformation currently built up on the top of the +/// transformation stack. +/// +/// @param[in] builder The builder. +/// @param[out] out_transform The transform. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderGetTransform( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerMatrix* IMPELLER_NONNULL out_transform); + +//------------------------------------------------------------------------------ +/// @brief Reset the transformation on top of the transformation stack to +/// identity. +/// +/// @param[in] builder The builder. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderResetTransform( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +/// @brief Get the current size of the save stack. +/// +/// @param[in] builder The builder. +/// +/// @return The save stack size. +/// +IMPELLER_EXPORT +uint32_t ImpellerDisplayListBuilderGetSaveCount( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder); + +//------------------------------------------------------------------------------ +/// @brief Effectively calls ImpellerDisplayListBuilderRestore till the +/// size of the save stack becomes a specified count. +/// +/// @param[in] builder The builder. +/// @param[in] count The count. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderRestoreToCount( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + uint32_t count); + +//------------------------------------------------------------------------------ +// Display List Builder: Clipping +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Reduces the clip region to the intersection of the current clip +/// and the given rectangle taking into account the clip operation. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// @param[in] op The operation. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderClipRect( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect, + ImpellerClipOperation op); + +//------------------------------------------------------------------------------ +/// @brief Reduces the clip region to the intersection of the current clip +/// and the given oval taking into account the clip operation. +/// +/// @param[in] builder The builder. +/// @param[in] oval_bounds The oval bounds. +/// @param[in] op The operation. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderClipOval( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL oval_bounds, + ImpellerClipOperation op); + +//------------------------------------------------------------------------------ +/// @brief Reduces the clip region to the intersection of the current clip +/// and the given rounded rectangle taking into account the clip +/// operation. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// @param[in] radii The radii. +/// @param[in] op The operation. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderClipRoundedRect( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect, + const ImpellerRoundingRadii* IMPELLER_NONNULL radii, + ImpellerClipOperation op); + +//------------------------------------------------------------------------------ +/// @brief Reduces the clip region to the intersection of the current clip +/// and the given path taking into account the clip operation. +/// +/// @param[in] builder The builder. +/// @param[in] path The path. +/// @param[in] op The operation. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderClipPath( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerPath IMPELLER_NONNULL path, + ImpellerClipOperation op); + +//------------------------------------------------------------------------------ +// Display List Builder: Drawing Shapes +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Fills the current clip with the specified paint. +/// +/// @param[in] builder The builder. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawPaint( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws a line segment. +/// +/// @param[in] builder The builder. +/// @param[in] from The starting point of the line. +/// @param[in] to The end point of the line. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawLine( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL from, + const ImpellerPoint* IMPELLER_NONNULL to, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws a dash line segment. +/// +/// @param[in] builder The builder. +/// @param[in] from The starting point of the line. +/// @param[in] to The end point of the line. +/// @param[in] on_length On length. +/// @param[in] off_length Off length. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawDashedLine( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerPoint* IMPELLER_NONNULL from, + const ImpellerPoint* IMPELLER_NONNULL to, + float on_length, + float off_length, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws a rectangle. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawRect( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws an oval. +/// +/// @param[in] builder The builder. +/// @param[in] oval_bounds The oval bounds. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawOval( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL oval_bounds, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws a rounded rect. +/// +/// @param[in] builder The builder. +/// @param[in] rect The rectangle. +/// @param[in] radii The radii. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawRoundedRect( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL rect, + const ImpellerRoundingRadii* IMPELLER_NONNULL radii, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws a shape that is the different between the specified +/// rectangles (each with configurable corner radii). +/// +/// @param[in] builder The builder. +/// @param[in] outer_rect The outer rectangle. +/// @param[in] outer_radii The outer radii. +/// @param[in] inner_rect The inner rectangle. +/// @param[in] inner_radii The inner radii. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawRoundedRectDifference( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + const ImpellerRect* IMPELLER_NONNULL outer_rect, + const ImpellerRoundingRadii* IMPELLER_NONNULL outer_radii, + const ImpellerRect* IMPELLER_NONNULL inner_rect, + const ImpellerRoundingRadii* IMPELLER_NONNULL inner_radii, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Draws the specified shape. +/// +/// @param[in] builder The builder. +/// @param[in] path The path. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawPath( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerPath IMPELLER_NONNULL path, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Flattens the contents of another display list into the one +/// currently being built. +/// +/// @param[in] builder The builder. +/// @param[in] display_list The display list. +/// @param[in] opacity The opacity. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawDisplayList( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerDisplayList IMPELLER_NONNULL display_list, + float opacity); + +//------------------------------------------------------------------------------ +/// @brief Draw a paragraph at the specified point. +/// +/// @param[in] builder The builder. +/// @param[in] paragraph The paragraph. +/// @param[in] point The point. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawParagraph( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerParagraph IMPELLER_NONNULL paragraph, + const ImpellerPoint* IMPELLER_NONNULL point); + +//------------------------------------------------------------------------------ +/// @brief Draw a shadow for a Path given a material elevation. If the +/// occluding object is not opaque, additional hints (via the +/// `occluder_is_transparent` argument) must be provided to render +/// the shadow correctly. +/// +/// @param[in] builder The builder. +/// @param[in] path The shadow path. +/// @param[in] color The shadow color. +/// @param[in] elevation The material elevation. +/// @param[in] occluder_is_transparent +/// If the object casting the shadow is transparent. +/// @param[in] device_pixel_ratio +/// The device pixel ratio. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawShadow( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerPath IMPELLER_NONNULL path, + const ImpellerColor* IMPELLER_NONNULL color, + float elevation, + bool occluder_is_transparent, + float device_pixel_ratio); + +//------------------------------------------------------------------------------ +// Display List Builder: Drawing Textures +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Draw a texture at the specified point. +/// +/// @param[in] builder The builder. +/// @param[in] texture The texture. +/// @param[in] point The point. +/// @param[in] sampling The sampling. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawTexture( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerTexture IMPELLER_NONNULL texture, + const ImpellerPoint* IMPELLER_NONNULL point, + ImpellerTextureSampling sampling, + ImpellerPaint IMPELLER_NULLABLE paint); + +//------------------------------------------------------------------------------ +/// @brief Draw a portion of texture at the specified location. +/// +/// @param[in] builder The builder. +/// @param[in] texture The texture. +/// @param[in] src_rect The source rectangle. +/// @param[in] dst_rect The destination rectangle. +/// @param[in] sampling The sampling. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerDisplayListBuilderDrawTextureRect( + ImpellerDisplayListBuilder IMPELLER_NONNULL builder, + ImpellerTexture IMPELLER_NONNULL texture, + const ImpellerRect* IMPELLER_NONNULL src_rect, + const ImpellerRect* IMPELLER_NONNULL dst_rect, + ImpellerTextureSampling sampling, + ImpellerPaint IMPELLER_NULLABLE paint); + +//------------------------------------------------------------------------------ +// Typography Context +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new typography contents. +/// +/// @return The typography context. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerTypographyContext IMPELLER_NULLABLE +ImpellerTypographyContextNew(); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] context The typography context. +/// +IMPELLER_EXPORT +void ImpellerTypographyContextRetain( + ImpellerTypographyContext IMPELLER_NULLABLE context); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] context The typography context. +/// +IMPELLER_EXPORT +void ImpellerTypographyContextRelease( + ImpellerTypographyContext IMPELLER_NULLABLE context); + +//------------------------------------------------------------------------------ +/// @brief Register a custom font. +/// +/// The following font formats are supported: +/// * OpenType font collections (.ttc extension) +/// * TrueType fonts: (.ttf extension) +/// * OpenType fonts: (.otf extension) +/// +/// @warning Web Open Font Formats (.woff and .woff2 extensions) are **not** +/// supported. +/// +/// The font data is specified as a mapping. It is possible for the +/// release callback of the mapping to not be called even past the +/// destruction of the typography context. Care must be taken to not +/// collect the mapping till the release callback is invoked by +/// Impeller. +/// +/// The family alias name can be NULL. In such cases, the font +/// family specified in paragraph styles must match the family that +/// is specified in the font data. +/// +/// If the family name alias is not NULL, that family name must be +/// used in the paragraph style to reference glyphs from this font +/// instead of the one encoded in the font itself. +/// +/// Multiple fonts (with glyphs for different styles) can be +/// specified with the same family. +/// +/// @see `ImpellerParagraphStyleSetFontFamily` +/// +/// @param[in] context The context. +/// @param[in] contents The contents. +/// @param[in] contents_on_release_user_data The user data baton to be passed +/// to the contents release callback. +/// @param[in] family_name_alias The family name alias or NULL if +/// the one specified in the font +/// data is to be used. +/// +/// @return If the font could be successfully registered. +/// +IMPELLER_EXPORT +bool ImpellerTypographyContextRegisterFont( + ImpellerTypographyContext IMPELLER_NONNULL context, + const ImpellerMapping* IMPELLER_NONNULL contents, + void* IMPELLER_NULLABLE contents_on_release_user_data, + const char* IMPELLER_NULLABLE family_name_alias); + +//------------------------------------------------------------------------------ +// Paragraph Style +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new paragraph style. +/// +/// @return The paragraph style. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerParagraphStyle IMPELLER_NULLABLE +ImpellerParagraphStyleNew(); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] paragraph_style The paragraph style. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleRetain( + ImpellerParagraphStyle IMPELLER_NULLABLE paragraph_style); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] paragraph_style The paragraph style. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleRelease( + ImpellerParagraphStyle IMPELLER_NULLABLE paragraph_style); + +//------------------------------------------------------------------------------ +/// @brief Set the paint used to render the text glyph contents. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetForeground( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Set the paint used to render the background of the text glyphs. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] paint The paint. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetBackground( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerPaint IMPELLER_NONNULL paint); + +//------------------------------------------------------------------------------ +/// @brief Set the weight of the font to select when rendering glyphs. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] weight The weight. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetFontWeight( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerFontWeight weight); + +//------------------------------------------------------------------------------ +/// @brief Set whether the glyphs should be bolded or italicized. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] style The style. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetFontStyle( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerFontStyle style); + +//------------------------------------------------------------------------------ +/// @brief Set the font family. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] family_name The family name. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetFontFamily( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + const char* IMPELLER_NONNULL family_name); + +//------------------------------------------------------------------------------ +/// @brief Set the font size. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] size The size. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetFontSize( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + float size); + +//------------------------------------------------------------------------------ +/// @brief The height of the text as a multiple of text size. +/// +/// When height is 0.0, the line height will be determined by the +/// font's metrics directly, which may differ from the font size. +/// Otherwise the line height of the text will be a multiple of font +/// size, and be exactly fontSize * height logical pixels tall. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] height The height. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetHeight( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + float height); + +//------------------------------------------------------------------------------ +/// @brief Set the alignment of text within the paragraph. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] align The align. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetTextAlignment( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerTextAlignment align); + +//------------------------------------------------------------------------------ +/// @brief Set the directionality of the text within the paragraph. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] direction The direction. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetTextDirection( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + ImpellerTextDirection direction); + +//------------------------------------------------------------------------------ +/// @brief Set the maximum line count within the paragraph. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] max_lines The maximum lines. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetMaxLines( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + uint32_t max_lines); + +//------------------------------------------------------------------------------ +/// @brief Set the paragraph locale. +/// +/// @param[in] paragraph_style The paragraph style. +/// @param[in] locale The locale. +/// +IMPELLER_EXPORT +void ImpellerParagraphStyleSetLocale( + ImpellerParagraphStyle IMPELLER_NONNULL paragraph_style, + const char* IMPELLER_NONNULL locale); + +//------------------------------------------------------------------------------ +// Paragraph Builder +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Create a new paragraph builder. +/// +/// @param[in] context The context. +/// +/// @return The paragraph builder. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerParagraphBuilder IMPELLER_NULLABLE +ImpellerParagraphBuilderNew(ImpellerTypographyContext IMPELLER_NONNULL context); + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] paragraph_builder The paragraph builder. +/// +IMPELLER_EXPORT +void ImpellerParagraphBuilderRetain( + ImpellerParagraphBuilder IMPELLER_NULLABLE paragraph_builder); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] paragraph_builder The paragraph_builder. +/// +IMPELLER_EXPORT +void ImpellerParagraphBuilderRelease( + ImpellerParagraphBuilder IMPELLER_NULLABLE paragraph_builder); + +//------------------------------------------------------------------------------ +/// @brief Push a new paragraph style onto the paragraph style stack +/// managed by the paragraph builder. +/// +/// Not all paragraph styles can be combined. For instance, it does +/// not make sense to mix text alignment for different text runs +/// within a paragraph. In such cases, the preference of the the +/// first paragraph style on the style stack will take hold. +/// +/// If text is pushed onto the paragraph builder without a style +/// previously pushed onto the stack, a default paragraph text style +/// will be used. This may not always be desirable because some +/// style element cannot be overridden. It is recommended that a +/// default paragraph style always be pushed onto the stack before +/// the addition of any text. +/// +/// @param[in] paragraph_builder The paragraph builder. +/// @param[in] style The style. +/// +IMPELLER_EXPORT +void ImpellerParagraphBuilderPushStyle( + ImpellerParagraphBuilder IMPELLER_NONNULL paragraph_builder, + ImpellerParagraphStyle IMPELLER_NONNULL style); + +//------------------------------------------------------------------------------ +/// @brief Pop a previously pushed paragraph style from the paragraph style +/// stack. +/// +/// @param[in] paragraph_builder The paragraph builder. +/// +IMPELLER_EXPORT +void ImpellerParagraphBuilderPopStyle( + ImpellerParagraphBuilder IMPELLER_NONNULL paragraph_builder); + +//------------------------------------------------------------------------------ +/// @brief Add UTF-8 encoded text to the paragraph. The text will be styled +/// according to the paragraph style already on top of the paragraph +/// style stack. +/// +/// @param[in] paragraph_builder The paragraph builder. +/// @param[in] data The data. +/// @param[in] length The length. +/// +IMPELLER_EXPORT +void ImpellerParagraphBuilderAddText( + ImpellerParagraphBuilder IMPELLER_NONNULL paragraph_builder, + const uint8_t* IMPELLER_NULLABLE data, + uint32_t length); + +//------------------------------------------------------------------------------ +/// @brief Layout and build a new paragraph using the specified width. The +/// resulting paragraph is immutable. The paragraph builder must be +/// discarded and a new one created to build more paragraphs. +/// +/// @param[in] paragraph_builder The paragraph builder. +/// @param[in] width The paragraph width. +/// +/// @return The paragraph if one can be created, NULL otherwise. +/// +IMPELLER_EXPORT IMPELLER_NODISCARD ImpellerParagraph IMPELLER_NULLABLE +ImpellerParagraphBuilderBuildParagraphNew( + ImpellerParagraphBuilder IMPELLER_NONNULL paragraph_builder, + float width); + +//------------------------------------------------------------------------------ +// Paragraph +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] paragraph The paragraph. +/// +IMPELLER_EXPORT +void ImpellerParagraphRetain(ImpellerParagraph IMPELLER_NULLABLE paragraph); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] paragraph The paragraph. +/// +IMPELLER_EXPORT +void ImpellerParagraphRelease(ImpellerParagraph IMPELLER_NULLABLE paragraph); + +//------------------------------------------------------------------------------ +/// @see `ImpellerParagraphGetMinIntrinsicWidth` +/// +/// @param[in] paragraph The paragraph. +/// +/// +/// @return The width provided to the paragraph builder during the call to +/// layout. This is the maximum width any line in the laid out +/// paragraph can occupy. But, it is not necessarily the actual +/// width of the paragraph after layout. +/// +IMPELLER_EXPORT +float ImpellerParagraphGetMaxWidth( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The height of the laid out paragraph. This is **not** a tight +/// bounding box and some glyphs may not reach the minimum location +/// they are allowed to reach. +/// +IMPELLER_EXPORT +float ImpellerParagraphGetHeight(ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The length of the longest line in the paragraph. This is the +/// horizontal distance between the left edge of the leftmost glyph +/// and the right edge of the rightmost glyph, in the longest line +/// in the paragraph. +/// +IMPELLER_EXPORT +float ImpellerParagraphGetLongestLineWidth( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @see `ImpellerParagraphGetMaxWidth` +/// +/// @param[in] paragraph The paragraph. +/// +/// @return The actual width of the longest line in the paragraph after +/// layout. This is expected to be less than or equal to +/// `ImpellerParagraphGetMaxWidth`. +/// +IMPELLER_EXPORT +float ImpellerParagraphGetMinIntrinsicWidth( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The width of the paragraph without line breaking. +/// +IMPELLER_EXPORT +float ImpellerParagraphGetMaxIntrinsicWidth( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The distance from the top of the paragraph to the ideographic +/// baseline of the first line when using ideographic fonts +/// (Japanese, Korean, etc...). +/// +IMPELLER_EXPORT +float ImpellerParagraphGetIdeographicBaseline( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The distance from the top of the paragraph to the alphabetic +/// baseline of the first line when using alphabetic fonts (A-Z, +/// a-z, Greek, etc...). +/// +IMPELLER_EXPORT +float ImpellerParagraphGetAlphabeticBaseline( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @param[in] paragraph The paragraph. +/// +/// @return The number of lines visible in the paragraph after line +/// breaking. +/// +IMPELLER_EXPORT +uint32_t ImpellerParagraphGetLineCount( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @brief Get the range into the UTF-16 code unit buffer that represents +/// the word at the specified caret location in the same buffer. +/// +/// Word boundaries are defined more precisely in [Unicode Standard +/// Annex #29](http://www.unicode.org/reports/tr29/#Word_Boundaries) +/// +/// @param[in] paragraph The paragraph +/// @param[in] code_unit_index The code unit index +/// +/// @return The impeller range. +/// +IMPELLER_EXPORT +ImpellerRange ImpellerParagraphGetWordBoundary( + ImpellerParagraph IMPELLER_NONNULL paragraph, + size_t code_unit_index); + +//------------------------------------------------------------------------------ +/// @brief Get the line metrics of this laid out paragraph. Calculating the +/// line metrics is expensive. The first time line metrics are +/// requested, they will be cached along with the paragraph (which +/// is immutable). +/// +/// @param[in] paragraph The paragraph. +/// +/// @return The line metrics. +/// +IMPELLER_EXPORT +ImpellerLineMetrics IMPELLER_NULLABLE ImpellerParagraphGetLineMetrics( + ImpellerParagraph IMPELLER_NONNULL paragraph); + +//------------------------------------------------------------------------------ +/// @brief Create a new instance of glyph info that can be queried for +/// information about the glyph at the given UTF-16 code unit index. +/// The instance must be freed using `ImpellerGlyphInfoRelease`. +/// +/// @param[in] paragraph The paragraph. +/// @param[in] code_unit_index The UTF-16 code unit index. +/// +/// @return The glyph information. +/// +IMPELLER_EXPORT +IMPELLER_NODISCARD ImpellerGlyphInfo IMPELLER_NULLABLE +ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew( + ImpellerParagraph IMPELLER_NONNULL paragraph, + size_t code_unit_index); + +//------------------------------------------------------------------------------ +/// @brief Create a new instance of glyph info that can be queried for +/// information about the glyph closest to the specified coordinates +/// relative to the origin of the paragraph. The instance must be +/// freed using `ImpellerGlyphInfoRelease`. +/// +/// @param[in] paragraph The paragraph. +/// @param[in] x The x coordinate relative to paragraph origin. +/// @param[in] y The x coordinate relative to paragraph origin. +/// +/// @return The glyph information. +/// +IMPELLER_EXPORT +IMPELLER_NODISCARD ImpellerGlyphInfo IMPELLER_NULLABLE +ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew( + ImpellerParagraph IMPELLER_NONNULL paragraph, + double x, + double y); + +//------------------------------------------------------------------------------ +// Line Metrics +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] line_metrics The line metrics. +/// +IMPELLER_EXPORT +void ImpellerLineMetricsRetain( + ImpellerLineMetrics IMPELLER_NULLABLE line_metrics); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] line_metrics The line metrics. +/// +IMPELLER_EXPORT +void ImpellerLineMetricsRelease( + ImpellerLineMetrics IMPELLER_NULLABLE line_metrics); + +//------------------------------------------------------------------------------ +/// @brief The rise from the baseline as calculated from the font and style +/// for this line ignoring the height from the text style. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The unscaled ascent. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetUnscaledAscent( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief The rise from the baseline as calculated from the font and style +/// for this line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The ascent. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetAscent( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief The drop from the baseline as calculated from the font and style +/// for this line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The descent. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetDescent( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief The y coordinate of the baseline for this line from the top of +/// the paragraph. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The baseline. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetBaseline( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Used to determine if this line ends with an explicit line break +/// (e.g. '\n') or is the end of the paragraph. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return True if the line is a hard break. +/// +IMPELLER_EXPORT +bool ImpellerLineMetricsIsHardbreak( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Width of the line from the left edge of the leftmost glyph to +/// the right edge of the rightmost glyph. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The width. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetWidth(ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Total height of the line from the top edge to the bottom edge. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The height. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetHeight( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief The x coordinate of left edge of the line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The left edge coordinate. +/// +IMPELLER_EXPORT +double ImpellerLineMetricsGetLeft(ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Fetch the start index in the buffer of UTF-16 code units used to +/// represent the paragraph line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The UTF-16 code units start index. +/// +IMPELLER_EXPORT +size_t ImpellerLineMetricsGetCodeUnitStartIndex( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Fetch the end index in the buffer of UTF-16 code units used to +/// represent the paragraph line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The UTF-16 code units end index. +/// +IMPELLER_EXPORT +size_t ImpellerLineMetricsGetCodeUnitEndIndex( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Fetch the end index (excluding whitespace) in the buffer of +/// UTF-16 code units used to represent the paragraph line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The UTF-16 code units end index excluding whitespace. +/// +IMPELLER_EXPORT +size_t ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +/// @brief Fetch the end index (including newlines) in the buffer of UTF-16 +/// code units used to represent the paragraph line. +/// +/// @param[in] metrics The metrics. +/// @param[in] line The line index (zero based). +/// +/// @return The UTF-16 code units end index including newlines. +/// +IMPELLER_EXPORT +size_t ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline( + ImpellerLineMetrics IMPELLER_NONNULL metrics, + size_t line); + +//------------------------------------------------------------------------------ +// Glyph Info +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +/// @brief Retain a strong reference to the object. The object can be NULL +/// in which case this method is a no-op. +/// +/// @param[in] glyph_info The glyph information. +/// +IMPELLER_EXPORT +void ImpellerGlyphInfoRetain(ImpellerGlyphInfo IMPELLER_NULLABLE glyph_info); + +//------------------------------------------------------------------------------ +/// @brief Release a previously retained reference to the object. The +/// object can be NULL in which case this method is a no-op. +/// +/// @param[in] glyph_info The glyph information. +/// +IMPELLER_EXPORT +void ImpellerGlyphInfoRelease(ImpellerGlyphInfo IMPELLER_NULLABLE glyph_info); + +//------------------------------------------------------------------------------ +/// @brief Fetch the start index in the buffer of UTF-16 code units used to +/// represent the grapheme cluster for a glyph. +/// +/// @param[in] glyph_info The glyph information. +/// +/// @return The UTF-16 code units start index. +/// +IMPELLER_EXPORT +size_t ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin( + ImpellerGlyphInfo IMPELLER_NONNULL glyph_info); + +//------------------------------------------------------------------------------ +/// @brief Fetch the end index in the buffer of UTF-16 code units used to +/// represent the grapheme cluster for a glyph. +/// +/// @param[in] glyph_info The glyph information. +/// +/// @return The UTF-16 code units end index. +/// +IMPELLER_EXPORT +size_t ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd( + ImpellerGlyphInfo IMPELLER_NONNULL glyph_info); + +//------------------------------------------------------------------------------ +/// @brief Fetch the bounds of the grapheme cluster for the glyph in the +/// coordinate space of the paragraph. +/// +/// @param[in] glyph_info The glyph information. +/// +/// @return The grapheme cluster bounds. +/// +IMPELLER_EXPORT +ImpellerRect ImpellerGlyphInfoGetGraphemeClusterBounds( + ImpellerGlyphInfo IMPELLER_NONNULL glyph_info); + +//------------------------------------------------------------------------------ +/// @param[in] glyph_info The glyph information. +/// +/// @return True if the glyph represents an ellipsis. False otherwise. +/// +IMPELLER_EXPORT +bool ImpellerGlyphInfoIsEllipsis(ImpellerGlyphInfo IMPELLER_NONNULL glyph_info); + +//------------------------------------------------------------------------------ +/// @param[in] glyph_info The glyph information. +/// +/// @return The direction of the run that contains the glyph. +/// +IMPELLER_EXPORT +ImpellerTextDirection ImpellerGlyphInfoGetTextDirection( + ImpellerGlyphInfo IMPELLER_NONNULL glyph_info); + +IMPELLER_EXTERN_C_END + +// NOLINTEND(google-objc-function-naming) + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.hpp b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.hpp new file mode 100644 index 0000000000000000000000000000000000000000..77cb632e374c420aae3f7b4931d58df217aa2eb2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller.hpp @@ -0,0 +1,1766 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_HPP_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_HPP_ + +#include +#include +#include +#include +#include + +#include "impeller.h" + +//------------------------------------------------------------------------------ +/// A C++ 17 wrapper to the C Impeller API. This is a convenience wrapper for +/// the C++ API and only depends on standard libc++ utilities in addition to +/// impeller.h +/// + +#ifndef IMPELLER_HPP_NAMESPACE +#define IMPELLER_HPP_NAMESPACE impeller::hpp +#endif // IMPELLER_HPP_NAMESPACE + +// Tripping this assertion means that the C++ wrapper needs to be updated to +// account for impeller.h changes as necessary. +static_assert(IMPELLER_VERSION == IMPELLER_MAKE_VERSION(1, 1, 3, 0), + "C++ bindings must be for the same version as the C API."); + +namespace IMPELLER_HPP_NAMESPACE { + +template +struct Proc { + using FunctionType = T; + + const char* name = nullptr; + + FunctionType* function = nullptr; + + template + auto operator()(Args&&... args) const { + return function(std::forward(args)...); + } +}; + +#define IMPELLER_HPP_EACH_PROC(PROC) \ + PROC(ImpellerColorFilterCreateBlendNew) \ + PROC(ImpellerColorFilterCreateColorMatrixNew) \ + PROC(ImpellerColorFilterRelease) \ + PROC(ImpellerColorFilterRetain) \ + PROC(ImpellerColorSourceCreateConicalGradientNew) \ + PROC(ImpellerColorSourceCreateImageNew) \ + PROC(ImpellerColorSourceCreateLinearGradientNew) \ + PROC(ImpellerColorSourceCreateRadialGradientNew) \ + PROC(ImpellerColorSourceCreateSweepGradientNew) \ + PROC(ImpellerColorSourceRelease) \ + PROC(ImpellerColorSourceRetain) \ + PROC(ImpellerContextCreateMetalNew) \ + PROC(ImpellerContextCreateOpenGLESNew) \ + PROC(ImpellerContextCreateVulkanNew) \ + PROC(ImpellerContextGetVulkanInfo) \ + PROC(ImpellerContextRelease) \ + PROC(ImpellerContextRetain) \ + PROC(ImpellerDisplayListBuilderClipOval) \ + PROC(ImpellerDisplayListBuilderClipPath) \ + PROC(ImpellerDisplayListBuilderClipRect) \ + PROC(ImpellerDisplayListBuilderClipRoundedRect) \ + PROC(ImpellerDisplayListBuilderCreateDisplayListNew) \ + PROC(ImpellerDisplayListBuilderDrawDashedLine) \ + PROC(ImpellerDisplayListBuilderDrawDisplayList) \ + PROC(ImpellerDisplayListBuilderDrawLine) \ + PROC(ImpellerDisplayListBuilderDrawOval) \ + PROC(ImpellerDisplayListBuilderDrawPaint) \ + PROC(ImpellerDisplayListBuilderDrawParagraph) \ + PROC(ImpellerDisplayListBuilderDrawPath) \ + PROC(ImpellerDisplayListBuilderDrawRect) \ + PROC(ImpellerDisplayListBuilderDrawRoundedRect) \ + PROC(ImpellerDisplayListBuilderDrawRoundedRectDifference) \ + PROC(ImpellerDisplayListBuilderDrawShadow) \ + PROC(ImpellerDisplayListBuilderDrawTexture) \ + PROC(ImpellerDisplayListBuilderDrawTextureRect) \ + PROC(ImpellerDisplayListBuilderGetSaveCount) \ + PROC(ImpellerDisplayListBuilderGetTransform) \ + PROC(ImpellerDisplayListBuilderNew) \ + PROC(ImpellerDisplayListBuilderRelease) \ + PROC(ImpellerDisplayListBuilderResetTransform) \ + PROC(ImpellerDisplayListBuilderRestore) \ + PROC(ImpellerDisplayListBuilderRestoreToCount) \ + PROC(ImpellerDisplayListBuilderRetain) \ + PROC(ImpellerDisplayListBuilderRotate) \ + PROC(ImpellerDisplayListBuilderSave) \ + PROC(ImpellerDisplayListBuilderSaveLayer) \ + PROC(ImpellerDisplayListBuilderScale) \ + PROC(ImpellerDisplayListBuilderSetTransform) \ + PROC(ImpellerDisplayListBuilderTransform) \ + PROC(ImpellerDisplayListBuilderTranslate) \ + PROC(ImpellerDisplayListRelease) \ + PROC(ImpellerDisplayListRetain) \ + PROC(ImpellerGetVersion) \ + PROC(ImpellerGlyphInfoGetGraphemeClusterBounds) \ + PROC(ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin) \ + PROC(ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd) \ + PROC(ImpellerGlyphInfoGetTextDirection) \ + PROC(ImpellerGlyphInfoIsEllipsis) \ + PROC(ImpellerGlyphInfoRelease) \ + PROC(ImpellerGlyphInfoRetain) \ + PROC(ImpellerImageFilterCreateBlurNew) \ + PROC(ImpellerImageFilterCreateComposeNew) \ + PROC(ImpellerImageFilterCreateDilateNew) \ + PROC(ImpellerImageFilterCreateErodeNew) \ + PROC(ImpellerImageFilterCreateMatrixNew) \ + PROC(ImpellerImageFilterRelease) \ + PROC(ImpellerImageFilterRetain) \ + PROC(ImpellerLineMetricsGetAscent) \ + PROC(ImpellerLineMetricsGetBaseline) \ + PROC(ImpellerLineMetricsGetCodeUnitEndIndex) \ + PROC(ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace) \ + PROC(ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline) \ + PROC(ImpellerLineMetricsGetCodeUnitStartIndex) \ + PROC(ImpellerLineMetricsGetDescent) \ + PROC(ImpellerLineMetricsGetHeight) \ + PROC(ImpellerLineMetricsIsHardbreak) \ + PROC(ImpellerLineMetricsGetLeft) \ + PROC(ImpellerLineMetricsGetUnscaledAscent) \ + PROC(ImpellerLineMetricsGetWidth) \ + PROC(ImpellerLineMetricsRelease) \ + PROC(ImpellerLineMetricsRetain) \ + PROC(ImpellerMaskFilterCreateBlurNew) \ + PROC(ImpellerMaskFilterRelease) \ + PROC(ImpellerMaskFilterRetain) \ + PROC(ImpellerPaintNew) \ + PROC(ImpellerPaintRelease) \ + PROC(ImpellerPaintRetain) \ + PROC(ImpellerPaintSetBlendMode) \ + PROC(ImpellerPaintSetColor) \ + PROC(ImpellerPaintSetColorFilter) \ + PROC(ImpellerPaintSetColorSource) \ + PROC(ImpellerPaintSetDrawStyle) \ + PROC(ImpellerPaintSetImageFilter) \ + PROC(ImpellerPaintSetMaskFilter) \ + PROC(ImpellerPaintSetStrokeCap) \ + PROC(ImpellerPaintSetStrokeJoin) \ + PROC(ImpellerPaintSetStrokeMiter) \ + PROC(ImpellerPaintSetStrokeWidth) \ + PROC(ImpellerParagraphBuilderAddText) \ + PROC(ImpellerParagraphBuilderBuildParagraphNew) \ + PROC(ImpellerParagraphBuilderNew) \ + PROC(ImpellerParagraphBuilderPopStyle) \ + PROC(ImpellerParagraphBuilderPushStyle) \ + PROC(ImpellerParagraphBuilderRelease) \ + PROC(ImpellerParagraphBuilderRetain) \ + PROC(ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew) \ + PROC(ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew) \ + PROC(ImpellerParagraphGetAlphabeticBaseline) \ + PROC(ImpellerParagraphGetHeight) \ + PROC(ImpellerParagraphGetIdeographicBaseline) \ + PROC(ImpellerParagraphGetLineCount) \ + PROC(ImpellerParagraphGetLineMetrics) \ + PROC(ImpellerParagraphGetLongestLineWidth) \ + PROC(ImpellerParagraphGetMaxIntrinsicWidth) \ + PROC(ImpellerParagraphGetMaxWidth) \ + PROC(ImpellerParagraphGetMinIntrinsicWidth) \ + PROC(ImpellerParagraphGetWordBoundary) \ + PROC(ImpellerParagraphRelease) \ + PROC(ImpellerParagraphRetain) \ + PROC(ImpellerParagraphStyleNew) \ + PROC(ImpellerParagraphStyleRelease) \ + PROC(ImpellerParagraphStyleRetain) \ + PROC(ImpellerParagraphStyleSetBackground) \ + PROC(ImpellerParagraphStyleSetFontFamily) \ + PROC(ImpellerParagraphStyleSetFontSize) \ + PROC(ImpellerParagraphStyleSetFontStyle) \ + PROC(ImpellerParagraphStyleSetFontWeight) \ + PROC(ImpellerParagraphStyleSetForeground) \ + PROC(ImpellerParagraphStyleSetHeight) \ + PROC(ImpellerParagraphStyleSetLocale) \ + PROC(ImpellerParagraphStyleSetMaxLines) \ + PROC(ImpellerParagraphStyleSetTextAlignment) \ + PROC(ImpellerParagraphStyleSetTextDirection) \ + PROC(ImpellerPathBuilderAddArc) \ + PROC(ImpellerPathBuilderAddOval) \ + PROC(ImpellerPathBuilderAddRect) \ + PROC(ImpellerPathBuilderAddRoundedRect) \ + PROC(ImpellerPathBuilderClose) \ + PROC(ImpellerPathBuilderCopyPathNew) \ + PROC(ImpellerPathBuilderCubicCurveTo) \ + PROC(ImpellerPathBuilderLineTo) \ + PROC(ImpellerPathBuilderMoveTo) \ + PROC(ImpellerPathBuilderNew) \ + PROC(ImpellerPathBuilderQuadraticCurveTo) \ + PROC(ImpellerPathBuilderRelease) \ + PROC(ImpellerPathBuilderRetain) \ + PROC(ImpellerPathBuilderTakePathNew) \ + PROC(ImpellerPathRelease) \ + PROC(ImpellerPathRetain) \ + PROC(ImpellerSurfaceCreateWrappedFBONew) \ + PROC(ImpellerSurfaceCreateWrappedMetalDrawableNew) \ + PROC(ImpellerSurfaceDrawDisplayList) \ + PROC(ImpellerSurfacePresent) \ + PROC(ImpellerSurfaceRelease) \ + PROC(ImpellerSurfaceRetain) \ + PROC(ImpellerTextureCreateWithContentsNew) \ + PROC(ImpellerTextureCreateWithOpenGLTextureHandleNew) \ + PROC(ImpellerTextureGetOpenGLHandle) \ + PROC(ImpellerTextureRelease) \ + PROC(ImpellerTextureRetain) \ + PROC(ImpellerTypographyContextNew) \ + PROC(ImpellerTypographyContextRegisterFont) \ + PROC(ImpellerTypographyContextRelease) \ + PROC(ImpellerTypographyContextRetain) \ + PROC(ImpellerVulkanSwapchainAcquireNextSurfaceNew) \ + PROC(ImpellerVulkanSwapchainCreateNew) \ + PROC(ImpellerVulkanSwapchainRelease) \ + PROC(ImpellerVulkanSwapchainRetain) + +struct ProcTable { + bool Initialize( + const std::function& resolver) { +#define IMPELLER_HPP_PROC(proc) \ + { \ + proc.function = \ + reinterpret_cast(resolver(proc.name)); \ + if (proc.function == nullptr) { \ + return false; \ + } \ + } + IMPELLER_HPP_EACH_PROC(IMPELLER_HPP_PROC) +#undef IMPELLER_HPP_PROC + return true; + } + +#define IMPELLER_HPP_PROC(name) Proc name = {#name, nullptr}; + IMPELLER_HPP_EACH_PROC(IMPELLER_HPP_PROC) +#undef IMPELLER_HPP_PROC +}; + +extern ProcTable gGlobalProcTable; + +enum class AdoptTag { + kAdopt, +}; + +template +class Object { + public: + Object() = default; + + explicit Object(T object) { Reset(object); } + + Object(T object, AdoptTag) : object_(object) {} + + ~Object() { Reset(); } + + Object(Object&& other) { std::swap(object_, other.object_); } + + Object(const Object& other) { Reset(other.Get()); } + + Object& operator=(Object&& other) { + std::swap(object_, other.object_); + return *this; + } + + Object& operator=(const Object& other) { + Reset(other.Get()); + return *this; + } + + T Get() const { return object_; } + + explicit operator bool() const { return object_ != nullptr; } + + private: + T object_ = nullptr; + + void Reset(T other = nullptr) { + if (object_ == other) { + return; + } + if (object_) { + Traits::Release(object_); + object_ = nullptr; + } + if (other) { + Traits::Retain(other); + object_ = other; + } + } + + [[nodiscard]] T Leak() { + T result = object_; + object_ = nullptr; + return result; + } +}; + +#define IMPELLER_HPP_DEFINE_TRAITS(object) \ + struct object##Traits { \ + static void Retain(object ctx) { \ + gGlobalProcTable.object##Retain(ctx); \ + } \ + static void Release(object ctx) { \ + gGlobalProcTable.object##Release(ctx); \ + } \ + }; + +IMPELLER_HPP_DEFINE_TRAITS(ImpellerColorFilter); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerColorSource); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerContext); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerDisplayList); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerDisplayListBuilder); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerGlyphInfo); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerImageFilter); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerLineMetrics); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerMaskFilter); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerPaint); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerParagraph); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerParagraphBuilder); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerParagraphStyle); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerPath); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerPathBuilder); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerSurface); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerTexture); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerTypographyContext); +IMPELLER_HPP_DEFINE_TRAITS(ImpellerVulkanSwapchain); + +#undef IMPELLER_HPP_DEFINE_TRAITS + +class Mapping final { + public: + Mapping(const uint8_t* mapping, + size_t size, + std::function release_callback) + : mapping_(mapping), + size_(size), + release_callback_(std::move(release_callback)) {} + + const uint8_t* GetMapping() const { return mapping_; } + + size_t GetSize() const { return size_; } + + private: + const uint8_t* mapping_ = nullptr; + size_t size_ = 0u; + std::function release_callback_; +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerContext +/// +class Context final : public Object { + public: + Context(ImpellerContext context, AdoptTag tag) : Object(context, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerContextCreateOpenGLESNew + /// + static Context OpenGLES( + const std::function& gl_proc_address_resolver) { + struct UserData { + std::function resolver; + }; + UserData user_data; + user_data.resolver = gl_proc_address_resolver; + ImpellerProcAddressCallback callback = [](const char* proc_name, + void* user_data) -> void* { + return reinterpret_cast(user_data)->resolver(proc_name); + }; + return Context( + gGlobalProcTable.ImpellerContextCreateOpenGLESNew(IMPELLER_VERSION, // + callback, // + &user_data // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerContextGetVulkanInfo + /// + bool GetVulkanInfo(ImpellerContextVulkanInfo& info) const { + return gGlobalProcTable.ImpellerContextGetVulkanInfo(Get(), &info); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerTexture +/// +class Texture final : public Object { + public: + Texture(ImpellerTexture texture, AdoptTag adopt) : Object(texture, adopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerTextureCreateWithContentsNew + /// + static Texture WithContents(const Context& context, + const ImpellerTextureDescriptor& descriptor, + std::unique_ptr mapping = nullptr) { + if (mapping == nullptr) { + mapping = std::make_unique(nullptr, 0u, nullptr); + } + ImpellerMapping c_mapping = {}; + c_mapping.data = mapping->GetMapping(); + c_mapping.length = mapping->GetSize(); + c_mapping.on_release = [](void* user_data) -> void { + delete reinterpret_cast(user_data); + }; + return Texture(gGlobalProcTable.ImpellerTextureCreateWithContentsNew( + context.Get(), // + &descriptor, // + &c_mapping, // + mapping.release() // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerTextureCreateWithOpenGLTextureHandleNew + /// + static Texture WithOpenGLTexture(const Context& context, + const ImpellerTextureDescriptor& descriptor, + uint64_t handle) { + return Texture( + gGlobalProcTable.ImpellerTextureCreateWithOpenGLTextureHandleNew( + context.Get(), // + &descriptor, // + handle // + ), + AdoptTag::kAdopt); + } + + uint64_t GetOpenGLHandle() const { + return gGlobalProcTable.ImpellerTextureGetOpenGLHandle(Get()); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerColorFilter +/// +class ColorFilter final + : public Object { + public: + ColorFilter(ImpellerColorFilter filter, AdoptTag tag) : Object(filter, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerColorFilterCreateBlendNew + /// + static ColorFilter Blend(const ImpellerColor& color, ImpellerBlendMode mode) { + return ColorFilter( + gGlobalProcTable.ImpellerColorFilterCreateBlendNew(&color, mode), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerColorFilterCreateColorMatrixNew + /// + static ColorFilter Matrix(const ImpellerColorMatrix& color_matrix) { + return ColorFilter( + gGlobalProcTable.ImpellerColorFilterCreateColorMatrixNew(&color_matrix), + AdoptTag::kAdopt); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerColorSource +/// +class ColorSource final + : public Object { + public: + ColorSource(ImpellerColorSource source, AdoptTag tag) : Object(source, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerColorSourceCreateConicalGradientNew + /// + static ColorSource ConicalGradient( + const ImpellerPoint& start_center, + float start_radius, + const ImpellerPoint& end_center, + float end_radius, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation = nullptr) { + return ColorSource( + gGlobalProcTable.ImpellerColorSourceCreateConicalGradientNew( + &start_center, // + start_radius, // + &end_center, // + end_radius, // + stop_count, // + colors, // + stops, // + tile_mode, // + transformation // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerColorSourceCreateImageNew + /// + static ColorSource Image(const Texture& image, + ImpellerTileMode horizontal_tile_mode, + ImpellerTileMode vertical_tile_mode, + ImpellerTextureSampling sampling, + const ImpellerMatrix* transformation = nullptr) { + return ColorSource(gGlobalProcTable.ImpellerColorSourceCreateImageNew( + image.Get(), // + horizontal_tile_mode, // + vertical_tile_mode, // + sampling, // + transformation // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerColorSourceCreateLinearGradientNew + /// + static ColorSource LinearGradient( + const ImpellerPoint& start_point, + const ImpellerPoint& end_point, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation = nullptr) { + return ColorSource( + gGlobalProcTable.ImpellerColorSourceCreateLinearGradientNew( + &start_point, + &end_point, // + stop_count, // + colors, // + stops, // + tile_mode, // + transformation // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerColorSourceCreateRadialGradientNew + /// + static ColorSource RadialGradient( + const ImpellerPoint& center, + float radius, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation = nullptr) { + return ColorSource( + gGlobalProcTable.ImpellerColorSourceCreateRadialGradientNew( + ¢er, // + radius, // + stop_count, // + colors, // + stops, // + tile_mode, // + transformation // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerColorSourceCreateSweepGradientNew + /// + static ColorSource SweepGradient( + const ImpellerPoint& center, + float start, + float end, + uint32_t stop_count, + const ImpellerColor* colors, + const float* stops, + ImpellerTileMode tile_mode, + const ImpellerMatrix* transformation = nullptr) { + return ColorSource( + gGlobalProcTable.ImpellerColorSourceCreateSweepGradientNew( + ¢er, // + start, // + end, // + stop_count, // + colors, // + stops, // + tile_mode, // + transformation // + ), + AdoptTag::kAdopt); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerImageFilter +/// +class ImageFilter final + : public Object { + public: + ImageFilter(ImpellerImageFilter filter, AdoptTag tag) : Object(filter, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerImageFilterCreateBlurNew + /// + static ImageFilter Blur(float x_sigma, + float y_sigma, + ImpellerTileMode tile_mode) { + return ImageFilter(gGlobalProcTable.ImpellerImageFilterCreateBlurNew( + x_sigma, y_sigma, tile_mode), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerImageFilterCreateComposeNew + /// + static ImageFilter Compose(const ImageFilter& outer, + const ImageFilter& inner) { + return ImageFilter(gGlobalProcTable.ImpellerImageFilterCreateComposeNew( + outer.Get(), inner.Get()), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerImageFilterCreateDilateNew + /// + static ImageFilter Dilate(float x_radius, float y_radius) { + return ImageFilter( + gGlobalProcTable.ImpellerImageFilterCreateDilateNew(x_radius, y_radius), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerImageFilterCreateErodeNew + /// + static ImageFilter Erode(float x_radius, float y_radius) { + return ImageFilter( + gGlobalProcTable.ImpellerImageFilterCreateErodeNew(x_radius, y_radius), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerImageFilterCreateMatrixNew + /// + static ImageFilter Matrix(const ImpellerMatrix& matrix, + ImpellerTextureSampling sampling) { + return ImageFilter( + gGlobalProcTable.ImpellerImageFilterCreateMatrixNew(&matrix, sampling), + AdoptTag::kAdopt); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerMaskFilter +/// +class MaskFilter final + : public Object { + public: + MaskFilter(ImpellerMaskFilter filter, AdoptTag tag) : Object(filter, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerMaskFilterCreateBlurNew + /// + static MaskFilter Blur(ImpellerBlurStyle style, float sigma) { + return MaskFilter( + gGlobalProcTable.ImpellerMaskFilterCreateBlurNew(style, sigma), + AdoptTag::kAdopt); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerGlyphInfo +/// +class GlyphInfo final + : public Object { + public: + GlyphInfo(ImpellerGlyphInfo info, AdoptTag tag) : Object(info, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin + /// + size_t GetGraphemeClusterCodeUnitRangeBegin() const { + return gGlobalProcTable + .ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd + /// + size_t GetGraphemeClusterCodeUnitRangeEnd() const { + return gGlobalProcTable.ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd( + Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetGraphemeClusterBounds + /// + ImpellerRect GetGraphemeClusterBounds() const { + return gGlobalProcTable.ImpellerGlyphInfoGetGraphemeClusterBounds(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoIsEllipsis + /// + bool IsEllipsis() const { + return gGlobalProcTable.ImpellerGlyphInfoIsEllipsis(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerGlyphInfoGetTextDirection + /// + ImpellerTextDirection GetTextDirection() const { + return gGlobalProcTable.ImpellerGlyphInfoGetTextDirection(Get()); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerLineMetrics +/// +class LineMetrics final + : public Object { + public: + LineMetrics(ImpellerLineMetrics metrics, AdoptTag tag) + : Object(metrics, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetUnscaledAscent + /// + double GetUnscaledAscent(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetUnscaledAscent(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetAscent + /// + double GetAscent(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetAscent(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetDescent + /// + double GetDescent(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetDescent(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetBaseline + /// + double GetBaseline(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetBaseline(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsIsHardbreak + /// + bool IsHardbreak(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsIsHardbreak(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetWidth + /// + double GetWidth(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetWidth(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetHeight + /// + double GetHeight(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetHeight(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetLeft + /// + double GetLeft(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetLeft(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitStartIndex + /// + size_t GetCodeUnitStartIndex(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetCodeUnitStartIndex(Get(), + line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndex + /// + size_t GetCodeUnitEndIndex(size_t line) const { + return gGlobalProcTable.ImpellerLineMetricsGetCodeUnitEndIndex(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace + /// + size_t GetCodeUnitEndIndexExcludingWhitespace(size_t line) const { + return gGlobalProcTable + .ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace(Get(), line); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline + /// + size_t GetCodeUnitEndIndexIncludingNewline(size_t line) const { + return gGlobalProcTable + .ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline(Get(), line); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerParagraph +/// +class Paragraph final + : public Object { + public: + Paragraph(ImpellerParagraph paragraph, AdoptTag tag) + : Object(paragraph, AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetAlphabeticBaseline + /// + float GetAlphabeticBaseline() { + return gGlobalProcTable.ImpellerParagraphGetAlphabeticBaseline(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetHeight + /// + float GetHeight() { + return gGlobalProcTable.ImpellerParagraphGetHeight(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetIdeographicBaseline + /// + float GetIdeographicBaseline() { + return gGlobalProcTable.ImpellerParagraphGetIdeographicBaseline(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetLineCount + /// + uint32_t GetLineCount() { + return gGlobalProcTable.ImpellerParagraphGetLineCount(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetLongestLineWidth + /// + float GetLongestLineWidth() { + return gGlobalProcTable.ImpellerParagraphGetLongestLineWidth(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetMaxIntrinsicWidth + /// + float GetMaxIntrinsicWidth() { + return gGlobalProcTable.ImpellerParagraphGetMaxIntrinsicWidth(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetMaxWidth + /// + float GetMaxWidth() { + return gGlobalProcTable.ImpellerParagraphGetMaxWidth(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetMinIntrinsicWidth + /// + float GetMinIntrinsicWidth() { + return gGlobalProcTable.ImpellerParagraphGetMinIntrinsicWidth(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetLineMetrics + /// + LineMetrics GetLineMetrics() const { + auto metrics = gGlobalProcTable.ImpellerParagraphGetLineMetrics(Get()); + gGlobalProcTable.ImpellerLineMetricsRetain(metrics); + return LineMetrics(metrics, AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew + /// + GlyphInfo GlyphInfoAtCodeUnitIndex(size_t code_unit_index) { + return GlyphInfo( + gGlobalProcTable.ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew( + Get(), code_unit_index), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew + /// + GlyphInfo GlyphInfoAtParagraphCoordinates(double x, double y) { + return GlyphInfo( + gGlobalProcTable + .ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew( + Get(), // + x, // + y // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphGetWordBoundary + /// + ImpellerRange GetWordBoundary(size_t code_unit_index) { + return gGlobalProcTable.ImpellerParagraphGetWordBoundary(Get(), + code_unit_index); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerPaint +/// +class Paint final : public Object { + public: + Paint() : Object(gGlobalProcTable.ImpellerPaintNew(), AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetColor + /// + Paint& SetColor(const ImpellerColor& color) { + gGlobalProcTable.ImpellerPaintSetColor(Get(), &color); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetBlendMode + /// + Paint& SetBlendMode(ImpellerBlendMode mode) { + gGlobalProcTable.ImpellerPaintSetBlendMode(Get(), mode); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetDrawStyle + /// + Paint& SetDrawStyle(ImpellerDrawStyle style) { + gGlobalProcTable.ImpellerPaintSetDrawStyle(Get(), style); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetStrokeCap + /// + Paint& SetStrokeCap(ImpellerStrokeCap cap) { + gGlobalProcTable.ImpellerPaintSetStrokeCap(Get(), cap); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetStrokeJoin + /// + Paint& SetStrokeJoin(ImpellerStrokeJoin join) { + gGlobalProcTable.ImpellerPaintSetStrokeJoin(Get(), join); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetStrokeWidth + /// + Paint& SetStrokeWidth(float width) { + gGlobalProcTable.ImpellerPaintSetStrokeWidth(Get(), width); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetStrokeMiter + /// + Paint& SetStrokeMiter(float miter) { + gGlobalProcTable.ImpellerPaintSetStrokeMiter(Get(), miter); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetColorFilter + /// + Paint& SetColorFilter(const ColorFilter& filter) { + gGlobalProcTable.ImpellerPaintSetColorFilter(Get(), filter.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetColorSource + /// + Paint& SetColorSource(const ColorSource& source) { + gGlobalProcTable.ImpellerPaintSetColorSource(Get(), source.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetImageFilter + /// + Paint& SetImageFilter(const ImageFilter& filter) { + gGlobalProcTable.ImpellerPaintSetImageFilter(Get(), filter.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPaintSetMaskFilter + /// + Paint& SetMaskFilter(const MaskFilter& filter) { + gGlobalProcTable.ImpellerPaintSetMaskFilter(Get(), filter.Get()); + return *this; + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerParagraphStyle +/// +class ParagraphStyle final + : public Object { + public: + ParagraphStyle() + : Object(gGlobalProcTable.ImpellerParagraphStyleNew(), AdoptTag::kAdopt) { + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetBackground + /// + ParagraphStyle& SetBackground(const Paint& paint) { + gGlobalProcTable.ImpellerParagraphStyleSetBackground(Get(), paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetFontFamily + /// + ParagraphStyle& SetFontFamily(const char* family_name) { + gGlobalProcTable.ImpellerParagraphStyleSetFontFamily(Get(), family_name); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetFontSize + /// + ParagraphStyle& SetFontSize(float size) { + gGlobalProcTable.ImpellerParagraphStyleSetFontSize(Get(), size); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetFontStyle + /// + ParagraphStyle& SetFontStyle(ImpellerFontStyle style) { + gGlobalProcTable.ImpellerParagraphStyleSetFontStyle(Get(), style); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetFontWeight + /// + ParagraphStyle& SetFontWeight(ImpellerFontWeight weight) { + gGlobalProcTable.ImpellerParagraphStyleSetFontWeight(Get(), weight); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetForeground + /// + ParagraphStyle& SetForeground(const Paint& paint) { + gGlobalProcTable.ImpellerParagraphStyleSetForeground(Get(), paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetHeight + /// + ParagraphStyle& SetHeight(float height) { + gGlobalProcTable.ImpellerParagraphStyleSetHeight(Get(), height); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetLocale + /// + ParagraphStyle& SetLocale(const char* locale) { + gGlobalProcTable.ImpellerParagraphStyleSetLocale(Get(), locale); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetMaxLines + /// + ParagraphStyle& SetMaxLines(uint32_t max_lines) { + gGlobalProcTable.ImpellerParagraphStyleSetMaxLines(Get(), max_lines); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetTextAlignment + /// + ParagraphStyle& SetTextAlignment(ImpellerTextAlignment align) { + gGlobalProcTable.ImpellerParagraphStyleSetTextAlignment(Get(), align); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphStyleSetTextDirection + /// + ParagraphStyle& SetTextDirection(ImpellerTextDirection direction) { + gGlobalProcTable.ImpellerParagraphStyleSetTextDirection(Get(), direction); + return *this; + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerTypographyContext +/// +class TypographyContext final : public Object { + public: + TypographyContext() + : Object(gGlobalProcTable.ImpellerTypographyContextNew(), + AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerTypographyContextRegisterFont + /// + bool RegisterFont(std::unique_ptr mapping, + const char* optional_family_name_alias = nullptr) { + if (!mapping) { + return false; + } + ImpellerMapping c_mapping = {}; + c_mapping.data = mapping->GetMapping(); + c_mapping.length = mapping->GetSize(); + c_mapping.on_release = [](void* user_data) { + delete reinterpret_cast(user_data); + }; + return gGlobalProcTable.ImpellerTypographyContextRegisterFont( + Get(), // + &c_mapping, // + mapping.release(), // + optional_family_name_alias // + ); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerParagraphBuilder +/// +class ParagraphBuilder final + : public Object { + public: + explicit ParagraphBuilder(const TypographyContext& context) + : Object(gGlobalProcTable.ImpellerParagraphBuilderNew(context.Get()), + AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderBuildParagraphNew + /// + Paragraph Build(float width) { + return Paragraph( + gGlobalProcTable.ImpellerParagraphBuilderBuildParagraphNew(Get(), // + width // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderPushStyle + /// + ParagraphBuilder& PushStyle(const ParagraphStyle& style) { + gGlobalProcTable.ImpellerParagraphBuilderPushStyle(Get(), style.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderPopStyle + /// + ParagraphBuilder& PopStyle() { + gGlobalProcTable.ImpellerParagraphBuilderPopStyle(Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderAddText + /// + ParagraphBuilder& AddText(const uint8_t* utf8_data, uint32_t length) { + gGlobalProcTable.ImpellerParagraphBuilderAddText(Get(), utf8_data, length); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderAddText + /// + ParagraphBuilder& AddText(const std::string& string) { + return AddText(reinterpret_cast(string.data()), + string.size()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerParagraphBuilderAddText + /// + ParagraphBuilder& AddText(const std::string_view& string) { + return AddText(reinterpret_cast(string.data()), + string.size()); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerPath +/// +class Path final : public Object { + public: + Path(ImpellerPath path, AdoptTag tag) : Object(path, tag) {} +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerPathBuilder +/// +class PathBuilder final + : public Object { + public: + PathBuilder() + : Object(gGlobalProcTable.ImpellerPathBuilderNew(), AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderCopyPathNew + /// + Path BuildCopy(ImpellerFillType fill = + ImpellerFillType::kImpellerFillTypeNonZero) const { + return Path(gGlobalProcTable.ImpellerPathBuilderCopyPathNew(Get(), fill), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderTakePathNew + /// + Path Build( + ImpellerFillType fill = ImpellerFillType::kImpellerFillTypeNonZero) { + return Path(gGlobalProcTable.ImpellerPathBuilderTakePathNew(Get(), fill), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderAddArc + /// + PathBuilder& AddArc(const ImpellerRect& oval_bounds, + float start_angle_degrees, + float end_angle_degrees) { + gGlobalProcTable.ImpellerPathBuilderAddArc(Get(), // + &oval_bounds, // + start_angle_degrees, // + end_angle_degrees // + ); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderAddOval + /// + PathBuilder& AddOval(const ImpellerRect& oval_bounds) { + gGlobalProcTable.ImpellerPathBuilderAddOval(Get(), &oval_bounds); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderAddRect + /// + PathBuilder& AddRect(const ImpellerRect& rect) { + gGlobalProcTable.ImpellerPathBuilderAddRect(Get(), &rect); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderAddRoundedRect + /// + PathBuilder& AddRoundedRect(const ImpellerRect& rect, + const ImpellerRoundingRadii& rounding_radii) { + gGlobalProcTable.ImpellerPathBuilderAddRoundedRect(Get(), &rect, + &rounding_radii); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderClose + /// + PathBuilder& Close() { + gGlobalProcTable.ImpellerPathBuilderClose(Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderCubicCurveTo + /// + PathBuilder& CubicCurveTo(const ImpellerPoint& control_point_1, + const ImpellerPoint& control_point_2, + const ImpellerPoint& end_point) { + gGlobalProcTable.ImpellerPathBuilderCubicCurveTo( + Get(), &control_point_1, &control_point_2, &end_point); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderLineTo + /// + PathBuilder& LineTo(const ImpellerPoint& location) { + gGlobalProcTable.ImpellerPathBuilderLineTo(Get(), &location); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderMoveTo + /// + PathBuilder& MoveTo(const ImpellerPoint& location) { + gGlobalProcTable.ImpellerPathBuilderMoveTo(Get(), &location); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerPathBuilderQuadraticCurveTo + /// + PathBuilder& QuadraticCurveTo(const ImpellerPoint& control_point, + const ImpellerPoint& end_point) { + gGlobalProcTable.ImpellerPathBuilderQuadraticCurveTo(Get(), &control_point, + &end_point); + return *this; + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerDisplayList +/// +class DisplayList final + : public Object { + public: + DisplayList(ImpellerDisplayList display_list, AdoptTag tag) + : Object(display_list, tag) {} +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerSurface +/// +class Surface final : public Object { + public: + explicit Surface(ImpellerSurface surface) : Object(surface) {} + + Surface(ImpellerSurface surface, AdoptTag tag) : Object(surface, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerSurfaceCreateWrappedFBONew + /// + static Surface WrapFBO(const Context& context, + uint64_t fbo, + ImpellerPixelFormat format, + const ImpellerISize& size) { + return Surface( + gGlobalProcTable.ImpellerSurfaceCreateWrappedFBONew(context.Get(), // + fbo, // + format, // + &size // + ), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerSurfaceCreateWrappedMetalDrawableNew + /// + static Surface WrapMetalDrawable(const Context& context, + void* metal_drawable) { + return Surface( + gGlobalProcTable.ImpellerSurfaceCreateWrappedMetalDrawableNew( + context.Get(), metal_drawable), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerSurfaceDrawDisplayList + /// + bool Draw(const DisplayList& display_list) const { + return gGlobalProcTable.ImpellerSurfaceDrawDisplayList(Get(), + display_list.Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerSurfacePresent + /// + bool Present() const { + return gGlobalProcTable.ImpellerSurfacePresent(Get()); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerVulkanSwapchain +/// +class VulkanSwapchain final + : public Object { + public: + VulkanSwapchain(ImpellerVulkanSwapchain swapchain, AdoptTag tag) + : Object(swapchain, tag) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerVulkanSwapchainCreateNew + /// + static VulkanSwapchain Create(const Context& context, + void* vulkan_surface_khr) { + return VulkanSwapchain(gGlobalProcTable.ImpellerVulkanSwapchainCreateNew( + context.Get(), vulkan_surface_khr), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerVulkanSwapchainAcquireNextSurfaceNew + /// + Surface AcquireNextSurface() const { + return Surface( + gGlobalProcTable.ImpellerVulkanSwapchainAcquireNextSurfaceNew(Get()), + AdoptTag::kAdopt); + } +}; + +//------------------------------------------------------------------------------ +/// @see ImpellerDisplayListBuilder +/// +class DisplayListBuilder final + : public Object { + public: + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderNew + /// + explicit DisplayListBuilder(const ImpellerRect* cull_rect = nullptr) + : Object(gGlobalProcTable.ImpellerDisplayListBuilderNew(cull_rect), + AdoptTag::kAdopt) {} + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderCreateDisplayListNew + /// + DisplayList Build() { + return DisplayList( + gGlobalProcTable.ImpellerDisplayListBuilderCreateDisplayListNew(Get()), + AdoptTag::kAdopt); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderClipOval + /// + DisplayListBuilder& ClipOval(const ImpellerRect& oval_bounds, + ImpellerClipOperation op) { + gGlobalProcTable.ImpellerDisplayListBuilderClipOval(Get(), // + &oval_bounds, // + op); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderClipPath + /// + DisplayListBuilder& ClipPath(const Path& path, ImpellerClipOperation op) { + gGlobalProcTable.ImpellerDisplayListBuilderClipPath(Get(), // + path.Get(), // + op); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderClipRect + /// + DisplayListBuilder& ClipRect(const ImpellerRect& rect, + ImpellerClipOperation op) { + gGlobalProcTable.ImpellerDisplayListBuilderClipRect(Get(), // + &rect, // + op); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderClipRoundedRect + /// + DisplayListBuilder& ClipRoundedRect(const ImpellerRect& rect, + const ImpellerRoundingRadii& radii, + ImpellerClipOperation op) { + gGlobalProcTable.ImpellerDisplayListBuilderClipRoundedRect(Get(), // + &rect, // + &radii, // + op // + ); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawDashedLine + /// + DisplayListBuilder& DrawDashedLine(const ImpellerPoint& from, + const ImpellerPoint& to, + float on_length, + float off_length, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawDashedLine(Get(), // + &from, // + &to, // + on_length, // + off_length, // + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawDisplayList + /// + DisplayListBuilder& DrawDisplayList(const DisplayList& display_list, + float opacity = 1.0f) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawDisplayList( + Get(), display_list.Get(), opacity); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawLine + /// + DisplayListBuilder& DrawLine(const ImpellerPoint& from, + const ImpellerPoint& to, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawLine(Get(), // + &from, // + &to, // + paint.Get() // + ); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawOval + /// + DisplayListBuilder& DrawOval(const ImpellerRect& oval_bounds, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawOval(Get(), // + &oval_bounds, // + paint.Get() // + ); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawPaint + /// + DisplayListBuilder& DrawPaint(const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawPaint(Get(), paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawParagraph + /// + DisplayListBuilder& DrawParagraph(const Paragraph& paragraph, + const ImpellerPoint& point) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawParagraph( + Get(), paragraph.Get(), &point); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawShadow + /// + DisplayListBuilder& DrawShadow(const Path& path, + const ImpellerColor& shadow_color, + float elevation, + bool occluder_is_transparent, + float device_pixel_ratio) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawShadow( + Get(), path.Get(), &shadow_color, elevation, occluder_is_transparent, + device_pixel_ratio); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawPath + /// + DisplayListBuilder& DrawPath(const Path& path, const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawPath(Get(), path.Get(), + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawRect + /// + DisplayListBuilder& DrawRect(const ImpellerRect& rect, const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawRect(Get(), &rect, + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawRoundedRect + /// + DisplayListBuilder& DrawRoundedRect(const ImpellerRect& rect, + const ImpellerRoundingRadii& radii, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawRoundedRect(Get(), // + &rect, // + &radii, // + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawRoundedRectDifference + /// + DisplayListBuilder& DrawRoundedRectDifference( + const ImpellerRect& outer_rect, + const ImpellerRoundingRadii& outer_radii, + const ImpellerRect& inner_rect, + const ImpellerRoundingRadii& inner_radii, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawRoundedRectDifference( + Get(), // + &outer_rect, // + &outer_radii, // + &inner_rect, // + &inner_radii, // + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawTexture + /// + DisplayListBuilder& DrawTexture(const Texture& texture, + const ImpellerPoint& point, + ImpellerTextureSampling sampling, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawTexture( + Get(), texture.Get(), &point, sampling, paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderDrawTextureRect + /// + DisplayListBuilder& DrawTextureRect(const Texture& texture, + const ImpellerRect& src_rect, + const ImpellerRect& dst_rect, + ImpellerTextureSampling sampling, + const Paint& paint) { + gGlobalProcTable.ImpellerDisplayListBuilderDrawTextureRect( + Get(), texture.Get(), // + &src_rect, // + &dst_rect, // + sampling, // + paint.Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderGetSaveCount + /// + uint32_t GetSaveCount() { + return gGlobalProcTable.ImpellerDisplayListBuilderGetSaveCount(Get()); + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderGetTransform + /// + ImpellerMatrix GetTransform() { + ImpellerMatrix result; + gGlobalProcTable.ImpellerDisplayListBuilderGetTransform(Get(), &result); + return result; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderResetTransform + /// + DisplayListBuilder& ResetTransform() { + gGlobalProcTable.ImpellerDisplayListBuilderResetTransform(Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderRestore + /// + DisplayListBuilder& Restore() { + gGlobalProcTable.ImpellerDisplayListBuilderRestore(Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderRestoreToCount + /// + DisplayListBuilder& RestoreToCount(uint32_t count) { + gGlobalProcTable.ImpellerDisplayListBuilderRestoreToCount(Get(), // + count); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderRotate + /// + DisplayListBuilder& Rotate(float angle_degrees) { + gGlobalProcTable.ImpellerDisplayListBuilderRotate(Get(), // + angle_degrees); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderSave + /// + DisplayListBuilder& Save() { + gGlobalProcTable.ImpellerDisplayListBuilderSave(Get()); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderSaveLayer + /// + DisplayListBuilder& SaveLayer(const ImpellerRect& bounds, + const Paint* paint = nullptr, + const ImageFilter* backdrop = nullptr) { + gGlobalProcTable.ImpellerDisplayListBuilderSaveLayer( + Get(), // + &bounds, // + paint ? paint->Get() : NULL, // + backdrop ? backdrop->Get() : NULL // + ); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderScale + /// + DisplayListBuilder& Scale(float x_scale, float y_scale) { + gGlobalProcTable.ImpellerDisplayListBuilderScale(Get(), // + x_scale, // + y_scale); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderSetTransform + /// + DisplayListBuilder& SetTransform(const ImpellerMatrix& transform) { + gGlobalProcTable.ImpellerDisplayListBuilderSetTransform(Get(), &transform); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderTransform + /// + DisplayListBuilder& Transform(const ImpellerMatrix& transform) { + gGlobalProcTable.ImpellerDisplayListBuilderTransform(Get(), &transform); + return *this; + } + + //---------------------------------------------------------------------------- + /// @see ImpellerDisplayListBuilderTranslate + /// + DisplayListBuilder& Translate(float x_translation, float y_translation) { + gGlobalProcTable.ImpellerDisplayListBuilderTranslate(Get(), // + x_translation, // + y_translation // + ); + return *this; + } +}; + +} // namespace IMPELLER_HPP_NAMESPACE + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_IMPELLER_HPP_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_c.c b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_c.c new file mode 100644 index 0000000000000000000000000000000000000000..721e5d8c3a52bd86ae8879af2124f055211e02eb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_c.c @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller.h" + +// This C file is only present to make sure the C header can be imported cleanly +// in a C translation unit. Accidental additions of C++ constructs to the header +// will lead to compilation errors in this translation unit. diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_cc.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_cc.cc new file mode 100644 index 0000000000000000000000000000000000000000..69323c90fd7fe14c16974b135e97e9cfbc894fd0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_cc.cc @@ -0,0 +1,8 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller.hpp" + +// This C++ file is only present to make sure the C++ header can be imported +// cleanly in a C++ translation unit. diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_unittests.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..16d0b484837c234167f4c32eaeb98a25601d2b7b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/impeller_unittests.cc @@ -0,0 +1,585 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/native_library.h" +#include "flutter/fml/string_conversion.h" +#include "flutter/testing/testing.h" +#include "impeller/base/allocation.h" +#include "impeller/renderer/backend/gles/context_gles.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/dl.h" +#include "impeller/toolkit/interop/dl_builder.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/impeller.hpp" +#include "impeller/toolkit/interop/paint.h" +#include "impeller/toolkit/interop/paragraph.h" +#include "impeller/toolkit/interop/paragraph_builder.h" +#include "impeller/toolkit/interop/paragraph_style.h" +#include "impeller/toolkit/interop/playground_test.h" +#include "impeller/toolkit/interop/surface.h" +#include "impeller/toolkit/interop/texture.h" +#include "impeller/toolkit/interop/typography_context.h" + +namespace impeller::interop::testing { + +using InteropPlaygroundTest = PlaygroundTest; +INSTANTIATE_PLAYGROUND_SUITE(InteropPlaygroundTest); + +TEST_P(InteropPlaygroundTest, CanCreateContext) { + auto context = CreateContext(); + ASSERT_TRUE(context); +} + +TEST_P(InteropPlaygroundTest, CanCreateDisplayListBuilder) { + hpp::DisplayListBuilder builder; + ASSERT_TRUE(builder); + ASSERT_TRUE(ToImpellerType(builder.GetTransform()).IsIdentity()); + ASSERT_EQ(builder.GetSaveCount(), 1u); + builder.Save(); + ASSERT_EQ(builder.GetSaveCount(), 2u); + builder.Restore(); + ASSERT_EQ(builder.GetSaveCount(), 1u); +} + +TEST_P(InteropPlaygroundTest, CanCreateSurface) { + if (GetBackend() != PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() + << "This test checks wrapping FBOs which is an OpenGL ES only call."; + return; + } + auto context = CreateContext(); + ASSERT_TRUE(context); + const auto window_size = GetWindowSize(); + ImpellerISize size = {window_size.width, window_size.height}; + auto surface = Adopt(ImpellerSurfaceCreateWrappedFBONew( + context.GetC(), // + 0u, // + ImpellerPixelFormat::kImpellerPixelFormatRGBA8888, // + &size) // + ); + ASSERT_TRUE(surface); +} + +TEST_P(InteropPlaygroundTest, CanDrawRect) { + auto builder = + Adopt(ImpellerDisplayListBuilderNew(nullptr)); + auto paint = Adopt(ImpellerPaintNew()); + ImpellerColor color = {0.0, 0.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint.GetC(), &color); + ImpellerRect rect = {10, 20, 100, 200}; + ImpellerDisplayListBuilderDrawRect(builder.GetC(), &rect, paint.GetC()); + color = {1.0, 0.0, 0.0, 1.0}; + ImpellerPaintSetColor(paint.GetC(), &color); + ImpellerDisplayListBuilderTranslate(builder.GetC(), 110, 210); + ImpellerMatrix scale_transform = { + // clang-format off + 2.0, 0.0, 0.0, 0.0, // + 0.0, 2.0, 0.0, 0.0, // + 0.0, 0.0, 1.0, 0.0, // + 0.0, 0.0, 0.0, 1.0, // + // clang-format on + }; + ImpellerDisplayListBuilderTransform(builder.GetC(), &scale_transform); + ImpellerDisplayListBuilderDrawRect(builder.GetC(), &rect, paint.GetC()); + auto dl = Adopt( + ImpellerDisplayListBuilderCreateDisplayListNew(builder.GetC())); + ASSERT_TRUE(dl); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + ImpellerSurfaceDrawDisplayList(surface.GetC(), dl.GetC()); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanDrawImage) { + auto compressed = LoadFixtureImageCompressed( + flutter::testing::OpenFixtureAsMapping("boston.jpg")); + ASSERT_NE(compressed, nullptr); + auto decompressed = compressed->Decode().ConvertToRGBA(); + ASSERT_TRUE(decompressed.IsValid()); + ImpellerMapping mapping = {}; + mapping.data = decompressed.GetAllocation()->GetMapping(); + mapping.length = decompressed.GetAllocation()->GetSize(); + + auto context = GetInteropContext(); + ImpellerTextureDescriptor desc = {}; + desc.pixel_format = ImpellerPixelFormat::kImpellerPixelFormatRGBA8888; + desc.size = {decompressed.GetSize().width, decompressed.GetSize().height}; + desc.mip_count = 1u; + auto texture = Adopt(ImpellerTextureCreateWithContentsNew( + context.GetC(), &desc, &mapping, nullptr)); + ASSERT_TRUE(texture); + auto builder = + Adopt(ImpellerDisplayListBuilderNew(nullptr)); + ImpellerPoint point = {100, 100}; + ImpellerDisplayListBuilderDrawTexture(builder.GetC(), texture.GetC(), &point, + kImpellerTextureSamplingLinear, + nullptr); + auto dl = Adopt( + ImpellerDisplayListBuilderCreateDisplayListNew(builder.GetC())); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + ImpellerSurfaceDrawDisplayList(surface.GetC(), dl.GetC()); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanCreateOpenGLImage) { + auto context = GetInteropContext(); + + auto impeller_context = context->GetContext(); + + if (impeller_context->GetBackendType() != + impeller::Context::BackendType::kOpenGLES) { + GTEST_SKIP() << "This test works with OpenGL handles is only suitable for " + "that backend."; + return; + } + + const auto& gl_context = ContextGLES::Cast(*impeller_context); + const auto& gl = gl_context.GetReactor()->GetProcTable(); + + constexpr ISize external_texture_size = {200, 300}; + + Allocation texture_data; + ASSERT_TRUE( + texture_data.Truncate(Bytes{external_texture_size.Area() * 4u}, false)); + + const auto kClearColor = Color::Fuchsia().ToR8G8B8A8(); + + for (size_t i = 0; i < external_texture_size.Area() * 4u; i += 4u) { + memcpy(texture_data.GetBuffer() + i, kClearColor.data(), 4); + } + + GLuint external_texture = GL_NONE; + gl.GenTextures(1u, &external_texture); + ASSERT_NE(external_texture, 0u); + gl.BindTexture(GL_TEXTURE_2D, external_texture); + gl.TexImage2D(GL_TEXTURE_2D, // + 0, // + GL_RGBA, // + external_texture_size.width, // + external_texture_size.height, // + 0, // + GL_RGBA, // + GL_UNSIGNED_BYTE, // + texture_data.GetBuffer() // + ); + + ImpellerTextureDescriptor desc = {}; + desc.pixel_format = ImpellerPixelFormat::kImpellerPixelFormatRGBA8888; + desc.size = {external_texture_size.width, external_texture_size.height}; + desc.mip_count = 1u; + auto texture = Adopt(ImpellerTextureCreateWithOpenGLTextureHandleNew( + context.GetC(), // + &desc, // + external_texture // + )); + ASSERT_TRUE(texture); + + ASSERT_EQ(ImpellerTextureGetOpenGLHandle(texture.GetC()), external_texture); + + auto builder = + Adopt(ImpellerDisplayListBuilderNew(nullptr)); + ImpellerPoint point = {100, 100}; + ImpellerDisplayListBuilderDrawTexture(builder.GetC(), texture.GetC(), &point, + kImpellerTextureSamplingLinear, + nullptr); + auto dl = Adopt( + ImpellerDisplayListBuilderCreateDisplayListNew(builder.GetC())); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + ImpellerSurfaceDrawDisplayList(surface.GetC(), dl.GetC()); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, ClearsOpenGLStancilStateAfterTransition) { + auto context = GetInteropContext(); + auto impeller_context = context->GetContext(); + if (impeller_context->GetBackendType() != + impeller::Context::BackendType::kOpenGLES) { + GTEST_SKIP() << "This test works with OpenGL handles is only suitable for " + "that backend."; + return; + } + const auto& gl_context = ContextGLES::Cast(*impeller_context); + const auto& gl = gl_context.GetReactor()->GetProcTable(); + auto builder = + Adopt(ImpellerDisplayListBuilderNew(nullptr)); + auto paint = Adopt(ImpellerPaintNew()); + ImpellerColor color = {0.0, 0.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint.GetC(), &color); + ImpellerRect rect = {10, 20, 100, 200}; + ImpellerDisplayListBuilderDrawRect(builder.GetC(), &rect, paint.GetC()); + color = {1.0, 0.0, 0.0, 1.0}; + ImpellerPaintSetColor(paint.GetC(), &color); + ImpellerDisplayListBuilderTranslate(builder.GetC(), 110, 210); + ImpellerDisplayListBuilderClipRect(builder.GetC(), &rect, + kImpellerClipOperationDifference); + ImpellerDisplayListBuilderDrawRect(builder.GetC(), &rect, paint.GetC()); + auto dl = Adopt( + ImpellerDisplayListBuilderCreateDisplayListNew(builder.GetC())); + ASSERT_TRUE(dl); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + ImpellerSurfaceDrawDisplayList(surface.GetC(), dl.GetC()); + // OpenGL state is reset even though the operations above enable a + // stencil check. + GLboolean stencil_enabled = true; + gl.GetBooleanv(GL_STENCIL_TEST, &stencil_enabled); + return stencil_enabled == GL_FALSE; + })); +} + +TEST_P(InteropPlaygroundTest, CanCreateParagraphs) { + // Create a typography context. + hpp::TypographyContext type_context; + ASSERT_TRUE(type_context); + + // Create a builder. + hpp::ParagraphBuilder builder(type_context); + ASSERT_TRUE(builder); + + // Create a paragraph style with the font size and foreground and background + // colors. + hpp::ParagraphStyle style; + ASSERT_TRUE(style); + style.SetFontSize(150.0f); + style.SetHeight(2.0f); + + { + hpp::Paint paint; + ASSERT_TRUE(paint); + paint.SetColor({1.0, 0.0, 0.0, 1.0}); + style.SetForeground(paint); + } + + { + hpp::Paint paint; + paint.SetColor({1.0, 1.0, 1.0, 1.0}); + style.SetBackground(paint); + } + + // Push the style onto the style stack. + builder.PushStyle(style); + std::string text = "the ⚡️ quick ⚡️ brown 🦊 fox jumps over the lazy dog 🐶."; + + // Add the paragraph text data. + builder.AddText(text); + + // Layout and build the paragraph. + auto paragraph = builder.Build(1200.0f); + ASSERT_TRUE(paragraph); + + // Create a display list with just the paragraph drawn into it. + hpp::DisplayListBuilder dl_builder; + dl_builder.DrawParagraph(paragraph, {20, 20}); + + // Build the display list. + auto dl = dl_builder.Build(); + + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + hpp::Surface window(surface.GetC()); + window.Draw(dl); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanCreateShapes) { + hpp::DisplayListBuilder builder; + + hpp::Paint red_paint; + red_paint.SetColor({1.0, 0.0, 0.0, 1.0}); + red_paint.SetStrokeWidth(10.0); + + builder.Translate(10, 10); + builder.DrawRect({0, 0, 100, 100}, red_paint); + builder.Translate(100, 100); + builder.DrawOval({0, 0, 100, 100}, red_paint); + builder.Translate(100, 100); + builder.DrawLine({0, 0}, {100, 100}, red_paint); + + builder.Translate(100, 100); + ImpellerRoundingRadii radii = {}; + radii.top_left = {10, 10}; + radii.bottom_right = {10, 10}; + builder.DrawRoundedRect({0, 0, 100, 100}, radii, red_paint); + + builder.Translate(100, 100); + builder.DrawPath(hpp::PathBuilder{}.AddOval({0, 0, 100, 100}).Build(), + red_paint); + + auto dl = builder.Build(); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + hpp::Surface window(surface.GetC()); + window.Draw(dl); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanCreateParagraphsWithCustomFont) { + // Create a typography context. + auto type_context = Adopt(ImpellerTypographyContextNew()); + ASSERT_TRUE(type_context); + + // Open the custom font file. + std::unique_ptr font_data = + flutter::testing::OpenFixtureAsMapping("wtf.otf"); + ASSERT_NE(font_data, nullptr); + ASSERT_GT(font_data->GetSize(), 0u); + ImpellerMapping font_data_mapping = { + .data = font_data->GetMapping(), + .length = font_data->GetSize(), + .on_release = [](auto ctx) { + delete reinterpret_cast(ctx); + }}; + auto registered = + ImpellerTypographyContextRegisterFont(type_context.GetC(), // + &font_data_mapping, // + font_data.release(), // + nullptr // + ); + ASSERT_TRUE(registered); + + // Create a builder. + auto builder = + Adopt(ImpellerParagraphBuilderNew(type_context.GetC())); + ASSERT_TRUE(builder); + + // Create a paragraph style with the font size and foreground and background + // colors. + auto style = Adopt(ImpellerParagraphStyleNew()); + ASSERT_TRUE(style); + ImpellerParagraphStyleSetFontSize(style.GetC(), 150.0f); + ImpellerParagraphStyleSetFontFamily(style.GetC(), "WhatTheFlutter"); + + { + auto paint = Adopt(ImpellerPaintNew()); + ASSERT_TRUE(paint); + ImpellerColor color = {0.0, 1.0, 1.0, 1.0}; + ImpellerPaintSetColor(paint.GetC(), &color); + ImpellerParagraphStyleSetForeground(style.GetC(), paint.GetC()); + } + + // Push the style onto the style stack. + ImpellerParagraphBuilderPushStyle(builder.GetC(), style.GetC()); + std::string text = "0F0F0F0"; + + // Add the paragraph text data. + ImpellerParagraphBuilderAddText(builder.GetC(), + reinterpret_cast(text.data()), + text.size()); + + // Layout and build the paragraph. + auto paragraph = Adopt( + ImpellerParagraphBuilderBuildParagraphNew(builder.GetC(), 1200.0f)); + ASSERT_TRUE(paragraph); + + // Create a display list with just the paragraph drawn into it. + auto dl_builder = + Adopt(ImpellerDisplayListBuilderNew(nullptr)); + ImpellerPoint point = {20, 20}; + ImpellerDisplayListBuilderDrawParagraph(dl_builder.GetC(), paragraph.GetC(), + &point); + auto dl = Adopt( + ImpellerDisplayListBuilderCreateDisplayListNew(dl_builder.GetC())); + + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + ImpellerSurfaceDrawDisplayList(surface.GetC(), dl.GetC()); + return true; + })); +} // namespace impeller::interop::testing + +static void DrawTextFrame(const hpp::TypographyContext& tc, + hpp::DisplayListBuilder& builder, + hpp::ParagraphStyle& p_style, + const hpp::Paint& bg, + ImpellerColor color, + ImpellerTextAlignment align, + float x_offset) { + const char text[] = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; + + hpp::Paint fg; + + // Draw a box. + fg.SetColor(color); + fg.SetDrawStyle(kImpellerDrawStyleStroke); + ImpellerRect box_rect = {10 + x_offset, 10, 200, 200}; + builder.DrawRect(box_rect, fg); + + // Draw text. + fg.SetDrawStyle(kImpellerDrawStyleFill); + p_style.SetForeground(fg); + p_style.SetBackground(bg); + p_style.SetTextAlignment(align); + + hpp::ParagraphBuilder p_builder(tc); + p_builder.PushStyle(p_style); + p_builder.AddText(reinterpret_cast(text), sizeof(text)); + + auto left_p = p_builder.Build(box_rect.width - 20.0); + ImpellerPoint pt = {20.0f + x_offset, 20.0f}; + float w = left_p.GetMaxWidth(); + float h = left_p.GetHeight(); + builder.DrawParagraph(left_p, pt); + fg.SetDrawStyle(kImpellerDrawStyleStroke); + + // Draw an inner box around the paragraph layout. + ImpellerRect inner_box_rect = {pt.x, pt.y, w, h}; + builder.DrawRect(inner_box_rect, fg); +} + +TEST_P(InteropPlaygroundTest, CanRenderTextAlignments) { + hpp::TypographyContext tc; + + hpp::DisplayListBuilder builder; + hpp::Paint bg; + hpp::ParagraphStyle p_style; + p_style.SetFontFamily("Roboto"); + p_style.SetFontSize(24.0); + p_style.SetFontWeight(kImpellerFontWeight400); + + // Clear the background to a white color. + ImpellerColor clear_color = {1.0, 1.0, 1.0, 1.0}; + bg.SetColor(clear_color); + builder.DrawPaint(bg); + + // Draw red, left-aligned text. + ImpellerColor red = {1.0, 0.0, 0.0, 1.0}; + DrawTextFrame(tc, builder, p_style, bg, red, kImpellerTextAlignmentLeft, 0.0); + + // Draw green, centered text. + ImpellerColor green = {0.0, 1.0, 0.0, 1.0}; + DrawTextFrame(tc, builder, p_style, bg, green, kImpellerTextAlignmentCenter, + 220.0); + + // Draw blue, right-aligned text. + ImpellerColor blue = {0.0, 0.0, 1.0, 1.0}; + DrawTextFrame(tc, builder, p_style, bg, blue, kImpellerTextAlignmentRight, + 440.0); + + auto dl = builder.Build(); + + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + hpp::Surface window(surface.GetC()); + window.Draw(dl); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanRenderShadows) { + hpp::DisplayListBuilder builder; + { + builder.DrawRect(ImpellerRect{0, 0, 400, 400}, + hpp::Paint{}.SetColor(ImpellerColor{ + 0.0, 1.0, 0.0, 1.0, kImpellerColorSpaceSRGB})); + } + ImpellerRect box = {100, 100, 100, 100}; + { + hpp::PathBuilder path_builder; + path_builder.AddRect(box); + ImpellerColor shadow_color = {0.0, 0.0, 0.0, 1.0, kImpellerColorSpaceSRGB}; + builder.DrawShadow(path_builder.Build(), shadow_color, 4.0f, false, 1.0f); + } + { + hpp::Paint red_paint; + red_paint.SetColor( + ImpellerColor{1.0, 0.0, 0.0, 1.0, kImpellerColorSpaceSRGB}); + builder.DrawRect(box, red_paint); + } + auto dl = builder.Build(); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + hpp::Surface window(surface.GetC()); + window.Draw(dl); + return true; + })); +} + +TEST_P(InteropPlaygroundTest, CanMeasureText) { + hpp::TypographyContext type_context; + hpp::ParagraphBuilder paragraph_builder(type_context); + hpp::ParagraphStyle paragraph_style; + paragraph_style.SetFontSize(50); + paragraph_builder.PushStyle(paragraph_style); + const std::string text = + "🏁 Can 👨‍👨‍👦‍👦 Measure 🔍 Text\nAnd this is line " + "two.\nWhoa! Three lines. How high does this go?\r\nI stopped counting."; + const auto u16text = fml::Utf8ToUtf16(text); + ASSERT_NE(text.size(), u16text.size()); + paragraph_builder.AddText(reinterpret_cast(text.data()), + text.size()); + hpp::DisplayListBuilder builder; + // Don't rely on implicit line breaks in this test to make it less brittle to + // different fonts being picked. + hpp::Paragraph paragraph = paragraph_builder.Build(FLT_MAX); + const auto line_count = paragraph.GetLineCount(); + ASSERT_EQ(line_count, 4u); + + // Line Metrics. + { + auto metrics = paragraph.GetLineMetrics(); + ASSERT_GT(metrics.GetAscent(0), 0.0); + ASSERT_GT(metrics.GetUnscaledAscent(0), 0.0); + ASSERT_GT(metrics.GetDescent(0), 0.0); + ASSERT_GT(metrics.GetBaseline(0), 0.0); + ASSERT_TRUE(metrics.IsHardbreak(0)); + ASSERT_DOUBLE_EQ(metrics.GetLeft(0), 0.0); + ASSERT_EQ(metrics.GetCodeUnitStartIndex(0), 0u); + ASSERT_EQ(metrics.GetCodeUnitEndIndexIncludingNewline(0), + metrics.GetCodeUnitEndIndex(0) + 1u); + ASSERT_GT(metrics.GetCodeUnitStartIndex(1), 0u); + // Last line should cover the entire range. + ASSERT_EQ(metrics.GetCodeUnitEndIndex(3), u16text.size()); + } + + // Glyph info by code point. + { + auto glyph = paragraph.GlyphInfoAtCodeUnitIndex(0u); + ASSERT_TRUE(glyph); + ASSERT_EQ(glyph.GetGraphemeClusterCodeUnitRangeBegin(), 0u); + ASSERT_EQ(glyph.GetGraphemeClusterCodeUnitRangeEnd(), + fml::Utf8ToUtf16("🏁").size()); + auto bounds = glyph.GetGraphemeClusterBounds(); + ASSERT_GT(bounds.width, 0.0); + ASSERT_GT(bounds.height, 0.0); + ASSERT_FALSE(glyph.IsEllipsis()); + ASSERT_EQ(glyph.GetTextDirection(), kImpellerTextDirectionLTR); + } + + // Glyph info by coordinates. + { + auto glyph = paragraph.GlyphInfoAtParagraphCoordinates(0.0, 0.0); + ASSERT_TRUE(glyph); + ASSERT_EQ(glyph.GetGraphemeClusterCodeUnitRangeEnd(), + fml::Utf8ToUtf16("🏁").size()); + } + + // Glyph Figure out word boundaries. + { + auto glyph = paragraph.GlyphInfoAtCodeUnitIndex(0u); + ASSERT_TRUE(glyph); + auto range = + paragraph.GetWordBoundary(glyph.GetGraphemeClusterCodeUnitRangeEnd()); + ASSERT_GT(range.end, 0u); + } + + builder.DrawParagraph(paragraph, ImpellerPoint{100, 100}); + auto dl = builder.Build(); + ASSERT_TRUE( + OpenPlaygroundHere([&](const auto& context, const auto& surface) -> bool { + hpp::Surface window(surface.GetC()); + window.Draw(dl); + return true; + })); +} + +} // namespace impeller::interop::testing diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.cc new file mode 100644 index 0000000000000000000000000000000000000000..59773389ca4da3e534b5bad17baec00f7095728c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.cc @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/impeller/toolkit/interop/line_metrics.h" + +namespace impeller::interop { + +LineMetrics::LineMetrics(const std::vector& metrics) { + // There aren't any guarantees (documented or otherwise) that metrics will + // have line numbers that are sorted or contiguous. + for (const auto& metric : metrics) { + metrics_[metric.line_number] = metric; + } +} + +LineMetrics::~LineMetrics() = default; + +double LineMetrics::GetAscent(size_t line) const { + return GetLine(line).ascent; +} + +double LineMetrics::GetUnscaledAscent(size_t line) const { + return GetLine(line).unscaled_ascent; +} + +double LineMetrics::GetDescent(size_t line) const { + return GetLine(line).descent; +} + +double LineMetrics::GetBaseline(size_t line) const { + return GetLine(line).baseline; +} + +bool LineMetrics::IsHardbreak(size_t line) const { + return GetLine(line).hard_break; +} + +double LineMetrics::GetWidth(size_t line) const { + return GetLine(line).width; +} + +double LineMetrics::GetHeight(size_t line) const { + return GetLine(line).height; +} + +double LineMetrics::GetLeft(size_t line) const { + return GetLine(line).left; +} + +size_t LineMetrics::GetCodeUnitStartIndex(size_t line) const { + return GetLine(line).start_index; +} + +size_t LineMetrics::GetCodeUnitEndIndex(size_t line) const { + return GetLine(line).end_index; +} + +size_t LineMetrics::GetCodeUnitEndIndexExcludingWhitespace(size_t line) const { + return GetLine(line).end_excluding_whitespace; +} + +size_t LineMetrics::GetCodeUnitEndIndexIncludingNewline(size_t line) const { + return GetLine(line).end_including_newline; +} + +const txt::LineMetrics& LineMetrics::GetLine(size_t line) const { + auto found = metrics_.find(line); + if (found != metrics_.end()) { + return found->second; + } + static txt::LineMetrics kDefaultMetrics = {}; + return kDefaultMetrics; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.h b/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.h new file mode 100644 index 0000000000000000000000000000000000000000..fdd1d396641a7b9a58ffd0efe78c78382b30ef27 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/line_metrics.h @@ -0,0 +1,104 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_LINE_METRICS_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_LINE_METRICS_H_ + +#include + +#include "flutter/txt/src/txt/line_metrics.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +//------------------------------------------------------------------------------ +/// @brief Internal C++ peer of ImpellerLineMetrics. For detailed +/// documentation, refer to the headerdocs in the public API in +/// impeller.h. +/// +/// Accessing metrics of missing lines returns default initialized +/// values. +/// +class LineMetrics final + : public Object { + public: + explicit LineMetrics(const std::vector& metrics); + + ~LineMetrics(); + + LineMetrics(const LineMetrics&) = delete; + + LineMetrics& operator=(const LineMetrics&) = delete; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetAscent. + /// + double GetAscent(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetUnscaledAscent. + /// + double GetUnscaledAscent(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetDescent. + /// + double GetDescent(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetBaseline. + /// + double GetBaseline(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsIsHardbreak. + /// + bool IsHardbreak(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetWidth. + /// + double GetWidth(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetHeight. + /// + double GetHeight(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetLeft. + /// + double GetLeft(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitStartIndex. + /// + size_t GetCodeUnitStartIndex(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndex. + /// + size_t GetCodeUnitEndIndex(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace. + /// + size_t GetCodeUnitEndIndexExcludingWhitespace(size_t line) const; + + //---------------------------------------------------------------------------- + /// @see ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline. + /// + size_t GetCodeUnitEndIndexIncludingNewline(size_t line) const; + + private: + std::map metrics_; + + const txt::LineMetrics& GetLine(size_t line) const; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_LINE_METRICS_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ff80b82a182f71f3d15153b53f446d700be24ef --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.cc @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/mask_filter.h" + +namespace impeller::interop { + +ScopedObject MaskFilter::MakeBlur(flutter::DlBlurStyle style, + float sigma) { + auto filter = flutter::DlBlurMaskFilter::Make(style, sigma); + if (!filter) { + return nullptr; + } + return Create(std::move(filter)); +} + +MaskFilter::MaskFilter(std::shared_ptr mask_filter) + : mask_filter_(std::move(mask_filter)) {} + +MaskFilter::~MaskFilter() = default; + +const std::shared_ptr& MaskFilter::GetMaskFilter() + const { + return mask_filter_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.h b/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..0d83e017b50195f2bcb96e21f51dd9d1a651fdd9 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/mask_filter.h @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_MASK_FILTER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_MASK_FILTER_H_ + +#include "flutter/display_list/effects/dl_mask_filter.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class MaskFilter final + : public Object { + public: + static ScopedObject MakeBlur(flutter::DlBlurStyle style, + float sigma); + + explicit MaskFilter(std::shared_ptr mask_filter); + + ~MaskFilter() override; + + MaskFilter(const MaskFilter&) = delete; + + MaskFilter& operator=(const MaskFilter&) = delete; + + const std::shared_ptr& GetMaskFilter() const; + + public: + std::shared_ptr mask_filter_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_MASK_FILTER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/object.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/object.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b21ca6132b140bfa63131e00ad1c7c955f75fdb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/object.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +// + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/object.h b/flutter/engine/src/flutter/impeller/toolkit/interop/object.h new file mode 100644 index 0000000000000000000000000000000000000000..e19fa352827ad4899ea1c217072126d81bb62dac --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/object.h @@ -0,0 +1,168 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_OBJECT_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_OBJECT_H_ + +#include +#include + +#include "flutter/fml/logging.h" + +namespace impeller::interop { + +class ObjectBase { + public: + ObjectBase() = default; + + virtual ~ObjectBase() = default; + + ObjectBase(const ObjectBase&) = delete; + + ObjectBase(ObjectBase&&) = delete; + + ObjectBase& operator=(const ObjectBase&) = delete; + + ObjectBase& operator=(ObjectBase&&) = delete; + + void Retain() { ref_count_++; } + + void Release() { + if (ref_count_-- == 1u) { + delete this; + } + } + + static void SafeRetain(void* ptr) { + if (ptr) { + reinterpret_cast(ptr)->Retain(); + } + } + + static void SafeRelease(void* ptr) { + if (ptr) { + reinterpret_cast(ptr)->Release(); + } + } + + uint64_t GetRefCountForTests() const { return ref_count_; } + + private: + std::atomic_uint64_t ref_count_ = {1u}; +}; + +template +class Object : public ObjectBase { + public: + using InteropClass = Clasz; + using InteropCSibling = CSibling; +}; + +enum class AdoptTag { + kAdopted, +}; + +template +class ScopedObject final { + public: + ScopedObject() = default; + + ScopedObject(std::nullptr_t) // NOLINT(google-explicit-constructor) + {} + + explicit ScopedObject(Object* ptr, AdoptTag) : object_(ptr) {} + + explicit ScopedObject(Object* ptr) : object_(ptr) { + if (object_) { + object_->Retain(); + } + } + + ~ScopedObject() { Release(); } + + ScopedObject(const ScopedObject& other) : ScopedObject(other.Get()) {} + + ScopedObject(ScopedObject&& other) { std::swap(object_, other.object_); } + + ScopedObject& operator=(const ScopedObject& other) { + // Self assignment. + if (object_ == other.object_) { + return *this; + } + if (other.object_) { + other.object_->Retain(); + } + Release(); + FML_DCHECK(object_ == nullptr); + object_ = other.object_; + return *this; + } + + ScopedObject& operator=(ScopedObject&& other) { + std::swap(object_, other.object_); + return *this; + } + + Object* Get() const { return object_; } + + typename Object::InteropCSibling* GetC() const { + return reinterpret_cast(Get()); + } + + Object& operator*() const { + FML_DCHECK(object_); + return *object_; + } + + Object* operator->() const { + FML_DCHECK(object_); + return object_; + } + + explicit operator bool() const { return !!object_; } + + [[nodiscard]] + typename Object::InteropCSibling* Leak() { + auto to_leak = object_; + object_ = nullptr; + return reinterpret_cast(to_leak); + } + + private: + Object* object_ = nullptr; + + void Release() { + if (object_) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDelete) + object_->Release(); + object_ = nullptr; + } + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) + } +}; + +template +ScopedObject Ref(Object* object) { + return ScopedObject{object}; +} + +template +ScopedObject Adopt(Object* object) { + return ScopedObject{object, AdoptTag::kAdopted}; +} + +template +ScopedObject Adopt(typename Object::InteropCSibling* object) { + return Adopt(reinterpret_cast(object)); +} + +template +ScopedObject Create(CtorArgs&&... args) { + return ScopedObject{new Object(std::forward(args)...), + AdoptTag::kAdopted}; +} + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_OBJECT_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/object_unittests.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/object_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..9a80d4a63b56d81e8a522d4ac88b9ad62c42ae71 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/object_unittests.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/testing/testing.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) + +namespace impeller::interop::testing { + +IMPELLER_DEFINE_HANDLE(FlagHandle); + +class FlagObject final + : public Object { + public: + explicit FlagObject(bool& destruction_flag) + : destruction_flag_(destruction_flag) { + FML_CHECK(!destruction_flag_) << "Destruction flag must be cleared."; + } + + ~FlagObject() { + FML_CHECK(!destruction_flag_) << "Already destructed."; + destruction_flag_ = true; + } + + private: + bool& destruction_flag_; +}; + +IMPELLER_DEFINE_HANDLE(TestHandle); + +class TestObject final + : public Object { + public: + TestObject(int arg1, double arg2, char arg3) + : arg1_(arg1), arg2_(arg2), arg3_(arg3) {} + + ~TestObject() = default; + + auto GetArg1() const { return arg1_; } + + auto GetArg2() const { return arg2_; } + + auto GetArg3() const { return arg3_; } + + private: + int arg1_ = {}; + double arg2_ = {}; + char arg3_ = {}; +}; + +TEST(InteropObjectTest, CanCreateScoped) { + bool destructed = false; + { + auto object = Adopt(new FlagObject(destructed)); // + } + ASSERT_TRUE(destructed); + + destructed = false; + { + auto object = Ref(new FlagObject(destructed)); + // New objects start with retain count of 1. + object->Release(); + } + ASSERT_TRUE(destructed); +} + +TEST(InteropObjectTest, CanCreate) { + auto object = Create(1, 1.3, 'c'); + ASSERT_EQ(object->GetArg1(), 1); + ASSERT_EQ(object->GetArg2(), 1.3); + ASSERT_EQ(object->GetArg3(), 'c'); +} + +TEST(InteropObjectTest, CanCopyAssignMove) { + auto o = Create(1, 2.3, 'd'); + ASSERT_EQ(o->GetRefCountForTests(), 1u); + { + auto o1 = o; // NOLINT(performance-unnecessary-copy-initialization) + ASSERT_EQ(o->GetRefCountForTests(), 2u); + auto o2 = o; // NOLINT(performance-unnecessary-copy-initialization) + ASSERT_EQ(o->GetRefCountForTests(), 3u); + auto o3 = o1; // NOLINT(performance-unnecessary-copy-initialization) + ASSERT_EQ(o->GetRefCountForTests(), 4u); + } + ASSERT_EQ(o->GetRefCountForTests(), 1u); + + { + auto o1(o); // NOLINT(performance-unnecessary-copy-initialization) + ASSERT_EQ(o->GetRefCountForTests(), 2u); + ASSERT_EQ(o1->GetRefCountForTests(), 2u); + } + + auto move_o = std::move(o); + ASSERT_EQ(move_o->GetRefCountForTests(), 1u); +} + +} // namespace impeller::interop::testing + +// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks) diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paint.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/paint.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a0774905e96cde8e4734535dfcbdacf396546ac --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paint.cc @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/paint.h" + +namespace impeller::interop { + +Paint::Paint() = default; + +Paint::~Paint() = default; + +const flutter::DlPaint& Paint::GetPaint() const { + return paint_; +} + +void Paint::SetColor(flutter::DlColor color) { + paint_.setColor(color); +} + +void Paint::SetBlendMode(BlendMode mode) { + paint_.setBlendMode(ToDisplayListType(mode)); +} + +void Paint::SetDrawStyle(flutter::DlDrawStyle style) { + paint_.setDrawStyle(style); +} + +void Paint::SetStrokeCap(flutter::DlStrokeCap stroke_cap) { + paint_.setStrokeCap(stroke_cap); +} + +void Paint::SetStrokeJoin(flutter::DlStrokeJoin stroke_join) { + paint_.setStrokeJoin(stroke_join); +} + +void Paint::SetStrokeWidth(Scalar width) { + paint_.setStrokeWidth(width); +} + +void Paint::SetStrokeMiter(Scalar miter) { + paint_.setStrokeMiter(miter); +} + +void Paint::SetColorFilter(const ColorFilter& filter) { + paint_.setColorFilter(filter.GetColorFilter()); +} + +void Paint::SetColorSource(const ColorSource& source) { + paint_.setColorSource(source.GetColorSource()); +} + +void Paint::SetImageFilter(const ImageFilter& filter) { + paint_.setImageFilter(filter.GetImageFilter()); +} + +void Paint::SetMaskFilter(const MaskFilter& filter) { + paint_.setMaskFilter(filter.GetMaskFilter()); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paint.h b/flutter/engine/src/flutter/impeller/toolkit/interop/paint.h new file mode 100644 index 0000000000000000000000000000000000000000..863656b096a3fdddb334f2622afb935801f3d625 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paint.h @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PAINT_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PAINT_H_ + +#include "flutter/display_list/dl_color.h" +#include "flutter/display_list/dl_paint.h" +#include "impeller/geometry/color.h" +#include "impeller/toolkit/interop/color_filter.h" +#include "impeller/toolkit/interop/color_source.h" +#include "impeller/toolkit/interop/formats.h" +#include "impeller/toolkit/interop/image_filter.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/mask_filter.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class Paint final + : public Object { + public: + Paint(); + + ~Paint() override; + + Paint(const Paint&) = delete; + + Paint& operator=(const Paint&) = delete; + + const flutter::DlPaint& GetPaint() const; + + void SetColor(flutter::DlColor color); + + void SetBlendMode(BlendMode mode); + + void SetDrawStyle(flutter::DlDrawStyle style); + + void SetStrokeCap(flutter::DlStrokeCap stroke_cap); + + void SetStrokeJoin(flutter::DlStrokeJoin stroke_join); + + void SetStrokeWidth(Scalar width); + + void SetStrokeMiter(Scalar miter); + + void SetColorFilter(const ColorFilter& filter); + + void SetColorSource(const ColorSource& source); + + void SetImageFilter(const ImageFilter& filter); + + void SetMaskFilter(const MaskFilter& filter); + + private: + flutter::DlPaint paint_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PAINT_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4388f369ab25e9873253e47d215606b98747e1e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.cc @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/paragraph.h" + +namespace impeller::interop { + +Paragraph::Paragraph(std::unique_ptr paragraph) + : paragraph_(std::move(paragraph)) {} + +Paragraph::~Paragraph() = default; + +Scalar Paragraph::GetMaxWidth() const { + return paragraph_->GetMaxWidth(); +} + +Scalar Paragraph::GetHeight() const { + return paragraph_->GetHeight(); +} + +Scalar Paragraph::GetLongestLineWidth() const { + return paragraph_->GetLongestLine(); +} + +Scalar Paragraph::GetMinIntrinsicWidth() const { + return paragraph_->GetMinIntrinsicWidth(); +} + +Scalar Paragraph::GetMaxIntrinsicWidth() const { + return paragraph_->GetMaxIntrinsicWidth(); +} + +Scalar Paragraph::GetIdeographicBaseline() const { + return paragraph_->GetIdeographicBaseline(); +} + +Scalar Paragraph::GetAlphabeticBaseline() const { + return paragraph_->GetAlphabeticBaseline(); +} + +uint32_t Paragraph::GetLineCount() const { + return paragraph_->GetNumberOfLines(); +} + +const std::unique_ptr& Paragraph::GetHandle() const { + return paragraph_; +} + +ScopedObject Paragraph::GetLineMetrics() const { + // Line metrics are expensive to calculate and the recommendation is that + // the metric after each layout must be cached. But interop::Paragraphs are + // immutable. So do the caching on behalf of the caller. + if (lazy_line_metrics_) { + return lazy_line_metrics_; + } + lazy_line_metrics_ = Create(paragraph_->GetLineMetrics()); + return lazy_line_metrics_; +} + +ScopedObject Paragraph::GetGlyphInfoAtCodeUnitIndex( + size_t code_unit_index) const { + skia::textlayout::Paragraph::GlyphInfo info = {}; + if (paragraph_->GetGlyphInfoAt(code_unit_index, &info)) { + return Create(info); + } + return nullptr; +} + +ScopedObject Paragraph::GetClosestGlyphInfoAtParagraphCoordinates( + double x, + double y) const { + skia::textlayout::Paragraph::GlyphInfo info = {}; + if (paragraph_->GetClosestGlyphInfoAtCoordinate(x, y, &info)) { + return Create(info); + } + return nullptr; +} + +ImpellerRange Paragraph::GetWordBoundary(size_t code_unit_index) const { + const auto range = paragraph_->GetWordBoundary(code_unit_index); + return ImpellerRange{range.start, range.end}; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.h b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.h new file mode 100644 index 0000000000000000000000000000000000000000..7635873f9d687aed3f0ca8b8c797578a36940bf3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph.h @@ -0,0 +1,67 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_H_ + +#include "flutter/txt/src/txt/paragraph.h" +#include "impeller/toolkit/interop/glyph_info.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/line_metrics.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +/** + * An immutable fully laid out paragraph. + */ +class Paragraph final + : public Object { + public: + explicit Paragraph(std::unique_ptr paragraph); + + ~Paragraph() override; + + Paragraph(const Paragraph&) = delete; + + Paragraph& operator=(const Paragraph&) = delete; + + Scalar GetMaxWidth() const; + + Scalar GetHeight() const; + + Scalar GetLongestLineWidth() const; + + Scalar GetMinIntrinsicWidth() const; + + Scalar GetMaxIntrinsicWidth() const; + + Scalar GetIdeographicBaseline() const; + + Scalar GetAlphabeticBaseline() const; + + uint32_t GetLineCount() const; + + const std::unique_ptr& GetHandle() const; + + ScopedObject GetLineMetrics() const; + + ScopedObject GetGlyphInfoAtCodeUnitIndex( + size_t code_unit_index) const; + + ScopedObject GetClosestGlyphInfoAtParagraphCoordinates( + double x, + double y) const; + + ImpellerRange GetWordBoundary(size_t code_unit_index) const; + + private: + std::unique_ptr paragraph_; + mutable ScopedObject lazy_line_metrics_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..9ddc2313f4650640dca373bce8f7de226f3e42d0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.cc @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/paragraph_builder.h" + +#include "flutter/txt/src/skia/paragraph_builder_skia.h" +#include "impeller/base/validation.h" +#include "impeller/toolkit/interop/paragraph.h" + +namespace impeller::interop { + +ParagraphBuilder::ParagraphBuilder(ScopedObject context) + : context_(std::move(context)) {} + +ParagraphBuilder::~ParagraphBuilder() = default; + +bool ParagraphBuilder::IsValid() const { + return !!context_; +} + +void ParagraphBuilder::PushStyle(const ParagraphStyle& style) { + GetBuilder(style.GetParagraphStyle())->PushStyle(style.CreateTextStyle()); +} + +void ParagraphBuilder::PopStyle() { + GetBuilder()->Pop(); +} + +void ParagraphBuilder::AddText(const uint8_t* data, size_t byte_length) { + GetBuilder()->AddText(data, byte_length); +} + +ScopedObject ParagraphBuilder::Build(Scalar width) const { + auto txt_paragraph = GetBuilder()->Build(); + if (!txt_paragraph) { + return nullptr; + } + txt_paragraph->Layout(width); + return Create(std::move(txt_paragraph)); +} + +const std::unique_ptr& ParagraphBuilder::GetBuilder( + const txt::ParagraphStyle& style) const { + if (lazy_builder_) { + return lazy_builder_; + } + lazy_builder_ = std::make_unique( + style, // + context_->GetFontCollection(), // + true // is impeller enabled + ); + return lazy_builder_; +} + +const std::unique_ptr& ParagraphBuilder::GetBuilder() + const { + static txt::ParagraphStyle kDefaultStyle; + return GetBuilder(kDefaultStyle); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.h b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..2305eccfdfa21a1301aabde53feedc94e441def8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_builder.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_BUILDER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_BUILDER_H_ + +#include + +#include "flutter/txt/src/txt/paragraph_builder.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/paragraph.h" +#include "impeller/toolkit/interop/paragraph_style.h" +#include "impeller/toolkit/interop/typography_context.h" + +namespace impeller::interop { + +class ParagraphBuilder final + : public Object { + public: + explicit ParagraphBuilder(ScopedObject context); + + ~ParagraphBuilder() override; + + ParagraphBuilder(const ParagraphBuilder&) = delete; + + ParagraphBuilder& operator=(const ParagraphBuilder&) = delete; + + bool IsValid() const; + + void PushStyle(const ParagraphStyle& style); + + void PopStyle(); + + void AddText(const uint8_t* data, size_t byte_length); + + ScopedObject Build(Scalar width) const; + + private: + ScopedObject context_; + mutable std::unique_ptr lazy_builder_; + + const std::unique_ptr& GetBuilder( + const txt::ParagraphStyle& style) const; + + const std::unique_ptr& GetBuilder() const; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.cc new file mode 100644 index 0000000000000000000000000000000000000000..d18943efcbf88fa88f3ec8a93f833050b8813207 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.cc @@ -0,0 +1,74 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/paragraph_style.h" + +namespace impeller::interop { + +ParagraphStyle::ParagraphStyle() = default; + +ParagraphStyle::~ParagraphStyle() = default; + +void ParagraphStyle::SetFontWeight(txt::FontWeight weight) { + style_.font_weight = weight; +} + +void ParagraphStyle::SetFontStyle(txt::FontStyle style) { + style_.font_style = style; +} + +void ParagraphStyle::SetFontFamily(std::string family) { + style_.font_family = std::move(family); +} + +void ParagraphStyle::SetFontSize(double size) { + style_.font_size = size; +} + +void ParagraphStyle::SetHeight(double height) { + style_.height = height; + style_.has_height_override = (height != 0.0); +} + +void ParagraphStyle::SetTextAlignment(txt::TextAlign alignment) { + style_.text_align = alignment; +} + +void ParagraphStyle::SetTextDirection(txt::TextDirection direction) { + style_.text_direction = direction; +} + +void ParagraphStyle::SetMaxLines(size_t max_lines) { + style_.max_lines = max_lines; +} + +void ParagraphStyle::SetLocale(std::string locale) { + style_.locale = std::move(locale); +} + +void ParagraphStyle::SetForeground(ScopedObject paint) { + foreground_ = std::move(paint); +} + +void ParagraphStyle::SetBackground(ScopedObject paint) { + background_ = std::move(paint); +} + +txt::TextStyle ParagraphStyle::CreateTextStyle() const { + auto style = style_.GetTextStyle(); + + if (foreground_) { + style.foreground = foreground_->GetPaint(); + } + if (background_) { + style.background = background_->GetPaint(); + } + return style; +} + +const txt::ParagraphStyle& ParagraphStyle::GetParagraphStyle() const { + return style_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.h b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.h new file mode 100644 index 0000000000000000000000000000000000000000..1e12f031a41de45568cb4d33c299331f2993ee0b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/paragraph_style.h @@ -0,0 +1,61 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_STYLE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_STYLE_H_ + +#include "flutter/txt/src/txt/paragraph_style.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/paint.h" + +namespace impeller::interop { + +class ParagraphStyle final + : public Object { + public: + explicit ParagraphStyle(); + + ~ParagraphStyle() override; + + ParagraphStyle(const ParagraphStyle&) = delete; + + ParagraphStyle& operator=(const ParagraphStyle&) = delete; + + void SetForeground(ScopedObject paint); + + void SetBackground(ScopedObject paint); + + void SetFontWeight(txt::FontWeight weight); + + void SetFontStyle(txt::FontStyle style); + + void SetFontFamily(std::string family); + + void SetFontSize(double size); + + void SetHeight(double height); + + void SetTextAlignment(txt::TextAlign alignment); + + void SetTextDirection(txt::TextDirection direction); + + void SetMaxLines(size_t max_lines); + + void SetLocale(std::string locale); + + txt::TextStyle CreateTextStyle() const; + + const txt::ParagraphStyle& GetParagraphStyle() const; + + private: + txt::ParagraphStyle style_; + ScopedObject foreground_; + ScopedObject background_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PARAGRAPH_STYLE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/path.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/path.cc new file mode 100644 index 0000000000000000000000000000000000000000..a004a99ed617ab8edc41af5544866d6166cb045e --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/path.cc @@ -0,0 +1,17 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/path.h" + +namespace impeller::interop { + +Path::Path(const SkPath& path) : path_(path) {} + +Path::~Path() = default; + +const SkPath& Path::GetPath() const { + return path_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/path.h b/flutter/engine/src/flutter/impeller/toolkit/interop/path.h new file mode 100644 index 0000000000000000000000000000000000000000..ddf96f91535e4ba6621b5a31e554943180c1a07c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/path.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_H_ + +#include "flutter/third_party/skia/include/core/SkPath.h" +#include "impeller/geometry/path.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class Path final + : public Object { + public: + explicit Path(const SkPath& path); + + ~Path(); + + Path(const Path&) = delete; + + Path& operator=(const Path&) = delete; + + const SkPath& GetPath() const; + + private: + SkPath path_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.cc new file mode 100644 index 0000000000000000000000000000000000000000..978b27112fee35b6f9a6e0a3f09f624f0ccb2264 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.cc @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/path_builder.h" + +#include "impeller/toolkit/interop/formats.h" + +namespace impeller::interop { + +PathBuilder::PathBuilder() = default; + +PathBuilder::~PathBuilder() = default; + +void PathBuilder::MoveTo(const Point& point) { + builder_.moveTo(ToSkiaType(point)); +} + +void PathBuilder::LineTo(const Point& location) { + builder_.lineTo(ToSkiaType(location)); +} + +void PathBuilder::QuadraticCurveTo(const Point& control_point, + const Point& end_point) { + builder_.quadTo(ToSkiaType(control_point), ToSkiaType(end_point)); +} + +void PathBuilder::CubicCurveTo(const Point& control_point_1, + const Point& control_point_2, + const Point& end_point) { + builder_.cubicTo(ToSkiaType(control_point_1), // + ToSkiaType(control_point_2), // + ToSkiaType(end_point) // + ); +} + +void PathBuilder::AddRect(const Rect& rect) { + builder_.addRect(ToSkiaType(rect)); +} + +void PathBuilder::AddArc(const Rect& oval_bounds, + Degrees start_angle, + Degrees end_angle) { + builder_.addArc(ToSkiaType(oval_bounds), // + start_angle.degrees, // + end_angle.degrees - start_angle.degrees // sweep + ); +} + +void PathBuilder::AddOval(const Rect& oval_bounds) { + builder_.addOval(ToSkiaType(oval_bounds)); +} + +void PathBuilder::AddRoundedRect(const Rect& rect, const RoundingRadii& radii) { + builder_.addRRect(ToSkiaType(rect, radii)); +} + +void PathBuilder::Close() { + builder_.close(); +} + +ScopedObject PathBuilder::TakePath(FillType fill) { + builder_.setFillType(ToSkiaType(fill)); + return Create(std::move(builder_)); +} + +ScopedObject PathBuilder::CopyPath(FillType fill) { + builder_.setFillType(ToSkiaType(fill)); + return Create(builder_); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.h b/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..bb77bbe08abcd1e5fea6c5fa62120096086c9484 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/path_builder.h @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_BUILDER_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_BUILDER_H_ + +#include "flutter/third_party/skia/include/core/SkPath.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/path_builder.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" +#include "impeller/toolkit/interop/path.h" + +namespace impeller::interop { + +class PathBuilder final + : public Object { + public: + PathBuilder(); + + ~PathBuilder(); + + PathBuilder(const PathBuilder&) = delete; + + PathBuilder& operator=(const PathBuilder&) = delete; + + void MoveTo(const Point& point); + + void LineTo(const Point& location); + + void QuadraticCurveTo(const Point& control_point, const Point& end_point); + + void CubicCurveTo(const Point& control_point_1, + const Point& control_point_2, + const Point& end_point); + + void AddRect(const Rect& rect); + + void AddArc(const Rect& oval_bounds, Degrees start_angle, Degrees end_angle); + + void AddOval(const Rect& oval_bounds); + + void AddRoundedRect(const Rect& rect, const RoundingRadii& radii); + + void Close(); + + ScopedObject TakePath(FillType fill); + + ScopedObject CopyPath(FillType fill); + + private: + SkPath builder_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PATH_BUILDER_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..920a91afbdccd38c24fb38ca788567e3df69b4e5 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.cc @@ -0,0 +1,181 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/playground_test.h" + +#include "impeller/toolkit/interop/impeller.hpp" + +#if IMPELLER_ENABLE_METAL +#include "impeller/toolkit/interop/backend/metal/context_mtl.h" +#include "impeller/toolkit/interop/backend/metal/surface_mtl.h" +#endif // IMPELLER_ENABLE_METAL + +#if IMPELLER_ENABLE_OPENGLES +#include "impeller/toolkit/interop/backend/gles/context_gles.h" +#include "impeller/toolkit/interop/backend/gles/surface_gles.h" +#endif // IMPELLER_ENABLE_METAL + +#if IMPELLER_ENABLE_VULKAN +#include "impeller/toolkit/interop/backend/vulkan/context_vk.h" +#include "impeller/toolkit/interop/backend/vulkan/surface_vk.h" +#endif // IMPELLER_ENABLE_VULKAN + +namespace IMPELLER_HPP_NAMESPACE { +ProcTable gGlobalProcTable; +} // namespace IMPELLER_HPP_NAMESPACE + +namespace impeller::interop::testing { + +static void SetupImpellerHPPProcTableOnce() { + static std::once_flag sOnceFlag; + std::call_once(sOnceFlag, []() { + std::map proc_map; +#define IMPELLER_HPP_PROC(name) \ + proc_map[#name] = reinterpret_cast(&name); + IMPELLER_HPP_EACH_PROC(IMPELLER_HPP_PROC) +#undef IMPELLER_HPP_PROC + hpp::gGlobalProcTable.Initialize( + [&](auto name) { return proc_map.at(name); }); + }); +} + +PlaygroundTest::PlaygroundTest() { + SetupImpellerHPPProcTableOnce(); +} + +PlaygroundTest::~PlaygroundTest() = default; + +// |PlaygroundTest| +void PlaygroundTest::SetUp() { + ::impeller::PlaygroundTest::SetUp(); +} + +// |PlaygroundTest| +void PlaygroundTest::TearDown() { + ::impeller::PlaygroundTest::TearDown(); +} + +ScopedObject PlaygroundTest::CreateContext() const { + switch (GetBackend()) { + case PlaygroundBackend::kMetal: + return Adopt( + ImpellerContextCreateMetalNew(ImpellerGetVersion())); + case PlaygroundBackend::kOpenGLES: { + Playground::GLProcAddressResolver playground_gl_proc_address_callback = + CreateGLProcAddressResolver(); + ImpellerProcAddressCallback gl_proc_address_callback = + [](const char* proc_name, void* user_data) -> void* { + return (*reinterpret_cast( + user_data))(proc_name); + }; + return Adopt(ImpellerContextCreateOpenGLESNew( + ImpellerGetVersion(), gl_proc_address_callback, + &playground_gl_proc_address_callback)); + } + case PlaygroundBackend::kVulkan: + ImpellerContextVulkanSettings settings = {}; + struct UserData { + Playground::VKProcAddressResolver resolver; + } user_data; + user_data.resolver = CreateVKProcAddressResolver(); + settings.user_data = &user_data; + settings.enable_vulkan_validation = switches_.enable_vulkan_validation; + settings.proc_address_callback = [](void* instance, // + const char* proc_name, // + void* user_data // + ) -> void* { + auto resolver = reinterpret_cast(user_data)->resolver; + if (resolver) { + return resolver(instance, proc_name); + } else { + return nullptr; + } + }; + return Adopt( + ImpellerContextCreateVulkanNew(ImpellerGetVersion(), &settings)); + } + FML_UNREACHABLE(); +} + +static ScopedObject CreateSharedSurface( + PlaygroundBackend backend, + Context& context, + std::shared_ptr shared_surface) { + switch (backend) { +#if IMPELLER_ENABLE_METAL + case PlaygroundBackend::kMetal: + return Adopt(new SurfaceMTL(context, std::move(shared_surface))); +#endif + +#if IMPELLER_ENABLE_OPENGLES + case PlaygroundBackend::kOpenGLES: + return Adopt( + new SurfaceGLES(context, std::move(shared_surface))); +#endif + +#if IMPELLER_ENABLE_VULKAN + case PlaygroundBackend::kVulkan: + return Adopt(new SurfaceVK(context, std::move(shared_surface))); +#endif + default: + return nullptr; + } + FML_UNREACHABLE(); +} + +bool PlaygroundTest::OpenPlaygroundHere(InteropPlaygroundCallback callback) { + auto interop_context = GetInteropContext(); + if (!interop_context) { + return false; + } + return Playground::OpenPlaygroundHere([&](RenderTarget& target) -> bool { + auto impeller_surface = std::make_shared(target); + auto surface = CreateSharedSurface(GetBackend(), // + *interop_context.Get(), // + std::move(impeller_surface) // + ); + if (!surface) { + VALIDATION_LOG << "Could not wrap test surface as an interop surface."; + return false; + } + return callback(interop_context, surface); + }); +} + +static ScopedObject CreateSharedContext( + PlaygroundBackend backend, + std::shared_ptr shared_context) { + switch (backend) { +#if IMPELLER_ENABLE_METAL + case PlaygroundBackend::kMetal: + return ContextMTL::Create(shared_context); +#endif +#if IMPELLER_ENABLE_OPENGLES + case PlaygroundBackend::kOpenGLES: + return ContextGLES::Create(std::move(shared_context)); +#endif +#if IMPELLER_ENABLE_VULKAN + case PlaygroundBackend::kVulkan: + return ContextVK::Create(std::move(shared_context)); +#endif + default: + return nullptr; + } + FML_UNREACHABLE(); +} + +ScopedObject PlaygroundTest::GetInteropContext() { + if (interop_context_) { + return interop_context_; + } + + auto context = CreateSharedContext(GetBackend(), GetContext()); + if (!context) { + return nullptr; + } + interop_context_ = std::move(context); + return interop_context_; +} + +} // namespace impeller::interop::testing diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.h b/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.h new file mode 100644 index 0000000000000000000000000000000000000000..5c8eb84bab5cd750e27322830e6849b1ccfe40ab --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/playground_test.h @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_PLAYGROUND_TEST_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_PLAYGROUND_TEST_H_ + +#include + +#include "impeller/playground/playground_test.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/surface.h" + +namespace impeller::interop::testing { + +class PlaygroundTest : public ::impeller::PlaygroundTest { + public: + PlaygroundTest(); + + // |PlaygroundTest| + ~PlaygroundTest() override; + + PlaygroundTest(const PlaygroundTest&) = delete; + + PlaygroundTest& operator=(const PlaygroundTest&) = delete; + + // |PlaygroundTest| + void SetUp() override; + + // |PlaygroundTest| + void TearDown() override; + + ScopedObject CreateContext() const; + + ScopedObject GetInteropContext(); + + using InteropPlaygroundCallback = + std::function& context, + const ScopedObject& surface)>; + bool OpenPlaygroundHere(InteropPlaygroundCallback callback); + + private: + ScopedObject interop_context_; +}; + +} // namespace impeller::interop::testing + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_PLAYGROUND_TEST_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/surface.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/surface.cc new file mode 100644 index 0000000000000000000000000000000000000000..0b20e43ce81595d5ff6339ca02e1700ff7ed400b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/surface.cc @@ -0,0 +1,52 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/surface.h" + +#include "impeller/base/validation.h" +#include "impeller/display_list/aiks_context.h" +#include "impeller/display_list/dl_dispatcher.h" +#include "impeller/toolkit/interop/formats.h" + +namespace impeller::interop { + +Surface::Surface(Context& context, std::shared_ptr surface) + : context_(Ref(&context)), surface_(std::move(surface)) { + is_valid_ = + context_ && context_->IsValid() && surface_ && surface_->IsValid(); +} + +Surface::~Surface() = default; + +bool Surface::IsValid() const { + return is_valid_; +} + +bool Surface::DrawDisplayList(const DisplayList& dl) const { + if (!IsValid() || !dl.IsValid()) { + return false; + } + + auto display_list = dl.GetDisplayList(); + auto& content_context = context_->GetAiksContext().GetContentContext(); + auto render_target = surface_->GetRenderTarget(); + + const auto cull_rect = IRect::MakeSize(surface_->GetSize()); + auto skia_cull_rect = + SkIRect::MakeWH(cull_rect.GetWidth(), cull_rect.GetHeight()); + + auto result = RenderToTarget(content_context, render_target, display_list, + skia_cull_rect, /*reset_host_buffer=*/true); + context_->GetContext()->ResetThreadLocalState(); + return result; +} + +bool Surface::Present() const { + if (!IsValid()) { + return false; + } + return surface_->Present(); +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/surface.h b/flutter/engine/src/flutter/impeller/toolkit/interop/surface.h new file mode 100644 index 0000000000000000000000000000000000000000..eb3467702b8886e5b6448feaa001dd8d24324800 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/surface.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_SURFACE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_SURFACE_H_ + +#include + +#include "impeller/renderer/surface.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/dl.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class Surface + : public Object { + public: + ~Surface() override; + + Surface(const Surface&) = delete; + + Surface& operator=(const Surface&) = delete; + + bool IsValid() const; + + bool DrawDisplayList(const DisplayList& dl) const; + + bool Present() const; + + protected: + explicit Surface(Context& context, + std::shared_ptr surface); + + private: + ScopedObject context_; + std::shared_ptr surface_; + bool is_valid_ = false; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_SURFACE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/texture.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/texture.cc new file mode 100644 index 0000000000000000000000000000000000000000..c74313133fad9888e2a7f3224a30a61a70cefd1c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/texture.cc @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/texture.h" + +namespace impeller::interop { + +Texture::Texture(const Context& context, const TextureDescriptor& descriptor) { + if (!context.IsValid()) { + return; + } + auto texture = + context.GetContext()->GetResourceAllocator()->CreateTexture(descriptor); + if (!texture || !texture->IsValid()) { + return; + } + texture->SetLabel("UserCreated"); + backend_ = context.GetContext()->GetBackendType(); + texture_ = std::move(texture); +} + +Texture::Texture(impeller::Context::BackendType backend, + std::shared_ptr texture) + : backend_(backend), texture_(std::move(texture)) {} + +Texture::~Texture() = default; + +bool Texture::IsValid() const { + return !!texture_; +} + +bool Texture::SetContents(const uint8_t* contents, uint64_t length) { + if (!IsValid()) { + return false; + } + return texture_->SetContents(contents, length); +} + +bool Texture::SetContents(std::shared_ptr contents) { + if (!IsValid()) { + return false; + } + return texture_->SetContents(std::move(contents)); +} + +sk_sp Texture::MakeImage() const { + return DlImageImpeller::Make(texture_); +} + +impeller::Context::BackendType Texture::GetBackendType() const { + return backend_; +} + +const std::shared_ptr& Texture::GetTexture() const { + return texture_; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/texture.h b/flutter/engine/src/flutter/impeller/toolkit/interop/texture.h new file mode 100644 index 0000000000000000000000000000000000000000..ab6c1df598bde90b7bfb49d57bbf8e5a30d92b27 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/texture.h @@ -0,0 +1,50 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_TEXTURE_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_TEXTURE_H_ + +#include "impeller/core/texture.h" +#include "impeller/display_list/dl_image_impeller.h" +#include "impeller/toolkit/interop/context.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class Texture final + : public Object { + public: + explicit Texture(const Context& context, const TextureDescriptor& descriptor); + + explicit Texture(impeller::Context::BackendType backend, + std::shared_ptr texture); + + ~Texture() override; + + Texture(const Texture&) = delete; + + Texture& operator=(const Texture&) = delete; + + bool IsValid() const; + + bool SetContents(const uint8_t* contents, uint64_t length); + + bool SetContents(std::shared_ptr contents); + + sk_sp MakeImage() const; + + impeller::Context::BackendType GetBackendType() const; + + const std::shared_ptr& GetTexture() const; + + private: + impeller::Context::BackendType backend_ = + impeller::Context::BackendType::kMetal; + std::shared_ptr texture_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_TEXTURE_H_ diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.cc b/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..5ee88858e44ac22c2e46b8f35aae75658868a27c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.cc @@ -0,0 +1,84 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/toolkit/interop/typography_context.h" + +#include + +#include "flutter/fml/icu_util.h" +#include "flutter/txt/src/txt/platform.h" +#include "impeller/base/validation.h" +#include "impeller/toolkit/interop/embedded_icu_data.h" + +namespace impeller::interop { + +TypographyContext::TypographyContext() + : collection_(std::make_shared()) { + static std::once_flag sICUInitOnceFlag; + std::call_once(sICUInitOnceFlag, []() { + auto icu_data = std::make_unique( + impeller_embedded_icu_data_data, impeller_embedded_icu_data_length); + fml::icu::InitializeICUFromMapping(std::move(icu_data)); + }); + // The fallback for all fonts. Looks in platform specific locations. + collection_->SetupDefaultFontManager(0u); + + // Looks for fonts in user supplied blobs. + asset_font_manager_ = sk_make_sp(); + collection_->SetAssetFontManager(asset_font_manager_); +} + +TypographyContext::~TypographyContext() = default; + +bool TypographyContext::IsValid() const { + return !!collection_; +} + +const std::shared_ptr& +TypographyContext::GetFontCollection() const { + return collection_; +} + +static sk_sp CreateTypefaceFromFontData( + std::unique_ptr font_data) { + if (!font_data) { + VALIDATION_LOG << "Invalid font data."; + return nullptr; + } + auto sk_data_context = font_data.release(); + auto sk_data = SkData::MakeWithProc( + sk_data_context->GetMapping(), // data ptr + sk_data_context->GetSize(), // data size + [](const void*, void* context) { + delete reinterpret_cast(context); + }, // release callback + sk_data_context // release callback context + ); + auto sk_data_stream = SkMemoryStream::Make(sk_data); + auto sk_typeface = + txt::GetDefaultFontManager()->makeFromStream(std::move(sk_data_stream)); + if (!sk_typeface) { + VALIDATION_LOG << "Could not create typeface with data."; + return nullptr; + } + return sk_typeface; +} + +bool TypographyContext::RegisterFont(std::unique_ptr font_data, + const char* family_name_alias) { + auto typeface = CreateTypefaceFromFontData(std::move(font_data)); + if (typeface == nullptr) { + return false; + } + size_t result = 0u; + if (family_name_alias == nullptr) { + result = asset_font_manager_->registerTypeface(std::move(typeface)); + } else { + result = asset_font_manager_->registerTypeface(std::move(typeface), + SkString{family_name_alias}); + } + return result != 0; +} + +} // namespace impeller::interop diff --git a/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.h b/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.h new file mode 100644 index 0000000000000000000000000000000000000000..d4f505df7524227c42ae2ab668d62cbd8d8e7ffe --- /dev/null +++ b/flutter/engine/src/flutter/impeller/toolkit/interop/typography_context.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TOOLKIT_INTEROP_TYPOGRAPHY_CONTEXT_H_ +#define FLUTTER_IMPELLER_TOOLKIT_INTEROP_TYPOGRAPHY_CONTEXT_H_ + +#include + +#include "flutter/third_party/skia/modules/skparagraph/include/TypefaceFontProvider.h" +#include "flutter/txt/src/txt/font_collection.h" +#include "impeller/toolkit/interop/impeller.h" +#include "impeller/toolkit/interop/object.h" + +namespace impeller::interop { + +class TypographyContext final + : public Object { + public: + TypographyContext(); + + ~TypographyContext() override; + + TypographyContext(const TypographyContext&) = delete; + + TypographyContext& operator=(const TypographyContext&) = delete; + + bool IsValid() const; + + const std::shared_ptr& GetFontCollection() const; + + //---------------------------------------------------------------------------- + /// @brief Registers custom font data. If an alias for the family name is + /// provided, subsequent lookups will need to use that same alias. + /// If not, the family name will be read from the font data. + /// + /// @param[in] font_data The font data + /// @param[in] family_name_alias The family name alias + /// + /// @return If the font data could be successfully registered. + /// + bool RegisterFont(std::unique_ptr font_data, + const char* family_name_alias); + + private: + std::shared_ptr collection_; + sk_sp asset_font_manager_; +}; + +} // namespace impeller::interop + +#endif // FLUTTER_IMPELLER_TOOLKIT_INTEROP_TYPOGRAPHY_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/tools/args.gni b/flutter/engine/src/flutter/impeller/tools/args.gni new file mode 100644 index 0000000000000000000000000000000000000000..adfc111ffce1546b446a29c634f8dbe0374e4794 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/args.gni @@ -0,0 +1,39 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +declare_args() { + impeller_debug = + flutter_runtime_mode == "debug" || flutter_runtime_mode == "profile" + + # Whether the Metal backend is enabled. + impeller_enable_metal = (is_mac || is_ios) && target_os != "fuchsia" + + # Whether the OpenGLES backend is enabled. + impeller_enable_opengles = (is_linux || is_win || is_android || is_mac || + enable_unittests) && target_os != "fuchsia" + + # Whether the Vulkan backend is enabled. + impeller_enable_vulkan = (is_linux || is_win || is_android || is_mac || + enable_unittests) && target_os != "fuchsia" +} + +# Arguments that are combinations of other arguments by default but which can +# be overridden by the user. + +declare_args() { + # Wether to build and include the validation layers. + impeller_enable_vulkan_validation_layers = + impeller_enable_vulkan && flutter_runtime_mode == "debug" && + target_cpu == "arm64" + + # Whether Impeller supports rendering on the platform. + impeller_supports_rendering = + impeller_enable_metal || impeller_enable_opengles || + impeller_enable_vulkan + + impeller_enable_compute = impeller_enable_vulkan || impeller_enable_metal +} diff --git a/flutter/engine/src/flutter/impeller/tools/compiler.gni b/flutter/engine/src/flutter/impeller/tools/compiler.gni new file mode 100644 index 0000000000000000000000000000000000000000..180600b8ea93d9dcab7761183481b53df6ac3411 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/compiler.gni @@ -0,0 +1,272 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/compiled_action.gni") +import("//flutter/impeller/tools/args.gni") + +# Dispatches to the build or prebuilt impellerc depending on the value of +# the `impeller_use_prebuilt_impellerc` argument. +# * When the `single_invocation` argument is false, all variables are +# forwarded to `compiled_action_foreach` or `action_foreach`, which will +# invoke `impellerc` separately for each source. +# * When the `single_invocation` argument is true, `impellerc` is only +# invoked once via `compiled_action` or `action`. +template("_impellerc") { + if (invoker.single_invocation) { + compiled_action(target_name) { + forward_variables_from(invoker, "*") + tool = "//flutter/impeller/compiler:impellerc" + } + } else { + compiled_action_foreach(target_name) { + forward_variables_from(invoker, "*") + tool = "//flutter/impeller/compiler:impellerc" + } + } +} + +# Required: shaders The list of shaders inputs to compile. +# Required: shader_target_flags The target flag(s) to append. Valid options: +# --sksl +# --metal-ios +# --metal-desktop +# --opengl-es +# --opengl-desktop +# --vulkan +# --runtime-stage-metal +# --runtime-stage-gles +# --runtime-stage-gles3 +# --runtime-stage-vulkan +# Not required for --shader_bundle mode. +# Required: sl_file_extension The file extension to use for output files. +# Not required for --shader_bundle mode. +# Optional: iplr Causes --sl output to be in iplr/runtime +# stage flatbuffer format. +# Optional: shader_bundle Specifies a Flutter GPU shader bundle +# configuration. +# Required: shader_bundle_output Specifies the output filename of the shader +# bundle. This is only required if +# shader_bundle is supplied. +# Optional: defines Specifies a list of valueless macro +# definitions. +# Optional: intermediates_subdir Specifies the subdirectory in which to put +# intermediates. +# Optional: json Causes output format to be JSON instead of +# flatbuffer. +template("impellerc") { + assert(defined(invoker.shaders), "Impeller shaders must be specified.") + assert(defined(invoker.shader_target_flags) || defined(invoker.shader_bundle), + "The flag to impellerc for target selection must be specified.") + assert(defined(invoker.sl_file_extension) || defined(invoker.shader_bundle), + "The extension of the SL file must be specified (metal, glsl, etc..).") + if (defined(invoker.shader_bundle)) { + assert( + defined(invoker.shader_bundle_output), + "When shader_bundle is specified, shader_bundle_output must also be specified.") + } + + if (defined(invoker.shader_target_flags)) { + shader_target_flags = invoker.shader_target_flags + } else { + shader_target_flags = [] + } + + sksl = false + foreach(shader_target_flag, shader_target_flags) { + sksl = shader_target_flag == "--sksl" + } + iplr = false + if (defined(invoker.iplr) && invoker.iplr) { + iplr = invoker.iplr + } + json = false + if (defined(invoker.json) && invoker.json) { + json = invoker.json + } + + # Not needed on every path. + not_needed([ + "iplr", + "sksl", + "shader_bundle", + "shader_bundle_output", + ]) + + _impellerc(target_name) { + pool = "//build/toolchain:toolchain_pool" + shader_bundle = defined(invoker.shader_bundle) + + # When single_invocation is true, impellerc will be invoked exactly once. When it's + # false, impellerc be invoked for each of the source file entries (invoker.shaders). + single_invocation = shader_bundle + + if (defined(invoker.intermediates_subdir)) { + subdir = invoker.intermediates_subdir + generated_dir = "$target_gen_dir/$subdir" + } else { + generated_dir = "$target_gen_dir" + } + + shader_lib_dir = rebase_path("//flutter/impeller/compiler/shader_lib") + args = [ "--include=$shader_lib_dir" ] + shader_target_flags + + # When we're in single invocation mode, we can't use source enumeration. + if (!single_invocation) { + depfile_path = "$generated_dir/{{source_file_part}}.d" + depfile_intermediate_path = rebase_path(depfile_path, root_build_dir) + depfile = depfile_path + args += [ + "--input={{source}}", + "--include={{source_dir}}", + "--depfile=$depfile_intermediate_path", + ] + + if (defined(invoker.shader_target_flag)) { + args += [ "${invoker.shader_target_flag}" ] + } + } + + if (defined(invoker.gles_language_version)) { + gles_language_version = invoker.gles_language_version + args += [ "--gles-language-version=$gles_language_version" ] + } + + if (defined(invoker.metal_version)) { + assert(is_mac || is_ios) + metal_version = invoker.metal_version + args += [ "--metal-version=$metal_version" ] + } + + if (defined(invoker.use_half_textures) && invoker.use_half_textures) { + args += [ "--use-half-textures" ] + } + if (defined(invoker.require_framebuffer_fetch) && + invoker.require_framebuffer_fetch) { + args += [ "--require-framebuffer-fetch" ] + } + + if (json) { + args += [ "--json" ] + } + + if (iplr) { + # When building in IPLR mode, the compiler may be executed twice + args += [ "--iplr" ] + } + + # The `sl_output` is the raw shader file output by the compiler. For --iplr + # and --shader-bundle, this is used as the filename for the flatbuffer to + # output. + + if (shader_bundle) { + # When a shader bundle is specified, don't bother supplying flags for + # the reflection state as these are ignored. In this mode, the compiler + # is invoked multiple times and the reflection state for each shader is + # written to the output flatbuffer. + sl_output = "$generated_dir/${invoker.shader_bundle_output}" + sl_output_path = rebase_path(sl_output, root_build_dir) + + args += [ + "--sl=$sl_output_path", + "--shader-bundle=${invoker.shader_bundle}", + ] + + outputs = [ sl_output ] + } else if (sksl) { + # When SkSL is selected as a `shader_target_flags`, don't generate + # C++ reflection state. Nothing needs to use it and it's likely invalid + # given the special cases when generating SkSL. + # Note that this configuration is orthogonal to the "--iplr" flag + sl_output = + "$generated_dir/{{source_file_part}}.${invoker.sl_file_extension}" + sl_output_path = rebase_path(sl_output, root_build_dir) + + spirv_intermediate = "$generated_dir/{{source_file_part}}.spirv" + spirv_intermediate_path = rebase_path(spirv_intermediate, root_build_dir) + args += [ + "--sl=$sl_output_path", + "--spirv=$spirv_intermediate_path", + ] + + outputs = [ sl_output ] + } else { + # The default branch. Here we just generate one shader along with all of + # its C++ reflection state. + + sl_output = + "$generated_dir/{{source_file_part}}.${invoker.sl_file_extension}" + sl_output_path = rebase_path(sl_output, root_build_dir) + + reflection_json_intermediate = "$generated_dir/{{source_file_part}}.json" + reflection_header_intermediate = "$generated_dir/{{source_file_part}}.h" + reflection_cc_intermediate = "$generated_dir/{{source_file_part}}.cc" + + spirv_intermediate = "$generated_dir/{{source_file_part}}.spirv" + spirv_intermediate_path = rebase_path(spirv_intermediate, root_build_dir) + reflection_json_path = + rebase_path(reflection_json_intermediate, root_build_dir) + reflection_header_path = + rebase_path(reflection_header_intermediate, root_build_dir) + reflection_cc_path = + rebase_path(reflection_cc_intermediate, root_build_dir) + + args += [ + "--sl=$sl_output_path", + "--spirv=$spirv_intermediate_path", + "--reflection-json=$reflection_json_path", + "--reflection-header=$reflection_header_path", + "--reflection-cc=$reflection_cc_path", + ] + + outputs = [ + sl_output, + reflection_header_intermediate, + reflection_cc_intermediate, + ] + } + + if (defined(invoker.defines)) { + foreach(def, invoker.defines) { + args += [ "--define=$def" ] + } + } + + if (single_invocation) { + inputs = invoker.shaders + } else { + sources = invoker.shaders + } + } +} + +template("impellerc_reflect") { + assert( + defined(invoker.impellerc_invocation), + "The target that specifies the ImpellerC invocation to reflect must be defined.") + + reflect_config = "reflect_$target_name" + config(reflect_config) { + include_dirs = [ get_path_info( + get_label_info("//flutter/impeller:impeller", "target_gen_dir"), + "dir") ] + } + + impellerc_invocation = invoker.impellerc_invocation + + source_set(target_name) { + public_configs = [ ":$reflect_config" ] + public = filter_include(get_target_outputs(impellerc_invocation), [ "*.h" ]) + sources = filter_include(get_target_outputs(impellerc_invocation), + [ + "*.h", + "*.cc", + "*.mm", + ]) + + deps = [ + "//flutter/impeller/core", + impellerc_invocation, + ] + } +} diff --git a/flutter/engine/src/flutter/impeller/tools/component.gni b/flutter/engine/src/flutter/impeller/tools/component.gni new file mode 100644 index 0000000000000000000000000000000000000000..d6fdef6b5e914c0fafa4f3e3dadce56e26a1320a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/component.gni @@ -0,0 +1,58 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +# ------------------------------------------------------------------------------ +# @brief Define an Impeller component. Components are different +# Impeller subsystems part of the umbrella framework. +# +# @param[optional] target_type The type of the component. This can be any of +# the target types supported by GN. Defaults to +# source_set. If Impeller is not supported on the +# target platform, this target is a no-op. +# +template("impeller_component") { + if (defined(invoker.testonly) && invoker.testonly && !enable_unittests) { + group(target_name) { + not_needed(invoker, "*") + } + } else { + target_type = "source_set" + if (defined(invoker.target_type)) { + target_type = invoker.target_type + } + target(target_type, target_name) { + forward_variables_from(invoker, "*") + + if (!defined(invoker.public_configs)) { + public_configs = [] + } + + public_configs += [ "//flutter/impeller:impeller_public_config" ] + + if (!defined(invoker.cflags)) { + cflags = [] + } + cflags += [ "-Wthread-safety-analysis" ] + + if (!defined(invoker.cflags_objc)) { + cflags_objc = [] + } + + if (is_ios || is_mac) { + cflags_objc += flutter_cflags_objc + } + + if (!defined(invoker.cflags_objcc)) { + cflags_objcc = [] + } + + if (is_ios || is_mac) { + cflags_objcc += flutter_cflags_objcc + } + } + } +} diff --git a/flutter/engine/src/flutter/impeller/tools/embed_blob.gni b/flutter/engine/src/flutter/impeller/tools/embed_blob.gni new file mode 100644 index 0000000000000000000000000000000000000000..b895d395a832ad152ca7e7a137656c71ecdba79b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/embed_blob.gni @@ -0,0 +1,47 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +template("embed_blob") { + assert(defined(invoker.symbol_name), "The symbol name must be specified.") + assert(defined(invoker.blob), "The blob file to embed must be specified") + assert(defined(invoker.hdr), + "The header file containing the symbol name must be specified.") + assert(defined(invoker.cc), + "The CC file containing the symbol data must be specified.") + assert(defined(invoker.deps), "The target dependencies must be specified") + + gen_blob_target_name = "gen_blob_$target_name" + action(gen_blob_target_name) { + inputs = [ invoker.blob ] + outputs = [ + invoker.hdr, + invoker.cc, + ] + args = [ + "--symbol-name", + invoker.symbol_name, + "--output-header", + rebase_path(invoker.hdr), + "--output-source", + rebase_path(invoker.cc), + "--source", + rebase_path(invoker.blob), + ] + script = "//flutter/impeller/tools/xxd.py" + deps = invoker.deps + } + + embed_config = "embed_$target_name" + config(embed_config) { + include_dirs = [ get_path_info( + get_label_info("//flutter/impeller:impeller", "target_gen_dir"), + "dir") ] + } + + source_set(target_name) { + public_configs = [ ":$embed_config" ] + sources = get_target_outputs(":$gen_blob_target_name") + deps = [ ":$gen_blob_target_name" ] + } +} diff --git a/flutter/engine/src/flutter/impeller/tools/impeller.gni b/flutter/engine/src/flutter/impeller/tools/impeller.gni new file mode 100644 index 0000000000000000000000000000000000000000..b9bda90d81d5ce87f792f43c7f068048bc1e0973 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/impeller.gni @@ -0,0 +1,12 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Global configuration options for Impeller. +import("//flutter/impeller/tools/args.gni") + +# The common template used by all Impeller components. +import("//flutter/impeller/tools/component.gni") + +# Templates for compiling, reflecting, and packaging shaders used by Impeller. +import("//flutter/impeller/tools/shaders.gni") diff --git a/flutter/engine/src/flutter/impeller/tools/malioc.gni b/flutter/engine/src/flutter/impeller/tools/malioc.gni new file mode 100644 index 0000000000000000000000000000000000000000..356fcdcbaea1cabd360d37b4623e101d0747a6e8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/malioc.gni @@ -0,0 +1,128 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/compiled_action.gni") +import("//flutter/common/config.gni") +import("//flutter/testing/testing.gni") + +declare_args() { + # Path to the Mali offline compiler tool 'malioc'. + impeller_malioc_path = "" + + impeller_malioc_core_filter = [ + "Mali-G78", + "Mali-T880", + ] +} + +if (impeller_malioc_path != "") { + _core_list_file = "$root_build_dir/mali_core_list.json" + exec_script("//flutter/impeller/tools/malioc_cores.py", + [ + "--malioc", + rebase_path(impeller_malioc_path, root_build_dir), + "--output", + rebase_path(_core_list_file), + ]) + _impeller_malioc_cores = read_file(_core_list_file, "json") +} + +template("malioc_analyze_shaders") { + if (impeller_malioc_path == "") { + group(target_name) { + not_needed(invoker, "*") + } + } else { + target_deps = [] + foreach(core, _impeller_malioc_cores) { + foreach(filter_core, impeller_malioc_core_filter) { + if (core.core == filter_core) { + foreach(source, invoker.shaders) { + # Should be "gles" or "vkspv" + backend_ext = get_path_info(source, "extension") + assert( + backend_ext == "gles" || backend_ext == "vkspv", + "Shader for unsupported backend passed to malioc: {{source}}") + shader_file_name = get_path_info(source, "name") + analysis_target = + "${target_name}_${shader_file_name}_${core.core}_malioc" + if ((backend_ext == "gles" && + defined(invoker.gles_language_version) && + core.opengles_max_version < invoker.gles_language_version) || + (backend_ext == "vkspv" && + defined(invoker.vulkan_language_version) && + core.vulkan_max_version < invoker.vulkan_language_version)) { + group(analysis_target) { + not_needed(invoker, "*") + } + } else { + target_deps += [ ":$analysis_target" ] + action(analysis_target) { + forward_variables_from(invoker, + "*", + [ + "args", + "depfile", + "inputs", + "outputs", + "pool", + "script", + ]) + + script = "//build/gn_run_malioc.py" + pool = "//build/toolchain:toolchain_pool" + + # Nest all malioc output under its own subdirectory of root_gen_dir + # so that it's easier to diff it against the state before any changes. + subdir = rebase_path(target_gen_dir, root_gen_dir) + output_file = "$root_gen_dir/malioc/$subdir/${shader_file_name}.${backend_ext}.${core.core}.json" + outputs = [ output_file ] + + # Determine the kind of the shader from the file name + name = get_path_info(source, "name") + shader_kind_ext = get_path_info(name, "extension") + + if (shader_kind_ext == "comp") { + shader_kind_flag = "--compute" + } else if (shader_kind_ext == "frag") { + shader_kind_flag = "--fragment" + } else if (shader_kind_ext == "geom") { + shader_kind_flag = "--geometry" + } else if (shader_kind_ext == "tesc") { + shader_kind_flag = "--tessellation_control" + } else if (shader_kind_ext == "tese") { + shader_kind_flag = "--tessellation_evaluation" + } else if (shader_kind_ext == "vert") { + shader_kind_flag = "--vertex" + } else { + assert(false, "Unknown shader kind: {{source}}") + } + + args = [ + rebase_path(impeller_malioc_path, root_build_dir), + rebase_path(output_file), + "--format", + "json", + shader_kind_flag, + "--core", + core.core, + ] + + if (backend_ext == "vkspv") { + args += [ "--vulkan" ] + } + + args += [ rebase_path(source) ] + } + } + } + } + } + } + + group(target_name) { + deps = target_deps + } + } +} diff --git a/flutter/engine/src/flutter/impeller/tools/malioc.json b/flutter/engine/src/flutter/impeller/tools/malioc.json new file mode 100644 index 0000000000000000000000000000000000000000..499e73d3ade569bb294d880908082315b820c950 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/malioc.json @@ -0,0 +1,11004 @@ +{ + "flutter/impeller/entity/advanced_blend.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/advanced_blend.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 2, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.53125, + 0.53125, + 0.21875, + 0.125, + 0.0, + 0.5, + 0.5 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.484375, + 0.484375, + 0.203125, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.53125, + 0.53125, + 0.296875, + 0.125, + 0.0, + 0.5, + 0.5 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 25 + } + } + } + }, + "flutter/impeller/entity/advanced_blend.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/advanced_blend.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 10 + } + } + } + }, + "flutter/impeller/entity/border_mask_blur.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/border_mask_blur.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 88, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.824999988079071, + 0.824999988079071, + 0.234375, + 0.25, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.824999988079071, + 0.824999988079071, + 0.234375, + 0.25, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.824999988079071, + 0.824999988079071, + 0.234375, + 0.25, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 16, + "work_registers_used": 16 + } + } + } + }, + "flutter/impeller/entity/clip.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/clip.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 0 + } + } + } + }, + "flutter/impeller/entity/clip.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/clip.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.015625, + 0.0625, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.015625, + 0.0625, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.015625, + 0.0625, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 24, + "work_registers_used": 32 + } + } + } + }, + "flutter/impeller/entity/color_matrix_color_filter.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/color_matrix_color_filter.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.28125, + 0.28125, + 0.0625, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.28125, + 0.28125, + 0.0625, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.28125, + 0.28125, + 0.0625, + 0.0625, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 16, + "work_registers_used": 9 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_fill_conical.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_fill_conical.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.675000011920929, + 0.46875, + 0.675000011920929, + 0.1875, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.265625, + 0.203125, + 0.265625, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.862500011920929, + 0.59375, + 0.862500011920929, + 0.3125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_fill_radial.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_fill_radial.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.328125, + 0.328125, + 0.296875, + 0.125, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.234375, + 0.234375, + 0.203125, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.421875, + 0.359375, + 0.421875, + 0.125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 12 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_fill_strip.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_fill_strip.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.421875, + 0.328125, + 0.421875, + 0.125, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.109375, + 0.0625, + 0.109375, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.546875, + 0.359375, + 0.546875, + 0.125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_fill_strip_radial.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_fill_strip_radial.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_ssbo_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_ssbo_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.625, + 0.359375, + 0.453125, + 0.625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 1.15625, + 0.78125, + 1.15625, + 0.8125, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 34, + "work_registers_used": 17 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_uniform_fill_conical.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_uniform_fill_conical.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.375, + 0.34375, + 0.375, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 1.2625000476837158, + 0.75, + 1.2625000476837158, + 0.4375, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 19 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_uniform_fill_radial.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_uniform_fill_radial.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma", + "varying" + ], + "shortest_path_cycles": [ + 0.25, + 0.25, + 0.21875, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.862500011920929, + 0.5, + 0.862500011920929, + 0.3125, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 19 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_uniform_fill_strip.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_uniform_fill_strip.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.234375, + 0.234375, + 0.21875, + 0.0625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.9375, + 0.515625, + 0.9375, + 0.25, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 19 + } + } + } + }, + "flutter/impeller/entity/conical_gradient_uniform_fill_strip_radial.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/conical_gradient_uniform_fill_strip_radial.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 5 + } + } + } + }, + "flutter/impeller/entity/fast_gradient.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/fast_gradient.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 85, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "longest_path_cycles": [ + 0.5, + 0.109375, + 0.109375, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.5, + 0.109375, + 0.109375, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "total_cycles": [ + 0.5, + 0.109375, + 0.109375, + 0.5, + 0.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/fast_gradient.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/fast_gradient.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/filter_position.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/filter_position.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/filter_position_uv.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/filter_position_uv.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/gaussian.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gaussian.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.125, + 0.0, + 0.125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.265625, + 0.09375, + 0.265625, + 0.0, + 1.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 13 + } + } + } + }, + "flutter/impeller/entity/gles/advanced_blend.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/advanced_blend.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 2, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.53125, + 0.53125, + 0.265625, + 0.125, + 0.0, + 0.5, + 0.5 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.484375, + 0.484375, + 0.21875, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.53125, + 0.53125, + 0.34375, + 0.125, + 0.0, + 0.5, + 0.5 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 14, + "work_registers_used": 23 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/advanced_blend.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 3.9600000381469727, + 2.0, + 2.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 3.299999952316284, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 4.666666507720947, + 2.0, + 2.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 4 + } + } + } + }, + "flutter/impeller/entity/gles/advanced_blend.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/advanced_blend.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.03125, + 0.03125, + 0.03125, + 0.0, + 4.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 10 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/advanced_blend.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 3.299999952316284, + 7.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 3.299999952316284, + 7.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.3333332538604736, + 7.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/border_mask_blur.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/border_mask_blur.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 81, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.9375, + 0.9375, + 0.296875, + 0.25, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.9375, + 0.9375, + 0.265625, + 0.25, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.9375, + 0.9375, + 0.296875, + 0.25, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 29 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/border_mask_blur.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 8.579999923706055, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 8.579999923706055, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 9.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/clip.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/clip.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.015625, + 0.0, + 0.015625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 1 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/clip.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 0.6666666865348816, + 0.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/clip.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/clip.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0625, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0625, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0625, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 32 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/clip.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 3.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 3.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.28125, + 0.28125, + 0.09375, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.28125, + 0.28125, + 0.0625, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.28125, + 0.28125, + 0.09375, + 0.0625, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 14, + "work_registers_used": 21 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/color_matrix_color_filter.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 2.9700000286102295, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 3.3333332538604736, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_fill_conical.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_conical.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.78125, + 0.46875, + 0.78125, + 0.25, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.265625, + 0.203125, + 0.265625, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.96875, + 0.59375, + 0.96875, + 0.375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 32, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_conical.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 9.899999618530273, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 3.630000114440918, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 13.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_fill_radial.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_radial.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.40625, + 0.328125, + 0.40625, + 0.1875, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt", + "varying" + ], + "shortest_path_cycles": [ + 0.25, + 0.234375, + 0.25, + 0.1875, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.5625, + 0.359375, + 0.5625, + 0.1875, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_radial.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 7.260000228881836, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 8.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 7, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_fill_strip.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_strip.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.53125, + 0.328125, + 0.53125, + 0.1875, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.109375, + 0.0625, + 0.109375, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.65625, + 0.359375, + 0.65625, + 0.1875, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_strip.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 8.25, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 9.666666984558105, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 7, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_fill_strip_radial.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_strip_radial.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 18 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_fill_strip_radial.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 0.6666666865348816, + 0.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 0, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_uniform_fill_conical.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_conical.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.3125, + 0.3125, + 0.296875, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 1.21875, + 0.737500011920929, + 1.21875, + 0.375, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 26, + "work_registers_used": 23 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_conical.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 4.289999961853027, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 14.333333015441895, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_uniform_fill_radial.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_radial.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma", + "varying" + ], + "shortest_path_cycles": [ + 0.25, + 0.25, + 0.21875, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.887499988079071, + 0.5, + 0.887499988079071, + 0.25, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 23 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_radial.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 10.0, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.171875, + 0.171875, + 0.140625, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.90625, + 0.5, + 0.90625, + 0.1875, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 23 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 11.0, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip_radial.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip_radial.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.109375, + 0.0, + 0.109375, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.078125, + 0.0, + 0.078125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.109375, + 0.0, + 0.109375, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 18 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/conical_gradient_uniform_fill_strip_radial.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 0.6666666865348816, + 0.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/fast_gradient.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/fast_gradient.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying" + ], + "longest_path_cycles": [ + 0.0625, + 0.0625, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.0625, + 0.0625, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "varying" + ], + "total_cycles": [ + 0.0625, + 0.0625, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/fast_gradient.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "longest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.6666666865348816, + 1.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/fast_gradient.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/fast_gradient.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 7 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/fast_gradient.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 5.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 5.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/filter_position.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/filter_position.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 8 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/filter_position.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.9700000286102295, + 4.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.0, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/filter_position_uv.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/filter_position_uv.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 8 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/filter_position_uv.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.9700000286102295, + 5.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 5.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.0, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/gaussian.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/gaussian.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.265625, + 0.09375, + 0.265625, + 0.0, + 1.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/gaussian.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "total_cycles": [ + 2.0, + 2.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/glyph_atlas.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/glyph_atlas.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.109375, + 0.03125, + 0.109375, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.0625, + 0.03125, + 0.0625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.125, + 0.0625, + 0.125, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/glyph_atlas.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "longest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 2.6666667461395264, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/glyph_atlas.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/glyph_atlas.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 7 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/glyph_atlas.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 5.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 5.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/gradient_fill.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/gradient_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 11 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/gradient_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 3.299999952316284, + 4.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 3.299999952316284, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.3333332538604736, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/line.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/line.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying" + ], + "longest_path_cycles": [ + 0.1875, + 0.1875, + 0.1875, + 0.0, + 0.0, + 1.75, + 0.5 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.171875, + 0.171875, + 0.109375, + 0.0, + 0.0, + 1.75, + 0.0 + ], + "total_bound_pipelines": [ + "varying" + ], + "total_cycles": [ + 0.1875, + 0.1875, + 0.1875, + 0.0, + 0.0, + 1.75, + 0.5 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 24 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/line.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 3.299999952316284, + 5.0, + 2.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.309999942779541, + 5.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.6666667461395264, + 5.0, + 2.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/line.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/line.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 10.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 10.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 10.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/line.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 12.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 12.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 12.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/linear_gradient_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/linear_gradient_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 4, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.40625, + 0.296875, + 0.40625, + 0.125, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.203125, + 0.1875, + 0.203125, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.53125, + 0.328125, + 0.53125, + 0.125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 16, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/linear_gradient_fill.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 7.260000228881836, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.309999942779541, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 8.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/linear_gradient_uniform_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/linear_gradient_uniform_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 2, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.203125, + 0.203125, + 0.171875, + 0.0625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.8125, + 0.453125, + 0.8125, + 0.1875, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 21 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/linear_gradient_uniform_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 9.666666984558105, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 40, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt", + "arith_sfu" + ], + "longest_path_cycles": [ + 0.4375, + 0.328125, + 0.4375, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.4375, + 0.328125, + 0.40625, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt", + "arith_sfu" + ], + "total_cycles": [ + 0.4375, + 0.328125, + 0.4375, + 0.4375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 30 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/linear_to_srgb_filter.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 4.949999809265137, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 4.949999809265137, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 5.333333492279053, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/morphology_filter.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/morphology_filter.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 80, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.234375, + 0.078125, + 0.234375, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 21 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/morphology_filter.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 2.6666667461395264, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 4 + } + } + } + }, + "flutter/impeller/entity/gles/porter_duff_blend.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/porter_duff_blend.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 71, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying" + ], + "longest_path_cycles": [ + 0.21875, + 0.21875, + 0.03125, + 0.0, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.21875, + 0.21875, + 0.0, + 0.0, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "varying" + ], + "total_cycles": [ + 0.21875, + 0.21875, + 0.03125, + 0.0, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/porter_duff_blend.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 1.3200000524520874, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.3200000524520874, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 1.6666666269302368, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/porter_duff_blend.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/porter_duff_blend.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.109375, + 0.015625, + 0.109375, + 0.0, + 4.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.109375, + 0.015625, + 0.109375, + 0.0, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.109375, + 0.015625, + 0.109375, + 0.0, + 4.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 9 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/porter_duff_blend.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.9700000286102295, + 7.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 7.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.0, + 7.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/radial_gradient_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/radial_gradient_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 3, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.4375, + 0.3125, + 0.4375, + 0.1875, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.234375, + 0.203125, + 0.234375, + 0.1875, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.5625, + 0.34375, + 0.5625, + 0.1875, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 14, + "work_registers_used": 20 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/radial_gradient_fill.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 7.260000228881836, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.309999942779541, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 8.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/radial_gradient_uniform_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/radial_gradient_uniform_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 28, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.203125, + 0.171875, + 0.203125, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.800000011920929, + 0.375, + 0.800000011920929, + 0.25, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 21 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/radial_gradient_uniform_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 10.0, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/rrect_blur.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/rrect_blur.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.625, + 0.625, + 0.21875, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.625, + 0.625, + 0.1875, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.625, + 0.625, + 0.21875, + 0.5, + 0.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 23 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/rrect_blur.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 6.599999904632568, + 1.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 6.599999904632568, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 7.0, + 1.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/rrect_blur.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/rrect_blur.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 7 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/rrect_blur.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 4.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/runtime_effect.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/runtime_effect.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 7 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/runtime_effect.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 4.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/solid_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/solid_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 18 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/solid_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 0.6666666865348816, + 0.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/solid_fill.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/solid_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 32 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/solid_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.640000104904175, + 3.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.640000104904175, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.6666667461395264, + 3.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 5, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 40, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.484375, + 0.328125, + 0.484375, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.453125, + 0.328125, + 0.453125, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.484375, + 0.328125, + 0.484375, + 0.4375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 28 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/srgb_to_linear_filter.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 4.949999809265137, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 4.949999809265137, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 5.333333492279053, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 2, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.484375, + 0.46875, + 0.484375, + 0.375, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.375, + 0.359375, + 0.25, + 0.375, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.578125, + 0.5, + 0.578125, + 0.375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 24 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/sweep_gradient_fill.frag.gles", + "has_uniform_computation": true, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 7.920000076293945, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 8.666666984558105, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/sweep_gradient_uniform_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/sweep_gradient_uniform_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.375, + 0.375, + 0.25, + 0.3125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.925000011920929, + 0.625, + 0.925000011920929, + 0.4375, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 25 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/sweep_gradient_uniform_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 10.0, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/texture_downsample.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_downsample.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.3125, + 0.140625, + 0.3125, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_downsample.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 2.6666667461395264, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 4 + } + } + } + }, + "flutter/impeller/entity/gles/texture_downsample_gles.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_downsample_gles.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.09375, + 0.0, + 0.09375, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.421875, + 0.140625, + 0.421875, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_downsample_gles.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 5.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 50, + "uniform_registers_used": 1, + "work_registers_used": 6 + } + } + } + }, + "flutter/impeller/entity/gles/texture_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.046875, + 0.03125, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.046875, + 0.03125, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "longest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "load_store", + "texture" + ], + "total_cycles": [ + 0.6666666865348816, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/texture_fill.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_fill.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 8 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.9700000286102295, + 5.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 2.9700000286102295, + 5.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.0, + 5.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 33, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.109375, + 0.03125, + 0.109375, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.078125, + 0.03125, + 0.078125, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.109375, + 0.03125, + 0.109375, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_fill_strict_src.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "longest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "total_cycles": [ + 1.0, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/texture_uv_fill.vert.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/texture_uv_fill.vert.gles", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.140625, + 0.140625, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 16, + "work_registers_used": 9 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/texture_uv_fill.vert.gles", + "has_uniform_computation": false, + "type": "Vertex", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 3.299999952316284, + 4.0, + 0.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 3.299999952316284, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 3.3333332538604736, + 4.0, + 0.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 7, + "work_registers_used": 3 + } + } + } + }, + "flutter/impeller/entity/gles/tiled_texture_fill.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/tiled_texture_fill.frag.gles", + "has_side_effects": false, + "has_uniform_computation": false, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.046875, + 0.03125, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.046875, + 0.03125, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/tiled_texture_fill.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "longest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_cycles": [ + 1.0, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "load_store", + "texture" + ], + "total_cycles": [ + 0.6666666865348816, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 1, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 35, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.421875, + 0.328125, + 0.421875, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.09375, + 0.03125, + 0.09375, + 0.0, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.546875, + 0.359375, + 0.546875, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 22 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/tiled_texture_fill_external.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 8.25, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 1.3200000524520874, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 9.666666984558105, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/gles/vertices_uber_1.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/vertices_uber_1.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.887499988079071, + 0.887499988079071, + 0.53125, + 0.125, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.421875, + 0.421875, + 0.34375, + 0.0625, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 1.625, + 1.625, + 1.34375, + 0.5, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 26 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/vertices_uber_1.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 9.569999694824219, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 3.9600000381469727, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 18.66666603088379, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 50, + "uniform_registers_used": 1, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/gles/vertices_uber_2.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/vertices_uber_2.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 1.2625000476837158, + 1.2625000476837158, + 0.637499988079071, + 0.3125, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.421875, + 0.421875, + 0.359375, + 0.0625, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 2.6875, + 2.6875, + 1.6749999523162842, + 0.5625, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 32 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/vertices_uber_2.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 11.550000190734863, + 1.0, + 1.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 4.289999961853027, + 1.0, + 1.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 31.66666603088379, + 1.0, + 1.0 + ] + }, + "thread_occupancy": 50, + "uniform_registers_used": 1, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "texture" + ], + "longest_path_cycles": [ + 0.15625, + 0.15625, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.5 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "texture" + ], + "shortest_path_cycles": [ + 0.15625, + 0.15625, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.5 + ], + "total_bound_pipelines": [ + "texture" + ], + "total_cycles": [ + 0.15625, + 0.15625, + 0.046875, + 0.0, + 0.0, + 0.25, + 0.5 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 19 + } + } + }, + "Mali-T880": { + "core": "Mali-T880", + "filename": "flutter/impeller/entity/gles/yuv_to_rgb_filter.frag.gles", + "has_uniform_computation": false, + "type": "Fragment", + "variants": { + "Main": { + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arithmetic" + ], + "longest_path_cycles": [ + 2.309999942779541, + 1.0, + 2.0 + ], + "pipelines": [ + "arithmetic", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arithmetic" + ], + "shortest_path_cycles": [ + 2.309999942779541, + 1.0, + 2.0 + ], + "total_bound_pipelines": [ + "arithmetic" + ], + "total_cycles": [ + 2.6666667461395264, + 1.0, + 2.0 + ] + }, + "thread_occupancy": 100, + "uniform_registers_used": 3, + "work_registers_used": 2 + } + } + } + }, + "flutter/impeller/entity/glyph_atlas.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/glyph_atlas.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.078125, + 0.03125, + 0.078125, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.0625, + 0.03125, + 0.0625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.09375, + 0.0625, + 0.09375, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 6 + } + } + } + }, + "flutter/impeller/entity/glyph_atlas.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/glyph_atlas.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/gradient_fill.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/gradient_fill.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 44, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0625, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 36, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/line.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/line.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 33, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying" + ], + "longest_path_cycles": [ + 0.1875, + 0.171875, + 0.15625, + 0.1875, + 0.0, + 1.75, + 0.5 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.1875, + 0.15625, + 0.109375, + 0.1875, + 0.0, + 1.75, + 0.0 + ], + "total_bound_pipelines": [ + "varying" + ], + "total_cycles": [ + 0.1875, + 0.171875, + 0.15625, + 0.1875, + 0.0, + 1.75, + 0.5 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 18 + } + } + } + }, + "flutter/impeller/entity/line.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/line.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.046875, + 0.0, + 0.046875, + 0.0, + 10.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.046875, + 0.0, + 0.046875, + 0.0, + 10.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.046875, + 0.0, + 0.046875, + 0.0, + 10.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 22 + } + } + } + }, + "flutter/impeller/entity/linear_gradient_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/linear_gradient_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 28, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.296875, + 0.234375, + 0.296875, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.171875, + 0.140625, + 0.171875, + 0.0625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.390625, + 0.265625, + 0.390625, + 0.0625, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/linear_gradient_ssbo_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/linear_gradient_ssbo_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 32, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.5625, + 0.203125, + 0.25, + 0.5625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.699999988079071, + 0.390625, + 0.699999988079071, + 0.5625, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 24, + "work_registers_used": 21 + } + } + } + }, + "flutter/impeller/entity/linear_gradient_uniform_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/linear_gradient_uniform_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 30, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.15625, + 0.15625, + 0.15625, + 0.0625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.84375, + 0.34375, + 0.84375, + 0.25, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 14, + "work_registers_used": 18 + } + } + } + }, + "flutter/impeller/entity/linear_to_srgb_filter.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/linear_to_srgb_filter.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 31, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "longest_path_cycles": [ + 0.4375, + 0.28125, + 0.40625, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.171875, + 0.140625, + 0.171875, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "total_cycles": [ + 0.4375, + 0.328125, + 0.40625, + 0.4375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 10 + } + } + } + }, + "flutter/impeller/entity/morphology_filter.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/morphology_filter.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 44, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.109375, + 0.0, + 0.109375, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.265625, + 0.046875, + 0.265625, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/porter_duff_blend.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/porter_duff_blend.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying" + ], + "longest_path_cycles": [ + 0.1875, + 0.1875, + 0.0, + 0.0, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.1875, + 0.1875, + 0.0, + 0.0, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "varying" + ], + "total_cycles": [ + 0.1875, + 0.1875, + 0.0, + 0.0, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/porter_duff_blend.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/porter_duff_blend.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.078125, + 0.015625, + 0.078125, + 0.0, + 4.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.078125, + 0.015625, + 0.078125, + 0.0, + 4.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.078125, + 0.015625, + 0.078125, + 0.0, + 4.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/radial_gradient_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/radial_gradient_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 16, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.328125, + 0.25, + 0.328125, + 0.125, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.203125, + 0.15625, + 0.203125, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.421875, + 0.28125, + 0.421875, + 0.125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 16, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/radial_gradient_ssbo_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/radial_gradient_ssbo_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 26, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.625, + 0.21875, + 0.28125, + 0.625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.737500011920929, + 0.4375, + 0.737500011920929, + 0.6875, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 17 + } + } + } + }, + "flutter/impeller/entity/radial_gradient_uniform_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/radial_gradient_uniform_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 28, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.1875, + 0.171875, + 0.1875, + 0.125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.875, + 0.375, + 0.875, + 0.3125, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 18 + } + } + } + }, + "flutter/impeller/entity/rrect_blur.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/rrect_blur.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.625, + 0.625, + 0.1875, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.625, + 0.625, + 0.1875, + 0.5, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 0.625, + 0.625, + 0.1875, + 0.5, + 0.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 18, + "work_registers_used": 11 + } + } + } + }, + "flutter/impeller/entity/rrect_blur.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/rrect_blur.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/runtime_effect.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/runtime_effect.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/solid_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/solid_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.0625, + 0.0, + 0.0625, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 5 + } + } + } + }, + "flutter/impeller/entity/solid_fill.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/solid_fill.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 32 + } + } + } + }, + "flutter/impeller/entity/srgb_to_linear_filter.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/srgb_to_linear_filter.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 20, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "longest_path_cycles": [ + 0.4375, + 0.28125, + 0.390625, + 0.4375, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.15625, + 0.140625, + 0.15625, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "total_cycles": [ + 0.4375, + 0.328125, + 0.390625, + 0.4375, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 9 + } + } + } + }, + "flutter/impeller/entity/sweep_gradient_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/sweep_gradient_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 10, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.40625, + 0.40625, + 0.359375, + 0.3125, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.3125, + 0.3125, + 0.234375, + 0.3125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.453125, + 0.4375, + 0.453125, + 0.3125, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 15 + } + } + } + }, + "flutter/impeller/entity/sweep_gradient_ssbo_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/sweep_gradient_ssbo_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_sfu" + ], + "shortest_path_cycles": [ + 0.8125, + 0.390625, + 0.328125, + 0.8125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.875, + 0.65625, + 0.78125, + 0.875, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 28, + "work_registers_used": 20 + } + } + } + }, + "flutter/impeller/entity/sweep_gradient_uniform_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/sweep_gradient_uniform_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.375, + 0.375, + 0.25, + 0.3125, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.887499988079071, + 0.625, + 0.887499988079071, + 0.5, + 4.0, + 0.25, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 20, + "work_registers_used": 23 + } + } + } + }, + "flutter/impeller/entity/texture_downsample.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_downsample.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.140625, + 0.0, + 0.140625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.34375, + 0.125, + 0.34375, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 14 + } + } + } + }, + "flutter/impeller/entity/texture_downsample_gles.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_downsample_gles.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + null + ], + "longest_path_cycles": [ + null, + null, + null, + null, + null, + null, + null + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.140625, + 0.0, + 0.140625, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.453125, + 0.125, + 0.453125, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 17 + } + } + } + }, + "flutter/impeller/entity/texture_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 5 + } + } + } + }, + "flutter/impeller/entity/texture_fill.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_fill.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 30, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.015625, + 0.015625, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 22, + "work_registers_used": 8 + } + } + } + }, + "flutter/impeller/entity/texture_fill_strict_src.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_fill_strict_src.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 33, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.078125, + 0.03125, + 0.078125, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.078125, + 0.03125, + 0.078125, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.078125, + 0.03125, + 0.078125, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 5 + } + } + } + }, + "flutter/impeller/entity/texture_uv_fill.vert.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/texture_uv_fill.vert.vkspv", + "has_uniform_computation": true, + "type": "Vertex", + "variants": { + "Position": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.125, + 0.125, + 0.0, + 0.0, + 2.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 40, + "work_registers_used": 32 + }, + "Varying": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.078125, + 0.078125, + 0.015625, + 0.0, + 3.0, + 0.0 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 32, + "work_registers_used": 9 + } + } + } + }, + "flutter/impeller/entity/tiled_texture_fill.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/tiled_texture_fill.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.03125, + 0.03125, + 0.015625, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 4, + "work_registers_used": 5 + } + } + } + }, + "flutter/impeller/entity/tiled_texture_fill_external.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/tiled_texture_fill_external.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 72, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "longest_path_cycles": [ + 0.375, + 0.1875, + 0.375, + 0.0625, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying" + ], + "shortest_path_cycles": [ + 0.140625, + 0.03125, + 0.140625, + 0.0625, + 0.0, + 0.25, + 0.0 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "total_cycles": [ + 0.4375, + 0.21875, + 0.4375, + 0.0625, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 6, + "work_registers_used": 7 + } + } + } + }, + "flutter/impeller/entity/vertices_uber_1.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/vertices_uber_1.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 0.887499988079071, + 0.887499988079071, + 0.46875, + 0.125, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.5625, + 0.5625, + 0.21875, + 0.125, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 1.6375000476837158, + 1.6375000476837158, + 1.1749999523162842, + 0.5, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 10, + "work_registers_used": 27 + } + } + } + }, + "flutter/impeller/entity/vertices_uber_2.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/vertices_uber_2.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 0, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "longest_path_cycles": [ + 1.1124999523162842, + 1.1124999523162842, + 0.737500011920929, + 0.3125, + 0.0, + 0.5, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "shortest_path_cycles": [ + 0.5625, + 0.5625, + 0.265625, + 0.125, + 0.0, + 0.5, + 0.25 + ], + "total_bound_pipelines": [ + "arith_total", + "arith_fma" + ], + "total_cycles": [ + 2.700000047683716, + 2.700000047683716, + 1.4249999523162842, + 0.5625, + 0.0, + 0.5, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 32 + } + } + } + }, + "flutter/impeller/entity/yuv_to_rgb_filter.frag.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/entity/yuv_to_rgb_filter.frag.vkspv", + "has_side_effects": false, + "has_uniform_computation": true, + "modifies_coverage": false, + "reads_color_buffer": false, + "type": "Fragment", + "uses_late_zs_test": false, + "uses_late_zs_update": false, + "variants": { + "Main": { + "fp16_arithmetic": 100, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "varying", + "texture" + ], + "longest_path_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "varying", + "texture" + ], + "shortest_path_bound_pipelines": [ + "varying", + "texture" + ], + "shortest_path_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0, + 0.0, + 0.25, + 0.25 + ], + "total_bound_pipelines": [ + "varying", + "texture" + ], + "total_cycles": [ + 0.15625, + 0.15625, + 0.0, + 0.0, + 0.0, + 0.25, + 0.25 + ] + }, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 12, + "work_registers_used": 6 + } + } + } + }, + "flutter/impeller/renderer/prefix_sum_test.comp.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/renderer/prefix_sum_test.comp.vkspv", + "has_uniform_computation": true, + "type": "Compute", + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 2.450000047683716, + 0.0, + 2.450000047683716, + 1.0, + 72.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "arith_total", + "arith_cvt" + ], + "shortest_path_cycles": [ + 0.762499988079071, + 0.0, + 0.762499988079071, + 0.0, + 0.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 2.46875, + 0.0, + 2.46875, + 1.0, + 72.0, + 0.0 + ] + }, + "shared_storage_used": 4096, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 8, + "work_registers_used": 18 + } + } + } + }, + "flutter/impeller/renderer/threadgroup_sizing_test.comp.vkspv": { + "Mali-G78": { + "core": "Mali-G78", + "filename": "flutter/impeller/renderer/threadgroup_sizing_test.comp.vkspv", + "has_uniform_computation": true, + "type": "Compute", + "variants": { + "Main": { + "fp16_arithmetic": null, + "has_stack_spilling": false, + "performance": { + "longest_path_bound_pipelines": [ + "load_store" + ], + "longest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 1.0, + 0.0 + ], + "pipelines": [ + "arith_total", + "arith_fma", + "arith_cvt", + "arith_sfu", + "load_store", + "texture" + ], + "shortest_path_bound_pipelines": [ + "load_store" + ], + "shortest_path_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 1.0, + 0.0 + ], + "total_bound_pipelines": [ + "load_store" + ], + "total_cycles": [ + 0.03125, + 0.0, + 0.03125, + 0.0, + 1.0, + 0.0 + ] + }, + "shared_storage_used": 0, + "stack_spill_bytes": 0, + "thread_occupancy": 100, + "uniform_registers_used": 2, + "work_registers_used": 4 + } + } + } + } +} \ No newline at end of file diff --git a/flutter/engine/src/flutter/impeller/tools/malioc_cores.py b/flutter/engine/src/flutter/impeller/tools/malioc_cores.py new file mode 100644 index 0000000000000000000000000000000000000000..9bd364ec1f6f4fe1ea86856a830ca84cef5bc025 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/malioc_cores.py @@ -0,0 +1,101 @@ +#!/usr/bin/env vpython3 +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import argparse +import json +import os +import subprocess +import sys + +# This script parses the JSON output produced by malioc about GPU cores, +# and outputs it in a form that can be consumed by GN + + +def parse_args(argv): + parser = argparse.ArgumentParser( + description='This script sanitizes GPU core info output from malioc', + ) + parser.add_argument( + '--malioc', + '-m', + type=str, + help='The path to malioc.', + ) + parser.add_argument( + '--output', + '-o', + type=str, + help='The output path.', + ) + return parser.parse_args(argv) + + +def validate_args(args): + if not args.malioc or not os.path.isfile(args.malioc): + print('The --malioc argument must refer to the malioc binary.') + return False + return True + + +def malioc_core_list(malioc): + malioc_cores = subprocess.check_output( + [malioc, '--list', '--format', 'json'], + stderr=subprocess.STDOUT, + ) + cores_json = json.loads(malioc_cores) + cores = [] + for core in cores_json['cores']: + cores.append(core['core']) + return cores + + +def malioc_core_info(malioc, core): + malioc_info = subprocess.check_output( + [malioc, '--info', '--core', core, '--format', 'json'], + stderr=subprocess.STDOUT, + ) + info_json = json.loads(malioc_info) + + apis = info_json['apis'] + + opengles_max_version = 0 + if 'opengles' in apis: + opengles = apis['opengles'] + if opengles['max_version'] is not None: + opengles_max_version = opengles['max_version'] + vulkan_max_version = 0 + if 'vulkan' in apis: + vulkan = apis['vulkan'] + if vulkan['max_version'] is not None: + vulkan_max_version = int(vulkan['max_version'] * 100) + + info = { + 'core': core, + 'opengles_max_version': opengles_max_version, + 'vulkan_max_version': vulkan_max_version, + } + return info + + +def main(argv): + args = parse_args(argv[1:]) + if not validate_args(args): + return 1 + + infos = [] + for core in malioc_core_list(args.malioc): + infos.append(malioc_core_info(args.malioc, core)) + + if args.output: + with open(args.output, 'w') as file: + json.dump(infos, file, sort_keys=True) + else: + print(infos) + + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/flutter/engine/src/flutter/impeller/tools/malioc_diff.py b/flutter/engine/src/flutter/impeller/tools/malioc_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..c48c5150847580704c6a2403c08b27b364d0a04a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/tools/malioc_diff.py @@ -0,0 +1,358 @@ +#!/usr/bin/env vpython3 +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import argparse +import difflib +import json +import os +import sys + +# This script detects performance impacting changes to shaders. +# +# When the GN build is configured with the path to the `malioc` tool, the +# results of its analysis will be placed under `out/$CONFIG/gen/malioc` in +# separate .json files. That path should be supplied to this script as the +# `--after` argument. This script compares those results against previous +# results in a golden file checked in to the tree under +# `flutter/impeller/tools/malioc.json`. That file should be passed to this +# script as the `--before` argument. To create or update the golden file, +# passing the `--update` flag will cause the data from the `--after` path to +# overwrite the file at the `--before` path. +# +# Configure and build: +# $ flutter/tools/gn --malioc-path path/to/malioc +# $ ninja -C out/host_debug +# +# Analyze +# $ flutter/impeller/tools/malioc_diff.py \ +# --before flutter/impeller/tools/malioc.json \ +# --after out/host_debug/gen/malioc +# +# If there are differences between before and after, whether positive or +# negative, the exit code for this script will be 1, and 0 otherwise. + +SRC_ROOT = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +) + +CORES = [ + 'Mali-G78', # Pixel 6 / 2020 + 'Mali-T880', # 2016 +] + +# Path to the engine root checkout. This is used to calculate absolute +# paths if relative ones are passed to the script. +BUILD_ROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..')) + + +def parse_args(argv): + parser = argparse.ArgumentParser( + description='A script that compares before/after malioc analysis results', + ) + parser.add_argument( + '--after', + '-a', + type=str, + help='The path to a directory tree containing new malioc results in json files.', + ) + parser.add_argument( + '--before', + '-b', + type=str, + help='The path to a json file containing existing malioc results.', + ) + parser.add_argument( + '--after-relative-to-src', + type=str, + help=( + 'A relative path calculated from the engine src directory to ' + 'a directory tree containing new malioc results in json files' + ), + ) + parser.add_argument( + '--before-relative-to-src', + type=str, + help=( + 'A relative path calculated from the engine src directory to ' + 'a json file containing existing malioc results in json files' + ), + ) + parser.add_argument( + '--print-diff', + '-p', + default=False, + action='store_true', + help='Print a unified diff to stdout when differences are found.', + ) + parser.add_argument( + '--update', + '-u', + default=False, + action='store_true', + help='Write results from the --after tree to the --before file.', + ) + parser.add_argument( + '--verbose', + '-v', + default=False, + action='store_true', + help='Emit verbose output.', + ) + return parser.parse_args(argv) + + +def validate_args(args): + if not args.after and not args.after_relative_to_src: + print('--after argument or --after-relative-to-src must be specified.') + return False + + if not args.before and not args.before_relative_to_src: + print('--before argument or --before-relative-to-src must be specified.') + return False + + # Generate full paths if relative ones are provided with before and + # after taking precedence. + args.before = (args.before or os.path.join(BUILD_ROOT_DIR, args.before_relative_to_src)) + args.after = (args.after or os.path.join(BUILD_ROOT_DIR, args.after_relative_to_src)) + + if not args.after or not os.path.isdir(args.after): + print('The --after argument must refer to a directory.') + return False + if not args.before or (not args.update and not os.path.isfile(args.before)): + print('The --before argument must refer to an existing file.') + return False + return True + + +# Reads the 'performance' section of the malioc analysis results. +def read_malioc_file_performance(performance_json): + performance = {} + performance['pipelines'] = performance_json['pipelines'] + + longest_path_cycles = performance_json['longest_path_cycles'] + performance['longest_path_cycles'] = longest_path_cycles['cycle_count'] + performance['longest_path_bound_pipelines'] = longest_path_cycles['bound_pipelines'] + + shortest_path_cycles = performance_json['shortest_path_cycles'] + performance['shortest_path_cycles'] = shortest_path_cycles['cycle_count'] + performance['shortest_path_bound_pipelines'] = shortest_path_cycles['bound_pipelines'] + + total_cycles = performance_json['total_cycles'] + performance['total_cycles'] = total_cycles['cycle_count'] + performance['total_bound_pipelines'] = total_cycles['bound_pipelines'] + return performance + + +# Parses the json output from malioc, which follows the schema defined in +# `mali_offline_compiler/samples/json_schemas/performance-schema.json`. +def read_malioc_file(malioc_tree, json_file): + with open(json_file, 'r') as file: + json_obj = json.load(file) + + build_gen_dir = os.path.dirname(malioc_tree) + + results = [] + for shader in json_obj['shaders']: + # Ignore cores not in the allowlist above. + if shader['hardware']['core'] not in CORES: + continue + result = {} + filename = os.path.relpath(shader['filename'], build_gen_dir) + if filename.startswith('../..'): + filename = filename[6:] + if filename.startswith('../'): + filename = filename[3:] + result['filename'] = filename + result['core'] = shader['hardware']['core'] + result['type'] = shader['shader']['type'] + for prop in shader['properties']: + result[prop['name']] = prop['value'] + + result['variants'] = {} + for variant in shader['variants']: + variant_result = {} + for prop in variant['properties']: + variant_result[prop['name']] = prop['value'] + + performance_json = variant['performance'] + performance = read_malioc_file_performance(performance_json) + variant_result['performance'] = performance + result['variants'][variant['name']] = variant_result + results.append(result) + + return results + + +# Parses a tree of malioc performance json files. +# +# The parsing results are returned in a map keyed by the shader file name, whose +# values are maps keyed by the core type. The values in these maps are the +# performance properties of the shader on the core reported by malioc. This +# structure allows for a fast lookup and comparison against the golen file. +def read_malioc_tree(malioc_tree): + results = {} + for root, _, files in os.walk(malioc_tree): + for file in files: + if not file.endswith('.json'): + continue + full_path = os.path.join(root, file) + for shader in read_malioc_file(malioc_tree, full_path): + if shader['filename'] not in results: + results[shader['filename']] = {} + results[shader['filename']][shader['core']] = shader + return results + + +# Converts a list to a string in which each list element is left-aligned in +# a space of `width` characters, and separated by `sep`. The separator does not +# count against the `width`. If `width` is 0, then the width is unconstrained. +def pretty_list(lst, fmt='s', sep='', width=12): + formats = ['{:<{width}{fmt}}' if ele is not None else '{:<{width}s}' for ele in lst] + sanitized_list = [x if x is not None else 'null' for x in lst] + return (sep.join(formats)).format(width='' if width == 0 else width, fmt=fmt, *sanitized_list) + + +def compare_performance(variant, before, after): + cycles = [['longest_path_cycles', 'longest_path_bound_pipelines'], + ['shortest_path_cycles', 'shortest_path_bound_pipelines'], + ['total_cycles', 'total_bound_pipelines']] + differences = [] + for cycle in cycles: + if before[cycle[0]] == after[cycle[0]]: + continue + before_cycles = before[cycle[0]] + before_bounds = before[cycle[1]] + after_cycles = after[cycle[0]] + after_bounds = after[cycle[1]] + differences += [ + '{} in variant {}\n{}{}\n{:<8}{}{}\n{:<8}{}{}\n'.format( + cycle[0], + variant, + ' ' * 8, + pretty_list(before['pipelines'] + ['bound']), # Column labels. + 'before', + pretty_list(before_cycles, fmt='f'), + pretty_list(before_bounds, sep=',', width=0), + 'after', + pretty_list(after_cycles, fmt='f'), + pretty_list(after_bounds, sep=',', width=0), + ) + ] + return differences + + +def compare_variants(befores, afters): + differences = [] + for variant_name, before_variant in befores.items(): + if variant_name in afters: + after_variant = afters[variant_name] + for variant_key, before_variant_val in before_variant.items(): + after_variant_val = after_variant[variant_key] + if variant_key == 'performance': + differences += compare_performance(variant_name, before_variant_val, after_variant_val) + elif before_variant_val != after_variant_val: + differences += [ + 'In variant {}:\n {vkey}: {} <- before\n {vkey}: {} <- after'.format( + variant_name, + before_variant_val, + after_variant_val, + vkey=variant_key, + ) + ] + return differences + + +# Compares two shaders. Prints a report and returns True if there are +# differences, and returns False otherwise. +def compare_shaders(malioc_tree, before_shader, after_shader): + differences = [] + for key, before_val in before_shader.items(): + after_val = after_shader[key] + if key == 'variants': + differences += compare_variants(before_val, after_val) + elif key == 'performance': + differences += compare_performance('Default', before_val, after_val) + elif before_val != after_val: + differences += ['{}:\n {} <- before\n {} <- after'.format(key, before_val, after_val)] + + if bool(differences): + build_gen_dir = os.path.dirname(malioc_tree) + filename = before_shader['filename'] + core = before_shader['core'] + typ = before_shader['type'] + print('Changes found in shader {} on core {}:'.format(filename, core)) + for diff in differences: + print(diff) + print( + '\nFor a full report, run:\n $ malioc --{} --core {} {}/{}\n'.format( + typ.lower(), core, build_gen_dir, filename + ) + ) + + return bool(differences) + + +def main(argv): + args = parse_args(argv[1:]) + if not validate_args(args): + return 1 + + after_json = read_malioc_tree(args.after) + if not bool(after_json): + print('Did not find any malioc results under {}.'.format(args.after)) + return 1 + + if args.update: + # Write the new results to the file given by --before, then exit. + with open(args.before, 'w') as file: + json.dump(after_json, file, sort_keys=True, indent=2) + return 0 + + with open(args.before, 'r') as file: + before_json = json.load(file) + + changed = False + for filename, shaders in before_json.items(): + if filename not in after_json.keys(): + print('Shader "{}" has been removed.'.format(filename)) + changed = True + continue + for core, before_shader in shaders.items(): + if core not in after_json[filename].keys(): + continue + after_shader = after_json[filename][core] + if compare_shaders(args.after, before_shader, after_shader): + changed = True + + for filename, shaders in after_json.items(): + if filename not in before_json: + print('Shader "{}" is new.'.format(filename)) + changed = True + + if changed: + print( + 'There are new shaders, shaders have been removed, or performance ' + 'changes to existing shaders. The golden file must be updated after a ' + 'build of android_debug_unopt using the --malioc-path flag to the ' + 'flutter/tools/gn script.\n\n' + '$ ./flutter/impeller/tools/malioc_diff.py --before {} --after {} --update'.format( + args.before, args.after + ) + ) + if args.print_diff: + before_lines = json.dumps(before_json, sort_keys=True, indent=2).splitlines(keepends=True) + after_lines = json.dumps(after_json, sort_keys=True, indent=2).splitlines(keepends=True) + before_path = os.path.relpath(os.path.abspath(args.before), start=SRC_ROOT) + diff = difflib.unified_diff(before_lines, after_lines, fromfile=before_path) + print('\nYou can alternately apply the diff below:') + print('patch -p0 <\n') + output.write( + f'alignas(std::max_align_t) const unsigned char impeller_{args.symbol_name}_data[] =\n' + ) + output.write('{\n') + while True: + byte = source.read(1) + if not byte: + break + data_len += 1 + output.write(f'{ord(byte)},') + output.write('};\n') + output.write(f'const unsigned long impeller_{args.symbol_name}_length = {data_len};\n') + + with open(output_header, 'w') as output: + output.write('#pragma once\n') + output.write('#ifdef __cplusplus\n') + output.write('extern "C" {\n') + output.write('#endif\n\n') + + output.write(f'extern const unsigned char impeller_{args.symbol_name}_data[];\n') + output.write(f'extern const unsigned long impeller_{args.symbol_name}_length;\n\n') + + output.write('#ifdef __cplusplus\n') + output.write('}\n') + output.write('#endif\n') + + +if __name__ == '__main__': + main() diff --git a/flutter/engine/src/flutter/impeller/typographer/BUILD.gn b/flutter/engine/src/flutter/impeller/typographer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d3d53c3320daed72d74509242f2a154489b9b1ec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("typographer") { + sources = [ + "font.cc", + "font.h", + "font_glyph_pair.cc", + "font_glyph_pair.h", + "glyph.cc", + "glyph.h", + "glyph_atlas.cc", + "glyph_atlas.h", + "lazy_glyph_atlas.cc", + "lazy_glyph_atlas.h", + "rectangle_packer.cc", + "rectangle_packer.h", + "text_frame.cc", + "text_frame.h", + "text_run.cc", + "text_run.h", + "typeface.cc", + "typeface.h", + "typographer_context.cc", + "typographer_context.h", + ] + + public_deps = [ + "../base", + "../geometry", + "../renderer", + ] + + if (!is_fuchsia) { + public_deps += + [ "//flutter/third_party/abseil-cpp/absl/container:flat_hash_map" ] + } + + deps = [ + "//flutter/fml", + "//flutter/skia", + ] +} + +impeller_component("typographer_unittests") { + testonly = true + + sources = [ "typographer_unittests.cc" ] + + deps = [ + "../playground:playground_test", + "backends/skia:typographer_skia_backend", + "//flutter/display_list/testing:display_list_testing", + "//flutter/txt", + ] +} diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/BUILD.gn b/flutter/engine/src/flutter/impeller/typographer/backends/skia/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..be13150037e05f5e67d11a095a9940b25ae2a2c8 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/impeller/tools/impeller.gni") + +impeller_component("typographer_skia_backend") { + sources = [ + "text_frame_skia.cc", + "text_frame_skia.h", + "typeface_skia.cc", + "typeface_skia.h", + "typographer_context_skia.cc", + "typographer_context_skia.h", + ] + + public_deps = [ + "//flutter/display_list", + "//flutter/impeller/typographer", + "//flutter/skia", + ] +} diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc b/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..db0f04b7a3e00338dd6a5a9a3905162db65edab3 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.cc @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/backends/skia/text_frame_skia.h" + +#include + +#include "flutter/display_list/geometry/dl_path.h" +#include "flutter/fml/logging.h" +#include "fml/status.h" +#include "impeller/typographer/backends/skia/typeface_skia.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/glyph.h" +#include "third_party/skia/include/core/SkFont.h" +#include "third_party/skia/include/core/SkFontMetrics.h" +#include "third_party/skia/include/core/SkPaint.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/modules/skparagraph/include/Paragraph.h" // nogncheck +#include "third_party/skia/src/core/SkStrikeSpec.h" // nogncheck +#include "third_party/skia/src/core/SkTextBlobPriv.h" // nogncheck + +namespace impeller { + +static Font ToFont(const SkTextBlobRunIterator& run, AxisAlignment alignment) { + auto& font = run.font(); + auto typeface = std::make_shared(font.refTypeface()); + + SkFontMetrics sk_metrics; + font.getMetrics(&sk_metrics); + + Font::Metrics metrics; + metrics.point_size = font.getSize(); + metrics.embolden = font.isEmbolden(); + metrics.skewX = font.getSkewX(); + metrics.scaleX = font.getScaleX(); + + return Font{std::move(typeface), metrics, alignment}; +} + +static Rect ToRect(const SkRect& rect) { + return Rect::MakeLTRB(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); +} + +std::shared_ptr MakeTextFrameFromTextBlobSkia( + const sk_sp& blob) { + bool has_color = false; + std::vector runs; + for (SkTextBlobRunIterator run(blob.get()); !run.done(); run.next()) { + SkStrikeSpec strikeSpec = SkStrikeSpec::MakeWithNoDevice(run.font()); + SkBulkGlyphMetricsAndPaths paths{strikeSpec}; + SkSpan glyphs = + paths.glyphs(SkSpan(run.glyphs(), run.glyphCount())); + + for (const auto& glyph : glyphs) { + has_color |= glyph->isColor(); + } + + AxisAlignment alignment = AxisAlignment::kNone; + if (run.font().isSubpixel() && run.font().isBaselineSnap() && !has_color) { + alignment = AxisAlignment::kX; + } + + switch (run.positioning()) { + case SkTextBlobRunIterator::kFull_Positioning: { + std::vector positions; + positions.reserve(run.glyphCount()); + for (auto i = 0u; i < run.glyphCount(); i++) { + // kFull_Positioning has two scalars per glyph. + const SkPoint* glyph_points = run.points(); + const SkPoint* point = glyph_points + i; + Glyph::Type type = + glyphs[i]->isColor() ? Glyph::Type::kBitmap : Glyph::Type::kPath; + positions.emplace_back(TextRun::GlyphPosition{ + Glyph{glyphs[i]->getGlyphID(), type}, Point{ + point->x(), + point->y(), + }}); + } + TextRun text_run(ToFont(run, alignment), positions); + runs.emplace_back(text_run); + break; + } + default: + FML_DLOG(ERROR) << "Unimplemented."; + continue; + } + } + return std::make_shared( + runs, ToRect(blob->bounds()), has_color, + [blob]() -> fml::StatusOr { + SkPath path = skia::textlayout::Paragraph::GetPath(blob.get()); + if (path.isEmpty()) { + return fml::Status(fml::StatusCode::kCancelled, "No path available"); + } + SkPath transformed = path.makeTransform( + SkMatrix::Translate(blob->bounds().left(), blob->bounds().top())); + return flutter::DlPath(transformed); + }); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h b/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..fb69bab359f207a3886a93e741e0fe0eef795634 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/text_frame_skia.h @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TEXT_FRAME_SKIA_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TEXT_FRAME_SKIA_H_ + +#include "impeller/typographer/text_frame.h" + +#include "third_party/skia/include/core/SkTextBlob.h" + +namespace impeller { + +std::shared_ptr MakeTextFrameFromTextBlobSkia( + const sk_sp& blob); + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TEXT_FRAME_SKIA_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..df0b88be16a5e8c526a8fade9b49e65fb999e5bc --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.cc @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/backends/skia/typeface_skia.h" + +namespace impeller { + +TypefaceSkia::TypefaceSkia(sk_sp typeface) + : typeface_(std::move(typeface)) {} + +TypefaceSkia::~TypefaceSkia() = default; + +bool TypefaceSkia::IsValid() const { + return !!typeface_; +} + +std::size_t TypefaceSkia::GetHash() const { + if (!IsValid()) { + return 0u; + } + + return reinterpret_cast(typeface_.get()); +} + +bool TypefaceSkia::IsEqual(const Typeface& other) const { + auto sk_other = reinterpret_cast(&other); + return sk_other->typeface_ == typeface_; +} + +const sk_sp& TypefaceSkia::GetSkiaTypeface() const { + return typeface_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..4d6ef0ca7fe43ba3291dcff73c45568b5b26d2fd --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typeface_skia.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPEFACE_SKIA_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPEFACE_SKIA_H_ + +#include "impeller/base/backend_cast.h" +#include "impeller/typographer/typeface.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkTypeface.h" + +namespace impeller { + +class TypefaceSkia final : public Typeface, + public BackendCast { + public: + explicit TypefaceSkia(sk_sp typeface); + + ~TypefaceSkia() override; + + // |Typeface| + bool IsValid() const override; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const Typeface& other) const override; + + const sk_sp& GetSkiaTypeface() const; + + private: + sk_sp typeface_; + + TypefaceSkia(const TypefaceSkia&) = delete; + + TypefaceSkia& operator=(const TypefaceSkia&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPEFACE_SKIA_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.cc b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.cc new file mode 100644 index 0000000000000000000000000000000000000000..a9d57b3fdff2262c01d8da9192632683f466521a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.cc @@ -0,0 +1,689 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/backends/skia/typographer_context_skia.h" + +#include +#include +#include +#include +#include +#include + +#include "flutter/fml/logging.h" +#include "flutter/fml/trace_event.h" +#include "fml/closure.h" + +#include "impeller/base/validation.h" +#include "impeller/core/allocator.h" +#include "impeller/core/buffer_view.h" +#include "impeller/core/formats.h" +#include "impeller/core/host_buffer.h" +#include "impeller/core/platform.h" +#include "impeller/core/texture_descriptor.h" +#include "impeller/geometry/rect.h" +#include "impeller/geometry/size.h" +#include "impeller/renderer/command_buffer.h" +#include "impeller/renderer/render_pass.h" +#include "impeller/renderer/render_target.h" +#include "impeller/typographer/backends/skia/typeface_skia.h" +#include "impeller/typographer/font_glyph_pair.h" +#include "impeller/typographer/glyph.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/rectangle_packer.h" +#include "impeller/typographer/typographer_context.h" +#include "include/core/SkColor.h" +#include "include/core/SkImageInfo.h" +#include "include/core/SkPaint.h" +#include "include/core/SkSize.h" + +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkBlendMode.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkFont.h" +#include "third_party/skia/include/core/SkSurface.h" + +namespace impeller { + +constexpr auto kPadding = 2; + +namespace { +SkPaint::Cap ToSkiaCap(Cap cap) { + switch (cap) { + case Cap::kButt: + return SkPaint::Cap::kButt_Cap; + case Cap::kRound: + return SkPaint::Cap::kRound_Cap; + case Cap::kSquare: + return SkPaint::Cap::kSquare_Cap; + } + FML_UNREACHABLE(); +} + +SkPaint::Join ToSkiaJoin(Join join) { + switch (join) { + case Join::kMiter: + return SkPaint::Join::kMiter_Join; + case Join::kRound: + return SkPaint::Join::kRound_Join; + case Join::kBevel: + return SkPaint::Join::kBevel_Join; + } + FML_UNREACHABLE(); +} +} // namespace + +std::shared_ptr TypographerContextSkia::Make() { + return std::make_shared(); +} + +TypographerContextSkia::TypographerContextSkia() = default; + +TypographerContextSkia::~TypographerContextSkia() = default; + +std::shared_ptr +TypographerContextSkia::CreateGlyphAtlasContext(GlyphAtlas::Type type) const { + return std::make_shared(type); +} + +static SkImageInfo GetImageInfo(const GlyphAtlas& atlas, Size size) { + switch (atlas.GetType()) { + case GlyphAtlas::Type::kAlphaBitmap: + return SkImageInfo::MakeA8(SkISize{static_cast(size.width), + static_cast(size.height)}); + case GlyphAtlas::Type::kColorBitmap: + return SkImageInfo::MakeN32Premul(size.width, size.height); + } + FML_UNREACHABLE(); +} + +/// Append as many glyphs to the texture as will fit, and return the first index +/// of [extra_pairs] that did not fit. +static size_t AppendToExistingAtlas( + const std::shared_ptr& atlas, + const std::vector& extra_pairs, + std::vector& glyph_positions, + const std::vector& glyph_sizes, + ISize atlas_size, + int64_t height_adjustment, + const std::shared_ptr& rect_packer) { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!rect_packer || atlas_size.IsEmpty()) { + return 0; + } + + for (size_t i = 0; i < extra_pairs.size(); i++) { + ISize glyph_size = ISize::Ceil(glyph_sizes[i].GetSize()); + IPoint16 location_in_atlas; + if (!rect_packer->AddRect(glyph_size.width + kPadding, // + glyph_size.height + kPadding, // + &location_in_atlas // + )) { + return i; + } + // Position the glyph in the center of the 1px padding. + glyph_positions.push_back(Rect::MakeXYWH( + location_in_atlas.x() + 1, // + location_in_atlas.y() + height_adjustment + 1, // + glyph_size.width, // + glyph_size.height // + )); + } + + return extra_pairs.size(); +} + +static size_t PairsFitInAtlasOfSize( + const std::vector& pairs, + const ISize& atlas_size, + std::vector& glyph_positions, + const std::vector& glyph_sizes, + int64_t height_adjustment, + const std::shared_ptr& rect_packer, + size_t start_index) { + FML_DCHECK(!atlas_size.IsEmpty()); + + for (size_t i = start_index; i < pairs.size(); i++) { + ISize glyph_size = ISize::Ceil(glyph_sizes[i].GetSize()); + IPoint16 location_in_atlas; + if (!rect_packer->AddRect(glyph_size.width + kPadding, // + glyph_size.height + kPadding, // + &location_in_atlas // + )) { + return i; + } + glyph_positions.push_back(Rect::MakeXYWH( + location_in_atlas.x() + 1, // + location_in_atlas.y() + height_adjustment + 1, // + glyph_size.width, // + glyph_size.height // + )); + } + + return pairs.size(); +} + +static ISize ComputeNextAtlasSize( + const std::shared_ptr& atlas_context, + const std::vector& extra_pairs, + std::vector& glyph_positions, + const std::vector& glyph_sizes, + size_t glyph_index_start, + int64_t max_texture_height) { + // Because we can't grow the skyline packer horizontally, pick a reasonable + // large width for all atlases. + static constexpr int64_t kAtlasWidth = 4096; + static constexpr int64_t kMinAtlasHeight = 1024; + + ISize current_size = ISize(kAtlasWidth, kMinAtlasHeight); + if (atlas_context->GetAtlasSize().height > current_size.height) { + current_size.height = atlas_context->GetAtlasSize().height * 2; + } + + auto height_adjustment = atlas_context->GetAtlasSize().height; + while (current_size.height <= max_texture_height) { + std::shared_ptr rect_packer; + if (atlas_context->GetRectPacker() || glyph_index_start) { + rect_packer = RectanglePacker::Factory( + kAtlasWidth, + current_size.height - atlas_context->GetAtlasSize().height); + } else { + rect_packer = RectanglePacker::Factory(kAtlasWidth, current_size.height); + } + glyph_positions.erase(glyph_positions.begin() + glyph_index_start, + glyph_positions.end()); + atlas_context->UpdateRectPacker(rect_packer); + auto next_index = PairsFitInAtlasOfSize( + extra_pairs, current_size, glyph_positions, glyph_sizes, + height_adjustment, rect_packer, glyph_index_start); + if (next_index == extra_pairs.size()) { + return current_size; + } + current_size = ISize(current_size.width, current_size.height * 2); + } + return {}; +} + +static Point SubpixelPositionToPoint(SubpixelPosition pos) { + return Point((pos & 0xff) / 4.f, (pos >> 2 & 0xff) / 4.f); +} + +static void DrawGlyph(SkCanvas* canvas, + const SkPoint position, + const ScaledFont& scaled_font, + const SubpixelGlyph& glyph, + const Rect& scaled_bounds, + const std::optional& prop, + bool has_color) { + const auto& metrics = scaled_font.font.GetMetrics(); + SkGlyphID glyph_id = glyph.glyph.index; + + SkFont sk_font( + TypefaceSkia::Cast(*scaled_font.font.GetTypeface()).GetSkiaTypeface(), + metrics.point_size, metrics.scaleX, metrics.skewX); + sk_font.setEdging(SkFont::Edging::kAntiAlias); + sk_font.setHinting(SkFontHinting::kSlight); + sk_font.setEmbolden(metrics.embolden); + sk_font.setSubpixel(true); + sk_font.setSize(sk_font.getSize() * static_cast(scaled_font.scale)); + + auto glyph_color = prop.has_value() ? prop->color.ToARGB() : SK_ColorBLACK; + + SkPaint glyph_paint; + glyph_paint.setColor(glyph_color); + glyph_paint.setBlendMode(SkBlendMode::kSrc); + if (prop.has_value() && prop->stroke) { + glyph_paint.setStroke(true); + glyph_paint.setStrokeWidth(prop->stroke_width * + static_cast(scaled_font.scale)); + glyph_paint.setStrokeCap(ToSkiaCap(prop->stroke_cap)); + glyph_paint.setStrokeJoin(ToSkiaJoin(prop->stroke_join)); + glyph_paint.setStrokeMiter(prop->stroke_miter); + } + canvas->save(); + Point subpixel_offset = SubpixelPositionToPoint(glyph.subpixel_offset); + canvas->translate(subpixel_offset.x, subpixel_offset.y); + canvas->drawGlyphs(1u, // count + &glyph_id, // glyphs + &position, // positions + SkPoint::Make(-scaled_bounds.GetLeft(), + -scaled_bounds.GetTop()), // origin + sk_font, // font + glyph_paint // paint + ); + canvas->restore(); +} + +/// @brief Batch render to a single surface. +/// +/// This is only safe for use when updating a fresh texture. +static bool BulkUpdateAtlasBitmap(const GlyphAtlas& atlas, + std::shared_ptr& blit_pass, + HostBuffer& host_buffer, + const std::shared_ptr& texture, + const std::vector& new_pairs, + size_t start_index, + size_t end_index) { + TRACE_EVENT0("impeller", __FUNCTION__); + + bool has_color = atlas.GetType() == GlyphAtlas::Type::kColorBitmap; + + SkBitmap bitmap; + bitmap.setInfo(GetImageInfo(atlas, Size(texture->GetSize()))); + if (!bitmap.tryAllocPixels()) { + return false; + } + + auto surface = SkSurfaces::WrapPixels(bitmap.pixmap()); + if (!surface) { + return false; + } + auto canvas = surface->getCanvas(); + if (!canvas) { + return false; + } + + for (size_t i = start_index; i < end_index; i++) { + const FontGlyphPair& pair = new_pairs[i]; + auto data = atlas.FindFontGlyphBounds(pair); + if (!data.has_value()) { + continue; + } + auto [pos, bounds, placeholder] = data.value(); + FML_DCHECK(!placeholder); + Size size = pos.GetSize(); + if (size.IsEmpty()) { + continue; + } + + DrawGlyph(canvas, SkPoint::Make(pos.GetLeft(), pos.GetTop()), + pair.scaled_font, pair.glyph, bounds, pair.glyph.properties, + has_color); + } + + // Writing to a malloc'd buffer and then copying to the staging buffers + // benchmarks as substantially faster on a number of Android devices. + BufferView buffer_view = host_buffer.Emplace( + bitmap.getAddr(0, 0), + texture->GetSize().Area() * + BytesPerPixelForPixelFormat( + atlas.GetTexture()->GetTextureDescriptor().format), + DefaultUniformAlignment()); + + return blit_pass->AddCopy(std::move(buffer_view), // + texture, // + IRect::MakeXYWH(0, 0, texture->GetSize().width, + texture->GetSize().height)); +} + +static bool UpdateAtlasBitmap(const GlyphAtlas& atlas, + std::shared_ptr& blit_pass, + HostBuffer& host_buffer, + const std::shared_ptr& texture, + const std::vector& new_pairs, + size_t start_index, + size_t end_index) { + TRACE_EVENT0("impeller", __FUNCTION__); + + bool has_color = atlas.GetType() == GlyphAtlas::Type::kColorBitmap; + + for (size_t i = start_index; i < end_index; i++) { + const FontGlyphPair& pair = new_pairs[i]; + auto data = atlas.FindFontGlyphBounds(pair); + if (!data.has_value()) { + continue; + } + auto [pos, bounds, placeholder] = data.value(); + FML_DCHECK(!placeholder); + + Size size = pos.GetSize(); + if (size.IsEmpty()) { + continue; + } + // The uploaded bitmap is expanded by 1px of padding + // on each side. + size.width += 2; + size.height += 2; + + SkBitmap bitmap; + bitmap.setInfo(GetImageInfo(atlas, size)); + if (!bitmap.tryAllocPixels()) { + return false; + } + + auto surface = SkSurfaces::WrapPixels(bitmap.pixmap()); + if (!surface) { + return false; + } + auto canvas = surface->getCanvas(); + if (!canvas) { + return false; + } + + DrawGlyph(canvas, SkPoint::Make(1, 1), pair.scaled_font, pair.glyph, bounds, + pair.glyph.properties, has_color); + + // Writing to a malloc'd buffer and then copying to the staging buffers + // benchmarks as substantially faster on a number of Android devices. + BufferView buffer_view = host_buffer.Emplace( + bitmap.getAddr(0, 0), + size.Area() * BytesPerPixelForPixelFormat( + atlas.GetTexture()->GetTextureDescriptor().format), + DefaultUniformAlignment()); + + // convert_to_read is set to false so that the texture remains in a transfer + // dst layout until we finish writing to it below. This only has an impact + // on Vulkan where we are responsible for managing image layouts. + if (!blit_pass->AddCopy(std::move(buffer_view), // + texture, // + IRect::MakeXYWH(pos.GetLeft() - 1, pos.GetTop() - 1, + size.width, size.height), // + /*label=*/"", // + /*mip_level=*/0, // + /*slice=*/0, // + /*convert_to_read=*/false // + )) { + return false; + } + } + return blit_pass->ConvertTextureToShaderRead(texture); +} + +static Rect ComputeGlyphSize(const SkFont& font, + const SubpixelGlyph& glyph, + Scalar scale) { + SkRect scaled_bounds; + SkPaint glyph_paint; + if (glyph.properties.has_value() && glyph.properties->stroke) { + glyph_paint.setStroke(true); + glyph_paint.setStrokeWidth(glyph.properties->stroke_width * scale); + glyph_paint.setStrokeCap(ToSkiaCap(glyph.properties->stroke_cap)); + glyph_paint.setStrokeJoin(ToSkiaJoin(glyph.properties->stroke_join)); + glyph_paint.setStrokeMiter(glyph.properties->stroke_miter); + } + font.getBounds(&glyph.glyph.index, 1, &scaled_bounds, &glyph_paint); + + // Expand the bounds of glyphs at subpixel offsets by 2 in the x direction. + Scalar adjustment = 0.0; + if (glyph.subpixel_offset != SubpixelPosition::kSubpixel00) { + adjustment = 1.0; + } + return Rect::MakeLTRB(scaled_bounds.fLeft - adjustment, scaled_bounds.fTop, + scaled_bounds.fRight + adjustment, + scaled_bounds.fBottom); +}; + +std::pair, std::vector> +TypographerContextSkia::CollectNewGlyphs( + const std::shared_ptr& atlas, + const std::vector>& text_frames) { + std::vector new_glyphs; + std::vector glyph_sizes; + size_t generation_id = atlas->GetAtlasGeneration(); + intptr_t atlas_id = reinterpret_cast(atlas.get()); + for (const auto& frame : text_frames) { +// TODO(jonahwilliams): determine how to re-enable this. See +// https://github.com/flutter/flutter/issues/163730 for example. This can +// happen when the Aiks/Typographer context are re-created, but the last +// DisplayList is re-used. The "atlas_id" check is not reliable, perhaps +// because it may end up with the same memory? +#if false + auto [frame_generation_id, frame_atlas_id] = + frame->GetAtlasGenerationAndID(); + if (atlas->IsValid() && frame->IsFrameComplete() && + frame_generation_id == generation_id && frame_atlas_id == atlas_id && + !frame->GetFrameBounds(0).is_placeholder) { + continue; + } +#endif // false + frame->ClearFrameBounds(); + frame->SetAtlasGeneration(generation_id, atlas_id); + + for (const auto& run : frame->GetRuns()) { + auto metrics = run.GetFont().GetMetrics(); + + auto rounded_scale = TextFrame::RoundScaledFontSize(frame->GetScale()); + ScaledFont scaled_font{.font = run.GetFont(), .scale = rounded_scale}; + + FontGlyphAtlas* font_glyph_atlas = + atlas->GetOrCreateFontGlyphAtlas(scaled_font); + FML_DCHECK(!!font_glyph_atlas); + + SkFont sk_font( + TypefaceSkia::Cast(*scaled_font.font.GetTypeface()).GetSkiaTypeface(), + metrics.point_size, metrics.scaleX, metrics.skewX); + sk_font.setEdging(SkFont::Edging::kAntiAlias); + sk_font.setHinting(SkFontHinting::kSlight); + sk_font.setEmbolden(metrics.embolden); + // Rather than computing the bounds at the requested point size and + // scaling up the bounds, we scale up the font size and request the + // bounds. This seems to give more accurate bounds information. + sk_font.setSize(sk_font.getSize() * + static_cast(scaled_font.scale)); + sk_font.setSubpixel(true); + + for (const auto& glyph_position : run.GetGlyphPositions()) { + SubpixelPosition subpixel = TextFrame::ComputeSubpixelPosition( + glyph_position, scaled_font.font.GetAxisAlignment(), + frame->GetOffsetTransform()); + SubpixelGlyph subpixel_glyph(glyph_position.glyph, subpixel, + frame->GetProperties()); + const auto& font_glyph_bounds = + font_glyph_atlas->FindGlyphBounds(subpixel_glyph); + + if (!font_glyph_bounds.has_value()) { + new_glyphs.push_back(FontGlyphPair{scaled_font, subpixel_glyph}); + auto glyph_bounds = ComputeGlyphSize( + sk_font, subpixel_glyph, static_cast(scaled_font.scale)); + glyph_sizes.push_back(glyph_bounds); + + auto frame_bounds = FrameBounds{ + Rect::MakeLTRB(0, 0, 0, 0), // + glyph_bounds, // + /*placeholder=*/true // + }; + + frame->AppendFrameBounds(frame_bounds); + font_glyph_atlas->AppendGlyph(subpixel_glyph, frame_bounds); + } else { + frame->AppendFrameBounds(font_glyph_bounds.value()); + } + } + } + } + return {std::move(new_glyphs), std::move(glyph_sizes)}; +} + +std::shared_ptr TypographerContextSkia::CreateGlyphAtlas( + Context& context, + GlyphAtlas::Type type, + HostBuffer& host_buffer, + const std::shared_ptr& atlas_context, + const std::vector>& text_frames) const { + TRACE_EVENT0("impeller", __FUNCTION__); + if (!IsValid()) { + return nullptr; + } + std::shared_ptr last_atlas = atlas_context->GetGlyphAtlas(); + FML_DCHECK(last_atlas->GetType() == type); + + if (text_frames.empty()) { + return last_atlas; + } + + // --------------------------------------------------------------------------- + // Step 1: Determine if the atlas type and font glyph pairs are compatible + // with the current atlas and reuse if possible. For each new font and + // glyph pair, compute the glyph size at scale. + // --------------------------------------------------------------------------- + auto [new_glyphs, glyph_sizes] = CollectNewGlyphs(last_atlas, text_frames); + if (new_glyphs.size() == 0) { + return last_atlas; + } + + // --------------------------------------------------------------------------- + // Step 2: Determine if the additional missing glyphs can be appended to the + // existing bitmap without recreating the atlas. + // --------------------------------------------------------------------------- + std::vector glyph_positions; + glyph_positions.reserve(new_glyphs.size()); + size_t first_missing_index = 0; + + if (last_atlas->GetTexture()) { + // Append all glyphs that fit into the current atlas. + first_missing_index = AppendToExistingAtlas( + last_atlas, new_glyphs, glyph_positions, glyph_sizes, + atlas_context->GetAtlasSize(), atlas_context->GetHeightAdjustment(), + atlas_context->GetRectPacker()); + + // --------------------------------------------------------------------------- + // Step 3a: Record the positions in the glyph atlas of the newly added + // glyphs. + // --------------------------------------------------------------------------- + for (size_t i = 0; i < first_missing_index; i++) { + last_atlas->AddTypefaceGlyphPositionAndBounds( + new_glyphs[i], glyph_positions[i], glyph_sizes[i]); + } + + std::shared_ptr cmd_buffer = context.CreateCommandBuffer(); + std::shared_ptr blit_pass = cmd_buffer->CreateBlitPass(); + + fml::ScopedCleanupClosure closure([&]() { + blit_pass->EncodeCommands(); + if (!context.EnqueueCommandBuffer(std::move(cmd_buffer))) { + VALIDATION_LOG << "Failed to submit glyph atlas command buffer"; + } + }); + + // --------------------------------------------------------------------------- + // Step 4a: Draw new font-glyph pairs into the a host buffer and encode + // the uploads into the blit pass. + // --------------------------------------------------------------------------- + if (!UpdateAtlasBitmap(*last_atlas, blit_pass, host_buffer, + last_atlas->GetTexture(), new_glyphs, 0, + first_missing_index)) { + return nullptr; + } + + // If all glyphs fit, just return the old atlas. + if (first_missing_index == new_glyphs.size()) { + return last_atlas; + } + } + + int64_t height_adjustment = atlas_context->GetAtlasSize().height; + const int64_t max_texture_height = + context.GetResourceAllocator()->GetMaxTextureSizeSupported().height; + + // IF the current atlas size is as big as it can get, then "GC" and create an + // atlas with only the required glyphs. OpenGLES cannot reliably perform the + // blit required here, as 1) it requires attaching textures as read and write + // framebuffers which has substantially smaller size limits that max textures + // and 2) is missing a GLES 2.0 implementation and cap check. + bool blit_old_atlas = true; + std::shared_ptr new_atlas = last_atlas; + if (atlas_context->GetAtlasSize().height >= max_texture_height || + context.GetBackendType() == Context::BackendType::kOpenGLES) { + blit_old_atlas = false; + new_atlas = std::make_shared( + type, /*initial_generation=*/last_atlas->GetAtlasGeneration() + 1); + + auto [update_glyphs, update_sizes] = + CollectNewGlyphs(new_atlas, text_frames); + new_glyphs = std::move(update_glyphs); + glyph_sizes = std::move(update_sizes); + + glyph_positions.clear(); + glyph_positions.reserve(new_glyphs.size()); + first_missing_index = 0; + + height_adjustment = 0; + atlas_context->UpdateRectPacker(nullptr); + atlas_context->UpdateGlyphAtlas(new_atlas, {0, 0}, 0); + } + + // A new glyph atlas must be created. + ISize atlas_size = ComputeNextAtlasSize(atlas_context, // + new_glyphs, // + glyph_positions, // + glyph_sizes, // + first_missing_index, // + max_texture_height // + ); + + atlas_context->UpdateGlyphAtlas(new_atlas, atlas_size, height_adjustment); + if (atlas_size.IsEmpty()) { + return nullptr; + } + FML_DCHECK(new_glyphs.size() == glyph_positions.size()); + + TextureDescriptor descriptor; + switch (type) { + case GlyphAtlas::Type::kAlphaBitmap: + descriptor.format = + context.GetCapabilities()->GetDefaultGlyphAtlasFormat(); + break; + case GlyphAtlas::Type::kColorBitmap: + descriptor.format = PixelFormat::kR8G8B8A8UNormInt; + break; + } + descriptor.size = atlas_size; + descriptor.storage_mode = StorageMode::kDevicePrivate; + descriptor.usage = TextureUsage::kShaderRead; + std::shared_ptr new_texture = + context.GetResourceAllocator()->CreateTexture(descriptor); + if (!new_texture) { + return nullptr; + } + + new_texture->SetLabel("GlyphAtlas"); + + std::shared_ptr cmd_buffer = context.CreateCommandBuffer(); + std::shared_ptr blit_pass = cmd_buffer->CreateBlitPass(); + + fml::ScopedCleanupClosure closure([&]() { + blit_pass->EncodeCommands(); + if (!context.EnqueueCommandBuffer(std::move(cmd_buffer))) { + VALIDATION_LOG << "Failed to submit glyph atlas command buffer"; + } + }); + + // Now append all remaining glyphs. This should never have any missing data... + auto old_texture = new_atlas->GetTexture(); + new_atlas->SetTexture(std::move(new_texture)); + + // --------------------------------------------------------------------------- + // Step 3a: Record the positions in the glyph atlas of the newly added + // glyphs. + // --------------------------------------------------------------------------- + for (size_t i = first_missing_index; i < glyph_positions.size(); i++) { + new_atlas->AddTypefaceGlyphPositionAndBounds( + new_glyphs[i], glyph_positions[i], glyph_sizes[i]); + } + + // --------------------------------------------------------------------------- + // Step 4a: Draw new font-glyph pairs into the a host buffer and encode + // the uploads into the blit pass. + // --------------------------------------------------------------------------- + if (!BulkUpdateAtlasBitmap(*new_atlas, blit_pass, host_buffer, + new_atlas->GetTexture(), new_glyphs, + first_missing_index, new_glyphs.size())) { + return nullptr; + } + + // Blit the old texture to the top left of the new atlas. + if (blit_old_atlas && old_texture) { + blit_pass->AddCopy(old_texture, new_atlas->GetTexture(), + IRect::MakeSize(new_atlas->GetTexture()->GetSize()), + {0, 0}); + } + + // --------------------------------------------------------------------------- + // Step 8b: Record the texture in the glyph atlas. + // --------------------------------------------------------------------------- + + return new_atlas; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.h b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.h new file mode 100644 index 0000000000000000000000000000000000000000..181839df9d4f3481d718805ce7d8b19446c1f8e2 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/backends/skia/typographer_context_skia.h @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPOGRAPHER_CONTEXT_SKIA_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPOGRAPHER_CONTEXT_SKIA_H_ + +#include "impeller/typographer/typographer_context.h" + +namespace impeller { + +class TypographerContextSkia : public TypographerContext { + public: + static std::shared_ptr Make(); + + TypographerContextSkia(); + + ~TypographerContextSkia() override; + + // |TypographerContext| + std::shared_ptr CreateGlyphAtlasContext( + GlyphAtlas::Type type) const override; + + // |TypographerContext| + std::shared_ptr CreateGlyphAtlas( + Context& context, + GlyphAtlas::Type type, + HostBuffer& host_buffer, + const std::shared_ptr& atlas_context, + const std::vector>& text_frames) + const override; + + private: + static std::pair, std::vector> + CollectNewGlyphs(const std::shared_ptr& atlas, + const std::vector>& text_frames); + + TypographerContextSkia(const TypographerContextSkia&) = delete; + + TypographerContextSkia& operator=(const TypographerContextSkia&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_BACKENDS_SKIA_TYPOGRAPHER_CONTEXT_SKIA_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/font.cc b/flutter/engine/src/flutter/impeller/typographer/font.cc new file mode 100644 index 0000000000000000000000000000000000000000..06aad9ad479f592d1ca262b28a759c47ccdefaed --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/font.cc @@ -0,0 +1,49 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/font.h" + +namespace impeller { + +Font::Font(std::shared_ptr typeface, + Metrics metrics, + AxisAlignment axis_alignment) + : typeface_(std::move(typeface)), + metrics_(metrics), + axis_alignment_(axis_alignment) { + if (!typeface_) { + return; + } + is_valid_ = true; +} + +Font::~Font() = default; + +bool Font::IsValid() const { + return is_valid_; +} + +const std::shared_ptr& Font::GetTypeface() const { + return typeface_; +} + +std::size_t Font::GetHash() const { + return fml::HashCombine(is_valid_, typeface_ ? typeface_->GetHash() : 0u, + metrics_); +} + +bool Font::IsEqual(const Font& other) const { + return DeepComparePointer(typeface_, other.typeface_) && + is_valid_ == other.is_valid_ && metrics_ == other.metrics_; +} + +AxisAlignment Font::GetAxisAlignment() const { + return axis_alignment_; +} + +const Font::Metrics& Font::GetMetrics() const { + return metrics_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/font.h b/flutter/engine/src/flutter/impeller/typographer/font.h new file mode 100644 index 0000000000000000000000000000000000000000..a48f8822dc243bd5bb76a2e6592003d028ab0b3f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/font.h @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_ + +#include + +#include "fml/hash_combine.h" +#include "impeller/base/comparable.h" +#include "impeller/geometry/scalar.h" +#include "impeller/typographer/typeface.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Determines the axis along which there is subpixel positioning. +/// +enum class AxisAlignment : uint8_t { + // No subpixel positioning. + kNone, + // Subpixel positioning in the X axis only. + kX, + // Subpixel positioning in the Y axis only. + kY, + // No specific axis, subpixel positioning in each direction. + kAll, +}; + +//------------------------------------------------------------------------------ +/// @brief Describes a typeface along with any modifications to its +/// intrinsic properties. +/// +class Font : public Comparable { + public: + //---------------------------------------------------------------------------- + /// @brief Describes the modifications made to the intrinsic properties + /// of a typeface. + /// + /// The coordinate system of a font has its origin at (0, 0) on + /// the baseline with an upper-left-origin coordinate system. + /// + struct Metrics { + //-------------------------------------------------------------------------- + /// The point size of the font. + /// + Scalar point_size = 12.0f; + bool embolden = false; + Scalar skewX = 0.0f; + Scalar scaleX = 1.0f; + + constexpr bool operator==(const Metrics& o) const { + return point_size == o.point_size && embolden == o.embolden && + skewX == o.skewX && scaleX == o.scaleX; + } + }; + + Font(std::shared_ptr typeface, + Metrics metrics, + AxisAlignment axis_alignment); + + ~Font(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief The typeface whose intrinsic properties this font modifies. + /// + /// @return The typeface. + /// + const std::shared_ptr& GetTypeface() const; + + const Metrics& GetMetrics() const; + + // |Comparable| + std::size_t GetHash() const override; + + // |Comparable| + bool IsEqual(const Font& other) const override; + + AxisAlignment GetAxisAlignment() const; + + private: + std::shared_ptr typeface_; + Metrics metrics_ = {}; + AxisAlignment axis_alignment_; + bool is_valid_ = false; +}; + +} // namespace impeller + +template <> +struct std::hash { + constexpr std::size_t operator()(const impeller::Font::Metrics& m) const { + return fml::HashCombine(m.point_size, m.skewX, m.scaleX); + } +}; + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_FONT_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.cc b/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.cc new file mode 100644 index 0000000000000000000000000000000000000000..667caadb4e827c68370a9456876aa0067ab5bd87 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/font_glyph_pair.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.h b/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.h new file mode 100644 index 0000000000000000000000000000000000000000..2905c678ac7c88352f7c6f27ebc702703f9844c0 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/font_glyph_pair.h @@ -0,0 +1,147 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_FONT_GLYPH_PAIR_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_FONT_GLYPH_PAIR_H_ + +#include "impeller/geometry/color.h" +#include "impeller/geometry/path.h" +#include "impeller/geometry/point.h" +#include "impeller/geometry/rational.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/glyph.h" + +namespace impeller { + +struct GlyphProperties { + Color color = Color::Black(); + Scalar stroke_width = 0.0; + Cap stroke_cap = Cap::kButt; + Join stroke_join = Join::kMiter; + Scalar stroke_miter = 4.0; + bool stroke = false; + + struct Equal { + constexpr bool operator()(const impeller::GlyphProperties& lhs, + const impeller::GlyphProperties& rhs) const { + return lhs.color.ToARGB() == rhs.color.ToARGB() && + lhs.stroke == rhs.stroke && lhs.stroke_cap == rhs.stroke_cap && + lhs.stroke_join == rhs.stroke_join && + lhs.stroke_miter == rhs.stroke_miter && + lhs.stroke_width == rhs.stroke_width; + } + }; +}; + +//------------------------------------------------------------------------------ +/// @brief A font and a scale. Used as a key that represents a typeface +/// within a glyph atlas. +/// +struct ScaledFont { + Font font; + Rational scale; + + template + friend H AbslHashValue(H h, const ScaledFont& sf) { + return H::combine(std::move(h), sf.font.GetHash(), sf.scale.GetHash()); + } + + struct Equal { + constexpr bool operator()(const impeller::ScaledFont& lhs, + const impeller::ScaledFont& rhs) const { + return lhs.font.IsEqual(rhs.font) && lhs.scale == rhs.scale; + } + }; +}; + +/// All possible positions for a subpixel alignment. +/// The name is in the format kSubpixelXY where X and Y are numerators to 1/4 +/// fractions in their respective directions. +enum SubpixelPosition : uint8_t { + // Subpixel at {0, 0}. + kSubpixel00 = 0x0, + // Subpixel at {0.25, 0}. + kSubpixel10 = 0x1, + // Subpixel at {0.5, 0}. + kSubpixel20 = 0x2, + // Subpixel at {0.75, 0}. + kSubpixel30 = 0x3, + // Subpixel at {0, 0.25}. + kSubpixel01 = kSubpixel10 << 2, + // Subpixel at {0, 0.5}. + kSubpixel02 = kSubpixel20 << 2, + // Subpixel at {0, 0.75}. + kSubpixel03 = kSubpixel30 << 2, + kSubpixel11 = kSubpixel10 | kSubpixel01, + kSubpixel12 = kSubpixel10 | kSubpixel02, + kSubpixel13 = kSubpixel10 | kSubpixel03, + kSubpixel21 = kSubpixel20 | kSubpixel01, + kSubpixel22 = kSubpixel20 | kSubpixel02, + kSubpixel23 = kSubpixel20 | kSubpixel03, + kSubpixel31 = kSubpixel30 | kSubpixel01, + kSubpixel32 = kSubpixel30 | kSubpixel02, + kSubpixel33 = kSubpixel30 | kSubpixel03, +}; + +//------------------------------------------------------------------------------ +/// @brief A glyph and its subpixel position. +/// +struct SubpixelGlyph { + Glyph glyph; + SubpixelPosition subpixel_offset; + std::optional properties; + + SubpixelGlyph(Glyph p_glyph, + SubpixelPosition p_subpixel_offset, + std::optional p_properties) + : glyph(p_glyph), + subpixel_offset(p_subpixel_offset), + properties(p_properties) {} + + template + friend H AbslHashValue(H h, const SubpixelGlyph& sg) { + if (!sg.properties.has_value()) { + return H::combine(std::move(h), sg.glyph.index, sg.subpixel_offset); + } + return H::combine(std::move(h), sg.glyph.index, sg.subpixel_offset, + sg.properties->color.ToARGB(), sg.properties->stroke, + sg.properties->stroke_cap, sg.properties->stroke_join, + sg.properties->stroke_miter, sg.properties->stroke_width); + } + + struct Equal { + constexpr bool operator()(const impeller::SubpixelGlyph& lhs, + const impeller::SubpixelGlyph& rhs) const { + // Check simple non-optionals first. + if (lhs.glyph.index != rhs.glyph.index || + lhs.glyph.type != rhs.glyph.type || + lhs.subpixel_offset != rhs.subpixel_offset || + // Mixmatch properties. + lhs.properties.has_value() != rhs.properties.has_value()) { + return false; + } + if (lhs.properties.has_value()) { + // Both have properties. + return GlyphProperties::Equal{}(lhs.properties.value(), + rhs.properties.value()); + } + return true; + } + }; +}; + +//------------------------------------------------------------------------------ +/// @brief A font along with a glyph in that font rendered at a particular +/// scale and subpixel position. +/// +struct FontGlyphPair { + FontGlyphPair(const ScaledFont& sf, const SubpixelGlyph& g) + : scaled_font(sf), glyph(g) {} + ScaledFont scaled_font; + SubpixelGlyph glyph; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_FONT_GLYPH_PAIR_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/glyph.cc b/flutter/engine/src/flutter/impeller/typographer/glyph.cc new file mode 100644 index 0000000000000000000000000000000000000000..9182d8f1f9082b6a6f9da6398117c51baebe5acb --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/glyph.cc @@ -0,0 +1,11 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/glyph.h" + +namespace impeller { + +// + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/glyph.h b/flutter/engine/src/flutter/impeller/typographer/glyph.h new file mode 100644 index 0000000000000000000000000000000000000000..3a1b813da734567227ed3b12ccadf38cf15cc17a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/glyph.h @@ -0,0 +1,63 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_ + +#include +#include + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief The glyph index in the typeface. +/// +struct Glyph { + enum class Type : uint8_t { + kPath, + kBitmap, + }; + + uint16_t index = 0; + + //------------------------------------------------------------------------------ + /// @brief Whether the glyph is a path or a bitmap. + /// + Type type = Type::kPath; + + Glyph(uint16_t p_index, Type p_type) : index(p_index), type(p_type) {} +}; + +// Many Glyph instances are instantiated, so care should be taken when +// increasing the size. +static_assert(sizeof(Glyph) == 4); + +} // namespace impeller + +template <> +struct std::hash { + constexpr std::size_t operator()(const impeller::Glyph& g) const { + static_assert(sizeof(g.index) == 2); + static_assert(sizeof(g.type) == 1); + return (static_cast(g.type) << 16) | g.index; + } +}; + +template <> +struct std::equal_to { + constexpr bool operator()(const impeller::Glyph& lhs, + const impeller::Glyph& rhs) const { + return lhs.index == rhs.index && lhs.type == rhs.type; + } +}; + +template <> +struct std::less { + constexpr bool operator()(const impeller::Glyph& lhs, + const impeller::Glyph& rhs) const { + return lhs.index < rhs.index; + } +}; + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.cc b/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d75d6271065c23eb978c1c1220dc30e6329986a --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.cc @@ -0,0 +1,145 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/glyph_atlas.h" + +#include +#include + +#include "impeller/typographer/font_glyph_pair.h" + +namespace impeller { + +GlyphAtlasContext::GlyphAtlasContext(GlyphAtlas::Type type) + : atlas_(std::make_shared(type, /*initial_generation=*/0)), + atlas_size_(ISize(0, 0)) {} + +GlyphAtlasContext::~GlyphAtlasContext() {} + +std::shared_ptr GlyphAtlasContext::GetGlyphAtlas() const { + return atlas_; +} + +const ISize& GlyphAtlasContext::GetAtlasSize() const { + return atlas_size_; +} + +int64_t GlyphAtlasContext::GetHeightAdjustment() const { + return height_adjustment_; +} + +std::shared_ptr GlyphAtlasContext::GetRectPacker() const { + return rect_packer_; +} + +void GlyphAtlasContext::UpdateGlyphAtlas(std::shared_ptr atlas, + ISize size, + int64_t height_adjustment) { + atlas_ = std::move(atlas); + atlas_size_ = size; + height_adjustment_ = height_adjustment; +} + +void GlyphAtlasContext::UpdateRectPacker( + std::shared_ptr rect_packer) { + rect_packer_ = std::move(rect_packer); +} + +GlyphAtlas::GlyphAtlas(Type type, size_t initial_generation) + : type_(type), generation_(initial_generation) {} + +GlyphAtlas::~GlyphAtlas() = default; + +bool GlyphAtlas::IsValid() const { + return !!texture_; +} + +GlyphAtlas::Type GlyphAtlas::GetType() const { + return type_; +} + +const std::shared_ptr& GlyphAtlas::GetTexture() const { + return texture_; +} + +void GlyphAtlas::SetTexture(std::shared_ptr texture) { + texture_ = std::move(texture); +} + +size_t GlyphAtlas::GetAtlasGeneration() const { + return generation_; +} + +void GlyphAtlas::SetAtlasGeneration(size_t generation) { + generation_ = generation; +} + +void GlyphAtlas::AddTypefaceGlyphPositionAndBounds(const FontGlyphPair& pair, + Rect position, + Rect bounds) { + FontAtlasMap::iterator it = font_atlas_map_.find(pair.scaled_font); + FML_DCHECK(it != font_atlas_map_.end()); + it->second.positions_[pair.glyph] = + FrameBounds{position, bounds, /*is_placeholder=*/false}; +} + +std::optional GlyphAtlas::FindFontGlyphBounds( + const FontGlyphPair& pair) const { + const auto& found = font_atlas_map_.find(pair.scaled_font); + if (found == font_atlas_map_.end()) { + return std::nullopt; + } + return found->second.FindGlyphBounds(pair.glyph); +} + +FontGlyphAtlas* GlyphAtlas::GetOrCreateFontGlyphAtlas( + const ScaledFont& scaled_font) { + auto [iter, inserted] = + font_atlas_map_.try_emplace(scaled_font, FontGlyphAtlas()); + return &iter->second; +} + +size_t GlyphAtlas::GetGlyphCount() const { + return std::accumulate(font_atlas_map_.begin(), font_atlas_map_.end(), 0, + [](const int a, const auto& b) { + return a + b.second.positions_.size(); + }); +} + +size_t GlyphAtlas::IterateGlyphs( + const std::function& iterator) const { + if (!iterator) { + return 0u; + } + + size_t count = 0u; + for (const auto& font_value : font_atlas_map_) { + for (const auto& glyph_value : font_value.second.positions_) { + count++; + if (!iterator(font_value.first, glyph_value.first, + glyph_value.second.atlas_bounds)) { + return count; + } + } + } + return count; +} + +std::optional FontGlyphAtlas::FindGlyphBounds( + const SubpixelGlyph& glyph) const { + const auto& found = positions_.find(glyph); + if (found == positions_.end()) { + return std::nullopt; + } + return found->second; +} + +void FontGlyphAtlas::AppendGlyph(const SubpixelGlyph& glyph, + const FrameBounds& frame_bounds) { + positions_[glyph] = frame_bounds; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.h b/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.h new file mode 100644 index 0000000000000000000000000000000000000000..de158bae31c737a8e062c93a622b0a9fd3316251 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/glyph_atlas.h @@ -0,0 +1,312 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_ATLAS_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_ATLAS_H_ + +#include +#include +#include + +#include "flutter/fml/build_config.h" + +#if defined(OS_FUCHSIA) +// TODO(gaaclarke): Migrate to use absl. I couldn't get it working since absl +// has special logic in its GN files for Fuchsia that I couldn't sort out. +#define IMPELLER_TYPOGRAPHER_USE_STD_HASH +#else +#include "flutter/third_party/abseil-cpp/absl/container/flat_hash_map.h" +#endif + +#include "impeller/core/texture.h" +#include "impeller/geometry/rect.h" +#include "impeller/typographer/font_glyph_pair.h" +#include "impeller/typographer/rectangle_packer.h" + +namespace impeller { + +class FontGlyphAtlas; + +/// Helper for AbslHashAdapter. Tallies a hash value with fml::HashCombine. +template +struct AbslHashAdapterCombiner { + std::size_t value = 0; + + template + static AbslHashAdapterCombiner combine(AbslHashAdapterCombiner combiner, + const Args&... args) { + combiner.value = fml::HashCombine(combiner.value, args...); + return combiner; + } +}; + +/// Adapts AbslHashValue functions to be used with std::unordered_map and the +/// fml hash functions. +template +struct AbslHashAdapter { + constexpr std::size_t operator()(const T& element) const { + AbslHashAdapterCombiner combiner; + combiner = AbslHashValue(std::move(combiner), element); + return combiner.value; + } +}; + +struct FrameBounds { + /// The bounds of the glyph within the glyph atlas. + Rect atlas_bounds; + /// The local glyph bounds. + Rect glyph_bounds; + /// Whether [atlas_bounds] are still a placeholder and have + /// not yet been computed. + bool is_placeholder = true; +}; + +//------------------------------------------------------------------------------ +/// @brief A texture containing the bitmap representation of glyphs in +/// different fonts along with the ability to query the location of +/// specific font glyphs within the texture. +/// +class GlyphAtlas { + public: + //---------------------------------------------------------------------------- + /// @brief Describes how the glyphs are represented in the texture. + enum class Type { + //-------------------------------------------------------------------------- + /// The glyphs are reprsented at their requested size using only an 8-bit + /// color channel. + /// + /// This might be backed by a grey or red single channel texture, depending + /// on the backend capabilities. + kAlphaBitmap, + + //-------------------------------------------------------------------------- + /// The glyphs are reprsented at their requested size using N32 premul + /// colors. + /// + kColorBitmap, + }; + + //---------------------------------------------------------------------------- + /// @brief Create an empty glyph atlas. + /// + /// @param[in] type How the glyphs are represented in the texture. + /// @param[in] initial_generation the atlas generation. + /// + GlyphAtlas(Type type, size_t initial_generation); + + ~GlyphAtlas(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Describes how the glyphs are represented in the texture. + /// + Type GetType() const; + + //---------------------------------------------------------------------------- + /// @brief Set the texture for the glyph atlas. + /// + /// @param[in] texture The texture + /// + void SetTexture(std::shared_ptr texture); + + //---------------------------------------------------------------------------- + /// @brief Get the texture for the glyph atlas. + /// + /// @return The texture. + /// + const std::shared_ptr& GetTexture() const; + + //---------------------------------------------------------------------------- + /// @brief Record the location of a specific font-glyph pair within the + /// atlas. + /// + /// @param[in] pair The font-glyph pair + /// @param[in] rect The position in the atlas + /// @param[in] bounds The bounds of the glyph at scale + /// + void AddTypefaceGlyphPositionAndBounds(const FontGlyphPair& pair, + Rect position, + Rect bounds); + + //---------------------------------------------------------------------------- + /// @brief Get the number of unique font-glyph pairs in this atlas. + /// + /// @return The glyph count. + /// + size_t GetGlyphCount() const; + + //---------------------------------------------------------------------------- + /// @brief Iterate of all the glyphs along with their locations in the + /// atlas. + /// + /// @param[in] iterator The iterator. Return `false` from the iterator to + /// stop iterating. + /// + /// @return The number of glyphs iterated over. + /// + size_t IterateGlyphs( + const std::function& iterator) const; + + //---------------------------------------------------------------------------- + /// @brief Find the location of a specific font-glyph pair in the atlas. + /// + /// @param[in] pair The font-glyph pair + /// + /// @return The location of the font-glyph pair in the atlas. + /// `std::nullopt` if the pair is not in the atlas. + /// + std::optional FindFontGlyphBounds( + const FontGlyphPair& pair) const; + + //---------------------------------------------------------------------------- + /// @brief Obtain an interface for querying the location of glyphs in the + /// atlas for the given font and scale. This provides a more + /// efficient way to look up a run of glyphs in the same font. + /// + /// @param[in] font The font + /// @param[in] scale The scale + /// + /// @return A pointer to a FontGlyphAtlas, or nullptr if the font and + /// scale are not available in the atlas. The pointer is only + /// valid for the lifetime of the GlyphAtlas. + /// + FontGlyphAtlas* GetOrCreateFontGlyphAtlas(const ScaledFont& scaled_font); + + //---------------------------------------------------------------------------- + /// @brief Retrieve the generation id for this glyph atlas. + /// + /// The generation id is used to match with a TextFrame to + /// determine if the frame is guaranteed to already be populated + /// in the atlas. + size_t GetAtlasGeneration() const; + + //---------------------------------------------------------------------------- + /// @brief Update the atlas generation. + void SetAtlasGeneration(size_t value); + + private: + const Type type_; + std::shared_ptr texture_; + size_t generation_ = 0; + +#if defined(IMPELLER_TYPOGRAPHER_USE_STD_HASH) + using FontAtlasMap = std::unordered_map, + ScaledFont::Equal>; +#else + using FontAtlasMap = absl::flat_hash_map, + ScaledFont::Equal>; +#endif + + FontAtlasMap font_atlas_map_; + + GlyphAtlas(const GlyphAtlas&) = delete; + + GlyphAtlas& operator=(const GlyphAtlas&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief A container for caching a glyph atlas across frames. +/// +class GlyphAtlasContext { + public: + explicit GlyphAtlasContext(GlyphAtlas::Type type); + + virtual ~GlyphAtlasContext(); + + //---------------------------------------------------------------------------- + /// @brief Retrieve the current glyph atlas. + std::shared_ptr GetGlyphAtlas() const; + + //---------------------------------------------------------------------------- + /// @brief Retrieve the size of the current glyph atlas. + const ISize& GetAtlasSize() const; + + //---------------------------------------------------------------------------- + /// @brief Retrieve the previous (if any) rect packer. + std::shared_ptr GetRectPacker() const; + + //---------------------------------------------------------------------------- + /// @brief A y-coordinate shift that must be applied to glyphs appended + /// to + /// the atlas. + /// + /// The rectangle packer is only initialized for unfilled regions + /// of the atlas. The area the rectangle packer covers is offset + /// from the origin by this height adjustment. + int64_t GetHeightAdjustment() const; + + //---------------------------------------------------------------------------- + /// @brief Update the context with a newly constructed glyph atlas. + void UpdateGlyphAtlas(std::shared_ptr atlas, + ISize size, + int64_t height_adjustment_); + + void UpdateRectPacker(std::shared_ptr rect_packer); + + private: + std::shared_ptr atlas_; + ISize atlas_size_; + std::shared_ptr rect_packer_; + int64_t height_adjustment_; + + GlyphAtlasContext(const GlyphAtlasContext&) = delete; + + GlyphAtlasContext& operator=(const GlyphAtlasContext&) = delete; +}; + +//------------------------------------------------------------------------------ +/// @brief An object that can look up glyph locations within the GlyphAtlas +/// for a particular typeface. +/// +class FontGlyphAtlas { + public: + FontGlyphAtlas() = default; + FontGlyphAtlas(FontGlyphAtlas&&) = default; + + //---------------------------------------------------------------------------- + /// @brief Find the location of a glyph in the atlas. + /// + /// @param[in] glyph The glyph + /// + /// @return The location of the glyph in the atlas. + /// `std::nullopt` if the glyph is not in the atlas. + /// + std::optional FindGlyphBounds(const SubpixelGlyph& glyph) const; + + //---------------------------------------------------------------------------- + /// @brief Append the frame bounds of a glyph to this atlas. + /// + /// This may indicate a placeholder glyph location to be replaced + /// at a later time, as indicated by FrameBounds.placeholder. + void AppendGlyph(const SubpixelGlyph& glyph, const FrameBounds& frame_bounds); + + private: + friend class GlyphAtlas; + +#if defined(IMPELLER_TYPOGRAPHER_USE_STD_HASH) + using PositionsMap = std::unordered_map, + SubpixelGlyph::Equal>; +#else + using PositionsMap = absl::flat_hash_map, + SubpixelGlyph::Equal>; +#endif + + PositionsMap positions_; + FontGlyphAtlas(const FontGlyphAtlas&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_GLYPH_ATLAS_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.cc b/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.cc new file mode 100644 index 0000000000000000000000000000000000000000..6575db7a75bba27b225252f6ccbf5bea93b4e870 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.cc @@ -0,0 +1,100 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/lazy_glyph_atlas.h" + +#include "fml/logging.h" +#include "impeller/base/validation.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_frame.h" +#include "impeller/typographer/typographer_context.h" + +#include +#include + +namespace impeller { + +static const std::shared_ptr kNullGlyphAtlas = nullptr; + +LazyGlyphAtlas::LazyGlyphAtlas( + std::shared_ptr typographer_context) + : typographer_context_(std::move(typographer_context)), + alpha_context_(typographer_context_ + ? typographer_context_->CreateGlyphAtlasContext( + GlyphAtlas::Type::kAlphaBitmap) + : nullptr), + color_context_(typographer_context_ + ? typographer_context_->CreateGlyphAtlasContext( + GlyphAtlas::Type::kColorBitmap) + : nullptr) {} + +LazyGlyphAtlas::~LazyGlyphAtlas() = default; + +void LazyGlyphAtlas::AddTextFrame(const std::shared_ptr& frame, + Rational scale, + Point offset, + const Matrix& transform, + std::optional properties) { + frame->SetPerFrameData(scale, offset, transform, properties); + FML_DCHECK(alpha_atlas_ == nullptr && color_atlas_ == nullptr); + if (frame->GetAtlasType() == GlyphAtlas::Type::kAlphaBitmap) { + alpha_text_frames_.push_back(frame); + } else { + color_text_frames_.push_back(frame); + } +} + +void LazyGlyphAtlas::ResetTextFrames() { + alpha_text_frames_.clear(); + color_text_frames_.clear(); + alpha_atlas_.reset(); + color_atlas_.reset(); +} + +const std::shared_ptr& LazyGlyphAtlas::CreateOrGetGlyphAtlas( + Context& context, + HostBuffer& host_buffer, + GlyphAtlas::Type type) const { + { + if (type == GlyphAtlas::Type::kAlphaBitmap && alpha_atlas_) { + return alpha_atlas_; + } + if (type == GlyphAtlas::Type::kColorBitmap && color_atlas_) { + return color_atlas_; + } + } + + if (!typographer_context_) { + VALIDATION_LOG << "Unable to render text because a TypographerContext has " + "not been set."; + return kNullGlyphAtlas; + } + if (!typographer_context_->IsValid()) { + VALIDATION_LOG + << "Unable to render text because the TypographerContext is invalid."; + return kNullGlyphAtlas; + } + + auto& glyph_map = type == GlyphAtlas::Type::kAlphaBitmap ? alpha_text_frames_ + : color_text_frames_; + const std::shared_ptr& atlas_context = + type == GlyphAtlas::Type::kAlphaBitmap ? alpha_context_ : color_context_; + std::shared_ptr atlas = typographer_context_->CreateGlyphAtlas( + context, type, host_buffer, atlas_context, glyph_map); + if (!atlas || !atlas->IsValid()) { + VALIDATION_LOG << "Could not create valid atlas."; + return kNullGlyphAtlas; + } + if (type == GlyphAtlas::Type::kAlphaBitmap) { + alpha_atlas_ = std::move(atlas); + return alpha_atlas_; + } + if (type == GlyphAtlas::Type::kColorBitmap) { + color_atlas_ = std::move(atlas); + return color_atlas_; + } + FML_UNREACHABLE(); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.h b/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.h new file mode 100644 index 0000000000000000000000000000000000000000..7c41fbfbabfc202afbc56fcbd880c2ffafd8797f --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/lazy_glyph_atlas.h @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_ + +#include "impeller/geometry/rational.h" +#include "impeller/renderer/context.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_frame.h" +#include "impeller/typographer/typographer_context.h" + +namespace impeller { + +class LazyGlyphAtlas { + public: + explicit LazyGlyphAtlas( + std::shared_ptr typographer_context); + + ~LazyGlyphAtlas(); + + void AddTextFrame(const std::shared_ptr& frame, + Rational scale, + Point offset, + const Matrix& transform, + std::optional properties); + + void ResetTextFrames(); + + const std::shared_ptr& CreateOrGetGlyphAtlas( + Context& context, + HostBuffer& host_buffer, + GlyphAtlas::Type type) const; + + private: + std::shared_ptr typographer_context_; + + std::vector> alpha_text_frames_; + std::vector> color_text_frames_; + std::shared_ptr alpha_context_; + std::shared_ptr color_context_; + mutable std::shared_ptr alpha_atlas_; + mutable std::shared_ptr color_atlas_; + + LazyGlyphAtlas(const LazyGlyphAtlas&) = delete; + + LazyGlyphAtlas& operator=(const LazyGlyphAtlas&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_LAZY_GLYPH_ATLAS_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.cc b/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.cc new file mode 100644 index 0000000000000000000000000000000000000000..c5e9e464e99e18ab518a654beed1399f2d9aea28 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.cc @@ -0,0 +1,180 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/rectangle_packer.h" + +#include +#include +#include + +#include "flutter/fml/logging.h" + +namespace impeller { + +// Pack rectangles and track the current silhouette +// Based, in part, on Jukka Jylanki's work at http://clb.demon.fi +// and ported from Skia's implementation +// https://github.com/google/skia/blob/b5de4b8ae95c877a9ecfad5eab0765bc22550301/src/gpu/RectanizerSkyline.cpp +class SkylineRectanglePacker final : public RectanglePacker { + public: + SkylineRectanglePacker(int w, int h) : RectanglePacker(w, h) { Reset(); } + + ~SkylineRectanglePacker() final {} + + void Reset() final { + area_so_far_ = 0; + skyline_.clear(); + skyline_.push_back(SkylineSegment{0, 0, width()}); + } + + bool AddRect(int w, int h, IPoint16* loc) final; + + Scalar PercentFull() const final { + return area_so_far_ / (static_cast(width()) * height()); + } + + private: + struct SkylineSegment { + int x_; + int y_; + int width_; + }; + + std::vector skyline_; + + int32_t area_so_far_; + + // Can a width x height rectangle fit in the free space represented by + // the skyline segments >= 'skyline_index'? If so, return true and fill in + // 'y' with the y-location at which it fits (the x location is pulled from + // 'skyline_index's segment. + bool RectangleFits(size_t skyline_index, int width, int height, int* y) const; + // Update the skyline structure to include a width x height rect located + // at x,y. + void AddSkylineLevel(size_t skylineIndex, + int x, + int y, + int width, + int height); +}; + +bool SkylineRectanglePacker::AddRect(int p_width, int p_height, IPoint16* loc) { + if (static_cast(p_width) > static_cast(width()) || + static_cast(p_height) > static_cast(height())) { + return false; + } + + // find position for new rectangle + int bestWidth = width() + 1; + int bestX = 0; + int bestY = height() + 1; + int bestIndex = -1; + for (auto i = 0u; i < skyline_.size(); ++i) { + int y; + if (RectangleFits(i, p_width, p_height, &y)) { + // minimize y position first, then width of skyline + if (y < bestY || (y == bestY && skyline_[i].width_ < bestWidth)) { + bestIndex = i; + bestWidth = skyline_[i].width_; + bestX = skyline_[i].x_; + bestY = y; + } + } + } + + // add rectangle to skyline + if (-1 != bestIndex) { + AddSkylineLevel(bestIndex, bestX, bestY, p_width, p_height); + loc->x_ = bestX; + loc->y_ = bestY; + + area_so_far_ += p_width * p_height; + return true; + } + + loc->x_ = 0; + loc->y_ = 0; + return false; +} + +bool SkylineRectanglePacker::RectangleFits(size_t skyline_index, + int p_width, + int p_height, + int* ypos) const { + int x = skyline_[skyline_index].x_; + if (x + p_width > width()) { + return false; + } + + int widthLeft = p_width; + size_t i = skyline_index; + int y = skyline_[skyline_index].y_; + while (widthLeft > 0) { + y = std::max(y, skyline_[i].y_); + if (y + p_height > height()) { + return false; + } + widthLeft -= skyline_[i].width_; + i++; + FML_CHECK(i < skyline_.size() || widthLeft <= 0); + } + + *ypos = y; + return true; +} + +void SkylineRectanglePacker::AddSkylineLevel(size_t skyline_index, + int x, + int y, + int p_width, + int p_height) { + SkylineSegment newSegment; + newSegment.x_ = x; + newSegment.y_ = y + p_height; + newSegment.width_ = p_width; + skyline_.insert(skyline_.begin() + skyline_index, newSegment); + + FML_DCHECK(newSegment.x_ + newSegment.width_ <= width()); + FML_DCHECK(newSegment.y_ <= height()); + + // delete width of the new skyline segment from following ones + for (auto i = skyline_index + 1; i < skyline_.size(); ++i) { + // The new segment subsumes all or part of skyline_[i] + FML_DCHECK(skyline_[i - 1].x_ <= skyline_[i].x_); + + if (skyline_[i].x_ < skyline_[i - 1].x_ + skyline_[i - 1].width_) { + int shrink = skyline_[i - 1].x_ + skyline_[i - 1].width_ - skyline_[i].x_; + + skyline_[i].x_ += shrink; + skyline_[i].width_ -= shrink; + + if (skyline_[i].width_ <= 0) { + // fully consumed + skyline_.erase(skyline_.begin() + i); + --i; + } else { + // only partially consumed + break; + } + } else { + break; + } + } + + // merge skylines + for (auto i = 0u; i < skyline_.size() - 1; ++i) { + if (skyline_[i].y_ == skyline_[i + 1].y_) { + skyline_[i].width_ += skyline_[i + 1].width_; + skyline_.erase(skyline_.begin() + i + 1); + --i; + } + } +} + +std::shared_ptr RectanglePacker::Factory(int width, + int height) { + return std::make_shared(width, height); +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.h b/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b1e1caf3966bcd232caec4d10125287dd54768 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/rectangle_packer.h @@ -0,0 +1,76 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_ + +#include "flutter/fml/logging.h" +#include "impeller/geometry/scalar.h" + +#include +#include + +namespace impeller { + +struct IPoint16 { + int16_t x() const { return x_; } + int16_t y() const { return y_; } + + int16_t x_; + int16_t y_; +}; + +//------------------------------------------------------------------------------ +/// @brief Packs rectangles into a specified area without rotating them. +/// +class RectanglePacker { + public: + //---------------------------------------------------------------------------- + /// @brief Return an empty packer with area specified by width and height. + /// + static std::shared_ptr Factory(int width, int height); + + virtual ~RectanglePacker() {} + + //---------------------------------------------------------------------------- + /// @brief Attempt to add a rect without moving already placed rectangles. + /// + /// @param[in] width The width of the rectangle to add. + /// @param[in] height The height of the rectangle to add. + /// @param[out] loc If successful, will be set to the position of the + /// upper-left corner of the rectangle. + /// + /// @return Return true on success; false on failure. + /// + virtual bool AddRect(int width, int height, IPoint16* loc) = 0; + + //---------------------------------------------------------------------------- + /// @brief Returns how much area has been filled with rectangles. + /// + /// @return Percentage as a decimal between 0.0 and 1.0 + /// + virtual Scalar PercentFull() const = 0; + + //---------------------------------------------------------------------------- + /// @brief Empty out all previously added rectangles. + /// + virtual void Reset() = 0; + + protected: + RectanglePacker(int width, int height) : width_(width), height_(height) { + FML_DCHECK(width >= 0); + FML_DCHECK(height >= 0); + } + + int width() const { return width_; } + int height() const { return height_; } + + private: + const int width_; + const int height_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_RECTANGLE_PACKER_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/text_frame.cc b/flutter/engine/src/flutter/impeller/typographer/text_frame.cc new file mode 100644 index 0000000000000000000000000000000000000000..073b34e7d16602882a313053576abe18bff43017 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/text_frame.cc @@ -0,0 +1,189 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/text_frame.h" +#include "flutter/display_list/geometry/dl_path.h" // nogncheck +#include "fml/status.h" +#include "impeller/geometry/scalar.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/font_glyph_pair.h" + +namespace impeller { + +TextFrame::TextFrame() = default; + +TextFrame::TextFrame(std::vector& runs, + Rect bounds, + bool has_color, + const PathCreator& path_creator) + : runs_(std::move(runs)), + bounds_(bounds), + has_color_(has_color), + path_creator_(path_creator) {} + +TextFrame::~TextFrame() = default; + +Rect TextFrame::GetBounds() const { + return bounds_; +} + +size_t TextFrame::GetRunCount() const { + return runs_.size(); +} + +const std::vector& TextFrame::GetRuns() const { + return runs_; +} + +GlyphAtlas::Type TextFrame::GetAtlasType() const { + return has_color_ ? GlyphAtlas::Type::kColorBitmap + : GlyphAtlas::Type::kAlphaBitmap; +} + +bool TextFrame::HasColor() const { + return has_color_; +} + +namespace { +constexpr uint32_t kDenominator = 200; +constexpr int32_t kMaximumTextScale = 48; +constexpr Rational kZero(0, kDenominator); +} // namespace + +// static +Rational TextFrame::RoundScaledFontSize(Scalar scale) { + if (scale > kMaximumTextScale) { + return Rational(kMaximumTextScale * kDenominator, kDenominator); + } + // An arbitrarily chosen maximum text scale to ensure that regardless of the + // CTM, a glyph will fit in the atlas. If we clamp significantly, this may + // reduce fidelity but is preferable to the alternative of failing to render. + Rational result = Rational(std::round(scale * kDenominator), kDenominator); + return result < kZero ? kZero : result; +} + +Rational TextFrame::RoundScaledFontSize(Rational scale) { + Rational result = Rational( + std::round((scale.GetNumerator() * static_cast(kDenominator))) / + scale.GetDenominator(), + kDenominator); + return std::clamp(result, Rational(0, kDenominator), + Rational(kMaximumTextScale * kDenominator, kDenominator)); +} + +static constexpr SubpixelPosition ComputeFractionalPosition(Scalar value) { + value += 0.125; + value = (value - floorf(value)); + if (value < 0.25) { + return SubpixelPosition::kSubpixel00; + } + if (value < 0.5) { + return SubpixelPosition::kSubpixel10; + } + if (value < 0.75) { + return SubpixelPosition::kSubpixel20; + } + return SubpixelPosition::kSubpixel30; +} + +// Compute subpixel position for glyphs based on X position and provided +// max basis length (scale). +// This logic is based on the SkPackedGlyphID logic in SkGlyph.h +// static +SubpixelPosition TextFrame::ComputeSubpixelPosition( + const TextRun::GlyphPosition& glyph_position, + AxisAlignment alignment, + const Matrix& transform) { + Point pos = transform * glyph_position.position; + switch (alignment) { + case AxisAlignment::kNone: + return SubpixelPosition::kSubpixel00; + case AxisAlignment::kX: + return ComputeFractionalPosition(pos.x); + case AxisAlignment::kY: + return static_cast(ComputeFractionalPosition(pos.y) + << 2); + case AxisAlignment::kAll: + return static_cast( + ComputeFractionalPosition(pos.x) | + (ComputeFractionalPosition(pos.y) << 2)); + } +} + +Matrix TextFrame::GetOffsetTransform() const { + return transform_ * Matrix::MakeTranslation(offset_); +} + +void TextFrame::SetPerFrameData(Rational scale, + Point offset, + const Matrix& transform, + std::optional properties) { + bound_values_.clear(); + scale_ = scale; + offset_ = offset; + properties_ = properties; + transform_ = transform; +} + +Rational TextFrame::GetScale() const { + return scale_; +} + +Point TextFrame::GetOffset() const { + return offset_; +} + +std::optional TextFrame::GetProperties() const { + return properties_; +} + +void TextFrame::AppendFrameBounds(const FrameBounds& frame_bounds) { + bound_values_.push_back(frame_bounds); +} + +void TextFrame::ClearFrameBounds() { + bound_values_.clear(); +} + +fml::StatusOr TextFrame::GetPath() const { + if (path_creator_) { + return path_creator_(); + } + return fml::Status(fml::StatusCode::kCancelled, "no path creator specified."); +} + +bool TextFrame::IsFrameComplete() const { + size_t run_size = 0; + for (const auto& x : runs_) { + run_size += x.GetGlyphCount(); + } + return bound_values_.size() == run_size; +} + +const Font& TextFrame::GetFont() const { + return runs_[0].GetFont(); +} + +std::optional TextFrame::AsSingleGlyph() const { + if (runs_.size() == 1 && runs_[0].GetGlyphCount() == 1) { + return runs_[0].GetGlyphPositions()[0].glyph; + } + return std::nullopt; +} + +const FrameBounds& TextFrame::GetFrameBounds(size_t index) const { + FML_DCHECK(index < bound_values_.size()); + return bound_values_[index]; +} + +std::pair TextFrame::GetAtlasGenerationAndID() const { + return std::make_pair(generation_, atlas_id_); +} + +void TextFrame::SetAtlasGeneration(size_t value, intptr_t atlas_id) { + generation_ = value; + atlas_id_ = atlas_id; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/text_frame.h b/flutter/engine/src/flutter/impeller/typographer/text_frame.h new file mode 100644 index 0000000000000000000000000000000000000000..24ddc24e11c5a3d1626aa6a373b708418d742000 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/text_frame.h @@ -0,0 +1,157 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_ + +#include + +#include "fml/status_or.h" +#include "impeller/geometry/rational.h" +#include "impeller/typographer/glyph.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_run.h" + +// TODO(https://github.com/flutter/flutter/issues/166593): This is required to +// break a cyclical dependency between display list, impeller, and typographer. +namespace flutter { +class DlPath; +} + +namespace impeller { + +using PathCreator = std::function()>; + +//------------------------------------------------------------------------------ +/// @brief Represents a collection of shaped text runs. +/// +/// This object is typically the entrypoint in the Impeller type +/// rendering subsystem. +/// +/// A text frame should not be reused in multiple places within a single frame, +/// as internally it is used as a cache for various glyph properties. +class TextFrame { + public: + TextFrame(); + + TextFrame(std::vector& runs, + Rect bounds, + bool has_color, + const PathCreator& path_creator = {}); + + ~TextFrame(); + + static SubpixelPosition ComputeSubpixelPosition( + const TextRun::GlyphPosition& glyph_position, + AxisAlignment alignment, + const Matrix& transform); + + static Rational RoundScaledFontSize(Scalar scale); + static Rational RoundScaledFontSize(Rational scale); + + //---------------------------------------------------------------------------- + /// @brief The conservative bounding box for this text frame. + /// + /// @return The bounds rectangle. If there are no glyphs in this text + /// frame and empty Rectangle is returned instead. + /// + Rect GetBounds() const; + + //---------------------------------------------------------------------------- + /// @brief The number of runs in this text frame. + /// + /// @return The run count. + /// + size_t GetRunCount() const; + + //---------------------------------------------------------------------------- + /// @brief Returns a reference to all the text runs in this frame. + /// + /// @return The runs in this frame. + /// + const std::vector& GetRuns() const; + + //---------------------------------------------------------------------------- + /// @brief Returns the paint color this text frame was recorded with. + /// + /// Non-bitmap/COLR fonts always use a black text color here, but + /// COLR fonts can potentially use the paint color in the glyph + /// atlas, so this color must be considered as part of the cache + /// key. + bool HasColor() const; + + //---------------------------------------------------------------------------- + /// @brief The type of atlas this run should be place in. + GlyphAtlas::Type GetAtlasType() const; + + /// @brief Verifies that all glyphs in this text frame have computed bounds + /// information. + bool IsFrameComplete() const; + + /// @brief Retrieve the frame bounds for the glyph at [index]. + /// + /// This method is only valid if [IsFrameComplete] returns true. + const FrameBounds& GetFrameBounds(size_t index) const; + + /// @brief If this text frame contains a single glyph (such as for an Icon), + /// then return it, otherwise std::nullopt. + std::optional AsSingleGlyph() const; + + /// @brief Return the font of the first glyph run. + const Font& GetFont() const; + + /// @brief Store text frame scale, offset, and properties for hashing in th + /// glyph atlas. + void SetPerFrameData(Rational scale, + Point offset, + const Matrix& transform, + std::optional properties); + + // A generation id for the glyph atlas this text run was associated + // with. As long as the frame generation matches the atlas generation, + // the contents are guaranteed to be populated and do not need to be + // processed. + std::pair GetAtlasGenerationAndID() const; + + Rational GetScale() const; + + const Matrix& GetTransform() const { return transform_; } + + fml::StatusOr GetPath() const; + + Point GetOffset() const; + + Matrix GetOffsetTransform() const; + + private: + friend class TypographerContextSkia; + friend class LazyGlyphAtlas; + + std::optional GetProperties() const; + + void AppendFrameBounds(const FrameBounds& frame_bounds); + + void ClearFrameBounds(); + + void SetAtlasGeneration(size_t value, intptr_t atlas_id); + + std::vector runs_; + Rect bounds_; + bool has_color_; + const PathCreator path_creator_; + + // Data that is cached when rendering the text frame and is only + // valid for the current atlas generation. + std::vector bound_values_; + Rational scale_ = Rational(0, 1); + size_t generation_ = 0; + intptr_t atlas_id_ = 0; + Point offset_; + std::optional properties_; + Matrix transform_; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_FRAME_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/text_run.cc b/flutter/engine/src/flutter/impeller/typographer/text_run.cc new file mode 100644 index 0000000000000000000000000000000000000000..6fc3a3ba261c4e17a28c703a898b3c6f60bc604b --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/text_run.cc @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/text_run.h" + +namespace impeller { + +TextRun::TextRun(const Font& font) : font_(font) { + if (!font_.IsValid()) { + return; + } + is_valid_ = true; +} + +TextRun::TextRun(const Font& font, std::vector& glyphs) + : font_(font), glyphs_(std::move(glyphs)) { + if (!font_.IsValid()) { + return; + } + is_valid_ = true; +} + +TextRun::~TextRun() = default; + +bool TextRun::AddGlyph(Glyph glyph, Point position) { + glyphs_.emplace_back(GlyphPosition{glyph, position}); + return true; +} + +bool TextRun::IsValid() const { + return is_valid_; +} + +const std::vector& TextRun::GetGlyphPositions() const { + return glyphs_; +} + +size_t TextRun::GetGlyphCount() const { + return glyphs_.size(); +} + +const Font& TextRun::GetFont() const { + return font_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/text_run.h b/flutter/engine/src/flutter/impeller/typographer/text_run.h new file mode 100644 index 0000000000000000000000000000000000000000..76da59ff6fcd6784a0b6c28ee0e52749377c733c --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/text_run.h @@ -0,0 +1,82 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_RUN_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_RUN_H_ + +#include + +#include "impeller/geometry/point.h" +#include "impeller/typographer/font.h" +#include "impeller/typographer/glyph.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief Represents a collection of positioned glyphs from a specific +/// font. +/// +class TextRun { + public: + struct GlyphPosition { + Glyph glyph; + Point position; + + GlyphPosition(Glyph p_glyph, Point p_position) + : glyph(p_glyph), position(p_position) {} + }; + + //---------------------------------------------------------------------------- + /// @brief Create an empty text run with the specified font. + /// + /// @param[in] font The font + /// + explicit TextRun(const Font& font); + + TextRun(const Font& font, std::vector& glyphs); + + ~TextRun(); + + bool IsValid() const; + + //---------------------------------------------------------------------------- + /// @brief Add a glyph at the specified position to the run. + /// + /// @param[in] glyph The glyph + /// @param[in] position The position + /// + /// @return If the glyph could be added to the run. + /// + bool AddGlyph(Glyph glyph, Point position); + + //---------------------------------------------------------------------------- + /// @brief Get the number of glyphs in the run. + /// + /// @return The glyph count. + /// + size_t GetGlyphCount() const; + + //---------------------------------------------------------------------------- + /// @brief Get a reference to all the glyph positions within the run. + /// + /// @return The glyph positions. + /// + const std::vector& GetGlyphPositions() const; + + //---------------------------------------------------------------------------- + /// @brief Get the font for this run. + /// + /// @return The font. + /// + const Font& GetFont() const; + + private: + Font font_; + std::vector glyphs_; + bool is_valid_ = false; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_TEXT_RUN_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/typeface.cc b/flutter/engine/src/flutter/impeller/typographer/typeface.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c5fdd5451ca563f7aac7954a337ac274f140f45 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/typeface.cc @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/typeface.h" + +namespace impeller { + +Typeface::Typeface() = default; + +Typeface::~Typeface() = default; + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/typeface.h b/flutter/engine/src/flutter/impeller/typographer/typeface.h new file mode 100644 index 0000000000000000000000000000000000000000..df99657d4045b24393c213ea2c15eaae961f6999 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/typeface.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_ + +#include "impeller/base/comparable.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief A typeface, usually obtained from a font-file, on disk describes +/// the intrinsic properties of the font. Typefaces are rarely used +/// directly. Instead, font refer to typefaces along with any +/// modifications applied to its intrinsic properties. +/// +class Typeface : public Comparable { + public: + Typeface(); + + virtual ~Typeface(); + + virtual bool IsValid() const = 0; + + private: + Typeface(const Typeface&) = delete; + + Typeface& operator=(const Typeface&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_TYPEFACE_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/typographer_context.cc b/flutter/engine/src/flutter/impeller/typographer/typographer_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..91c3129039ccf19a47f20521a7c4bf2eda87c5ec --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/typographer_context.cc @@ -0,0 +1,21 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "impeller/typographer/typographer_context.h" + +#include + +namespace impeller { + +TypographerContext::TypographerContext() { + is_valid_ = true; +} + +TypographerContext::~TypographerContext() = default; + +bool TypographerContext::IsValid() const { + return is_valid_; +} + +} // namespace impeller diff --git a/flutter/engine/src/flutter/impeller/typographer/typographer_context.h b/flutter/engine/src/flutter/impeller/typographer/typographer_context.h new file mode 100644 index 0000000000000000000000000000000000000000..138a911d89c10d124871545a941eaa63fc087329 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/typographer_context.h @@ -0,0 +1,56 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_IMPELLER_TYPOGRAPHER_TYPOGRAPHER_CONTEXT_H_ +#define FLUTTER_IMPELLER_TYPOGRAPHER_TYPOGRAPHER_CONTEXT_H_ + +#include + +#include "impeller/renderer/context.h" +#include "impeller/typographer/glyph_atlas.h" +#include "impeller/typographer/text_frame.h" + +namespace impeller { + +//------------------------------------------------------------------------------ +/// @brief The graphics context necessary to render text. +/// +/// This is necessary to create and reference resources related to +/// rendering text on the GPU. +/// +/// +class TypographerContext { + public: + virtual ~TypographerContext(); + + virtual bool IsValid() const; + + virtual std::shared_ptr CreateGlyphAtlasContext( + GlyphAtlas::Type type) const = 0; + + virtual std::shared_ptr CreateGlyphAtlas( + Context& context, + GlyphAtlas::Type type, + HostBuffer& host_buffer, + const std::shared_ptr& atlas_context, + const std::vector>& text_frames) const = 0; + + protected: + //---------------------------------------------------------------------------- + /// @brief Create a new context to render text that talks to an + /// underlying graphics context. + /// + TypographerContext(); + + private: + bool is_valid_ = false; + + TypographerContext(const TypographerContext&) = delete; + + TypographerContext& operator=(const TypographerContext&) = delete; +}; + +} // namespace impeller + +#endif // FLUTTER_IMPELLER_TYPOGRAPHER_TYPOGRAPHER_CONTEXT_H_ diff --git a/flutter/engine/src/flutter/impeller/typographer/typographer_unittests.cc b/flutter/engine/src/flutter/impeller/typographer/typographer_unittests.cc new file mode 100644 index 0000000000000000000000000000000000000000..82c8c1aa9ba3110a857ad59e42872e11e6dcea71 --- /dev/null +++ b/flutter/engine/src/flutter/impeller/typographer/typographer_unittests.cc @@ -0,0 +1,662 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/display_list/testing/dl_test_snippets.h" +#include "flutter/testing/testing.h" +#include "gtest/gtest.h" +#include "impeller/core/host_buffer.h" +#include "impeller/playground/playground.h" +#include "impeller/playground/playground_test.h" +#include "impeller/typographer/backends/skia/text_frame_skia.h" +#include "impeller/typographer/backends/skia/typographer_context_skia.h" +#include "impeller/typographer/font_glyph_pair.h" +#include "impeller/typographer/lazy_glyph_atlas.h" +#include "impeller/typographer/rectangle_packer.h" +#include "third_party/skia/include/core/SkFont.h" +#include "third_party/skia/include/core/SkFontMgr.h" +#include "third_party/skia/include/core/SkRect.h" +#include "third_party/skia/include/core/SkTextBlob.h" +#include "third_party/skia/include/core/SkTypeface.h" +#include "txt/platform.h" + +// TODO(zanderso): https://github.com/flutter/flutter/issues/127701 +// NOLINTBEGIN(bugprone-unchecked-optional-access) + +namespace impeller { +namespace testing { + +using TypographerTest = PlaygroundTest; +INSTANTIATE_PLAYGROUND_SUITE(TypographerTest); + +static std::shared_ptr CreateGlyphAtlas( + Context& context, + const TypographerContext* typographer_context, + HostBuffer& host_buffer, + GlyphAtlas::Type type, + Rational scale, + const std::shared_ptr& atlas_context, + const std::shared_ptr& frame) { + frame->SetPerFrameData(scale, {0, 0}, Matrix(), std::nullopt); + return typographer_context->CreateGlyphAtlas(context, type, host_buffer, + atlas_context, {frame}); +} + +static std::shared_ptr CreateGlyphAtlas( + Context& context, + const TypographerContext* typographer_context, + HostBuffer& host_buffer, + GlyphAtlas::Type type, + Rational scale, + const std::shared_ptr& atlas_context, + const std::vector>& frames, + const std::vector>& properties) { + size_t offset = 0; + for (auto& frame : frames) { + frame->SetPerFrameData(scale, {0, 0}, Matrix(), properties[offset++]); + } + return typographer_context->CreateGlyphAtlas(context, type, host_buffer, + atlas_context, frames); +} + +TEST_P(TypographerTest, CanConvertTextBlob) { + SkFont font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + ASSERT_EQ(frame->GetRunCount(), 1u); + for (const auto& run : frame->GetRuns()) { + ASSERT_TRUE(run.IsValid()); + ASSERT_EQ(run.GetGlyphCount(), 45u); + } +} + +TEST_P(TypographerTest, CanCreateRenderContext) { + auto context = TypographerContextSkia::Make(); + ASSERT_TRUE(context && context->IsValid()); +} + +TEST_P(TypographerTest, CanCreateGlyphAtlas) { + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString("hello", sk_font); + ASSERT_TRUE(blob); + auto atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + + ASSERT_NE(atlas, nullptr); + ASSERT_NE(atlas->GetTexture(), nullptr); + ASSERT_EQ(atlas->GetType(), GlyphAtlas::Type::kAlphaBitmap); + ASSERT_EQ(atlas->GetGlyphCount(), 4llu); + + std::optional first_scaled_font; + std::optional first_glyph; + Rect first_rect; + atlas->IterateGlyphs([&](const ScaledFont& scaled_font, + const SubpixelGlyph& glyph, + const Rect& rect) -> bool { + first_scaled_font = scaled_font; + first_glyph = glyph; + first_rect = rect; + return false; + }); + + ASSERT_TRUE(first_scaled_font.has_value()); + ASSERT_TRUE(atlas + ->FindFontGlyphBounds( + {first_scaled_font.value(), first_glyph.value()}) + .has_value()); +} + +TEST_P(TypographerTest, LazyAtlasTracksColor) { + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); +#if FML_OS_MACOSX + auto mapping = flutter::testing::OpenFixtureAsSkData("Apple Color Emoji.ttc"); +#else + auto mapping = flutter::testing::OpenFixtureAsSkData("NotoColorEmoji.ttf"); +#endif + ASSERT_TRUE(mapping); + sk_sp font_mgr = txt::GetDefaultFontManager(); + SkFont emoji_font(font_mgr->makeFromData(mapping), 50.0); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + + auto blob = SkTextBlob::MakeFromString("hello", sk_font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + + ASSERT_FALSE(frame->GetAtlasType() == GlyphAtlas::Type::kColorBitmap); + + LazyGlyphAtlas lazy_atlas(TypographerContextSkia::Make()); + + lazy_atlas.AddTextFrame(frame, Rational(1), {0, 0}, Matrix(), {}); + + frame = MakeTextFrameFromTextBlobSkia( + SkTextBlob::MakeFromString("😀 ", emoji_font)); + + ASSERT_TRUE(frame->GetAtlasType() == GlyphAtlas::Type::kColorBitmap); + + lazy_atlas.AddTextFrame(frame, Rational(1), {0, 0}, Matrix(), {}); + + // Creates different atlases for color and red bitmap. + auto color_atlas = lazy_atlas.CreateOrGetGlyphAtlas( + *GetContext(), *host_buffer, GlyphAtlas::Type::kColorBitmap); + + auto bitmap_atlas = lazy_atlas.CreateOrGetGlyphAtlas( + *GetContext(), *host_buffer, GlyphAtlas::Type::kAlphaBitmap); + + ASSERT_FALSE(color_atlas == bitmap_atlas); +} + +TEST_P(TypographerTest, GlyphAtlasWithOddUniqueGlyphSize) { + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString("AGH", sk_font); + ASSERT_TRUE(blob); + auto atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + ASSERT_NE(atlas, nullptr); + ASSERT_NE(atlas->GetTexture(), nullptr); + + EXPECT_EQ(atlas->GetTexture()->GetSize().width, 4096u); + EXPECT_EQ(atlas->GetTexture()->GetSize().height, 1024u); +} + +TEST_P(TypographerTest, GlyphAtlasIsRecycledIfUnchanged) { + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + ASSERT_TRUE(context && context->IsValid()); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString("spooky skellingtons", sk_font); + ASSERT_TRUE(blob); + auto atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + ASSERT_NE(atlas, nullptr); + ASSERT_NE(atlas->GetTexture(), nullptr); + ASSERT_EQ(atlas, atlas_context->GetGlyphAtlas()); + + // now attempt to re-create an atlas with the same text blob. + + auto next_atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + ASSERT_EQ(atlas, next_atlas); + ASSERT_EQ(atlas_context->GetGlyphAtlas(), atlas); +} + +TEST_P(TypographerTest, GlyphAtlasWithLotsOfdUniqueGlyphSize) { + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + ASSERT_TRUE(context && context->IsValid()); + + const char* test_string = + "QWERTYUIOPASDFGHJKLZXCVBNMqewrtyuiopasdfghjklzxcvbnm,.<>[]{};':" + "2134567890-=!@#$%^&*()_+" + "œ∑´®†¥¨ˆøπ““‘‘åß∂ƒ©˙∆˚¬…æ≈ç√∫˜µ≤≥≥≥≥÷¡™£¢∞§¶•ªº–≠⁄€‹›fifl‡°·‚—±Œ„´‰Á¨Ø∏”’/" + "* Í˝ */¸˛Ç◊ı˜Â¯˘¿"; + + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString(test_string, sk_font); + ASSERT_TRUE(blob); + + size_t size_count = 8; + std::vector> frames; + for (size_t index = 0; index < size_count; index += 1) { + frames.push_back(MakeTextFrameFromTextBlobSkia(blob)); + frames.back()->SetPerFrameData(Rational(6 * index, 10), {0, 0}, Matrix(), + {}); + }; + auto atlas = + context->CreateGlyphAtlas(*GetContext(), GlyphAtlas::Type::kAlphaBitmap, + *host_buffer, atlas_context, frames); + ASSERT_NE(atlas, nullptr); + ASSERT_NE(atlas->GetTexture(), nullptr); + + std::set unique_glyphs; + std::vector total_glyphs; + atlas->IterateGlyphs([&](const ScaledFont& scaled_font, + const SubpixelGlyph& glyph, const Rect& rect) { + unique_glyphs.insert(glyph.glyph.index); + total_glyphs.push_back(glyph.glyph.index); + return true; + }); + + // These numbers may be different due to subpixel positions. + EXPECT_LE(unique_glyphs.size() * size_count, atlas->GetGlyphCount()); + EXPECT_EQ(total_glyphs.size(), atlas->GetGlyphCount()); + + EXPECT_TRUE(atlas->GetGlyphCount() > 0); + EXPECT_TRUE(atlas->GetTexture()->GetSize().width > 0); + EXPECT_TRUE(atlas->GetTexture()->GetSize().height > 0); +} + +TEST_P(TypographerTest, GlyphAtlasTextureIsRecycledIfUnchanged) { + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + ASSERT_TRUE(context && context->IsValid()); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString("spooky 1", sk_font); + ASSERT_TRUE(blob); + auto atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + auto old_packer = atlas_context->GetRectPacker(); + + ASSERT_NE(atlas, nullptr); + ASSERT_NE(atlas->GetTexture(), nullptr); + ASSERT_EQ(atlas, atlas_context->GetGlyphAtlas()); + + auto* first_texture = atlas->GetTexture().get(); + + // Now create a new glyph atlas with a nearly identical blob. + + auto blob2 = SkTextBlob::MakeFromString("spooky 2", sk_font); + auto next_atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob2)); + ASSERT_EQ(atlas, next_atlas); + auto* second_texture = next_atlas->GetTexture().get(); + + auto new_packer = atlas_context->GetRectPacker(); + + ASSERT_EQ(second_texture, first_texture); + ASSERT_EQ(old_packer, new_packer); +} + +TEST_P(TypographerTest, GlyphColorIsPartOfCacheKey) { + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); +#if FML_OS_MACOSX + auto mapping = flutter::testing::OpenFixtureAsSkData("Apple Color Emoji.ttc"); +#else + auto mapping = flutter::testing::OpenFixtureAsSkData("NotoColorEmoji.ttf"); +#endif + ASSERT_TRUE(mapping); + sk_sp font_mgr = txt::GetDefaultFontManager(); + SkFont emoji_font(font_mgr->makeFromData(mapping), 50.0); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kColorBitmap); + + // Create two frames with the same character and a different color, expect + // that it adds a character. + auto frame = MakeTextFrameFromTextBlobSkia( + SkTextBlob::MakeFromString("😂", emoji_font)); + auto frame_2 = MakeTextFrameFromTextBlobSkia( + SkTextBlob::MakeFromString("😂", emoji_font)); + std::vector> properties = { + GlyphProperties{.color = Color::Red()}, + GlyphProperties{.color = Color::Blue()}, + }; + + auto next_atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kColorBitmap, Rational(1), + atlas_context, {frame, frame_2}, properties); + + EXPECT_EQ(next_atlas->GetGlyphCount(), 2u); +} + +TEST_P(TypographerTest, GlyphColorIsIgnoredForNonEmojiFonts) { + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + sk_sp font_mgr = txt::GetDefaultFontManager(); + sk_sp typeface = + font_mgr->matchFamilyStyle("Arial", SkFontStyle::Normal()); + SkFont sk_font(typeface, 0.5f); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kColorBitmap); + + // Create two frames with the same character and a different color, but as a + // non-emoji font the text frame constructor will ignore it. + auto frame = + MakeTextFrameFromTextBlobSkia(SkTextBlob::MakeFromString("A", sk_font)); + auto frame_2 = + MakeTextFrameFromTextBlobSkia(SkTextBlob::MakeFromString("A", sk_font)); + std::vector> properties = { + GlyphProperties{}, + GlyphProperties{}, + }; + + auto next_atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kColorBitmap, Rational(1), + atlas_context, {frame, frame_2}, properties); + + EXPECT_EQ(next_atlas->GetGlyphCount(), 1u); +} + +TEST_P(TypographerTest, RectanglePackerAddsNonoverlapingRectangles) { + auto packer = RectanglePacker::Factory(200, 100); + ASSERT_NE(packer, nullptr); + ASSERT_EQ(packer->PercentFull(), 0); + + const SkIRect packer_area = SkIRect::MakeXYWH(0, 0, 200, 100); + + IPoint16 first_output = {-1, -1}; // Fill with sentinel values + ASSERT_TRUE(packer->AddRect(20, 20, &first_output)); + // Make sure the rectangle is placed such that it is inside the bounds of + // the packer's area. + const SkIRect first_rect = + SkIRect::MakeXYWH(first_output.x(), first_output.y(), 20, 20); + ASSERT_TRUE(SkIRect::Intersects(packer_area, first_rect)); + + // Initial area was 200 x 100 = 20_000 + // We added 20x20 = 400. 400 / 20_000 == 0.02 == 2% + ASSERT_TRUE(flutter::testing::NumberNear(packer->PercentFull(), 0.02)); + + IPoint16 second_output = {-1, -1}; + ASSERT_TRUE(packer->AddRect(140, 90, &second_output)); + const SkIRect second_rect = + SkIRect::MakeXYWH(second_output.x(), second_output.y(), 140, 90); + // Make sure the rectangle is placed such that it is inside the bounds of + // the packer's area but not in the are of the first rectangle. + ASSERT_TRUE(SkIRect::Intersects(packer_area, second_rect)); + ASSERT_FALSE(SkIRect::Intersects(first_rect, second_rect)); + + // We added another 90 x 140 = 12_600 units, now taking us to 13_000 + // 13_000 / 20_000 == 0.65 == 65% + ASSERT_TRUE(flutter::testing::NumberNear(packer->PercentFull(), 0.65)); + + // There's enough area to add this rectangle, but no space big enough for + // the 50 units of width. + IPoint16 output; + ASSERT_FALSE(packer->AddRect(50, 50, &output)); + // Should be unchanged. + ASSERT_TRUE(flutter::testing::NumberNear(packer->PercentFull(), 0.65)); + + packer->Reset(); + // Should be empty now. + ASSERT_EQ(packer->PercentFull(), 0); +} + +TEST(TypographerTest, RectanglePackerFillsRows) { + auto skyline = RectanglePacker::Factory(257, 256); + + // Fill up the first row. + IPoint16 loc; + for (auto i = 0u; i < 16; i++) { + skyline->AddRect(16, 16, &loc); + } + // Last rectangle still in first row. + EXPECT_EQ(loc.x(), 256 - 16); + EXPECT_EQ(loc.y(), 0); + + // Fill up second row. + for (auto i = 0u; i < 16; i++) { + skyline->AddRect(16, 16, &loc); + } + + EXPECT_EQ(loc.x(), 256 - 16); + EXPECT_EQ(loc.y(), 16); +} + +TEST_P(TypographerTest, GlyphAtlasTextureWillGrowTilMaxTextureSize) { + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + GTEST_SKIP() << "Atlas growth isn't supported for OpenGLES currently."; + } + + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + ASSERT_TRUE(context && context->IsValid()); + SkFont sk_font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString("A", sk_font); + ASSERT_TRUE(blob); + auto atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + // Continually append new glyphs until the glyph size grows to the maximum. + // Note that the sizes here are more or less experimentally determined, but + // the important expectation is that the atlas size will shrink again after + // growing to the maximum size. + constexpr ISize expected_sizes[13] = { + {4096, 4096}, // + {4096, 4096}, // + {4096, 8192}, // + {4096, 8192}, // + {4096, 8192}, // + {4096, 8192}, // + {4096, 16384}, // + {4096, 16384}, // + {4096, 16384}, // + {4096, 16384}, // + {4096, 16384}, // + {4096, 16384}, // + {4096, 4096} // Shrinks! + }; + + SkFont sk_font_small = flutter::testing::CreateTestFontOfSize(10); + + for (int i = 0; i < 13; i++) { + SkTextBlobBuilder builder; + + auto add_char = [&](const SkFont& sk_font, char c) { + int count = sk_font.countText(&c, 1, SkTextEncoding::kUTF8); + auto buffer = builder.allocRunPos(sk_font, count); + sk_font.textToGlyphs(&c, 1, SkTextEncoding::kUTF8, buffer.glyphs, count); + sk_font.getPos(buffer.glyphs, count, buffer.points(), {0, 0}); + }; + + SkFont sk_font = flutter::testing::CreateTestFontOfSize(50 + i); + add_char(sk_font, 'A'); + add_char(sk_font_small, 'B'); + auto blob = builder.make(); + + atlas = + CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, Rational(50 + i, 1), + atlas_context, MakeTextFrameFromTextBlobSkia(blob)); + ASSERT_TRUE(!!atlas); + EXPECT_EQ(atlas->GetTexture()->GetTextureDescriptor().size, + expected_sizes[i]); + } + + // The final atlas should contain both the "A" glyph (which was not present + // in the previous atlas) and the "B" glyph (which existed in the previous + // atlas). + ASSERT_EQ(atlas->GetGlyphCount(), 2u); +} + +TEST_P(TypographerTest, TextFrameInitialBoundsArePlaceholder) { + SkFont font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + + EXPECT_FALSE(frame->IsFrameComplete()); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The glyph position in the atlas was not known when this value + // was recorded. It is marked as a placeholder. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_TRUE(frame->GetFrameBounds(0).is_placeholder); + + atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The second time the glyph is rendered, the bounds are correcly known. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_FALSE(frame->GetFrameBounds(0).is_placeholder); +} + +TEST_P(TypographerTest, TextFrameInvalidationWithScale) { + SkFont font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + + EXPECT_FALSE(frame->IsFrameComplete()); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The glyph position in the atlas was not known when this value + // was recorded. It is marked as a placeholder. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_TRUE(frame->GetFrameBounds(0).is_placeholder); + + // Change the scale and the glyph data will still be a placeholder, as the + // old data is no longer valid. + atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(2), atlas_context, frame); + + // The second time the glyph is rendered, the bounds are correcly known. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_TRUE(frame->GetFrameBounds(0).is_placeholder); +} + +TEST_P(TypographerTest, TextFrameAtlasGenerationTracksState) { + SkFont font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + + EXPECT_FALSE(frame->IsFrameComplete()); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The glyph position in the atlas was not known when this value + // was recorded. It is marked as a placeholder. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_TRUE(frame->GetFrameBounds(0).is_placeholder); + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + // OpenGLES must always increase the atlas backend if the texture grows. + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 1u); + } else { + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 0u); + } + + atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The second time the glyph is rendered, the bounds are correcly known. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_FALSE(frame->GetFrameBounds(0).is_placeholder); + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 1u); + } else { + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 0u); + } + + // Force increase the generation. + atlas_context->GetGlyphAtlas()->SetAtlasGeneration(2u); + atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 2u); +} + +TEST_P(TypographerTest, InvalidAtlasForcesRepopulation) { + SkFont font = flutter::testing::CreateTestFontOfSize(12); + auto blob = SkTextBlob::MakeFromString( + "the quick brown fox jumped over the lazy dog.", font); + ASSERT_TRUE(blob); + auto frame = MakeTextFrameFromTextBlobSkia(blob); + + EXPECT_FALSE(frame->IsFrameComplete()); + + auto context = TypographerContextSkia::Make(); + auto atlas_context = + context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + auto host_buffer = HostBuffer::Create(GetContext()->GetResourceAllocator(), + GetContext()->GetIdleWaiter()); + + auto atlas = CreateGlyphAtlas(*GetContext(), context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), atlas_context, frame); + + // The glyph position in the atlas was not known when this value + // was recorded. It is marked as a placeholder. + EXPECT_TRUE(frame->IsFrameComplete()); + EXPECT_TRUE(frame->GetFrameBounds(0).is_placeholder); + if (GetBackend() == PlaygroundBackend::kOpenGLES) { + // OpenGLES must always increase the atlas backend if the texture grows. + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 1u); + } else { + EXPECT_EQ(frame->GetAtlasGenerationAndID().first, 0u); + } + + auto second_context = TypographerContextSkia::Make(); + auto second_atlas_context = + second_context->CreateGlyphAtlasContext(GlyphAtlas::Type::kAlphaBitmap); + + EXPECT_FALSE(second_atlas_context->GetGlyphAtlas()->IsValid()); + + atlas = CreateGlyphAtlas(*GetContext(), second_context.get(), *host_buffer, + GlyphAtlas::Type::kAlphaBitmap, + /*scale=*/Rational(1), second_atlas_context, frame); + + EXPECT_TRUE(second_atlas_context->GetGlyphAtlas()->IsValid()); +} + +} // namespace testing +} // namespace impeller + +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/flutter/engine/src/flutter/lib/gpu/dist/BUILD.gn b/flutter/engine/src/flutter/lib/gpu/dist/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c8ea07f21641256d7f4a243735845078af9571e0 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/dist/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//flutter/build/zip_bundle.gni") + +# Similar to `sky_engine`, zip up the `flutter_gpu` Dart package and upload +# it to GCS for distribution. This is only done during Android builds on CI. +# +# Then, the Flutter tool downloads and extracts `flutter_gpu.zip` into the +# package cache (`bin/cache/pkg`) during artifact initialization. +# +# Note that unlike with `sky_engine`, the `lib/gpu` directory is already a +# complete Dart package. So no additional build steps are necessary beyond +# zipping it up. + +if (is_android) { + zip_bundle("zip") { + output = "$android_zip_archive_dir/flutter_gpu.zip" + files = [ + { + source = "//flutter/lib/gpu" + destination = "flutter_gpu" + }, + ] + deps = [] + } + + zip_bundle("zip_old_location") { + # TODO: remove after we migrate the tool to use the new location. + # Bug: https://github.com/flutter/flutter/issues/105351 + output = "flutter_gpu.zip" + files = [ + { + source = "//flutter/lib/gpu" + destination = "flutter_gpu" + }, + ] + deps = [] + } +} + +group("dist") { + if (is_android) { + deps = [ ":zip" ] + } +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/gpu.dart b/flutter/engine/src/flutter/lib/gpu/lib/gpu.dart new file mode 100644 index 0000000000000000000000000000000000000000..3fd13133dbd7edadccd666aaafb5f820c2a9de11 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/gpu.dart @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// Flutter GPU is a low level API for building rendering packages from scratch. +/// +/// To use, first add an SDK dependency in your `pubspec.yaml` file: +/// ``` +/// dependencies: +/// flutter_gpu: +/// sdk: flutter +/// ``` +/// And then add an import statement in your Dart files: +/// ```dart +/// import `package:flutter_gpu/gpu.dart`; +/// ``` +/// +/// See also: +/// +/// * [Flutter GPU documentation](https://github.com/flutter/engine/blob/main/docs/impeller/Flutter-GPU.md). +library flutter_gpu; + +import 'dart:ffi'; +import 'dart:nativewrappers'; +import 'dart:typed_data'; +// ignore: uri_does_not_exist +import 'dart:ui' as ui; + +import 'package:vector_math/vector_math.dart' as vm; + +part 'src/buffer.dart'; +part 'src/command_buffer.dart'; +part 'src/context.dart'; +part 'src/formats.dart'; +part 'src/texture.dart'; +part 'src/render_pass.dart'; +part 'src/render_pipeline.dart'; +part 'src/shader.dart'; +part 'src/shader_library.dart'; diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/buffer.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/buffer.dart new file mode 100644 index 0000000000000000000000000000000000000000..59da03408cb8fcc12b2102e0dd845144134814da --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/buffer.dart @@ -0,0 +1,322 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +/// A reference to a byte range within a GPU-resident [Buffer]. +class BufferView { + /// The device buffer of this view. + final DeviceBuffer buffer; + + /// The start of the view, in bytes starting from the beginning of the + /// [buffer]. + final int offsetInBytes; + + /// The length of the view. + final int lengthInBytes; + + /// Create a new view into a buffer on the GPU. + const BufferView( + this.buffer, { + required this.offsetInBytes, + required this.lengthInBytes, + }); +} + +/// [DeviceBuffer] is a region of memory allocated on the device heap +/// (GPU-resident memory). +base class DeviceBuffer extends NativeFieldWrapperClass1 { + bool _valid = false; + get isValid { + return _valid; + } + + /// Creates a new DeviceBuffer. + DeviceBuffer._initialize( + GpuContext gpuContext, + StorageMode storageMode, + int sizeInBytes, + ) : storageMode = storageMode, + sizeInBytes = sizeInBytes { + _valid = _initialize(gpuContext, storageMode.index, sizeInBytes); + } + + /// Creates a new host visible DeviceBuffer with data copied from the host. + DeviceBuffer._initializeWithHostData(GpuContext gpuContext, ByteData data) + : storageMode = StorageMode.hostVisible, + sizeInBytes = data.lengthInBytes { + _valid = _initializeWithHostData(gpuContext, data); + } + + final StorageMode storageMode; + final int sizeInBytes; + + void _bindAsVertexBuffer( + RenderPass renderPass, + int offsetInBytes, + int lengthInBytes, + int vertexCount, + ) { + renderPass._bindVertexBufferDevice( + this, + offsetInBytes, + lengthInBytes, + vertexCount, + ); + } + + void _bindAsIndexBuffer( + RenderPass renderPass, + int offsetInBytes, + int lengthInBytes, + IndexType indexType, + int indexCount, + ) { + renderPass._bindIndexBufferDevice( + this, + offsetInBytes, + lengthInBytes, + indexType.index, + indexCount, + ); + } + + bool _bindAsUniform( + RenderPass renderPass, + UniformSlot slot, + int offsetInBytes, + int lengthInBytes, + ) { + return renderPass._bindUniformDevice( + slot.shader, + slot.uniformName, + this, + offsetInBytes, + lengthInBytes, + ); + } + + /// Wrap with native counterpart. + @Native, Int, Int)>( + symbol: 'InternalFlutterGpu_DeviceBuffer_Initialize', + ) + external bool _initialize( + GpuContext gpuContext, + int storageMode, + int sizeInBytes, + ); + + /// Wrap with native counterpart. + @Native, Handle)>( + symbol: 'InternalFlutterGpu_DeviceBuffer_InitializeWithHostData', + ) + external bool _initializeWithHostData(GpuContext gpuContext, ByteData data); + + /// Overwrite a range of bytes within an existing [DeviceBuffer]. + /// + /// This method can only be used if the [DeviceBuffer] was created with + /// [StorageMode.hostVisible]. An exception will be thrown otherwise. + /// + /// After new writes have been staged, the [DeviceBuffer.flush] should be + /// called prior to accessing the data. Otherwise, the updated data will not + /// be copied to the GPU on devices that don't have host coherent memory. + /// + /// The entire length of [sourceBytes] will be copied into the [DeviceBuffer], + /// starting at byte index [destinationOffsetInBytes] in the [DeviceBuffer]. + /// If performing this copy would result in an out of bounds write to the + /// buffer, then the write will not be attempted and will fail. + /// + /// Returns [true] if the write was successful, or [false] if the write + /// failed due to an internal error. + bool overwrite(ByteData sourceBytes, {int destinationOffsetInBytes = 0}) { + if (storageMode != StorageMode.hostVisible) { + throw Exception( + 'DeviceBuffer.overwrite can only be used with DeviceBuffers that are host visible', + ); + } + if (destinationOffsetInBytes < 0) { + throw Exception('destinationOffsetInBytes must be positive'); + } + return _overwrite(sourceBytes, destinationOffsetInBytes); + } + + @Native, Handle, Int)>( + symbol: 'InternalFlutterGpu_DeviceBuffer_Overwrite', + ) + external bool _overwrite(ByteData bytes, int destinationOffsetInBytes); + + /// Flush the contents of the [DeviceBuffer] to the GPU. + /// + /// This method can only be used if the [DeviceBuffer] was created with + /// [StorageMode.hostVisible]. An exception will be thrown otherwise. + /// + /// If [lengthInBytes] is set to -1, the entire buffer will be flushed. + /// + /// On devices with coherent host memory (memory shared between the CPU and + /// GPU), this method is a no-op. + void flush({int offsetInBytes = 0, int lengthInBytes = -1}) { + if (storageMode != StorageMode.hostVisible) { + throw Exception( + 'DeviceBuffer.flush can only be used with DeviceBuffers that are host visible', + ); + } + if (offsetInBytes < 0 || offsetInBytes >= sizeInBytes) { + throw Exception('offsetInBytes must be within the bounds of the buffer'); + } + if (lengthInBytes < -1) { + throw Exception('lengthInBytes must be either positive or -1'); + } + if (lengthInBytes != -1 && offsetInBytes + lengthInBytes > sizeInBytes) { + throw Exception( + 'The provided range must not be too large to fit within the buffer', + ); + } + _flush(offsetInBytes, lengthInBytes); + } + + @Native, Int, Int)>( + symbol: 'InternalFlutterGpu_DeviceBuffer_Flush', + ) + external void _flush(int offsetInBytes, int lengthInBytes); +} + +/// [HostBuffer] is a bump allocator that managed a [DeviceBuffer] block list. +/// +/// This is useful for chunking sparse data uploads, especially ephemeral +/// uniform or vertex data that needs to change from frame to frame. +/// +/// Different platforms have different data alignment requirements when reading +/// [DeviceBuffer] data for shader uniforms. [HostBuffer] uses +/// [GpuContext.minimumUniformByteAlignment] to align each emplacement +/// automatically, so that they may be used in uniform bindings. +/// +/// The length of each [DeviceBuffer] block is determined by +/// [blockLengthInBytes] and cannot be changed after creation of the +/// [HostBuffer]. If [HostBuffer.emplace] is given a [ByteData] that is larger +/// than [blockLengthInBytes], a new [DeviceBuffer] block is created that +/// matches the size of the oversized [ByteData]. +base class HostBuffer { + /// The default length to use for each [DeviceBuffer] block. + static const int kDefaultBlockLengthInBytes = 1024000; // 1024 Kb + + /// The length to use for each [DeviceBuffer] block. + final int blockLengthInBytes; + + static const int _kFrameCount = 4; + + /// The number of frames to cycle through before reusing device buffers. + /// Cycling to the next frame happens when [reset] is called. + int get frameCount { + return _kFrameCount; + } + + final GpuContext _gpuContext; + + /// The current frame. Rotates through [frameCount] frames when [reset] is + /// called. + int _frameCursor = 0; + + /// The buffer within the current frame to be used for the next emplacement. + int _bufferCursor = 0; + + /// The offset within the current block to be used for the next emplacement. + int _offsetCursor = 0; + + final List> _buffers = []; + + /// Creates a new HostBuffer. + HostBuffer._initialize( + this._gpuContext, { + this.blockLengthInBytes = HostBuffer.kDefaultBlockLengthInBytes, + }) { + for (int i = 0; i < frameCount; i++) { + List frame = []; + _buffers.add(frame); + _buffers[i].add(_allocateNewBlock(blockLengthInBytes)); + } + } + + DeviceBuffer _allocateNewBlock(length) { + final buffer = _gpuContext.createDeviceBuffer( + StorageMode.hostVisible, + length, + ); + return buffer; + } + + /// Prepare a new buffer range to be used for storing the given bytes. + /// Allocates a new block if necessary. + BufferView _allocateEmplacement(ByteData bytes) { + if (bytes.lengthInBytes > blockLengthInBytes) { + return BufferView( + _allocateNewBlock(bytes.lengthInBytes), + offsetInBytes: 0, + lengthInBytes: bytes.lengthInBytes, + ); + } + + int padding = + _gpuContext.minimumUniformByteAlignment - + (_offsetCursor % _gpuContext.minimumUniformByteAlignment); + // If the padding is the full alignment size, then we're already aligned. + // So reset the padding to zero. + padding %= _gpuContext.minimumUniformByteAlignment; + if (_offsetCursor + padding >= blockLengthInBytes) { + DeviceBuffer buffer = _allocateNewBlock(blockLengthInBytes); + _buffers[_frameCursor].add(buffer); + _bufferCursor++; + _offsetCursor = bytes.lengthInBytes; + + return BufferView( + buffer, + offsetInBytes: 0, + lengthInBytes: blockLengthInBytes, + ); + } + + _offsetCursor += padding; + final view = BufferView( + _buffers[_frameCursor][_bufferCursor], + offsetInBytes: _offsetCursor, + lengthInBytes: bytes.lengthInBytes, + ); + _offsetCursor += bytes.lengthInBytes; + return view; + } + + /// Append byte data to the end of the [HostBuffer] and produce a [BufferView] + /// that references the new data in the buffer. + /// + /// This method automatically inserts padding in-between emplace calls in the + /// buffer if necessary to abide by platform-specific uniform alignment + /// requirements. + /// + /// The [DeviceBuffer] referenced in the [BufferView] has already been + /// flushed, so there is no need to call [DeviceBuffer.flush] before + /// referencing it in a command. + BufferView emplace(ByteData bytes) { + BufferView view = _allocateEmplacement(bytes); + if (!view.buffer.overwrite( + bytes, + destinationOffsetInBytes: view.offsetInBytes, + )) { + throw Exception( + 'Failed to write range (offset=${view.offsetInBytes}, length=${view.lengthInBytes}) ' + 'to HostBuffer-managed DeviceBuffer (frame=$_frameCursor, buffer=$_bufferCursor, offset=$_offsetCursor).', + ); + } + + return view; + } + + /// Resets the bump allocator to the beginning of the first [DeviceBuffer] + /// block. + void reset() { + _frameCursor = (_frameCursor + 1) % frameCount; + _bufferCursor = 0; + _offsetCursor = 0; + } +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/command_buffer.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/command_buffer.dart new file mode 100644 index 0000000000000000000000000000000000000000..4d4a24ee70ea3f9e9b06cff61f63aff55ab65fd9 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/command_buffer.dart @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +typedef CompletionCallback = void Function(bool success); + +base class CommandBuffer extends NativeFieldWrapperClass1 { + final GpuContext _gpuContext; + + /// Creates a new CommandBuffer. + CommandBuffer._(this._gpuContext) { + _initialize(_gpuContext); + } + + RenderPass createRenderPass(RenderTarget renderTarget) { + return RenderPass._(_gpuContext, this, renderTarget); + } + + void submit({CompletionCallback? completionCallback}) { + String? error = _submit(completionCallback); + if (error != null) { + throw Exception(error); + } + } + + /// Wrap with native counterpart. + @Native)>( + symbol: 'InternalFlutterGpu_CommandBuffer_Initialize', + ) + external bool _initialize(GpuContext gpuContext); + + @Native, Handle)>( + symbol: 'InternalFlutterGpu_CommandBuffer_Submit', + ) + external String? _submit(CompletionCallback? completionCallback); +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/context.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/context.dart new file mode 100644 index 0000000000000000000000000000000000000000..e86ec6bd21188136ff425b350d51288dc21f3320 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/context.dart @@ -0,0 +1,187 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +/// A handle to a graphics context. Used to create and manage GPU resources. +/// +/// To obtain the default graphics context, use [getContext]. +base class GpuContext extends NativeFieldWrapperClass1 { + /// Creates a new graphics context that corresponds to the default Impeller + /// context. + GpuContext._createDefault() { + final String? error = _initializeDefault(); + if (error != null) { + throw Exception(error); + } + } + + /// A supported [PixelFormat] for textures that store 4-channel colors + /// (red/green/blue/alpha). + PixelFormat get defaultColorFormat { + return PixelFormat.values[_getDefaultColorFormat()]; + } + + /// A supported [PixelFormat] for textures that store stencil information. + /// May include a depth channel if a stencil-only format is not available. + PixelFormat get defaultStencilFormat { + return PixelFormat.values[_getDefaultStencilFormat()]; + } + + /// A supported `PixelFormat` for textures that store both a stencil and depth + /// component. This will never return a depth-only or stencil-only texture. + /// + /// May be [PixelFormat.unknown] if no suitable depth+stencil format was + /// found. + PixelFormat get defaultDepthStencilFormat { + return PixelFormat.values[_getDefaultDepthStencilFormat()]; + } + + /// The minimum alignment required when referencing uniform blocks stored in a + /// `DeviceBuffer`. + int get minimumUniformByteAlignment { + return _getMinimumUniformByteAlignment(); + } + + /// Whether the backend supports multisample anti-aliasing for offscreen + /// color and stencil attachments. A subset of OpenGLES-only devices do not + /// support this functionality. + /// + /// Any texture created via [createTexture] is an offscreen texture. + /// There is currently no way to render directly against the "onscreen" + /// texture that the framework renders to, so all Flutter GPU textures are + /// "offscreen". + bool get doesSupportOffscreenMSAA { + return _getSupportsOffscreenMSAA(); + } + + /// Allocates a new region of GPU-resident memory. + /// + /// The [storageMode] must be either [StorageMode.hostVisible] or + /// [StorageMode.devicePrivate], otherwise an exception will be thrown. + /// + /// Throws an exception if the [DeviceBuffer] creation failed. + DeviceBuffer createDeviceBuffer(StorageMode storageMode, int sizeInBytes) { + if (storageMode == StorageMode.deviceTransient) { + throw Exception( + 'DeviceBuffers cannot be set to StorageMode.deviceTransient', + ); + } + DeviceBuffer result = DeviceBuffer._initialize( + this, + storageMode, + sizeInBytes, + ); + if (!result.isValid) { + throw Exception('DeviceBuffer creation failed'); + } + return result; + } + + /// Allocates a new region of host-visible GPU-resident memory, initialized + /// with the given [data]. + /// + /// Given that the buffer will be immediately populated with [data] uploaded + /// from the host, the [StorageMode] of the new [DeviceBuffer] is + /// automatically set to [StorageMode.hostVisible]. + /// + /// Throws an exception if the [DeviceBuffer] creation failed. + DeviceBuffer createDeviceBufferWithCopy(ByteData data) { + DeviceBuffer result = DeviceBuffer._initializeWithHostData(this, data); + if (!result.isValid) { + throw Exception('DeviceBuffer creation failed'); + } + return result; + } + + /// Creates a bump allocator that managed a [DeviceBuffer] block list. + /// + /// See also [HostBuffer]. + HostBuffer createHostBuffer({ + int blockLengthInBytes = HostBuffer.kDefaultBlockLengthInBytes, + }) { + return HostBuffer._initialize(this, blockLengthInBytes: blockLengthInBytes); + } + + /// Allocates a new texture in GPU-resident memory. + /// + /// Throws an exception if the [Texture] creation failed. + Texture createTexture( + StorageMode storageMode, + int width, + int height, { + PixelFormat format = PixelFormat.r8g8b8a8UNormInt, + sampleCount = 1, + TextureCoordinateSystem coordinateSystem = + TextureCoordinateSystem.renderToTexture, + bool enableRenderTargetUsage = true, + bool enableShaderReadUsage = true, + bool enableShaderWriteUsage = false, + }) { + Texture result = Texture._initialize( + this, + storageMode, + format, + width, + height, + sampleCount, + coordinateSystem, + enableRenderTargetUsage, + enableShaderReadUsage, + enableShaderWriteUsage, + ); + if (!result.isValid) { + throw Exception('Texture creation failed'); + } + return result; + } + + /// Create a new command buffer that can be used to submit GPU commands. + CommandBuffer createCommandBuffer() { + return CommandBuffer._(this); + } + + RenderPipeline createRenderPipeline( + Shader vertexShader, + Shader fragmentShader, + ) { + return RenderPipeline._(this, vertexShader, fragmentShader); + } + + /// Associates the default Impeller context with this Context. + @Native( + symbol: 'InternalFlutterGpu_Context_InitializeDefault', + ) + external String? _initializeDefault(); + + @Native)>( + symbol: 'InternalFlutterGpu_Context_GetDefaultColorFormat', + ) + external int _getDefaultColorFormat(); + + @Native)>( + symbol: 'InternalFlutterGpu_Context_GetDefaultStencilFormat', + ) + external int _getDefaultStencilFormat(); + + @Native)>( + symbol: 'InternalFlutterGpu_Context_GetDefaultDepthStencilFormat', + ) + external int _getDefaultDepthStencilFormat(); + + @Native)>( + symbol: 'InternalFlutterGpu_Context_GetMinimumUniformByteAlignment', + ) + external int _getMinimumUniformByteAlignment(); + + @Native)>( + symbol: 'InternalFlutterGpu_Context_GetSupportsOffscreenMSAA', + ) + external bool _getSupportsOffscreenMSAA(); +} + +/// The default graphics context. +final GpuContext gpuContext = GpuContext._createDefault(); diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/formats.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/formats.dart new file mode 100644 index 0000000000000000000000000000000000000000..2bfa6eb18043e90b3331a403cc554f4c40e431fe --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/formats.dart @@ -0,0 +1,164 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +// ATTENTION! ATTENTION! ATTENTION! +// All enum classes defined in this file must exactly match the contents and +// order of the corresponding enums defined in `gpu/formats.h`. + +/// Specifies where an allocation resides and how it may be used. +enum StorageMode { + /// Allocations can be mapped onto the hosts address space and also be used by + /// the device. + hostVisible, + + /// Allocations can only be used by the device. This location is optimal for + /// use by the device. If the host needs to access these allocations, the + /// data must first be copied into a host visible allocation. + devicePrivate, + + /// Used by the device for temporary render targets. These allocations cannot + /// be copied to or from other allocations. This storage mode is only valid + /// for Textures. + /// + /// These allocations reside in tile memory which has higher bandwidth, lower + /// latency and lower power consumption. The total device memory usage is + /// also lower as a separate allocation does not need to be created in + /// device memory. Prefer using these allocations for intermediates like depth + /// and stencil buffers. + deviceTransient, +} + +enum PixelFormat { + unknown, + a8UNormInt, + r8UNormInt, + r8g8UNormInt, + r8g8b8a8UNormInt, + r8g8b8a8UNormIntSRGB, + b8g8r8a8UNormInt, + b8g8r8a8UNormIntSRGB, + r32g32b32a32Float, + r16g16b16a16Float, + b10g10r10XR, + b10g10r10XRSRGB, + b10g10r10a10XR, + // Depth and stencil formats. + s8UInt, + d24UnormS8Uint, + d32FloatS8UInt, +} + +enum TextureCoordinateSystem { + /// Alternative coordinate system used when uploading texture data from the + /// host. + /// (0, 0) is the bottom-left of the image with +Y going up. + uploadFromHost, + + /// Default coordinate system. + /// (0, 0) is the top-left of the image with +Y going down. + renderToTexture, +} + +enum BlendFactor { + zero, + one, + sourceColor, + oneMinusSourceColor, + sourceAlpha, + oneMinusSourceAlpha, + destinationColor, + oneMinusDestinationColor, + destinationAlpha, + oneMinusDestinationAlpha, + sourceAlphaSaturated, + blendColor, + oneMinusBlendColor, + blendAlpha, + oneMinusBlendAlpha, +} + +enum BlendOperation { add, subtract, reverseSubtract } + +enum LoadAction { dontCare, load, clear } + +enum StoreAction { + dontCare, + store, + multisampleResolve, + storeAndMultisampleResolve, +} + +enum ShaderStage { vertex, fragment } + +enum MinMagFilter { nearest, linear } + +enum MipFilter { nearest, linear } + +enum SamplerAddressMode { clampToEdge, repeat, mirror } + +enum IndexType { int16, int32 } + +enum PrimitiveType { triangle, triangleStrip, line, lineStrip, point } + +enum CullMode { none, frontFace, backFace } + +enum WindingOrder { clockwise, counterClockwise } + +enum PolygonMode { fill, line } + +enum CompareFunction { + /// Comparison test never passes. + never, + + /// Comparison test passes always passes. + always, + + /// Comparison test passes if new_value < current_value. + less, + + /// Comparison test passes if new_value == current_value. + equal, + + /// Comparison test passes if new_value <= current_value. + lessEqual, + + /// Comparison test passes if new_value > current_value. + greater, + + /// Comparison test passes if new_value != current_value. + notEqual, + + /// Comparison test passes if new_value >= current_value. + greaterEqual, +} + +enum StencilOperation { + /// Don't modify the current stencil value. + keep, + + /// Reset the stencil value to zero. + zero, + + /// Reset the stencil value to the reference value. + setToReferenceValue, + + /// Increment the current stencil value by 1. Clamp it to the maximum. + incrementClamp, + + /// Decrement the current stencil value by 1. Clamp it to zero. + decrementClamp, + + /// Perform a logical bitwise invert on the current stencil value. + invert, + + /// Increment the current stencil value by 1. If at maximum, set to zero. + incrementWrap, + + /// Decrement the current stencil value by 1. If at zero, set to maximum. + decrementWrap, +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/render_pass.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/render_pass.dart new file mode 100644 index 0000000000000000000000000000000000000000..86a7fadbefa43936b64dd12dcdb4dccb1f9552f5 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/render_pass.dart @@ -0,0 +1,670 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +base class ColorAttachment { + ColorAttachment({ + this.loadAction = LoadAction.clear, + this.storeAction = StoreAction.store, + vm.Vector4? clearValue = null, + required this.texture, + this.resolveTexture = null, + }) : clearValue = clearValue ?? vm.Vector4.zero(); + + LoadAction loadAction; + StoreAction storeAction; + vm.Vector4 clearValue; + + Texture texture; + Texture? resolveTexture; + + void _validate() { + if (resolveTexture != null) { + if (resolveTexture!.format != texture.format) { + throw Exception( + "ColorAttachment MSAA resolve texture must have the same format as the texture", + ); + } + if (resolveTexture!.width != texture.width || + resolveTexture!.height != texture.height) { + throw Exception( + "ColorAttachment MSAA resolve texture must have the same dimensions as the texture", + ); + } + if (resolveTexture!.sampleCount != 1) { + throw Exception( + "ColorAttachment MSAA resolve texture must have a sample count of 1", + ); + } + if (texture.sampleCount <= 1) { + throw Exception( + "ColorAttachment must have a sample count greater than 1 when a MSAA resolve texture is set", + ); + } + if (storeAction != StoreAction.multisampleResolve && + storeAction != StoreAction.storeAndMultisampleResolve) { + throw Exception( + "ColorAttachment StoreAction must be multisampleResolve or storeAndMultisampleResolve when a resolve texture is set", + ); + } + if (resolveTexture!.storageMode == StorageMode.deviceTransient) { + throw Exception( + "ColorAttachment MSAA resolve texture must not have a storage mode of deviceTransient", + ); + } + } + } +} + +base class DepthStencilAttachment { + DepthStencilAttachment({ + this.depthLoadAction = LoadAction.clear, + this.depthStoreAction = StoreAction.dontCare, + this.depthClearValue = 0.0, + this.stencilLoadAction = LoadAction.clear, + this.stencilStoreAction = StoreAction.dontCare, + this.stencilClearValue = 0, + required this.texture, + }); + + LoadAction depthLoadAction; + StoreAction depthStoreAction; + double depthClearValue; + + LoadAction stencilLoadAction; + StoreAction stencilStoreAction; + int stencilClearValue; + + Texture texture; + + void _validate() { + if (texture.storageMode == StorageMode.deviceTransient) { + if (depthLoadAction == LoadAction.load) { + throw Exception( + "DepthStencilAttachment depthLoadAction must not be load when the texture has a storage mode of deviceTransient", + ); + } + if (stencilLoadAction == LoadAction.load) { + throw Exception( + "DepthStencilAttachment stencilLoadAction must not be load when the texture has a storage mode of deviceTransient", + ); + } + } + } +} + +base class StencilConfig { + StencilConfig({ + this.compareFunction = CompareFunction.always, + this.stencilFailureOperation = StencilOperation.keep, + this.depthFailureOperation = StencilOperation.keep, + this.depthStencilPassOperation = StencilOperation.keep, + this.readMask = 0xFFFFFFFF, + this.writeMask = 0xFFFFFFFF, + }); + + CompareFunction compareFunction; + StencilOperation stencilFailureOperation; + StencilOperation depthFailureOperation; + StencilOperation depthStencilPassOperation; + int readMask; + int writeMask; +} + +// Note: When modifying this enum, also update +// `InternalFlutterGpu_RenderPass_SetStencilConfig` in `gpu/render_pass.cc`. +enum StencilFace { both, front, back } + +base class ColorBlendEquation { + ColorBlendEquation({ + this.colorBlendOperation = BlendOperation.add, + this.sourceColorBlendFactor = BlendFactor.one, + this.destinationColorBlendFactor = BlendFactor.oneMinusSourceAlpha, + this.alphaBlendOperation = BlendOperation.add, + this.sourceAlphaBlendFactor = BlendFactor.one, + this.destinationAlphaBlendFactor = BlendFactor.oneMinusSourceAlpha, + }); + + BlendOperation colorBlendOperation; + BlendFactor sourceColorBlendFactor; + BlendFactor destinationColorBlendFactor; + + BlendOperation alphaBlendOperation; + BlendFactor sourceAlphaBlendFactor; + BlendFactor destinationAlphaBlendFactor; +} + +base class SamplerOptions { + SamplerOptions({ + this.minFilter = MinMagFilter.nearest, + this.magFilter = MinMagFilter.nearest, + this.mipFilter = MipFilter.nearest, + this.widthAddressMode = SamplerAddressMode.clampToEdge, + this.heightAddressMode = SamplerAddressMode.clampToEdge, + }); + + MinMagFilter minFilter; + MinMagFilter magFilter; + MipFilter mipFilter; + SamplerAddressMode widthAddressMode; + SamplerAddressMode heightAddressMode; +} + +base class Scissor { + Scissor({this.x = 0, this.y = 0, this.width = 0, this.height = 0}); + + int x, y, width, height; + + void _validate() { + if (x < 0 || y < 0 || width < 0 || height < 0) { + throw Exception( + "Invalid values for scissor. All values should be positive.", + ); + } + } +} + +base class DepthRange { + DepthRange({this.zNear = 0.0, this.zFar = 1.0}); + + double zNear; + double zFar; +} + +base class Viewport { + Viewport({ + this.x = 0, + this.y = 0, + this.width = 0, + this.height = 0, + DepthRange? depthRange = null, + }) : this.depthRange = depthRange ?? DepthRange(); + + int x, y, width, height; + DepthRange depthRange; + + void _validate() { + if (x < 0 || y < 0 || width < 0 || height < 0) { + throw Exception( + "Invalid values for viewport. All values should be positive.", + ); + } + } +} + +base class RenderTarget { + const RenderTarget({ + this.colorAttachments = const [], + this.depthStencilAttachment, + }); + + RenderTarget.singleColor( + ColorAttachment colorAttachment, { + DepthStencilAttachment? depthStencilAttachment, + }) : this( + colorAttachments: [colorAttachment], + depthStencilAttachment: depthStencilAttachment, + ); + + _validate() { + for (final color in colorAttachments) { + color._validate(); + } + if (depthStencilAttachment != null) { + depthStencilAttachment!._validate(); + } + } + + final List colorAttachments; + final DepthStencilAttachment? depthStencilAttachment; +} + +base class RenderPass extends NativeFieldWrapperClass1 { + /// Creates a new RenderPass. + RenderPass._( + GpuContext gpuContext, + CommandBuffer commandBuffer, + RenderTarget renderTarget, + ) { + assert(() { + renderTarget._validate(); + return true; + }()); + + _initialize(); + String? error; + for (final (index, color) in renderTarget.colorAttachments.indexed) { + error = _setColorAttachment( + gpuContext, + index, + color.loadAction.index, + color.storeAction.index, + color.clearValue.r, + color.clearValue.g, + color.clearValue.b, + color.clearValue.a, + color.texture, + color.resolveTexture, + ); + if (error != null) { + throw Exception(error); + } + } + if (renderTarget.depthStencilAttachment != null) { + final ds = renderTarget.depthStencilAttachment!; + error = _setDepthStencilAttachment( + ds.depthLoadAction.index, + ds.depthStoreAction.index, + ds.depthClearValue, + ds.stencilLoadAction.index, + ds.stencilStoreAction.index, + ds.stencilClearValue, + ds.texture, + ); + if (error != null) { + throw Exception(error); + } + } + error = _begin(commandBuffer); + if (error != null) { + throw Exception(error); + } + } + + void bindPipeline(RenderPipeline pipeline) { + _bindPipeline(pipeline); + } + + void bindVertexBuffer(BufferView bufferView, int vertexCount) { + bufferView.buffer._bindAsVertexBuffer( + this, + bufferView.offsetInBytes, + bufferView.lengthInBytes, + vertexCount, + ); + } + + void bindIndexBuffer( + BufferView bufferView, + IndexType indexType, + int indexCount, + ) { + bufferView.buffer._bindAsIndexBuffer( + this, + bufferView.offsetInBytes, + bufferView.lengthInBytes, + indexType, + indexCount, + ); + } + + void bindUniform(UniformSlot slot, BufferView bufferView) { + bool success = bufferView.buffer._bindAsUniform( + this, + slot, + bufferView.offsetInBytes, + bufferView.lengthInBytes, + ); + if (!success) { + throw Exception("Failed to bind uniform"); + } + } + + void bindTexture( + UniformSlot slot, + Texture texture, { + SamplerOptions? sampler, + }) { + if (sampler == null) { + sampler = SamplerOptions(); + } + + assert(() { + if (texture.storageMode == StorageMode.deviceTransient) { + throw Exception( + "Textures with StorageMode.deviceTransient cannot be bound to a RenderPass", + ); + } + return true; + }()); + + bool success = _bindTexture( + slot.shader, + slot.uniformName, + texture, + sampler.minFilter.index, + sampler.magFilter.index, + sampler.mipFilter.index, + sampler.widthAddressMode.index, + sampler.heightAddressMode.index, + ); + if (!success) { + throw Exception("Failed to bind texture"); + } + } + + void clearBindings() { + _clearBindings(); + } + + void setColorBlendEnable(bool enable, {int colorAttachmentIndex = 0}) { + _setColorBlendEnable(colorAttachmentIndex, enable); + } + + void setColorBlendEquation( + ColorBlendEquation equation, { + int colorAttachmentIndex = 0, + }) { + _setColorBlendEquation( + colorAttachmentIndex, + equation.colorBlendOperation.index, + equation.sourceColorBlendFactor.index, + equation.destinationColorBlendFactor.index, + equation.alphaBlendOperation.index, + equation.sourceAlphaBlendFactor.index, + equation.destinationAlphaBlendFactor.index, + ); + } + + void setDepthWriteEnable(bool enable) { + _setDepthWriteEnable(enable); + } + + void setViewport(Viewport viewport) { + assert(() { + viewport._validate(); + return true; + }()); + _setViewport( + viewport.x, + viewport.y, + viewport.width, + viewport.height, + viewport.depthRange.zNear, + viewport.depthRange.zFar, + ); + } + + void setDepthCompareOperation(CompareFunction compareFunction) { + _setDepthCompareOperation(compareFunction.index); + } + + void setStencilReference(int referenceValue) { + if (referenceValue < 0 || referenceValue > 0xFFFFFFFF) { + throw Exception( + "The stencil reference value must be in the range [0, 2^32 - 1]", + ); + } + _setStencilReference(referenceValue); + } + + void setStencilConfig( + StencilConfig configuration, { + StencilFace targetFace = StencilFace.both, + }) { + if (configuration.readMask < 0 || configuration.readMask > 0xFFFFFFFF) { + throw Exception("The stencil read mask must be in the range [0, 255]"); + } + if (configuration.writeMask < 0 || configuration.writeMask > 0xFFFFFFFF) { + throw Exception("The stencil write mask must be in the range [0, 255]"); + } + _setStencilConfig( + configuration.compareFunction.index, + configuration.stencilFailureOperation.index, + configuration.depthFailureOperation.index, + configuration.depthStencilPassOperation.index, + configuration.readMask, + configuration.writeMask, + targetFace.index, + ); + } + + void setScissor(Scissor scissor) { + assert(() { + scissor._validate(); + return true; + }()); + _setScissor(scissor.x, scissor.y, scissor.width, scissor.height); + } + + void setCullMode(CullMode cullMode) { + _setCullMode(cullMode.index); + } + + void setPolygonMode(PolygonMode polygonMode) { + _setPolygonMode(polygonMode.index); + } + + void setPrimitiveType(PrimitiveType primitiveType) { + _setPrimitiveType(primitiveType.index); + } + + void setWindingOrder(WindingOrder windingOrder) { + _setWindingOrder(windingOrder.index); + } + + void draw() { + if (!_draw()) { + throw Exception("Failed to append draw"); + } + } + + /// Wrap with native counterpart. + @Native( + symbol: 'InternalFlutterGpu_RenderPass_Initialize', + ) + external void _initialize(); + + @Native< + Handle Function( + Pointer, + Pointer, + Int, + Int, + Int, + Float, + Float, + Float, + Float, + Pointer, + Handle, + ) + >(symbol: 'InternalFlutterGpu_RenderPass_SetColorAttachment') + external String? _setColorAttachment( + GpuContext context, + int colorAttachmentIndex, + int loadAction, + int storeAction, + double clearColorR, + double clearColorG, + double clearColorB, + double clearColorA, + Texture texture, + Texture? resolveTexture, + ); + + @Native< + Handle Function( + Pointer, + Int, + Int, + Float, + Int, + Int, + Int, + Pointer, + ) + >(symbol: 'InternalFlutterGpu_RenderPass_SetDepthStencilAttachment') + external String? _setDepthStencilAttachment( + int depthLoadAction, + int depthStoreAction, + double depthClearValue, + int stencilLoadAction, + int stencilStoreAction, + int stencilClearValue, + Texture texture, + ); + + @Native, Pointer)>( + symbol: 'InternalFlutterGpu_RenderPass_Begin', + ) + external String? _begin(CommandBuffer commandBuffer); + + @Native, Pointer)>( + symbol: 'InternalFlutterGpu_RenderPass_BindPipeline', + ) + external void _bindPipeline(RenderPipeline pipeline); + + @Native, Pointer, Int, Int, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_BindVertexBufferDevice', + ) + external void _bindVertexBufferDevice( + DeviceBuffer buffer, + int offsetInBytes, + int lengthInBytes, + int vertexCount, + ); + + @Native, Pointer, Int, Int, Int, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_BindIndexBufferDevice', + ) + external void _bindIndexBufferDevice( + DeviceBuffer buffer, + int offsetInBytes, + int lengthInBytes, + int indexType, + int indexCount, + ); + + @Native< + Bool Function(Pointer, Pointer, Handle, Pointer, Int, Int) + >(symbol: 'InternalFlutterGpu_RenderPass_BindUniformDevice') + external bool _bindUniformDevice( + Shader shader, + String uniformName, + DeviceBuffer buffer, + int offsetInBytes, + int lengthInBytes, + ); + + @Native, Int, Int, Int, Int, Float, Float)>( + symbol: 'InternalFlutterGpu_RenderPass_SetViewport', + ) + external void _setViewport( + int x, + int y, + int width, + int height, + double depthRangeZNear, + double depthRangeZFar, + ); + + @Native< + Bool Function( + Pointer, + Pointer, + Handle, + Pointer, + Int, + Int, + Int, + Int, + Int, + ) + >(symbol: 'InternalFlutterGpu_RenderPass_BindTexture') + external bool _bindTexture( + Shader shader, + String uniformName, + Texture texture, + int minFilter, + int magFilter, + int mipFilter, + int widthAddressMode, + int heightAddressMode, + ); + + @Native)>( + symbol: 'InternalFlutterGpu_RenderPass_ClearBindings', + ) + external void _clearBindings(); + + @Native, Int, Bool)>( + symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEnable', + ) + external void _setColorBlendEnable(int colorAttachmentIndex, bool enable); + + @Native, Int, Int, Int, Int, Int, Int, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetColorBlendEquation', + ) + external void _setColorBlendEquation( + int colorAttachmentIndex, + int colorBlendOperation, + int sourceColorBlendFactor, + int destinationColorBlendFactor, + int alphaBlendOperation, + int sourceAlphaBlendFactor, + int destinationAlphaBlendFactor, + ); + + @Native, Bool)>( + symbol: 'InternalFlutterGpu_RenderPass_SetDepthWriteEnable', + ) + external void _setDepthWriteEnable(bool enable); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetDepthCompareOperation', + ) + external void _setDepthCompareOperation(int compareOperation); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetStencilReference', + ) + external void _setStencilReference(int referenceValue); + + @Native, Int, Int, Int, Int, Int, Int, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetStencilConfig', + ) + external void _setStencilConfig( + int compareFunction, + int stencilFailureOperation, + int depthFailureOperation, + int depthStencilPassOperation, + int readMask, + int writeMask, + int target_face, + ); + + @Native, Int, Int, Int, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetScissor', + ) + external void _setScissor(int x, int y, int width, int height); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetCullMode', + ) + external void _setCullMode(int cullMode); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetPrimitiveType', + ) + external void _setPrimitiveType(int primitiveType); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetWindingOrder', + ) + external void _setWindingOrder(int windingOrder); + + @Native, Int)>( + symbol: 'InternalFlutterGpu_RenderPass_SetPolygonMode', + ) + external void _setPolygonMode(int polygonMode); + + @Native)>( + symbol: 'InternalFlutterGpu_RenderPass_Draw', + ) + external bool _draw(); +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/render_pipeline.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/render_pipeline.dart new file mode 100644 index 0000000000000000000000000000000000000000..0086d0de9849430dab4bd48bd3636f45156c6908 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/render_pipeline.dart @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +base class RenderPipeline extends NativeFieldWrapperClass1 { + /// Creates a new RenderPipeline. + RenderPipeline._( + GpuContext gpuContext, + Shader vertexShader, + Shader fragmentShader, + ) : vertexShader = vertexShader, + fragmentShader = fragmentShader { + String? error = _initialize(gpuContext, vertexShader, fragmentShader); + if (error != null) { + throw Exception(error); + } + } + + final Shader vertexShader; + final Shader fragmentShader; + + /// Wrap with native counterpart. + @Native, Pointer, Pointer)>( + symbol: 'InternalFlutterGpu_RenderPipeline_Initialize', + ) + external String? _initialize( + GpuContext gpuContext, + Shader vertexShader, + Shader fragmentShader, + ); +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/shader.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/shader.dart new file mode 100644 index 0000000000000000000000000000000000000000..526bf927536ab3b66bb8413b33441c0ed3e53a71 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/shader.dart @@ -0,0 +1,54 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +base class UniformSlot { + UniformSlot._(this.shader, this.uniformName); + final Shader shader; + final String uniformName; + + /// The reflected total size of a shader's uniform struct by name. + /// + /// Returns [null] if the shader does not contain a uniform struct with the + /// given name. + int? get sizeInBytes { + int size = shader._getUniformStructSize(uniformName); + return size < 0 ? null : size; + } + + /// Get the reflected offset of a named member in the uniform struct. + /// + /// Returns [null] if the shader does not contain a uniform struct with the + /// given name, or if the uniform struct does not contain a member with the + /// given name. + int? getMemberOffsetInBytes(String memberName) { + int offset = shader._getUniformMemberOffset(uniformName, memberName); + return offset < 0 ? null : offset; + } +} + +base class Shader extends NativeFieldWrapperClass1 { + // [Shader] handles are instantiated when interacting with a [ShaderLibrary]. + Shader._(); + + UniformSlot getUniformSlot(String uniformName) { + return UniformSlot._(this, uniformName); + } + + @Native, Handle)>( + symbol: 'InternalFlutterGpu_Shader_GetUniformStructSize', + ) + external int _getUniformStructSize(String uniformStructName); + + @Native, Handle, Handle)>( + symbol: 'InternalFlutterGpu_Shader_GetUniformMemberOffset', + ) + external int _getUniformMemberOffset( + String uniformStructName, + String memberName, + ); +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/shader_library.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/shader_library.dart new file mode 100644 index 0000000000000000000000000000000000000000..b4c41f08bf70e5421caf540bbfb52d8a8436809b --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/shader_library.dart @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +base class ShaderLibrary extends NativeFieldWrapperClass1 { + static ShaderLibrary? fromAsset(String assetName) { + final lib = ShaderLibrary._(); + final error = lib._initializeWithAsset(assetName); + if (error != null) { + throw Exception("Failed to initialize ShaderLibrary: ${error}"); + } + return lib; + } + + ShaderLibrary._(); + + // Hold a Dart-side reference to shaders in the library as they're wrapped for + // the first time. This prevents the wrapper from getting prematurely + // destroyed. + final Map shaders_ = {}; + + Shader? operator [](String shaderName) { + // This `flutter_gpu` library isn't always registered as part of the builtin + // DartClassLibrary, and so we can't instantiate the Dart classes on the + // engine side. + // Providing a new wrapper to [_getShader] for wrapping the native + // counterpart (if it hasn't been wrapped already) is a hack to work around + // this. + return shaders_.putIfAbsent( + shaderName, + () => _getShader(shaderName, Shader._()), + ); + } + + @Native( + symbol: 'InternalFlutterGpu_ShaderLibrary_InitializeWithAsset', + ) + external String? _initializeWithAsset(String assetName); + + @Native, Handle, Handle)>( + symbol: 'InternalFlutterGpu_ShaderLibrary_GetShader', + ) + external Shader? _getShader(String shaderName, Shader shaderWrapper); +} diff --git a/flutter/engine/src/flutter/lib/gpu/lib/src/texture.dart b/flutter/engine/src/flutter/lib/gpu/lib/src/texture.dart new file mode 100644 index 0000000000000000000000000000000000000000..4c266e37c88f2d1648bbfad8daf8744cea3e5227 --- /dev/null +++ b/flutter/engine/src/flutter/lib/gpu/lib/src/texture.dart @@ -0,0 +1,165 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +part of flutter_gpu; + +base class Texture extends NativeFieldWrapperClass1 { + bool _valid = false; + get isValid { + return _valid; + } + + /// Creates a new Texture. + Texture._initialize( + GpuContext gpuContext, + this.storageMode, + this.format, + this.width, + this.height, + this.sampleCount, + TextureCoordinateSystem coordinateSystem, + this.enableRenderTargetUsage, + this.enableShaderReadUsage, + this.enableShaderWriteUsage, + ) : _coordinateSystem = coordinateSystem { + if (sampleCount != 1 && sampleCount != 4) { + throw Exception("Only a sample count of 1 or 4 is currently supported"); + } + _valid = _initialize( + gpuContext, + storageMode.index, + format.index, + width, + height, + sampleCount, + coordinateSystem.index, + enableRenderTargetUsage, + enableShaderReadUsage, + enableShaderWriteUsage, + ); + } + + final StorageMode storageMode; + final PixelFormat format; + final int width; + final int height; + final int sampleCount; + + /// Enable using this texture as a render pass attachment. + final bool enableRenderTargetUsage; + + /// Enable reading or sampling from this texture in a shader. + final bool enableShaderReadUsage; + + /// Enable writing to the texture in a shader. + /// + /// Note that this is distinct from [enableRenderTargetUsage]. + final bool enableShaderWriteUsage; + + TextureCoordinateSystem _coordinateSystem; + TextureCoordinateSystem get coordinateSystem { + return _coordinateSystem; + } + + set coordinateSystem(TextureCoordinateSystem value) { + value; + _setCoordinateSystem(value.index); + } + + int get bytesPerTexel { + return _bytesPerTexel(); + } + + int getBaseMipLevelSizeInBytes() { + return bytesPerTexel * width * height; + } + + /// Overwrite the entire base mipmap level of this [Texture]. + /// + /// This method can only be used if the [Texture] was created with + /// [StorageMode.hostVisible]. An exception will be thrown otherwise. + /// + /// The length of [sourceBytes] must be exactly the size of the base mip + /// level, otherwise an exception will be thrown. The size of the base mip + /// level is always `width * height * bytesPerPixel`. + /// + /// Throws an exception if the write failed due to an internal error. + void overwrite(ByteData sourceBytes) { + if (storageMode != StorageMode.hostVisible) { + throw Exception( + 'Texture.overwrite can only be used with Textures that are host visible', + ); + } + int baseMipSize = getBaseMipLevelSizeInBytes(); + if (sourceBytes.lengthInBytes != baseMipSize) { + throw Exception( + 'The length of sourceBytes (bytes: ${sourceBytes.lengthInBytes}) must exactly match the size of the base mip level (bytes: ${baseMipSize})', + ); + } + bool success = _overwrite(sourceBytes); + if (!success) { + throw Exception("Texture overwrite failed"); + } + } + + ui.Image asImage() { + if (!enableShaderReadUsage) { + throw Exception( + 'Only shader readable Flutter GPU textures can be used as UI Images', + ); + } + return _asImage(); + } + + /// Wrap with native counterpart. + @Native< + Bool Function( + Handle, + Pointer, + Int, + Int, + Int, + Int, + Int, + Int, + Bool, + Bool, + Bool, + ) + >(symbol: 'InternalFlutterGpu_Texture_Initialize') + external bool _initialize( + GpuContext gpuContext, + int storageMode, + int format, + int width, + int height, + int sampleCount, + int coordinateSystem, + bool enableRenderTargetUsage, + bool enableShaderReadUsage, + bool enableShaderWriteUsage, + ); + + @Native( + symbol: 'InternalFlutterGpu_Texture_SetCoordinateSystem', + ) + external void _setCoordinateSystem(int coordinateSystem); + + @Native)>( + symbol: 'InternalFlutterGpu_Texture_BytesPerTexel', + ) + external int _bytesPerTexel(); + + @Native, Handle)>( + symbol: 'InternalFlutterGpu_Texture_Overwrite', + ) + external bool _overwrite(ByteData bytes); + + @Native)>( + symbol: 'InternalFlutterGpu_Texture_AsImage', + ) + external ui.Image _asImage(); +} diff --git a/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/33_OpTypeFunction.frag b/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/33_OpTypeFunction.frag new file mode 100644 index 0000000000000000000000000000000000000000..b9db34335a0be56729e8f5898f112455787a2e0a --- /dev/null +++ b/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/33_OpTypeFunction.frag @@ -0,0 +1,23 @@ +#version 320 es + +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +precision highp float; + +layout(location = 0) out vec4 fragColor; + +layout(location = 0) uniform float a; + +float zero() { + return 0.0; +} + +float one() { + return a; +} + +void main() { + fragColor = vec4(zero(), one(), zero(), one()); +} diff --git a/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/BUILD.gn b/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b0c3c8a79ac5c18d0dcffb9646fd27e90428536c --- /dev/null +++ b/flutter/engine/src/flutter/lib/ui/fixtures/shaders/supported_op_shaders/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright 2013 The Flutter Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/compiled_action.gni") +import("//flutter/impeller/tools/impeller.gni") +import("//flutter/testing/testing.gni") + +if (enable_unittests) { + test_shaders = [ + "127_OpFNegate.frag", + "129_OpFAdd.frag", + "131_OpFSub.frag", + "142_OpVectorTimesScalar.frag", + "143_OpMatrixTimesScalar.frag", + "144_OpVectorTimesMatrix.frag", + "145_OpMatrixTimesVector.frag", + "146_OpMatrixTimesMatrix.frag", + "148_OpDot.frag", + "164_OpLogicalEqual.frag", + "165_OpLogicalNotEqual.frag", + "166_OpLogicalOr.frag", + "167_OpLogicalAnd.frag", + "168_OpLogicalNot.frag", + "180_OpFOrdEqual.frag", + "183_OpFUnordNotEqual.frag", + "184_OpFOrdLessThan.frag", + "186_OpFOrdGreaterThan.frag", + "188_OpFOrdLessThanEqual.frag", + "190_OpFOrdGreaterThanEqual.frag", + "19_OpTypeVoid.frag", + "20_OpTypeBool.frag", + "21_OpTypeInt.frag", + "22_OpTypeFloat.frag", + "23_OpTypeVector.frag", + "246_OpLoopMerge.frag", + "24_OpTypeMatrix.frag", + "250_OpBranchConditional.frag", + "33_OpTypeFunction.frag", + ] + + group("supported_op_shaders") { + testonly = true + deps = [ ":fixtures" ] + } + + impellerc("compile_supported_op_shaders") { + shaders = test_shaders + shader_target_flags = [ "--sksl" ] + intermediates_subdir = "iplr" + sl_file_extension = "iplr" + iplr = true + } + + test_fixtures("fixtures") { + deps = [ ":compile_supported_op_shaders" ] + fixtures = get_target_outputs(":compile_supported_op_shaders") + dest = "$root_gen_dir/flutter/lib/ui" + } +} diff --git a/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm64-profile/flutter.jar b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm64-profile/flutter.jar new file mode 100644 index 0000000000000000000000000000000000000000..859777f7f5fe1b9008fb3ada59eca86857213b35 --- /dev/null +++ b/novelforge-project/agent-workspace/flutter/bin/cache/artifacts/engine/android-arm64-profile/flutter.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:877ac96f4c0ce9d00d318b5596186e8fbde742c49dd5e814937256b28b09b68c +size 128