text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 The Flutter Authors. All 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_MESSAGE_LOOP_IMPL_H_ #define FLUTTER_FML_MESSAGE_LOOP_IMPL_H_ #include <atomic> #include <deque> #include <map> #include <mutex> #include <queue> #include <utility> #include "flutter/fml/closure.h" #include "flutter/fml/delayed_task.h" #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_counted.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/message_loop_task_queues.h" #include "flutter/fml/time/time_point.h" #include "flutter/fml/wakeable.h" namespace fml { /// An abstract class that represents the differences in implementation of a \p /// fml::MessageLoop depending on the platform. /// \see fml::MessageLoop /// \see fml::MessageLoopAndroid /// \see fml::MessageLoopDarwin class MessageLoopImpl : public Wakeable, public fml::RefCountedThreadSafe<MessageLoopImpl> { public: static fml::RefPtr<MessageLoopImpl> Create(); virtual ~MessageLoopImpl(); virtual void Run() = 0; virtual void Terminate() = 0; void PostTask(const fml::closure& task, fml::TimePoint target_time); void AddTaskObserver(intptr_t key, const fml::closure& callback); void RemoveTaskObserver(intptr_t key); void DoRun(); void DoTerminate(); virtual TaskQueueId GetTaskQueueId() const; protected: // Exposed for the embedder shell which allows clients to poll for events // instead of dedicating a thread to the message loop. friend class MessageLoop; void RunExpiredTasksNow(); void RunSingleExpiredTaskNow(); protected: MessageLoopImpl(); private: fml::MessageLoopTaskQueues* task_queue_; TaskQueueId queue_id_; std::atomic_bool terminated_; void FlushTasks(FlushType type); FML_DISALLOW_COPY_AND_ASSIGN(MessageLoopImpl); }; } // namespace fml #endif // FLUTTER_FML_MESSAGE_LOOP_IMPL_H_
engine/fml/message_loop_impl.h/0
{ "file_path": "engine/fml/message_loop_impl.h", "repo_id": "engine", "token_count": 678 }
222
// Copyright 2013 The Flutter Authors. All 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_PLATFORM_ANDROID_JNI_WEAK_REF_H_ #define FLUTTER_FML_PLATFORM_ANDROID_JNI_WEAK_REF_H_ #include <jni.h> #include "flutter/fml/platform/android/scoped_java_ref.h" namespace fml { namespace jni { // Manages WeakGlobalRef lifecycle. // This class is not thread-safe w.r.t. get() and reset(). Multiple threads may // safely use get() concurrently, but if the user calls reset() (or of course, // calls the destructor) they'll need to provide their own synchronization. class JavaObjectWeakGlobalRef { public: JavaObjectWeakGlobalRef(); JavaObjectWeakGlobalRef(const JavaObjectWeakGlobalRef& orig); JavaObjectWeakGlobalRef(JNIEnv* env, jobject obj); virtual ~JavaObjectWeakGlobalRef(); void operator=(const JavaObjectWeakGlobalRef& rhs); ScopedJavaLocalRef<jobject> get(JNIEnv* env) const; bool is_empty() const { return obj_ == NULL; } void reset(); private: void Assign(const JavaObjectWeakGlobalRef& rhs); jweak obj_; }; // Get the real object stored in the weak reference returned as a // ScopedJavaLocalRef. ScopedJavaLocalRef<jobject> GetRealObject(JNIEnv* env, jweak obj); } // namespace jni } // namespace fml #endif // FLUTTER_FML_PLATFORM_ANDROID_JNI_WEAK_REF_H_
engine/fml/platform/android/jni_weak_ref.h/0
{ "file_path": "engine/fml/platform/android/jni_weak_ref.h", "repo_id": "engine", "token_count": 458 }
223
// Copyright 2013 The Flutter Authors. All 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_PLATFORM_DARWIN_SCOPED_BLOCK_H_ #define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_ #include <Block.h> #include "flutter/fml/compiler_specific.h" #include "flutter/fml/platform/darwin/scoped_typeref.h" #if defined(__has_feature) && __has_feature(objc_arc) #define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) (__bridge TYPE)(VALUE) #else #define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) VALUE #endif namespace fml { namespace internal { template <typename B> struct ScopedBlockTraits { static B InvalidValue() { return nullptr; } static B Retain(B block) { return BASE_MAC_BRIDGE_CAST( B, Block_copy(BASE_MAC_BRIDGE_CAST(const void*, block))); } static void Release(B block) { Block_release(BASE_MAC_BRIDGE_CAST(const void*, block)); } }; } // namespace internal // ScopedBlock<> is patterned after ScopedCFTypeRef<>, but uses Block_copy() and // Block_release() instead of CFRetain() and CFRelease(). template <typename B> using ScopedBlock = ScopedTypeRef<B, internal::ScopedBlockTraits<B>>; } // namespace fml #undef BASE_MAC_BRIDGE_CAST #endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_
engine/fml/platform/darwin/scoped_block.h/0
{ "file_path": "engine/fml/platform/darwin/scoped_block.h", "repo_id": "engine", "token_count": 492 }
224
// Copyright 2013 The Flutter Authors. 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/message_loop.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/fml/platform/darwin/weak_nsobject.h" #include "flutter/fml/task_runner.h" #include "flutter/fml/thread.h" #include "gtest/gtest.h" namespace fml { namespace { TEST(WeakNSObjectTest, WeakNSObject) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); EXPECT_TRUE(w1); p1.reset(); EXPECT_FALSE(w1); } TEST(WeakNSObjectTest, MultipleWeakNSObject) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) WeakNSObject<NSObject> w2(w1); EXPECT_TRUE(w1); EXPECT_TRUE(w2); EXPECT_TRUE(w1.get() == w2.get()); p1.reset(); EXPECT_FALSE(w1); EXPECT_FALSE(w2); } TEST(WeakNSObjectTest, WeakNSObjectDies) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); { WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); EXPECT_TRUE(w1); } } TEST(WeakNSObjectTest, WeakNSObjectReset) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); EXPECT_TRUE(w1); w1.reset(); EXPECT_FALSE(w1); EXPECT_TRUE(p1); EXPECT_TRUE([p1 description]); } TEST(WeakNSObjectTest, WeakNSObjectEmpty) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObject<NSObject> w1; EXPECT_FALSE(w1); WeakNSObjectFactory factory(p1.get()); w1 = factory.GetWeakNSObject(); EXPECT_TRUE(w1); p1.reset(); EXPECT_FALSE(w1); } TEST(WeakNSObjectTest, WeakNSObjectCopy) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) WeakNSObject<NSObject> w2(w1); EXPECT_TRUE(w1); EXPECT_TRUE(w2); p1.reset(); EXPECT_FALSE(w1); EXPECT_FALSE(w2); } TEST(WeakNSObjectTest, WeakNSObjectAssignment) { scoped_nsobject<NSObject> p1([[NSObject alloc] init]); WeakNSObjectFactory factory(p1.get()); WeakNSObject<NSObject> w1 = factory.GetWeakNSObject(); // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) WeakNSObject<NSObject> w2 = w1; EXPECT_TRUE(w1); EXPECT_TRUE(w2); p1.reset(); EXPECT_FALSE(w1); EXPECT_FALSE(w2); } } // namespace } // namespace fml
engine/fml/platform/darwin/weak_nsobject_unittests.mm/0
{ "file_path": "engine/fml/platform/darwin/weak_nsobject_unittests.mm", "repo_id": "engine", "token_count": 1104 }
225
// Copyright 2013 The Flutter Authors. All 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_PLATFORM_WIN_MESSAGE_LOOP_WIN_H_ #define FLUTTER_FML_PLATFORM_WIN_MESSAGE_LOOP_WIN_H_ #include <windows.h> #include <atomic> #include "flutter/fml/macros.h" #include "flutter/fml/message_loop_impl.h" #include "flutter/fml/unique_object.h" namespace fml { class MessageLoopWin : public MessageLoopImpl { private: struct UniqueHandleTraits { static HANDLE InvalidValue() { return NULL; } static bool IsValid(HANDLE value) { return value != NULL; } static void Free(HANDLE value) { CloseHandle(value); } }; bool running_; fml::UniqueObject<HANDLE, UniqueHandleTraits> timer_; uint32_t timer_resolution_; MessageLoopWin(); ~MessageLoopWin() override; void Run() override; void Terminate() override; void WakeUp(fml::TimePoint time_point) override; FML_FRIEND_MAKE_REF_COUNTED(MessageLoopWin); FML_FRIEND_REF_COUNTED_THREAD_SAFE(MessageLoopWin); FML_DISALLOW_COPY_AND_ASSIGN(MessageLoopWin); }; } // namespace fml #endif // FLUTTER_FML_PLATFORM_WIN_MESSAGE_LOOP_WIN_H_
engine/fml/platform/win/message_loop_win.h/0
{ "file_path": "engine/fml/platform/win/message_loop_win.h", "repo_id": "engine", "token_count": 440 }
226
// Copyright 2013 The Flutter Authors. All 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_STATUS_H_ #define FLUTTER_FML_STATUS_H_ #include <string_view> namespace fml { enum class StatusCode { kOk, kCancelled, kUnknown, kInvalidArgument, kDeadlineExceeded, kNotFound, kAlreadyExists, kPermissionDenied, kResourceExhausted, kFailedPrecondition, kAborted, kOutOfRange, kUnimplemented, kInternal, kUnavailable, kDataLoss, kUnauthenticated }; /// Class that represents the resolution of the execution of a procedure. This /// is used similarly to how exceptions might be used, typically as the return /// value to a synchronous procedure or an argument to an asynchronous callback. class Status final { public: /// Creates an 'ok' status. Status(); Status(fml::StatusCode code, std::string_view message); fml::StatusCode code() const; /// A noop that helps with static analysis tools if you decide to ignore an /// error. void IgnoreError() const; /// @return 'true' when the code is kOk. bool ok() const; std::string_view message() const; private: fml::StatusCode code_; std::string_view message_; }; inline Status::Status() : code_(fml::StatusCode::kOk), message_() {} inline Status::Status(fml::StatusCode code, std::string_view message) : code_(code), message_(message) {} inline fml::StatusCode Status::code() const { return code_; } inline void Status::IgnoreError() const { // noop } inline bool Status::ok() const { return code_ == fml::StatusCode::kOk; } inline std::string_view Status::message() const { return message_; } } // namespace fml #endif // FLUTTER_FML_STATUS_H_
engine/fml/status.h/0
{ "file_path": "engine/fml/status.h", "repo_id": "engine", "token_count": 572 }
227
// Copyright 2013 The Flutter Authors. All 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_SYNC_SWITCH_H_ #define FLUTTER_FML_SYNCHRONIZATION_SYNC_SWITCH_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #include "flutter/fml/synchronization/shared_mutex.h" namespace fml { /// A threadsafe structure that allows you to switch between 2 different /// execution paths. /// /// Execution and setting the switch is exclusive, i.e. only one will happen /// at a time. class SyncSwitch { public: /// Observes changes to the SyncSwitch. class Observer { public: virtual ~Observer() = default; /// `new_is_disabled` not guaranteed to be the value of the SyncSwitch /// during execution, it should be checked with calls to /// SyncSwitch::Execute. virtual void OnSyncSwitchUpdate(bool new_is_disabled) = 0; }; /// Represents the 2 code paths available when calling |SyncSwitch::Execute|. struct Handlers { /// Sets the handler that will be executed if the |SyncSwitch| is true. Handlers& SetIfTrue(const std::function<void()>& handler); /// Sets the handler that will be executed if the |SyncSwitch| is false. Handlers& SetIfFalse(const std::function<void()>& handler); std::function<void()> true_handler = [] {}; std::function<void()> false_handler = [] {}; }; /// Create a |SyncSwitch| with the specified value. /// /// @param[in] value Default value for the |SyncSwitch|. explicit SyncSwitch(bool value = false); /// Diverge execution between true and false values of the SyncSwitch. /// /// This can be called on any thread. Note that attempting to call /// |SetSwitch| inside of the handlers will result in a self deadlock. /// /// @param[in] handlers Called for the correct value of the |SyncSwitch|. void Execute(const Handlers& handlers) const; /// Set the value of the SyncSwitch. /// /// This can be called on any thread. /// /// @param[in] value New value for the |SyncSwitch|. void SetSwitch(bool value); /// Threadsafe. void AddObserver(Observer* observer) const; /// Threadsafe. void RemoveObserver(Observer* observer) const; private: mutable std::unique_ptr<fml::SharedMutex> mutex_; mutable std::vector<Observer*> observers_; bool value_; FML_DISALLOW_COPY_AND_ASSIGN(SyncSwitch); }; } // namespace fml #endif // FLUTTER_FML_SYNCHRONIZATION_SYNC_SWITCH_H_
engine/fml/synchronization/sync_switch.h/0
{ "file_path": "engine/fml/synchronization/sync_switch.h", "repo_id": "engine", "token_count": 805 }
228
// Copyright 2013 The Flutter Authors. All 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_TIME_CHRONO_TIMESTAMP_PROVIDER_H_ #define FLUTTER_FML_TIME_CHRONO_TIMESTAMP_PROVIDER_H_ #include "flutter/fml/time/timestamp_provider.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_point.h" namespace fml { /// TimestampProvider implementation that is backed by std::chrono::steady_clock /// meant to be used only in tests for `fml`. Other components needing the /// current time ticks since epoch should instantiate their own time stamp /// provider backed by Dart clock. class ChronoTimestampProvider : TimestampProvider { public: static ChronoTimestampProvider& Instance() { static ChronoTimestampProvider instance; return instance; } ~ChronoTimestampProvider() override; fml::TimePoint Now() override; private: ChronoTimestampProvider(); FML_DISALLOW_COPY_AND_ASSIGN(ChronoTimestampProvider); }; fml::TimePoint ChronoTicksSinceEpoch(); } // namespace fml #endif // FLUTTER_FML_TIME_CHRONO_TIMESTAMP_PROVIDER_H_
engine/fml/time/chrono_timestamp_provider.h/0
{ "file_path": "engine/fml/time/chrono_timestamp_provider.h", "repo_id": "engine", "token_count": 372 }
229
# Copyright 2013 The Flutter 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/glfw/glfw_args.gni") import("tools/impeller.gni") config("impeller_public_config") { include_dirs = [ ".." ] defines = [] if (impeller_debug) { defines += [ "IMPELLER_DEBUG=1" ] } if (impeller_capture) { defines += [ "IMPELLER_ENABLE_CAPTURE=1" ] } if (impeller_supports_rendering) { defines += [ "IMPELLER_SUPPORTS_RENDERING=1" ] } if (impeller_enable_metal) { defines += [ "IMPELLER_ENABLE_METAL=1" ] } if (impeller_enable_opengles) { defines += [ "IMPELLER_ENABLE_OPENGLES=1" ] } if (impeller_enable_vulkan) { defines += [ "IMPELLER_ENABLE_VULKAN=1" ] } if (impeller_trace_all_gl_calls) { defines += [ "IMPELLER_TRACE_ALL_GL_CALLS" ] } if (is_win) { defines += [ # TODO(dnfield): https://github.com/flutter/flutter/issues/50053 "_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING", ] } if (impeller_enable_3d) { defines += [ "IMPELLER_ENABLE_3D" ] } } group("impeller") { public_deps = [ "base", "geometry", "tessellator", ] if (impeller_supports_rendering) { public_deps += [ "aiks", "display_list", "entity", "renderer", "renderer/backend", "typographer/backends/skia:typographer_skia_backend", ] } } impeller_component("impeller_unittests") { target_type = "executable" testonly = true deps = [ "base:base_unittests", "compiler:compiler_unittests", "core:allocator_unittests", "display_list:skia_conversions_unittests", "geometry:geometry_unittests", "renderer/backend/metal:metal_unittests", "runtime_stage:runtime_stage_unittests", "scene/importer:importer_unittests", "shader_archive:shader_archive_unittests", "tessellator:tessellator_unittests", ] if (impeller_supports_rendering) { deps += [ "aiks:aiks_unittests", "display_list:display_list_unittests", "entity:entity_unittests", "fixtures", "geometry:geometry_unittests", "playground", "renderer:renderer_unittests", "scene:scene_unittests", "typographer:typographer_unittests", ] } if (impeller_enable_vulkan) { deps += [ "//flutter/impeller/renderer/backend/vulkan:vulkan_unittests" ] } if (impeller_enable_opengles) { deps += [ "//flutter/impeller/renderer/backend/gles:gles_unittests" ] } if (glfw_vulkan_library != "") { deps += [ "//flutter/third_party/swiftshader", "//flutter/third_party/vulkan-deps/vulkan-loader/src:libvulkan", "//third_party/vulkan_validation_layers", "//third_party/vulkan_validation_layers:vulkan_gen_json_files", ] } if (impeller_enable_compute) { deps += [ "renderer:compute_tessellation_unittests" ] } } if (impeller_supports_rendering) { impeller_component("impeller_dart_unittests") { target_type = "executable" testonly = true deps = [ "renderer:renderer_dart_unittests" ] } }
engine/impeller/BUILD.gn/0
{ "file_path": "engine/impeller/BUILD.gn", "repo_id": "engine", "token_count": 1404 }
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. #include "flutter/benchmarking/benchmarking.h" #include "impeller/aiks/canvas.h" namespace impeller { namespace { using CanvasCallback = size_t (*)(Canvas&); size_t DrawRect(Canvas& canvas) { for (auto i = 0; i < 500; i++) { canvas.DrawRect(Rect::MakeLTRB(0, 0, 100, 100), {.color = Color::DarkKhaki()}); } return 500; } size_t DrawCircle(Canvas& canvas) { for (auto i = 0; i < 500; i++) { canvas.DrawCircle({100, 100}, 5, {.color = Color::DarkKhaki()}); } return 500; } size_t DrawLine(Canvas& canvas) { for (auto i = 0; i < 500; i++) { canvas.DrawLine({0, 0}, {100, 100}, {.color = Color::DarkKhaki()}); } return 500; } } // namespace // A set of benchmarks that measures the CPU cost of encoding canvas operations. // These benchmarks do not measure the cost of conversion through the HAL, no // do they measure the GPU side cost of executing the required shader programs. template <class... Args> static void BM_CanvasRecord(benchmark::State& state, Args&&... args) { auto args_tuple = std::make_tuple(std::move(args)...); auto test_proc = std::get<CanvasCallback>(args_tuple); size_t op_count = 0u; size_t canvas_count = 0u; while (state.KeepRunning()) { // A new canvas is allocated for each iteration to avoid the benchmark // becoming a measurement of only the entity vector re-allocation time. Canvas canvas; op_count += test_proc(canvas); canvas_count++; } state.counters["TotalOpCount"] = op_count; state.counters["TotalCanvasCount"] = canvas_count; } BENCHMARK_CAPTURE(BM_CanvasRecord, draw_rect, &DrawRect); BENCHMARK_CAPTURE(BM_CanvasRecord, draw_circle, &DrawCircle); BENCHMARK_CAPTURE(BM_CanvasRecord, draw_line, &DrawLine); } // namespace impeller
engine/impeller/aiks/canvas_benchmarks.cc/0
{ "file_path": "engine/impeller/aiks/canvas_benchmarks.cc", "repo_id": "engine", "token_count": 687 }
231
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_AIKS_PAINT_PASS_DELEGATE_H_ #define FLUTTER_IMPELLER_AIKS_PAINT_PASS_DELEGATE_H_ #include <optional> #include "flutter/fml/macros.h" #include "impeller/aiks/paint.h" #include "impeller/entity/entity_pass_delegate.h" namespace impeller { class PaintPassDelegate final : public EntityPassDelegate { public: explicit PaintPassDelegate(Paint paint); // |EntityPassDelgate| ~PaintPassDelegate() override; // |EntityPassDelgate| bool CanElide() override; // |EntityPassDelgate| bool CanCollapseIntoParentPass(EntityPass* entity_pass) override; // |EntityPassDelgate| std::shared_ptr<Contents> CreateContentsForSubpassTarget( std::shared_ptr<Texture> target, const Matrix& effect_transform) override; // |EntityPassDelgate| std::shared_ptr<FilterContents> WithImageFilter( const FilterInput::Variant& input, const Matrix& effect_transform) const override; private: const Paint paint_; PaintPassDelegate(const PaintPassDelegate&) = delete; PaintPassDelegate& operator=(const PaintPassDelegate&) = delete; }; /// A delegate that attempts to forward opacity from a save layer to /// child contents. /// /// Currently this has a hardcoded limit of 3 entities in a pass, and /// cannot forward to child subpass delegates. class OpacityPeepholePassDelegate final : public EntityPassDelegate { public: explicit OpacityPeepholePassDelegate(Paint paint); // |EntityPassDelgate| ~OpacityPeepholePassDelegate() override; // |EntityPassDelgate| bool CanElide() override; // |EntityPassDelgate| bool CanCollapseIntoParentPass(EntityPass* entity_pass) override; // |EntityPassDelgate| std::shared_ptr<Contents> CreateContentsForSubpassTarget( std::shared_ptr<Texture> target, const Matrix& effect_transform) override; // |EntityPassDelgate| std::shared_ptr<FilterContents> WithImageFilter( const FilterInput::Variant& input, const Matrix& effect_transform) const override; private: const Paint paint_; OpacityPeepholePassDelegate(const OpacityPeepholePassDelegate&) = delete; OpacityPeepholePassDelegate& operator=(const OpacityPeepholePassDelegate&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_AIKS_PAINT_PASS_DELEGATE_H_
engine/impeller/aiks/paint_pass_delegate.h/0
{ "file_path": "engine/impeller/aiks/paint_pass_delegate.h", "repo_id": "engine", "token_count": 798 }
232
// Copyright 2013 The Flutter Authors. 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<MyMaskBits>; 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(); int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) FML_ALLOW_UNUSED_LOCAL(b); 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); int b = f.a; // NOLINT(clang-analyzer-deadcode.DeadStores) FML_ALLOW_UNUSED_LOCAL(b); } // 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<std::thread> 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<std::thread> 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<int> wrapper; std::future future = wrapper.get_future(); wrapper.set_value(123); ASSERT_EQ(future.get(), 123); } TEST(BaseTest, NoExceptionPromiseEmpty) { auto wrapper = std::make_shared<NoExceptionPromise<int>>(); 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<uint32_t>(mask), 0u); ASSERT_FALSE(mask); } { MyMask mask(MyMaskBits::kBar); ASSERT_EQ(static_cast<uint32_t>(mask), 1u); ASSERT_TRUE(mask); } { MyMask mask2(MyMaskBits::kBar); MyMask mask(mask2); ASSERT_EQ(static_cast<uint32_t>(mask), 1u); ASSERT_TRUE(mask); } { MyMask mask2(MyMaskBits::kBar); MyMask mask(std::move(mask2)); // NOLINT ASSERT_EQ(static_cast<uint32_t>(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<uint32_t>(m1 & m2), 0u); ASSERT_FALSE(m1 & m2); } { MyMask m1(MyMaskBits::kBar); MyMask m2(MyMaskBits::kBaz); ASSERT_EQ(static_cast<uint32_t>(m1 | m2), ((1u << 0u) | (1u << 1u))); ASSERT_TRUE(m1 | m2); } { MyMask m1(MyMaskBits::kBar); MyMask m2(MyMaskBits::kBaz); ASSERT_EQ(static_cast<uint32_t>(m1 ^ m2), ((1u << 0u) ^ (1u << 1u))); ASSERT_TRUE(m1 ^ m2); } { MyMask m1(MyMaskBits::kBar); ASSERT_EQ(static_cast<uint32_t>(~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
engine/impeller/base/base_unittests.cc/0
{ "file_path": "engine/impeller/base/base_unittests.cc", "repo_id": "engine", "token_count": 4883 }
233
// Copyright 2013 The Flutter Authors. All 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 <sstream> namespace impeller { std::optional<Version> Version::FromVector(const std::vector<size_t>& 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
engine/impeller/base/version.cc/0
{ "file_path": "engine/impeller/base/version.cc", "repo_id": "engine", "token_count": 291 }
234
// Copyright 2013 The Flutter Authors. All 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 <cstring> #include "flutter/fml/paths.h" namespace impeller { namespace compiler { Includer::Includer(std::shared_ptr<fml::UniqueFD> working_directory, std::vector<IncludeDir> include_dirs, std::function<void(std::string)> 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<fml::FileMapping> 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<fml::FileMapping> 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<shaderc_include_result>(); // 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<IncluderData>(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_cast<decltype(result->content)>( 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<IncluderData*>(data->user_data); delete data; } } // namespace compiler } // namespace impeller
engine/impeller/compiler/includer.cc/0
{ "file_path": "engine/impeller/compiler/includer.cc", "repo_id": "engine", "token_count": 1307 }
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. #ifndef BLENDING_GLSL_ #define BLENDING_GLSL_ #include <impeller/branching.glsl> #include <impeller/color.glsl> #include <impeller/constants.glsl> #include <impeller/types.glsl> /// 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
engine/impeller/compiler/shader_lib/impeller/blending.glsl/0
{ "file_path": "engine/impeller/compiler/shader_lib/impeller/blending.glsl", "repo_id": "engine", "token_count": 2992 }
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. #ifndef FLUTTER_IMPELLER_COMPILER_SOURCE_OPTIONS_H_ #define FLUTTER_IMPELLER_COMPILER_SOURCE_OPTIONS_H_ #include <cstdint> #include <memory> #include <string> #include <vector> #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<fml::UniqueFD> working_directory; std::vector<IncludeDir> include_dirs; std::string file_name = "main.glsl"; std::string entry_point_name = "main"; uint32_t gles_language_version = 100; std::vector<std::string> 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_
engine/impeller/compiler/source_options.h/0
{ "file_path": "engine/impeller/compiler/source_options.h", "repo_id": "engine", "token_count": 527 }
237
// Copyright 2013 The Flutter Authors. All rights 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/core/device_buffer_descriptor.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<DeviceBuffer> CreateBuffer( const DeviceBufferDescriptor& desc); std::shared_ptr<Texture> 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<DeviceBuffer> CreateBufferWithCopy(const uint8_t* buffer, size_t length); std::shared_ptr<DeviceBuffer> 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 only supported on the Vulkan backend. virtual void DebugTraceMemoryStatistics() const {}; protected: Allocator(); virtual std::shared_ptr<DeviceBuffer> OnCreateBuffer( const DeviceBufferDescriptor& desc) = 0; virtual std::shared_ptr<Texture> OnCreateTexture( const TextureDescriptor& desc) = 0; private: Allocator(const Allocator&) = delete; Allocator& operator=(const Allocator&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_CORE_ALLOCATOR_H_
engine/impeller/core/allocator.h/0
{ "file_path": "engine/impeller/core/allocator.h", "repo_id": "engine", "token_count": 701 }
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 "display_list/dl_color.h" #include "display_list/dl_tile_mode.h" #include "flutter/testing/testing.h" #include "impeller/display_list/skia_conversions.h" #include "impeller/geometry/scalar.h" namespace impeller { namespace testing { TEST(SkiaConversionsTest, SkPointToPoint) { for (int x = -100; x < 100; x += 4) { for (int y = -100; y < 100; y += 4) { EXPECT_EQ(skia_conversions::ToPoint(SkPoint::Make(x * 0.25f, y * 0.25f)), Point(x * 0.25f, y * 0.25f)); } } } TEST(SkiaConversionsTest, SkPointToSize) { for (int x = -100; x < 100; x += 4) { for (int y = -100; y < 100; y += 4) { EXPECT_EQ(skia_conversions::ToSize(SkPoint::Make(x * 0.25f, y * 0.25f)), Size(x * 0.25f, y * 0.25f)); } } } TEST(SkiaConversionsTest, ToColor) { // Create a color with alpha, red, green, and blue values that are all // trivially divisible by 255 so that we can test the conversion results in // correct scalar values. // AARRGGBB const flutter::DlColor color = flutter::DlColor(0x8040C020); auto converted_color = skia_conversions::ToColor(color); ASSERT_TRUE(ScalarNearlyEqual(converted_color.alpha, 0x80 * (1.0f / 255))); ASSERT_TRUE(ScalarNearlyEqual(converted_color.red, 0x40 * (1.0f / 255))); ASSERT_TRUE(ScalarNearlyEqual(converted_color.green, 0xC0 * (1.0f / 255))); ASSERT_TRUE(ScalarNearlyEqual(converted_color.blue, 0x20 * (1.0f / 255))); } TEST(SkiaConversionsTest, GradientStopConversion) { // Typical gradient. std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(), flutter::DlColor::kRed(), flutter::DlColor::kGreen()}; std::vector<float> stops = {0.0, 0.5, 1.0}; const auto gradient = flutter::DlColorSource::MakeLinear(SkPoint::Make(0, 0), // SkPoint::Make(1.0, 1.0), // 3, // colors.data(), // stops.data(), // flutter::DlTileMode::kClamp, // nullptr // ); std::vector<Color> converted_colors; std::vector<Scalar> converted_stops; skia_conversions::ConvertStops(gradient.get(), converted_colors, converted_stops); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[0], 0.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[1], 0.5f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[2], 1.0f)); } TEST(SkiaConversionsTest, GradientMissing0) { std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(), flutter::DlColor::kRed()}; std::vector<float> stops = {0.5, 1.0}; const auto gradient = flutter::DlColorSource::MakeLinear(SkPoint::Make(0, 0), // SkPoint::Make(1.0, 1.0), // 2, // colors.data(), // stops.data(), // flutter::DlTileMode::kClamp, // nullptr // ); std::vector<Color> converted_colors; std::vector<Scalar> converted_stops; skia_conversions::ConvertStops(gradient.get(), converted_colors, converted_stops); // First color is inserted as blue. ASSERT_TRUE(ScalarNearlyEqual(converted_colors[0].blue, 1.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[0], 0.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[1], 0.5f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[2], 1.0f)); } TEST(SkiaConversionsTest, GradientMissingLastValue) { std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(), flutter::DlColor::kRed()}; std::vector<float> stops = {0.0, .5}; const auto gradient = flutter::DlColorSource::MakeLinear(SkPoint::Make(0, 0), // SkPoint::Make(1.0, 1.0), // 2, // colors.data(), // stops.data(), // flutter::DlTileMode::kClamp, // nullptr // ); std::vector<Color> converted_colors; std::vector<Scalar> converted_stops; skia_conversions::ConvertStops(gradient.get(), converted_colors, converted_stops); // Last color is inserted as red. ASSERT_TRUE(ScalarNearlyEqual(converted_colors[2].red, 1.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[0], 0.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[1], 0.5f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[2], 1.0f)); } TEST(SkiaConversionsTest, GradientStopGreaterThan1) { std::vector<flutter::DlColor> colors = {flutter::DlColor::kBlue(), flutter::DlColor::kGreen(), flutter::DlColor::kRed()}; std::vector<float> stops = {0.0, 100, 1.0}; const auto gradient = flutter::DlColorSource::MakeLinear(SkPoint::Make(0, 0), // SkPoint::Make(1.0, 1.0), // 3, // colors.data(), // stops.data(), // flutter::DlTileMode::kClamp, // nullptr // ); std::vector<Color> converted_colors; std::vector<Scalar> converted_stops; skia_conversions::ConvertStops(gradient.get(), converted_colors, converted_stops); // Value is clamped to 1.0 ASSERT_TRUE(ScalarNearlyEqual(converted_stops[0], 0.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[1], 1.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[2], 1.0f)); } TEST(SkiaConversionsTest, GradientConversionNonMonotonic) { std::vector<flutter::DlColor> colors = { flutter::DlColor::kBlue(), flutter::DlColor::kGreen(), flutter::DlColor::kGreen(), flutter::DlColor::kRed()}; std::vector<float> stops = {0.0, 0.5, 0.4, 1.0}; const auto gradient = flutter::DlColorSource::MakeLinear(SkPoint::Make(0, 0), // SkPoint::Make(1.0, 1.0), // 4, // colors.data(), // stops.data(), // flutter::DlTileMode::kClamp, // nullptr // ); std::vector<Color> converted_colors; std::vector<Scalar> converted_stops; skia_conversions::ConvertStops(gradient.get(), converted_colors, converted_stops); // Value is clamped to 0.5 ASSERT_TRUE(ScalarNearlyEqual(converted_stops[0], 0.0f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[1], 0.5f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[2], 0.5f)); ASSERT_TRUE(ScalarNearlyEqual(converted_stops[3], 1.0f)); } } // namespace testing } // namespace impeller
engine/impeller/display_list/skia_conversions_unittests.cc/0
{ "file_path": "engine/impeller/display_list/skia_conversions_unittests.cc", "repo_id": "engine", "token_count": 4550 }
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 <optional> #include <unordered_map> #include <utility> #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/filters/color_filter_contents.h" #include "impeller/entity/contents/texture_contents.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" #include "impeller/renderer/vertex_buffer_builder.h" namespace impeller { AtlasContents::AtlasContents() = default; AtlasContents::~AtlasContents() = default; void AtlasContents::SetTexture(std::shared_ptr<Texture> texture) { texture_ = std::move(texture); } std::shared_ptr<Texture> AtlasContents::GetTexture() const { return texture_; } void AtlasContents::SetTransforms(std::vector<Matrix> transforms) { transforms_ = std::move(transforms); bounding_box_cache_.reset(); } void AtlasContents::SetTextureCoordinates(std::vector<Rect> texture_coords) { texture_coords_ = std::move(texture_coords); bounding_box_cache_.reset(); } void AtlasContents::SetColors(std::vector<Color> colors) { colors_ = std::move(colors); } void AtlasContents::SetAlpha(Scalar alpha) { alpha_ = alpha; } void AtlasContents::SetBlendMode(BlendMode blend_mode) { blend_mode_ = blend_mode; } void AtlasContents::SetCullRect(std::optional<Rect> cull_rect) { cull_rect_ = cull_rect; } struct AtlasBlenderKey { Color color; Rect rect; uint32_t color_key; struct Hash { std::size_t operator()(const AtlasBlenderKey& key) const { return fml::HashCombine(key.color_key, key.rect.GetWidth(), key.rect.GetHeight(), key.rect.GetX(), key.rect.GetY()); } }; struct Equal { bool operator()(const AtlasBlenderKey& lhs, const AtlasBlenderKey& rhs) const { return lhs.rect == rhs.rect && lhs.color_key == rhs.color_key; } }; }; std::shared_ptr<SubAtlasResult> AtlasContents::GenerateSubAtlas() const { FML_DCHECK(colors_.size() > 0 && blend_mode_ != BlendMode::kSource && blend_mode_ != BlendMode::kDestination); std::unordered_map<AtlasBlenderKey, std::vector<Matrix>, AtlasBlenderKey::Hash, AtlasBlenderKey::Equal> sub_atlas = {}; for (auto i = 0u; i < texture_coords_.size(); i++) { AtlasBlenderKey key = {.color = colors_[i], .rect = texture_coords_[i], .color_key = Color::ToIColor(colors_[i])}; if (sub_atlas.find(key) == sub_atlas.end()) { sub_atlas[key] = {transforms_[i]}; } else { sub_atlas[key].push_back(transforms_[i]); } } auto result = std::make_shared<SubAtlasResult>(); Scalar x_offset = 0.0; Scalar y_offset = 0.0; Scalar x_extent = 0.0; Scalar y_extent = 0.0; for (auto it = sub_atlas.begin(); it != sub_atlas.end(); it++) { // This size was arbitrarily chosen to keep the textures from getting too // wide. We could instead use a more generic rect packer but in the majority // of cases the sample rects will be fairly close in size making this a good // enough approximation. if (x_offset >= 1000) { y_offset = y_extent + 1; x_offset = 0.0; } auto key = it->first; auto transforms = it->second; auto new_rect = Rect::MakeXYWH(x_offset, y_offset, key.rect.GetWidth(), key.rect.GetHeight()); auto sub_transform = Matrix::MakeTranslation(Vector2(x_offset, y_offset)); x_offset += std::ceil(key.rect.GetWidth()) + 1.0; result->sub_texture_coords.push_back(key.rect); result->sub_colors.push_back(key.color); result->sub_transforms.push_back(sub_transform); x_extent = std::max(x_extent, x_offset); y_extent = std::max(y_extent, std::ceil(y_offset + key.rect.GetHeight())); for (auto transform : transforms) { result->result_texture_coords.push_back(new_rect); result->result_transforms.push_back(transform); } } result->size = ISize(std::ceil(x_extent), std::ceil(y_extent)); return result; } std::optional<Rect> AtlasContents::GetCoverage(const Entity& entity) const { if (cull_rect_.has_value()) { return cull_rect_.value().TransformBounds(entity.GetTransform()); } return ComputeBoundingBox().TransformBounds(entity.GetTransform()); } Rect AtlasContents::ComputeBoundingBox() const { if (!bounding_box_cache_.has_value()) { Rect bounding_box = {}; for (size_t i = 0; i < texture_coords_.size(); i++) { auto matrix = transforms_[i]; auto sample_rect = texture_coords_[i]; auto bounds = Rect::MakeSize(sample_rect.GetSize()).TransformBounds(matrix); bounding_box = bounds.Union(bounding_box); } bounding_box_cache_ = bounding_box; } return bounding_box_cache_.value(); } void AtlasContents::SetSamplerDescriptor(SamplerDescriptor desc) { sampler_descriptor_ = std::move(desc); } const SamplerDescriptor& AtlasContents::GetSamplerDescriptor() const { return sampler_descriptor_; } const std::vector<Matrix>& AtlasContents::GetTransforms() const { return transforms_; } const std::vector<Rect>& AtlasContents::GetTextureCoordinates() const { return texture_coords_; } const std::vector<Color>& AtlasContents::GetColors() const { return colors_; } bool AtlasContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { if (texture_ == nullptr || blend_mode_ == BlendMode::kClear || alpha_ <= 0.0) { return true; } // Ensure that we use the actual computed bounds and not a cull-rect // approximation of them. auto coverage = ComputeBoundingBox(); if (blend_mode_ == BlendMode::kSource || colors_.size() == 0) { auto child_contents = AtlasTextureContents(*this); child_contents.SetAlpha(alpha_); child_contents.SetCoverage(coverage); return child_contents.Render(renderer, entity, pass); } if (blend_mode_ == BlendMode::kDestination) { auto child_contents = AtlasColorContents(*this); child_contents.SetAlpha(alpha_); child_contents.SetCoverage(coverage); return child_contents.Render(renderer, entity, pass); } constexpr size_t indices[6] = {0, 1, 2, 1, 2, 3}; if (blend_mode_ <= BlendMode::kModulate) { // Simple Porter-Duff blends can be accomplished without a subpass. using VS = PorterDuffBlendPipeline::VertexShader; using FS = PorterDuffBlendPipeline::FragmentShader; VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.Reserve(texture_coords_.size() * 6); const auto texture_size = texture_->GetSize(); auto& host_buffer = renderer.GetTransientsBuffer(); for (size_t i = 0; i < texture_coords_.size(); i++) { auto sample_rect = texture_coords_[i]; auto matrix = transforms_[i]; auto points = sample_rect.GetPoints(); auto transformed_points = Rect::MakeSize(sample_rect.GetSize()).GetTransformedPoints(matrix); auto color = colors_[i].Premultiply(); for (size_t j = 0; j < 6; j++) { VS::PerVertexData data; data.vertices = transformed_points[indices[j]]; data.texture_coords = points[indices[j]] / texture_size; data.color = color; vtx_builder.AppendVertex(data); } } #ifdef IMPELLER_DEBUG pass.SetCommandLabel( SPrintF("DrawAtlas Blend (%s)", BlendModeToString(blend_mode_))); #endif // IMPELLER_DEBUG pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer)); pass.SetStencilReference(entity.GetClipDepth()); pass.SetPipeline( renderer.GetPorterDuffBlendPipeline(OptionsFromPass(pass))); FS::FragInfo frag_info; VS::FrameInfo frame_info; frame_info.depth = entity.GetShaderClipDepth(); auto dst_sampler_descriptor = sampler_descriptor_; if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { dst_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; dst_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; } const std::unique_ptr<const Sampler>& dst_sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( dst_sampler_descriptor); FS::BindTextureSamplerDst(pass, texture_, dst_sampler); frame_info.texture_sampler_y_coord_scale = texture_->GetYCoordScale(); frag_info.output_alpha = alpha_; frag_info.input_alpha = 1.0; auto inverted_blend_mode = InvertPorterDuffBlend(blend_mode_).value_or(BlendMode::kSource); auto blend_coefficients = kPorterDuffCoefficients[static_cast<int>(inverted_blend_mode)]; frag_info.src_coeff = blend_coefficients[0]; frag_info.src_coeff_dst_alpha = blend_coefficients[1]; frag_info.dst_coeff = blend_coefficients[2]; frag_info.dst_coeff_src_alpha = blend_coefficients[3]; frag_info.dst_coeff_src_color = blend_coefficients[4]; FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform(); auto uniform_view = host_buffer.EmplaceUniform(frame_info); VS::BindFrameInfo(pass, uniform_view); return pass.Draw().ok(); } // Advanced blends. auto sub_atlas = GenerateSubAtlas(); auto sub_coverage = Rect::MakeSize(sub_atlas->size); auto src_contents = std::make_shared<AtlasTextureContents>(*this); src_contents->SetSubAtlas(sub_atlas); src_contents->SetCoverage(sub_coverage); auto dst_contents = std::make_shared<AtlasColorContents>(*this); dst_contents->SetSubAtlas(sub_atlas); dst_contents->SetCoverage(sub_coverage); Entity untransformed_entity; auto contents = ColorFilterContents::MakeBlend( blend_mode_, {FilterInput::Make(dst_contents), FilterInput::Make(src_contents)}); auto snapshot = contents->RenderToSnapshot(renderer, // renderer untransformed_entity, // entity std::nullopt, // coverage_limit std::nullopt, // sampler_descriptor true, // msaa_enabled /*mip_count=*/1, "AtlasContents Snapshot"); // label if (!snapshot.has_value()) { return false; } auto child_contents = AtlasTextureContents(*this); child_contents.SetAlpha(alpha_); child_contents.SetCoverage(coverage); child_contents.SetTexture(snapshot.value().texture); child_contents.SetUseDestination(true); child_contents.SetSubAtlas(sub_atlas); return child_contents.Render(renderer, entity, pass); } // AtlasTextureContents // --------------------------------------------------------- AtlasTextureContents::AtlasTextureContents(const AtlasContents& parent) : parent_(parent) {} AtlasTextureContents::~AtlasTextureContents() {} std::optional<Rect> AtlasTextureContents::GetCoverage( const Entity& entity) const { return coverage_.TransformBounds(entity.GetTransform()); } void AtlasTextureContents::SetAlpha(Scalar alpha) { alpha_ = alpha; } void AtlasTextureContents::SetCoverage(Rect coverage) { coverage_ = coverage; } void AtlasTextureContents::SetUseDestination(bool value) { use_destination_ = value; } void AtlasTextureContents::SetSubAtlas( const std::shared_ptr<SubAtlasResult>& subatlas) { subatlas_ = subatlas; } void AtlasTextureContents::SetTexture(std::shared_ptr<Texture> texture) { texture_ = std::move(texture); } bool AtlasTextureContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { using VS = TextureFillVertexShader; using FS = TextureFillFragmentShader; auto texture = texture_ ? texture_ : parent_.GetTexture(); if (texture == nullptr) { return true; } std::vector<Rect> texture_coords; std::vector<Matrix> transforms; if (subatlas_) { texture_coords = use_destination_ ? subatlas_->result_texture_coords : subatlas_->sub_texture_coords; transforms = use_destination_ ? subatlas_->result_transforms : subatlas_->sub_transforms; } else { texture_coords = parent_.GetTextureCoordinates(); transforms = parent_.GetTransforms(); } const Size texture_size(texture->GetSize()); VertexBufferBuilder<VS::PerVertexData> vertex_builder; vertex_builder.Reserve(texture_coords.size() * 6); constexpr size_t indices[6] = {0, 1, 2, 1, 2, 3}; for (size_t i = 0; i < texture_coords.size(); i++) { auto sample_rect = texture_coords[i]; auto matrix = transforms[i]; auto points = sample_rect.GetPoints(); auto transformed_points = Rect::MakeSize(sample_rect.GetSize()).GetTransformedPoints(matrix); for (size_t j = 0; j < 6; j++) { VS::PerVertexData data; data.position = transformed_points[indices[j]]; data.texture_coords = points[indices[j]] / texture_size; vertex_builder.AppendVertex(data); } } if (!vertex_builder.HasVertices()) { return true; } pass.SetCommandLabel("AtlasTexture"); auto& host_buffer = renderer.GetTransientsBuffer(); VS::FrameInfo frame_info; frame_info.depth = entity.GetShaderClipDepth(); frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform(); frame_info.texture_sampler_y_coord_scale = texture->GetYCoordScale(); frame_info.alpha = alpha_; auto options = OptionsFromPassAndEntity(pass, entity); pass.SetPipeline(renderer.GetTexturePipeline(options)); pass.SetStencilReference(entity.GetClipDepth()); pass.SetVertexBuffer(vertex_builder.CreateVertexBuffer(host_buffer)); VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); FS::BindTextureSampler(pass, texture, renderer.GetContext()->GetSamplerLibrary()->GetSampler( parent_.GetSamplerDescriptor())); return pass.Draw().ok(); } // AtlasColorContents // --------------------------------------------------------- AtlasColorContents::AtlasColorContents(const AtlasContents& parent) : parent_(parent) {} AtlasColorContents::~AtlasColorContents() {} std::optional<Rect> AtlasColorContents::GetCoverage( const Entity& entity) const { return coverage_.TransformBounds(entity.GetTransform()); } void AtlasColorContents::SetAlpha(Scalar alpha) { alpha_ = alpha; } void AtlasColorContents::SetCoverage(Rect coverage) { coverage_ = coverage; } void AtlasColorContents::SetSubAtlas( const std::shared_ptr<SubAtlasResult>& subatlas) { subatlas_ = subatlas; } bool AtlasColorContents::Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { using VS = GeometryColorPipeline::VertexShader; using FS = GeometryColorPipeline::FragmentShader; std::vector<Rect> texture_coords; std::vector<Matrix> transforms; std::vector<Color> colors; if (subatlas_) { texture_coords = subatlas_->sub_texture_coords; colors = subatlas_->sub_colors; transforms = subatlas_->sub_transforms; } else { texture_coords = parent_.GetTextureCoordinates(); transforms = parent_.GetTransforms(); colors = parent_.GetColors(); } VertexBufferBuilder<VS::PerVertexData> vertex_builder; vertex_builder.Reserve(texture_coords.size() * 6); constexpr size_t indices[6] = {0, 1, 2, 1, 2, 3}; for (size_t i = 0; i < texture_coords.size(); i++) { auto sample_rect = texture_coords[i]; auto matrix = transforms[i]; auto transformed_points = Rect::MakeSize(sample_rect.GetSize()).GetTransformedPoints(matrix); for (size_t j = 0; j < 6; j++) { VS::PerVertexData data; data.position = transformed_points[indices[j]]; data.color = colors[i].Premultiply(); vertex_builder.AppendVertex(data); } } if (!vertex_builder.HasVertices()) { return true; } pass.SetCommandLabel("AtlasColors"); auto& host_buffer = renderer.GetTransientsBuffer(); VS::FrameInfo frame_info; frame_info.depth = entity.GetShaderClipDepth(); frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform(); FS::FragInfo frag_info; frag_info.alpha = alpha_; auto opts = OptionsFromPassAndEntity(pass, entity); opts.blend_mode = BlendMode::kSourceOver; pass.SetPipeline(renderer.GetGeometryColorPipeline(opts)); pass.SetStencilReference(entity.GetClipDepth()); pass.SetVertexBuffer(vertex_builder.CreateVertexBuffer(host_buffer)); VS::BindFrameInfo(pass, host_buffer.EmplaceUniform(frame_info)); FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); return pass.Draw().ok(); } } // namespace impeller
engine/impeller/entity/contents/atlas_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/atlas_contents.cc", "repo_id": "engine", "token_count": 6687 }
240
// Copyright 2013 The Flutter Authors. All 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 <array> #include <memory> #include <optional> #include "impeller/base/strings.h" #include "impeller/core/formats.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/geometry/color.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/snapshot.h" namespace impeller { std::optional<BlendMode> InvertPorterDuffBlend(BlendMode blend_mode) { switch (blend_mode) { case BlendMode::kClear: return BlendMode::kClear; case BlendMode::kSource: return BlendMode::kDestination; case BlendMode::kDestination: return BlendMode::kSource; case BlendMode::kSourceOver: return BlendMode::kDestinationOver; case BlendMode::kDestinationOver: return BlendMode::kSourceOver; case BlendMode::kSourceIn: return BlendMode::kDestinationIn; case BlendMode::kDestinationIn: return BlendMode::kSourceIn; case BlendMode::kSourceOut: return BlendMode::kDestinationOut; case BlendMode::kDestinationOut: return BlendMode::kSourceOut; case BlendMode::kSourceATop: return BlendMode::kDestinationATop; case BlendMode::kDestinationATop: return BlendMode::kSourceATop; 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::kSourceOver); } BlendFilterContents::~BlendFilterContents() = default; using PipelineProc = std::shared_ptr<Pipeline<PipelineDescriptor>> ( ContentContext::*)(ContentContextOptions) const; template <typename TPipeline> static std::optional<Entity> AdvancedBlend( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Rect& coverage, BlendMode blend_mode, std::optional<Color> foreground_color, ColorFilterContents::AbsorbOpacity absorb_opacity, PipelineProc pipeline_proc, std::optional<Scalar> 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<Snapshot> src_snapshot; std::array<Point, 4> 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(), entity.GetClipDepth()); } 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(), entity.GetClipDepth()); } 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(); VertexBufferBuilder<typename VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {Point(0, 0), dst_uvs[0], src_uvs[0]}, {Point(size.width, 0), dst_uvs[1], src_uvs[1]}, {Point(0, size.height), dst_uvs[2], src_uvs[2]}, {Point(size.width, size.height), dst_uvs[3], src_uvs[3]}, }); auto vtx_buffer = vtx_builder.CreateVertexBuffer(host_buffer); auto options = OptionsFromPass(pass); options.primitive_type = PrimitiveType::kTriangleStrip; options.blend_mode = BlendMode::kSource; std::shared_ptr<Pipeline<PipelineDescriptor>> pipeline = std::invoke(pipeline_proc, renderer, options); #ifdef IMPELLER_DEBUG pass.SetCommandLabel( SPrintF("Advanced Blend Filter (%s)", BlendModeToString(blend_mode))); #endif // IMPELLER_DEBUG pass.SetVertexBuffer(std::move(vtx_buffer)); pass.SetPipeline(pipeline); typename FS::BlendInfo blend_info; typename VS::FrameInfo frame_info; auto dst_sampler_descriptor = dst_snapshot->sampler_descriptor; if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { dst_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; dst_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; } const std::unique_ptr<const Sampler>& dst_sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( dst_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 { 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; } const std::unique_ptr<const Sampler>& src_sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( src_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(); }; fml::StatusOr<RenderTarget> render_target = renderer.MakeSubpass( "Advanced Blend Filter", ISize(subpass_coverage.GetSize()), callback); if (!render_target.ok()) { 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(), entity.GetClipDepth()); } std::optional<Entity> BlendFilterContents::CreateForegroundAdvancedBlend( const std::shared_ptr<FilterInput>& input, const ContentContext& renderer, const Entity& entity, const Rect& coverage, Color foreground_color, BlendMode blend_mode, std::optional<Scalar> 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, coverage, 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 maybe_dst_uvs = dst_snapshot->GetCoverageUVs(coverage); if (!maybe_dst_uvs.has_value()) { return false; } auto dst_uvs = maybe_dst_uvs.value(); auto size = coverage.GetSize(); auto origin = coverage.GetOrigin(); VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {origin, dst_uvs[0], dst_uvs[0]}, {Point(origin.x + size.width, origin.y), dst_uvs[1], dst_uvs[1]}, {Point(origin.x, origin.y + size.height), dst_uvs[2], dst_uvs[2]}, {Point(origin.x + size.width, origin.y + size.height), dst_uvs[3], dst_uvs[3]}, }); auto vtx_buffer = vtx_builder.CreateVertexBuffer(host_buffer); #ifdef IMPELLER_DEBUG pass.SetCommandLabel(SPrintF("Foreground Advanced Blend Filter (%s)", BlendModeToString(blend_mode))); #endif // IMPELLER_DEBUG pass.SetVertexBuffer(std::move(vtx_buffer)); pass.SetStencilReference(entity.GetClipDepth()); auto options = OptionsFromPass(pass); 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; auto dst_sampler_descriptor = dst_snapshot->sampler_descriptor; if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { dst_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; dst_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; } const std::unique_ptr<const Sampler>& dst_sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( dst_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 * 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); frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform(); 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<Rect> { return coverage.TransformBounds(entity.GetTransform()); }; auto contents = AnonymousContents::Make(render_proc, coverage_proc); Entity sub_entity; sub_entity.SetContents(std::move(contents)); sub_entity.SetClipDepth(entity.GetClipDepth()); return sub_entity; } std::optional<Entity> BlendFilterContents::CreateForegroundPorterDuffBlend( const std::shared_ptr<FilterInput>& input, const ContentContext& renderer, const Entity& entity, const Rect& coverage, Color foreground_color, BlendMode blend_mode, std::optional<Scalar> alpha, ColorFilterContents::AbsorbOpacity absorb_opacity) const { if (blend_mode == BlendMode::kClear) { return std::nullopt; } if (blend_mode == BlendMode::kSource) { auto contents = std::make_shared<SolidColorContents>(); contents->SetGeometry(Geometry::MakeRect(coverage)); contents->SetColor(foreground_color); Entity foreground_entity; foreground_entity.SetBlendMode(entity.GetBlendMode()); foreground_entity.SetClipDepth(entity.GetClipDepth()); foreground_entity.SetContents(std::move(contents)); return foreground_entity; } auto dst_snapshot = input->GetSnapshot("ForegroundPorterDuffBlend", renderer, entity); if (!dst_snapshot.has_value()) { return std::nullopt; } if (blend_mode == BlendMode::kDestination) { return Entity::FromSnapshot(dst_snapshot.value(), entity.GetBlendMode(), entity.GetClipDepth()); } RenderProc render_proc = [foreground_color, coverage, 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 maybe_dst_uvs = dst_snapshot->GetCoverageUVs(coverage); if (!maybe_dst_uvs.has_value()) { return false; } auto dst_uvs = maybe_dst_uvs.value(); auto size = coverage.GetSize(); auto origin = coverage.GetOrigin(); auto color = foreground_color.Premultiply(); VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {origin, dst_uvs[0], color}, {Point(origin.x + size.width, origin.y), dst_uvs[1], color}, {Point(origin.x, origin.y + size.height), dst_uvs[2], color}, {Point(origin.x + size.width, origin.y + size.height), dst_uvs[3], color}, }); auto vtx_buffer = vtx_builder.CreateVertexBuffer(host_buffer); #ifdef IMPELLER_DEBUG pass.SetCommandLabel(SPrintF("Foreground PorterDuff Blend Filter (%s)", BlendModeToString(blend_mode))); #endif // IMPELLER_DEBUG pass.SetVertexBuffer(std::move(vtx_buffer)); pass.SetStencilReference(entity.GetClipDepth()); auto options = OptionsFromPass(pass); options.primitive_type = PrimitiveType::kTriangleStrip; pass.SetPipeline(renderer.GetPorterDuffBlendPipeline(options)); FS::FragInfo frag_info; VS::FrameInfo frame_info; frame_info.depth = entity.GetShaderClipDepth(); auto dst_sampler_descriptor = dst_snapshot->sampler_descriptor; if (renderer.GetDeviceCapabilities().SupportsDecalSamplerAddressMode()) { dst_sampler_descriptor.width_address_mode = SamplerAddressMode::kDecal; dst_sampler_descriptor.height_address_mode = SamplerAddressMode::kDecal; } const std::unique_ptr<const Sampler>& dst_sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( dst_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; auto blend_coefficients = kPorterDuffCoefficients[static_cast<int>(blend_mode)]; frag_info.src_coeff = blend_coefficients[0]; frag_info.src_coeff_dst_alpha = blend_coefficients[1]; frag_info.dst_coeff = blend_coefficients[2]; frag_info.dst_coeff_src_alpha = blend_coefficients[3]; frag_info.dst_coeff_src_color = blend_coefficients[4]; FS::BindFragInfo(pass, host_buffer.EmplaceUniform(frag_info)); frame_info.mvp = pass.GetOrthographicTransform() * entity.GetTransform(); 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<Rect> { return coverage.TransformBounds(entity.GetTransform()); }; auto contents = AnonymousContents::Make(render_proc, coverage_proc); Entity sub_entity; sub_entity.SetContents(std::move(contents)); sub_entity.SetClipDepth(entity.GetClipDepth()); return sub_entity; } static std::optional<Entity> PipelineBlend( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Rect& coverage, BlendMode blend_mode, std::optional<Color> foreground_color, ColorFilterContents::AbsorbOpacity absorb_opacity, std::optional<Scalar> alpha) { using VS = BlendPipeline::VertexShader; using FS = BlendPipeline::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( SPrintF("Pipeline Blend Filter (%s)", BlendModeToString(blend_mode))); #endif // IMPELLER_DEBUG auto options = OptionsFromPass(pass); options.primitive_type = PrimitiveType::kTriangleStrip; auto add_blend_command = [&](std::optional<Snapshot> input) { if (!input.has_value()) { return false; } auto input_coverage = input->GetCoverage(); if (!input_coverage.has_value()) { return false; } const std::unique_ptr<const Sampler>& sampler = renderer.GetContext()->GetSamplerLibrary()->GetSampler( input->sampler_descriptor); FS::BindTextureSamplerSrc(pass, input->texture, sampler); auto size = input->texture->GetSize(); VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {Point(0, 0), Point(0, 0)}, {Point(size.width, 0), Point(1, 0)}, {Point(0, size.height), Point(0, 1)}, {Point(size.width, size.height), Point(1, 1)}, }); pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer)); 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.input_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::kSource; pass.SetPipeline(renderer.GetBlendPipeline(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.GetBlendPipeline(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<SolidColorContents>(); contents->SetGeometry( Geometry::MakeRect(Rect::MakeSize(pass.GetRenderTargetSize()))); 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; }; fml::StatusOr<RenderTarget> render_target = renderer.MakeSubpass( "Pipeline Blend Filter", ISize(subpass_coverage.GetSize()), callback); if (!render_target.ok()) { 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(), entity.GetClipDepth()); } #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<Color> fg_color, \ ColorFilterContents::AbsorbOpacity absorb_opacity, \ std::optional<Scalar> alpha) { \ PipelineProc p = &ContentContext::GetBlend##mode##Pipeline; \ return AdvancedBlend<Blend##mode##Pipeline>( \ 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<int>(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> color) { foreground_color_ = color; } std::optional<Entity> BlendFilterContents::RenderFilter( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Matrix& effect_transform, const Rect& coverage, const std::optional<Rect>& 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::kSource, 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 (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
engine/impeller/entity/contents/filters/blend_filter_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/blend_filter_contents.cc", "repo_id": "engine", "token_count": 11943 }
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. #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| Variant GetInput() const override; // |FilterInput| std::optional<Snapshot> GetSnapshot(const std::string& label, const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit, int32_t mip_count) const override; // |FilterInput| std::optional<Rect> GetCoverage(const Entity& entity) const override; // |FilterInput| std::optional<Rect> 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| void PopulateGlyphAtlas( const std::shared_ptr<LazyGlyphAtlas>& lazy_glyph_atlas, Scalar scale) override; // |FilterInput| bool IsTranslationOnly() const override; // |FilterInput| bool IsLeaf() const override; // |FilterInput| void SetLeafInputs(const FilterInput::Vector& inputs) override; // |FilterInput| virtual void SetEffectTransform(const Matrix& matrix) override; // |FilterInput| virtual void SetRenderingMode(Entity::RenderingMode rendering_mode) override; private: explicit FilterContentsFilterInput(std::shared_ptr<FilterContents> filter); std::shared_ptr<FilterContents> filter_; mutable std::optional<Snapshot> snapshot_; friend FilterInput; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_FILTERS_INPUTS_FILTER_CONTENTS_FILTER_INPUT_H_
engine/impeller/entity/contents/filters/inputs/filter_contents_filter_input.h/0
{ "file_path": "engine/impeller/entity/contents/filters/inputs/filter_contents_filter_input.h", "repo_id": "engine", "token_count": 811 }
242
// Copyright 2013 The Flutter Authors. All 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<Entity> SrgbToLinearFilterContents::RenderFilter( const FilterInput::Vector& inputs, const ContentContext& renderer, const Entity& entity, const Matrix& effect_transform, const Rect& coverage, const std::optional<Rect>& 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"); pass.SetStencilReference(entity.GetClipDepth()); auto options = OptionsFromPassAndEntity(pass, entity); options.primitive_type = PrimitiveType::kTriangleStrip; pass.SetPipeline(renderer.GetSrgbToLinearFilterPipeline(options)); auto size = input_snapshot->texture->GetSize(); VertexBufferBuilder<VS::PerVertexData> vtx_builder; vtx_builder.AddVertices({ {Point(0, 0)}, {Point(1, 0)}, {Point(0, 1)}, {Point(1, 1)}, }); auto& host_buffer = renderer.GetTransientsBuffer(); pass.SetVertexBuffer(vtx_builder.CreateVertexBuffer(host_buffer)); VS::FrameInfo frame_info; frame_info.depth = entity.GetShaderClipDepth(); frame_info.mvp = pass.GetOrthographicTransform() * 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; const std::unique_ptr<const Sampler>& 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<Rect> { return coverage.TransformBounds(entity.GetTransform()); }; auto contents = AnonymousContents::Make(render_proc, coverage_proc); Entity sub_entity; sub_entity.SetContents(std::move(contents)); sub_entity.SetClipDepth(entity.GetClipDepth()); sub_entity.SetBlendMode(entity.GetBlendMode()); return sub_entity; } } // namespace impeller
engine/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc/0
{ "file_path": "engine/impeller/entity/contents/filters/srgb_to_linear_filter_contents.cc", "repo_id": "engine", "token_count": 1389 }
243
// Copyright 2013 The Flutter Authors. All rights 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_SCENE_CONTENTS_H_ #define FLUTTER_IMPELLER_ENTITY_CONTENTS_SCENE_CONTENTS_H_ #if !IMPELLER_ENABLE_3D static_assert(false); #endif #include <memory> #include "impeller/entity/contents/color_source_contents.h" #include "impeller/geometry/matrix.h" #include "impeller/geometry/rect.h" #include "impeller/scene/node.h" namespace impeller { class SceneContents final : public ColorSourceContents { public: SceneContents(); ~SceneContents() override; void SetCameraTransform(Matrix matrix); void SetNode(std::shared_ptr<scene::Node> node); // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; private: Matrix camera_transform_; std::shared_ptr<scene::Node> node_; }; } // namespace impeller #endif // FLUTTER_IMPELLER_ENTITY_CONTENTS_SCENE_CONTENTS_H_
engine/impeller/entity/contents/scene_contents.h/0
{ "file_path": "engine/impeller/entity/contents/scene_contents.h", "repo_id": "engine", "token_count": 384 }
244
// Copyright 2013 The Flutter Authors. All rights 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 <functional> #include <memory> #include <vector> #include "flutter/fml/macros.h" #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/geometry/path.h" #include "impeller/renderer/capabilities.h" namespace impeller { class TiledTextureContents final : public ColorSourceContents { public: TiledTextureContents(); ~TiledTextureContents() override; using ColorFilterProc = std::function<std::shared_ptr<ColorFilterContents>(FilterInput::Ref)>; // |Contents| bool IsOpaque() const override; // |Contents| bool Render(const ContentContext& renderer, const Entity& entity, RenderPass& pass) const override; void SetTexture(std::shared_ptr<Texture> texture); void SetTileModes(Entity::TileMode x_tile_mode, Entity::TileMode y_tile_mode); void SetSamplerDescriptor(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<Snapshot> RenderToSnapshot( const ContentContext& renderer, const Entity& entity, std::optional<Rect> coverage_limit = std::nullopt, const std::optional<SamplerDescriptor>& sampler_descriptor = std::nullopt, bool msaa_enabled = true, int32_t mip_count = 1, const std::string& label = "Tiled Texture Snapshot") const override; private: std::shared_ptr<Texture> CreateFilterTexture( const ContentContext& renderer) const; SamplerDescriptor CreateSamplerDescriptor( const Capabilities& capabilities) const; bool UsesEmulatedTileMode(const Capabilities& capabilities) const; std::shared_ptr<Texture> 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_
engine/impeller/entity/contents/tiled_texture_contents.h/0
{ "file_path": "engine/impeller/entity/contents/tiled_texture_contents.h", "repo_id": "engine", "token_count": 991 }
245
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <cstring> #include <memory> #include <optional> #include <utility> #include <vector> #include "flutter/display_list/testing/dl_test_snippets.h" #include "fml/logging.h" #include "gtest/gtest.h" #include "impeller/core/formats.h" #include "impeller/core/texture_descriptor.h" #include "impeller/entity/contents/atlas_contents.h" #include "impeller/entity/contents/clip_contents.h" #include "impeller/entity/contents/conical_gradient_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/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/linear_gradient_contents.h" #include "impeller/entity/contents/radial_gradient_contents.h" #include "impeller/entity/contents/runtime_effect_contents.h" #include "impeller/entity/contents/solid_color_contents.h" #include "impeller/entity/contents/solid_rrect_blur_contents.h" #include "impeller/entity/contents/text_contents.h" #include "impeller/entity/contents/texture_contents.h" #include "impeller/entity/contents/tiled_texture_contents.h" #include "impeller/entity/entity.h" #include "impeller/entity/entity_pass.h" #include "impeller/entity/entity_pass_delegate.h" #include "impeller/entity/entity_playground.h" #include "impeller/entity/geometry/geometry.h" #include "impeller/entity/geometry/point_field_geometry.h" #include "impeller/entity/geometry/stroke_path_geometry.h" #include "impeller/entity/render_target_cache.h" #include "impeller/geometry/color.h" #include "impeller/geometry/geometry_asserts.h" #include "impeller/geometry/path_builder.h" #include "impeller/geometry/point.h" #include "impeller/geometry/sigma.h" #include "impeller/geometry/vector.h" #include "impeller/playground/playground.h" #include "impeller/playground/widgets.h" #include "impeller/renderer/command.h" #include "impeller/renderer/pipeline_descriptor.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/render_target.h" #include "impeller/renderer/testing/mocks.h" #include "impeller/renderer/vertex_buffer_builder.h" #include "impeller/typographer/backends/skia/text_frame_skia.h" #include "impeller/typographer/backends/skia/typographer_context_skia.h" #include "third_party/imgui/imgui.h" #include "third_party/skia/include/core/SkTextBlob.h" // TODO(zanderso): https://github.com/flutter/flutter/issues/127701 // NOLINTBEGIN(bugprone-unchecked-optional-access) namespace impeller { namespace testing { using EntityTest = EntityPlayground; INSTANTIATE_PLAYGROUND_SUITE(EntityTest); TEST_P(EntityTest, CanCreateEntity) { Entity entity; ASSERT_TRUE(entity.GetTransform().IsIdentity()); } class TestPassDelegate final : public EntityPassDelegate { public: explicit TestPassDelegate(bool collapse = false) : collapse_(collapse) {} // |EntityPassDelegate| ~TestPassDelegate() override = default; // |EntityPassDelgate| bool CanElide() override { return false; } // |EntityPassDelgate| bool CanCollapseIntoParentPass(EntityPass* entity_pass) override { return collapse_; } // |EntityPassDelgate| std::shared_ptr<Contents> CreateContentsForSubpassTarget( std::shared_ptr<Texture> target, const Matrix& transform) override { return nullptr; } // |EntityPassDelegate| std::shared_ptr<FilterContents> WithImageFilter( const FilterInput::Variant& input, const Matrix& effect_transform) const override { return nullptr; } private: const std::optional<Rect> coverage_; const bool collapse_; }; auto CreatePassWithRectPath( Rect rect, std::optional<Rect> bounds_hint, ContentBoundsPromise bounds_promise = ContentBoundsPromise::kUnknown, bool collapse = false) { auto subpass = std::make_unique<EntityPass>(); Entity entity; entity.SetContents(SolidColorContents::Make( PathBuilder{}.AddRect(rect).TakePath(), Color::Red())); subpass->AddEntity(std::move(entity)); subpass->SetDelegate(std::make_unique<TestPassDelegate>(collapse)); subpass->SetBoundsLimit(bounds_hint, bounds_promise); return subpass; } TEST_P(EntityTest, EntityPassRespectsUntrustedSubpassBoundsLimit) { EntityPass pass; auto subpass0 = CreatePassWithRectPath(Rect::MakeLTRB(0, 0, 100, 100), Rect::MakeLTRB(50, 50, 150, 150)); auto subpass1 = CreatePassWithRectPath(Rect::MakeLTRB(500, 500, 1000, 1000), Rect::MakeLTRB(800, 800, 900, 900)); auto subpass0_coverage = pass.GetSubpassCoverage(*subpass0.get(), std::nullopt); ASSERT_TRUE(subpass0_coverage.has_value()); ASSERT_RECT_NEAR(subpass0_coverage.value(), Rect::MakeLTRB(50, 50, 100, 100)); auto subpass1_coverage = pass.GetSubpassCoverage(*subpass1.get(), std::nullopt); ASSERT_TRUE(subpass1_coverage.has_value()); ASSERT_RECT_NEAR(subpass1_coverage.value(), Rect::MakeLTRB(800, 800, 900, 900)); pass.AddSubpass(std::move(subpass0)); pass.AddSubpass(std::move(subpass1)); auto coverage = pass.GetElementsCoverage(std::nullopt); ASSERT_TRUE(coverage.has_value()); ASSERT_RECT_NEAR(coverage.value(), Rect::MakeLTRB(50, 50, 900, 900)); } TEST_P(EntityTest, EntityPassTrustsSnugSubpassBoundsLimit) { EntityPass pass; auto subpass0 = // CreatePassWithRectPath(Rect::MakeLTRB(10, 10, 90, 90), Rect::MakeLTRB(5, 5, 95, 95), ContentBoundsPromise::kContainsContents); auto subpass1 = // CreatePassWithRectPath(Rect::MakeLTRB(500, 500, 1000, 1000), Rect::MakeLTRB(495, 495, 1005, 1005), ContentBoundsPromise::kContainsContents); auto subpass0_coverage = pass.GetSubpassCoverage(*subpass0.get(), std::nullopt); EXPECT_TRUE(subpass0_coverage.has_value()); // Result should be the overridden bounds // (we lied about them being snug, but the property is respected) EXPECT_RECT_NEAR(subpass0_coverage.value(), Rect::MakeLTRB(5, 5, 95, 95)); auto subpass1_coverage = pass.GetSubpassCoverage(*subpass1.get(), std::nullopt); EXPECT_TRUE(subpass1_coverage.has_value()); // Result should be the overridden bounds // (we lied about them being snug, but the property is respected) EXPECT_RECT_NEAR(subpass1_coverage.value(), Rect::MakeLTRB(495, 495, 1005, 1005)); pass.AddSubpass(std::move(subpass0)); pass.AddSubpass(std::move(subpass1)); auto coverage = pass.GetElementsCoverage(std::nullopt); EXPECT_TRUE(coverage.has_value()); // This result should be the union of the overridden bounds EXPECT_RECT_NEAR(coverage.value(), Rect::MakeLTRB(5, 5, 1005, 1005)); } TEST_P(EntityTest, EntityPassCanMergeSubpassIntoParent) { // Both a red and a blue box should appear if the pass merging has worked // correctly. EntityPass pass; auto subpass = CreatePassWithRectPath(Rect::MakeLTRB(0, 0, 100, 100), Rect::MakeLTRB(50, 50, 150, 150), ContentBoundsPromise::kUnknown, true); pass.AddSubpass(std::move(subpass)); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(Geometry::MakeRect(Rect::MakeLTRB(100, 100, 200, 200))); contents->SetColor(Color::Blue()); entity.SetContents(std::move(contents)); pass.AddEntity(std::move(entity)); ASSERT_TRUE(OpenPlaygroundHere(pass)); } TEST_P(EntityTest, EntityPassCoverageRespectsCoverageLimit) { // Rect is drawn entirely in negative area. auto pass = CreatePassWithRectPath(Rect::MakeLTRB(-200, -200, -100, -100), std::nullopt); // Without coverage limit. { auto pass_coverage = pass->GetElementsCoverage(std::nullopt); ASSERT_TRUE(pass_coverage.has_value()); ASSERT_RECT_NEAR(pass_coverage.value(), Rect::MakeLTRB(-200, -200, -100, -100)); } // With limit that doesn't overlap. { auto pass_coverage = pass->GetElementsCoverage(Rect::MakeLTRB(0, 0, 100, 100)); ASSERT_FALSE(pass_coverage.has_value()); } // With limit that partially overlaps. { auto pass_coverage = pass->GetElementsCoverage(Rect::MakeLTRB(-150, -150, 0, 0)); ASSERT_TRUE(pass_coverage.has_value()); ASSERT_RECT_NEAR(pass_coverage.value(), Rect::MakeLTRB(-150, -150, -100, -100)); } } TEST_P(EntityTest, FilterCoverageRespectsCropRect) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend(BlendMode::kSoftLight, FilterInput::Make({image})); // Without the crop rect (default behavior). { auto actual = filter->GetCoverage({}); auto expected = Rect::MakeSize(image->GetSize()); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } // With the crop rect. { auto expected = Rect::MakeLTRB(50, 50, 100, 100); filter->SetCoverageHint(expected); auto actual = filter->GetCoverage({}); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } } TEST_P(EntityTest, CanDrawRect) { auto contents = std::make_shared<SolidColorContents>(); contents->SetGeometry(Geometry::MakeRect(Rect::MakeXYWH(100, 100, 100, 100))); contents->SetColor(Color::Red()); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); entity.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, CanDrawRRect) { auto contents = std::make_shared<SolidColorContents>(); auto path = PathBuilder{} .SetConvexity(Convexity::kConvex) .AddRoundedRect(Rect::MakeXYWH(100, 100, 100, 100), 10.0) .TakePath(); contents->SetGeometry(Geometry::MakeFillPath(path)); contents->SetColor(Color::Red()); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); entity.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, GeometryBoundsAreTransformed) { auto geometry = Geometry::MakeRect(Rect::MakeXYWH(100, 100, 100, 100)); auto transform = Matrix::MakeScale({2.0, 2.0, 2.0}); ASSERT_RECT_NEAR(geometry->GetCoverage(transform).value(), Rect::MakeXYWH(200, 200, 200, 200)); } TEST_P(EntityTest, ThreeStrokesInOnePath) { Path path = PathBuilder{} .MoveTo({100, 100}) .LineTo({100, 200}) .MoveTo({100, 300}) .LineTo({100, 400}) .MoveTo({100, 500}) .LineTo({100, 600}) .TakePath(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(Geometry::MakeStrokePath(path, 5.0)); contents->SetColor(Color::Red()); entity.SetContents(std::move(contents)); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, StrokeWithTextureContents) { auto bridge = CreateTextureForFixture("bay_bridge.jpg"); Path path = PathBuilder{} .MoveTo({100, 100}) .LineTo({100, 200}) .MoveTo({100, 300}) .LineTo({100, 400}) .MoveTo({100, 500}) .LineTo({100, 600}) .TakePath(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto contents = std::make_unique<TiledTextureContents>(); contents->SetGeometry(Geometry::MakeStrokePath(path, 100.0)); contents->SetTexture(bridge); contents->SetTileModes(Entity::TileMode::kClamp, Entity::TileMode::kClamp); entity.SetContents(std::move(contents)); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, TriangleInsideASquare) { auto callback = [&](ContentContext& context, RenderPass& pass) { Point offset(100, 100); static PlaygroundPoint point_a(Point(10, 10) + offset, 20, Color::White()); Point a = DrawPlaygroundPoint(point_a); static PlaygroundPoint point_b(Point(210, 10) + offset, 20, Color::White()); Point b = DrawPlaygroundPoint(point_b); static PlaygroundPoint point_c(Point(210, 210) + offset, 20, Color::White()); Point c = DrawPlaygroundPoint(point_c); static PlaygroundPoint point_d(Point(10, 210) + offset, 20, Color::White()); Point d = DrawPlaygroundPoint(point_d); static PlaygroundPoint point_e(Point(50, 50) + offset, 20, Color::White()); Point e = DrawPlaygroundPoint(point_e); static PlaygroundPoint point_f(Point(100, 50) + offset, 20, Color::White()); Point f = DrawPlaygroundPoint(point_f); static PlaygroundPoint point_g(Point(50, 150) + offset, 20, Color::White()); Point g = DrawPlaygroundPoint(point_g); Path path = PathBuilder{} .MoveTo(a) .LineTo(b) .LineTo(c) .LineTo(d) .Close() .MoveTo(e) .LineTo(f) .LineTo(g) .Close() .TakePath(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(Geometry::MakeStrokePath(path, 20.0)); contents->SetColor(Color::Red()); entity.SetContents(std::move(contents)); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, StrokeCapAndJoinTest) { const Point padding(300, 250); const Point margin(140, 180); auto callback = [&](ContentContext& context, RenderPass& pass) { // Slightly above sqrt(2) by default, so that right angles are just below // the limit and acute angles are over the limit (causing them to get // beveled). static Scalar miter_limit = 1.41421357; static Scalar width = 30; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); { ImGui::SliderFloat("Miter limit", &miter_limit, 0, 30); ImGui::SliderFloat("Stroke width", &width, 0, 100); if (ImGui::Button("Reset")) { miter_limit = 1.41421357; width = 30; } } ImGui::End(); auto world_matrix = Matrix::MakeScale(GetContentScale()); auto render_path = [width = width, &context, &pass, &world_matrix]( const Path& path, Cap cap, Join join) { auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry( Geometry::MakeStrokePath(path, width, miter_limit, cap, join)); contents->SetColor(Color::Red()); Entity entity; entity.SetTransform(world_matrix); entity.SetContents(std::move(contents)); auto coverage = entity.GetCoverage(); if (coverage.has_value()) { auto bounds_contents = std::make_unique<SolidColorContents>(); bounds_contents->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(entity.GetCoverage().value()).TakePath())); bounds_contents->SetColor(Color::Green().WithAlpha(0.5)); Entity bounds_entity; bounds_entity.SetContents(std::move(bounds_contents)); bounds_entity.Render(context, pass); } entity.Render(context, pass); }; const Point a_def(0, 0), b_def(0, 100), c_def(150, 0), d_def(150, -100), e_def(75, 75); const Scalar r = 30; // Cap::kButt demo. { Point off = Point(0, 0) * padding + margin; static PlaygroundPoint point_a(off + a_def, r, Color::Black()); static PlaygroundPoint point_b(off + b_def, r, Color::White()); auto [a, b] = DrawPlaygroundLine(point_a, point_b); static PlaygroundPoint point_c(off + c_def, r, Color::Black()); static PlaygroundPoint point_d(off + d_def, r, Color::White()); auto [c, d] = DrawPlaygroundLine(point_c, point_d); render_path(PathBuilder{}.AddCubicCurve(a, b, d, c).TakePath(), Cap::kButt, Join::kBevel); } // Cap::kSquare demo. { Point off = Point(1, 0) * padding + margin; static PlaygroundPoint point_a(off + a_def, r, Color::Black()); static PlaygroundPoint point_b(off + b_def, r, Color::White()); auto [a, b] = DrawPlaygroundLine(point_a, point_b); static PlaygroundPoint point_c(off + c_def, r, Color::Black()); static PlaygroundPoint point_d(off + d_def, r, Color::White()); auto [c, d] = DrawPlaygroundLine(point_c, point_d); render_path(PathBuilder{}.AddCubicCurve(a, b, d, c).TakePath(), Cap::kSquare, Join::kBevel); } // Cap::kRound demo. { Point off = Point(2, 0) * padding + margin; static PlaygroundPoint point_a(off + a_def, r, Color::Black()); static PlaygroundPoint point_b(off + b_def, r, Color::White()); auto [a, b] = DrawPlaygroundLine(point_a, point_b); static PlaygroundPoint point_c(off + c_def, r, Color::Black()); static PlaygroundPoint point_d(off + d_def, r, Color::White()); auto [c, d] = DrawPlaygroundLine(point_c, point_d); render_path(PathBuilder{}.AddCubicCurve(a, b, d, c).TakePath(), Cap::kRound, Join::kBevel); } // Join::kBevel demo. { Point off = Point(0, 1) * padding + margin; static PlaygroundPoint point_a = PlaygroundPoint(off + a_def, r, Color::White()); static PlaygroundPoint point_b = PlaygroundPoint(off + e_def, r, Color::White()); static PlaygroundPoint point_c = PlaygroundPoint(off + c_def, r, Color::White()); Point a = DrawPlaygroundPoint(point_a); Point b = DrawPlaygroundPoint(point_b); Point c = DrawPlaygroundPoint(point_c); render_path( PathBuilder{}.MoveTo(a).LineTo(b).LineTo(c).Close().TakePath(), Cap::kButt, Join::kBevel); } // Join::kMiter demo. { Point off = Point(1, 1) * padding + margin; static PlaygroundPoint point_a(off + a_def, r, Color::White()); static PlaygroundPoint point_b(off + e_def, r, Color::White()); static PlaygroundPoint point_c(off + c_def, r, Color::White()); Point a = DrawPlaygroundPoint(point_a); Point b = DrawPlaygroundPoint(point_b); Point c = DrawPlaygroundPoint(point_c); render_path( PathBuilder{}.MoveTo(a).LineTo(b).LineTo(c).Close().TakePath(), Cap::kButt, Join::kMiter); } // Join::kRound demo. { Point off = Point(2, 1) * padding + margin; static PlaygroundPoint point_a(off + a_def, r, Color::White()); static PlaygroundPoint point_b(off + e_def, r, Color::White()); static PlaygroundPoint point_c(off + c_def, r, Color::White()); Point a = DrawPlaygroundPoint(point_a); Point b = DrawPlaygroundPoint(point_b); Point c = DrawPlaygroundPoint(point_c); render_path( PathBuilder{}.MoveTo(a).LineTo(b).LineTo(c).Close().TakePath(), Cap::kButt, Join::kRound); } return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, CubicCurveTest) { // Compare with https://fiddle.skia.org/c/b3625f26122c9de7afe7794fcf25ead3 Path path = PathBuilder{} .MoveTo({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}) .Close() .TakePath(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); entity.SetContents(SolidColorContents::Make(path, Color::Red())); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, CanDrawCorrectlyWithRotatedTransform) { auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { const char* input_axis[] = {"X", "Y", "Z"}; static int rotation_axis_index = 0; static float rotation = 0; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::SliderFloat("Rotation", &rotation, -kPi, kPi); ImGui::Combo("Rotation Axis", &rotation_axis_index, input_axis, sizeof(input_axis) / sizeof(char*)); Matrix rotation_matrix; switch (rotation_axis_index) { case 0: rotation_matrix = Matrix::MakeRotationX(Radians(rotation)); break; case 1: rotation_matrix = Matrix::MakeRotationY(Radians(rotation)); break; case 2: rotation_matrix = Matrix::MakeRotationZ(Radians(rotation)); break; default: rotation_matrix = Matrix{}; break; } if (ImGui::Button("Reset")) { rotation = 0; } ImGui::End(); Matrix current_transform = Matrix::MakeScale(GetContentScale()) .MakeTranslation( Vector3(Point(pass.GetRenderTargetSize().width / 2.0, pass.GetRenderTargetSize().height / 2.0))); Matrix result_transform = current_transform * rotation_matrix; Path path = PathBuilder{}.AddRect(Rect::MakeXYWH(-300, -400, 600, 800)).TakePath(); Entity entity; entity.SetTransform(result_transform); entity.SetContents(SolidColorContents::Make(path, Color::Red())); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, CubicCurveAndOverlapTest) { // Compare with https://fiddle.skia.org/c/7a05a3e186c65a8dfb732f68020aae06 Path path = PathBuilder{} .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}) .Close() .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}) .Close() .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}) .Close() .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}) .Close() .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}) .Close() .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}) .Close() .TakePath(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); entity.SetContents(SolidColorContents::Make(path, Color::Red())); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, SolidColorContentsStrokeSetStrokeCapsAndJoins) { { auto geometry = Geometry::MakeStrokePath(Path{}); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); // Defaults. ASSERT_EQ(path_geometry->GetStrokeCap(), Cap::kButt); ASSERT_EQ(path_geometry->GetStrokeJoin(), Join::kMiter); } { auto geometry = Geometry::MakeStrokePath(Path{}, 1.0, 4.0, Cap::kSquare); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); ASSERT_EQ(path_geometry->GetStrokeCap(), Cap::kSquare); } { auto geometry = Geometry::MakeStrokePath(Path{}, 1.0, 4.0, Cap::kRound); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); ASSERT_EQ(path_geometry->GetStrokeCap(), Cap::kRound); } } TEST_P(EntityTest, SolidColorContentsStrokeSetMiterLimit) { { auto geometry = Geometry::MakeStrokePath(Path{}); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); ASSERT_FLOAT_EQ(path_geometry->GetMiterLimit(), 4); } { auto geometry = Geometry::MakeStrokePath(Path{}, 1.0, /*miter_limit=*/8.0); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); ASSERT_FLOAT_EQ(path_geometry->GetMiterLimit(), 8); } { auto geometry = Geometry::MakeStrokePath(Path{}, 1.0, /*miter_limit=*/-1.0); auto path_geometry = static_cast<StrokePathGeometry*>(geometry.get()); ASSERT_FLOAT_EQ(path_geometry->GetMiterLimit(), 4); } } TEST_P(EntityTest, BlendingModeOptions) { std::vector<const char*> blend_mode_names; std::vector<BlendMode> blend_mode_values; { // Force an exhausiveness check with a switch. When adding blend modes, // update this switch with a new name/value to make it selectable in the // test GUI. const BlendMode b{}; static_assert(b == BlendMode::kClear); // Ensure the first item in // the switch is the first // item in the enum. static_assert(Entity::kLastPipelineBlendMode == BlendMode::kModulate); switch (b) { case BlendMode::kClear: blend_mode_names.push_back("Clear"); blend_mode_values.push_back(BlendMode::kClear); case BlendMode::kSource: blend_mode_names.push_back("Source"); blend_mode_values.push_back(BlendMode::kSource); case BlendMode::kDestination: blend_mode_names.push_back("Destination"); blend_mode_values.push_back(BlendMode::kDestination); case BlendMode::kSourceOver: blend_mode_names.push_back("SourceOver"); blend_mode_values.push_back(BlendMode::kSourceOver); case BlendMode::kDestinationOver: blend_mode_names.push_back("DestinationOver"); blend_mode_values.push_back(BlendMode::kDestinationOver); case BlendMode::kSourceIn: blend_mode_names.push_back("SourceIn"); blend_mode_values.push_back(BlendMode::kSourceIn); case BlendMode::kDestinationIn: blend_mode_names.push_back("DestinationIn"); blend_mode_values.push_back(BlendMode::kDestinationIn); case BlendMode::kSourceOut: blend_mode_names.push_back("SourceOut"); blend_mode_values.push_back(BlendMode::kSourceOut); case BlendMode::kDestinationOut: blend_mode_names.push_back("DestinationOut"); blend_mode_values.push_back(BlendMode::kDestinationOut); case BlendMode::kSourceATop: blend_mode_names.push_back("SourceATop"); blend_mode_values.push_back(BlendMode::kSourceATop); case BlendMode::kDestinationATop: blend_mode_names.push_back("DestinationATop"); blend_mode_values.push_back(BlendMode::kDestinationATop); case BlendMode::kXor: blend_mode_names.push_back("Xor"); blend_mode_values.push_back(BlendMode::kXor); case BlendMode::kPlus: blend_mode_names.push_back("Plus"); blend_mode_values.push_back(BlendMode::kPlus); case BlendMode::kModulate: blend_mode_names.push_back("Modulate"); blend_mode_values.push_back(BlendMode::kModulate); }; } auto callback = [&](ContentContext& context, RenderPass& pass) { auto world_matrix = Matrix::MakeScale(GetContentScale()); auto draw_rect = [&context, &pass, &world_matrix]( Rect rect, Color color, BlendMode blend_mode) -> bool { using VS = SolidFillPipeline::VertexShader; VertexBufferBuilder<VS::PerVertexData> vtx_builder; { auto r = rect.GetLTRB(); vtx_builder.AddVertices({ {Point(r[0], r[1])}, {Point(r[2], r[1])}, {Point(r[2], r[3])}, {Point(r[0], r[1])}, {Point(r[2], r[3])}, {Point(r[0], r[3])}, }); } pass.SetCommandLabel("Blended Rectangle"); auto options = OptionsFromPass(pass); options.blend_mode = blend_mode; options.primitive_type = PrimitiveType::kTriangle; pass.SetPipeline(context.GetSolidFillPipeline(options)); pass.SetVertexBuffer( vtx_builder.CreateVertexBuffer(context.GetTransientsBuffer())); VS::FrameInfo frame_info; frame_info.mvp = pass.GetOrthographicTransform() * world_matrix; frame_info.color = color.Premultiply(); VS::BindFrameInfo( pass, context.GetTransientsBuffer().EmplaceUniform(frame_info)); return pass.Draw().ok(); }; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); static Color color1(1, 0, 0, 0.5), color2(0, 1, 0, 0.5); ImGui::ColorEdit4("Color 1", reinterpret_cast<float*>(&color1)); ImGui::ColorEdit4("Color 2", reinterpret_cast<float*>(&color2)); static int current_blend_index = 3; ImGui::ListBox("Blending mode", &current_blend_index, blend_mode_names.data(), blend_mode_names.size()); ImGui::End(); BlendMode selected_mode = blend_mode_values[current_blend_index]; Point a, b, c, d; static PlaygroundPoint point_a(Point(400, 100), 20, Color::White()); static PlaygroundPoint point_b(Point(200, 300), 20, Color::White()); std::tie(a, b) = DrawPlaygroundLine(point_a, point_b); static PlaygroundPoint point_c(Point(470, 190), 20, Color::White()); static PlaygroundPoint point_d(Point(270, 390), 20, Color::White()); std::tie(c, d) = DrawPlaygroundLine(point_c, point_d); bool result = true; result = result && draw_rect(Rect::MakeXYWH(0, 0, pass.GetRenderTargetSize().width, pass.GetRenderTargetSize().height), Color(), BlendMode::kClear); result = result && draw_rect(Rect::MakeLTRB(a.x, a.y, b.x, b.y), color1, BlendMode::kSourceOver); result = result && draw_rect(Rect::MakeLTRB(c.x, c.y, d.x, d.y), color2, selected_mode); return result; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, BezierCircleScaled) { auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { static float scale = 20; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::SliderFloat("Scale", &scale, 1, 100); ImGui::End(); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto path = PathBuilder{} .MoveTo({97.325, 34.818}) .CubicCurveTo({98.50862885295136, 34.81812293973836}, {99.46822048142015, 33.85863261475589}, {99.46822048142015, 32.67499810206613}) .CubicCurveTo({99.46822048142015, 31.491363589376355}, {98.50862885295136, 30.53187326439389}, {97.32499434685802, 30.531998226542708}) .CubicCurveTo({96.14153655073771, 30.532123170035373}, {95.18222070648729, 31.491540299350355}, {95.18222070648729, 32.67499810206613}) .CubicCurveTo({95.18222070648729, 33.85845590478189}, {96.14153655073771, 34.81787303409686}, {97.32499434685802, 34.81799797758954}) .Close() .TakePath(); entity.SetTransform( Matrix::MakeScale({scale, scale, 1.0}).Translate({-90, -20, 0})); entity.SetContents(SolidColorContents::Make(path, Color::Red())); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, Filters) { auto bridge = CreateTextureForFixture("bay_bridge.jpg"); auto boston = CreateTextureForFixture("boston.jpg"); auto kalimba = CreateTextureForFixture("kalimba.jpg"); ASSERT_TRUE(bridge && boston && kalimba); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { auto fi_bridge = FilterInput::Make(bridge); auto fi_boston = FilterInput::Make(boston); auto fi_kalimba = FilterInput::Make(kalimba); std::shared_ptr<FilterContents> blend0 = ColorFilterContents::MakeBlend( BlendMode::kModulate, {fi_kalimba, fi_boston}); auto blend1 = ColorFilterContents::MakeBlend( BlendMode::kScreen, {FilterInput::Make(blend0), fi_bridge, fi_bridge, fi_bridge}); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(blend1); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, GaussianBlurFilter) { auto boston = CreateTextureForFixture("boston.jpg", /*enable_mipmapping=*/true); ASSERT_TRUE(boston); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { const char* input_type_names[] = {"Texture", "Solid Color"}; const char* blur_type_names[] = {"Image blur", "Mask blur"}; const char* pass_variation_names[] = {"New"}; const char* blur_style_names[] = {"Normal", "Solid", "Outer", "Inner"}; const char* tile_mode_names[] = {"Clamp", "Repeat", "Mirror", "Decal"}; const FilterContents::BlurStyle blur_styles[] = { FilterContents::BlurStyle::kNormal, FilterContents::BlurStyle::kSolid, FilterContents::BlurStyle::kOuter, FilterContents::BlurStyle::kInner}; const Entity::TileMode tile_modes[] = { Entity::TileMode::kClamp, Entity::TileMode::kRepeat, Entity::TileMode::kMirror, Entity::TileMode::kDecal}; // UI state. static int selected_input_type = 0; static Color input_color = Color::Black(); static int selected_blur_type = 0; static int selected_pass_variation = 0; static bool combined_sigma = false; static float blur_amount_coarse[2] = {0, 0}; static float blur_amount_fine[2] = {10, 10}; static int selected_blur_style = 0; static int selected_tile_mode = 3; static Color cover_color(1, 0, 0, 0.2); static Color bounds_color(0, 1, 0, 0.1); static float offset[2] = {500, 400}; static float rotation = 0; static float scale[2] = {0.65, 0.65}; static float skew[2] = {0, 0}; static float path_rect[4] = {0, 0, static_cast<float>(boston->GetSize().width), static_cast<float>(boston->GetSize().height)}; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); { ImGui::Combo("Input type", &selected_input_type, input_type_names, sizeof(input_type_names) / sizeof(char*)); if (selected_input_type == 0) { ImGui::SliderFloat("Input opacity", &input_color.alpha, 0, 1); } else { ImGui::ColorEdit4("Input color", reinterpret_cast<float*>(&input_color)); } ImGui::Combo("Blur type", &selected_blur_type, blur_type_names, sizeof(blur_type_names) / sizeof(char*)); if (selected_blur_type == 0) { ImGui::Combo("Pass variation", &selected_pass_variation, pass_variation_names, sizeof(pass_variation_names) / sizeof(char*)); } ImGui::Checkbox("Combined sigma", &combined_sigma); if (combined_sigma) { ImGui::SliderFloat("Sigma (coarse)", blur_amount_coarse, 0, 1000); ImGui::SliderFloat("Sigma (fine)", blur_amount_fine, 0, 10); blur_amount_coarse[1] = blur_amount_coarse[0]; blur_amount_fine[1] = blur_amount_fine[0]; } else { ImGui::SliderFloat2("Sigma (coarse)", blur_amount_coarse, 0, 1000); ImGui::SliderFloat2("Sigma (fine)", blur_amount_fine, 0, 10); } ImGui::Combo("Blur style", &selected_blur_style, blur_style_names, sizeof(blur_style_names) / sizeof(char*)); ImGui::Combo("Tile mode", &selected_tile_mode, tile_mode_names, sizeof(tile_mode_names) / sizeof(char*)); ImGui::ColorEdit4("Cover color", reinterpret_cast<float*>(&cover_color)); ImGui::ColorEdit4("Bounds color", reinterpret_cast<float*>(&bounds_color)); ImGui::SliderFloat2("Translation", offset, 0, pass.GetRenderTargetSize().width); ImGui::SliderFloat("Rotation", &rotation, 0, kPi * 2); ImGui::SliderFloat2("Scale", scale, 0, 3); ImGui::SliderFloat2("Skew", skew, -3, 3); ImGui::SliderFloat4("Path XYWH", path_rect, -1000, 1000); } ImGui::End(); auto blur_sigma_x = Sigma{blur_amount_coarse[0] + blur_amount_fine[0]}; auto blur_sigma_y = Sigma{blur_amount_coarse[1] + blur_amount_fine[1]}; std::shared_ptr<Contents> input; Size input_size; auto input_rect = Rect::MakeXYWH(path_rect[0], path_rect[1], path_rect[2], path_rect[3]); if (selected_input_type == 0) { auto texture = std::make_shared<TextureContents>(); texture->SetSourceRect(Rect::MakeSize(boston->GetSize())); texture->SetDestinationRect(input_rect); texture->SetTexture(boston); texture->SetOpacity(input_color.alpha); input = texture; input_size = input_rect.GetSize(); } else { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(input_color); fill->SetGeometry( Geometry::MakeFillPath(PathBuilder{}.AddRect(input_rect).TakePath())); input = fill; input_size = input_rect.GetSize(); } std::shared_ptr<FilterContents> blur; switch (selected_pass_variation) { case 0: blur = std::make_shared<GaussianBlurFilterContents>( blur_sigma_x.sigma, blur_sigma_y.sigma, tile_modes[selected_tile_mode], blur_styles[selected_blur_style], /*geometry=*/nullptr); blur->SetInputs({FilterInput::Make(input)}); break; case 1: blur = FilterContents::MakeGaussianBlur( FilterInput::Make(input), blur_sigma_x, blur_sigma_y, tile_modes[selected_tile_mode], blur_styles[selected_blur_style]); break; }; FML_CHECK(blur); auto mask_blur = FilterContents::MakeBorderMaskBlur( FilterInput::Make(input), blur_sigma_x, blur_sigma_y, blur_styles[selected_blur_style]); auto ctm = Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation(Vector3(offset[0], offset[1])) * Matrix::MakeRotationZ(Radians(rotation)) * Matrix::MakeScale(Vector2(scale[0], scale[1])) * Matrix::MakeSkew(skew[0], skew[1]) * Matrix::MakeTranslation(-Point(input_size) / 2); auto target_contents = selected_blur_type == 0 ? blur : mask_blur; Entity entity; entity.SetContents(target_contents); entity.SetTransform(ctm); entity.Render(context, pass); // Renders a red "cover" rectangle that shows the original position of the // unfiltered input. Entity cover_entity; cover_entity.SetContents(SolidColorContents::Make( PathBuilder{}.AddRect(input_rect).TakePath(), cover_color)); cover_entity.SetTransform(ctm); cover_entity.Render(context, pass); // Renders a green bounding rect of the target filter. Entity bounds_entity; std::optional<Rect> target_contents_coverage = target_contents->GetCoverage(entity); if (target_contents_coverage.has_value()) { bounds_entity.SetContents(SolidColorContents::Make( PathBuilder{} .AddRect(target_contents->GetCoverage(entity).value()) .TakePath(), bounds_color)); bounds_entity.SetTransform(Matrix()); bounds_entity.Render(context, pass); } return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, MorphologyFilter) { auto boston = CreateTextureForFixture("boston.jpg"); ASSERT_TRUE(boston); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { const char* morphology_type_names[] = {"Dilate", "Erode"}; const FilterContents::MorphType morphology_types[] = { FilterContents::MorphType::kDilate, FilterContents::MorphType::kErode}; static Color input_color = Color::Black(); // UI state. static int selected_morphology_type = 0; static float radius[2] = {20, 20}; static Color cover_color(1, 0, 0, 0.2); static Color bounds_color(0, 1, 0, 0.1); static float offset[2] = {500, 400}; static float rotation = 0; static float scale[2] = {0.65, 0.65}; static float skew[2] = {0, 0}; static float path_rect[4] = {0, 0, static_cast<float>(boston->GetSize().width), static_cast<float>(boston->GetSize().height)}; static float effect_transform_scale = 1; ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); { ImGui::Combo("Morphology type", &selected_morphology_type, morphology_type_names, sizeof(morphology_type_names) / sizeof(char*)); ImGui::SliderFloat2("Radius", radius, 0, 200); ImGui::SliderFloat("Input opacity", &input_color.alpha, 0, 1); ImGui::ColorEdit4("Cover color", reinterpret_cast<float*>(&cover_color)); ImGui::ColorEdit4("Bounds color", reinterpret_cast<float*>(&bounds_color)); ImGui::SliderFloat2("Translation", offset, 0, pass.GetRenderTargetSize().width); ImGui::SliderFloat("Rotation", &rotation, 0, kPi * 2); ImGui::SliderFloat2("Scale", scale, 0, 3); ImGui::SliderFloat2("Skew", skew, -3, 3); ImGui::SliderFloat4("Path XYWH", path_rect, -1000, 1000); ImGui::SliderFloat("Effect transform scale", &effect_transform_scale, 0, 3); } ImGui::End(); std::shared_ptr<Contents> input; Size input_size; auto input_rect = Rect::MakeXYWH(path_rect[0], path_rect[1], path_rect[2], path_rect[3]); auto texture = std::make_shared<TextureContents>(); texture->SetSourceRect(Rect::MakeSize(boston->GetSize())); texture->SetDestinationRect(input_rect); texture->SetTexture(boston); texture->SetOpacity(input_color.alpha); input = texture; input_size = input_rect.GetSize(); auto contents = FilterContents::MakeMorphology( FilterInput::Make(input), Radius{radius[0]}, Radius{radius[1]}, morphology_types[selected_morphology_type]); contents->SetEffectTransform(Matrix::MakeScale( Vector2{effect_transform_scale, effect_transform_scale})); auto ctm = Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation(Vector3(offset[0], offset[1])) * Matrix::MakeRotationZ(Radians(rotation)) * Matrix::MakeScale(Vector2(scale[0], scale[1])) * Matrix::MakeSkew(skew[0], skew[1]) * Matrix::MakeTranslation(-Point(input_size) / 2); Entity entity; entity.SetContents(contents); entity.SetTransform(ctm); entity.Render(context, pass); // Renders a red "cover" rectangle that shows the original position of the // unfiltered input. Entity cover_entity; cover_entity.SetContents(SolidColorContents::Make( PathBuilder{}.AddRect(input_rect).TakePath(), cover_color)); cover_entity.SetTransform(ctm); cover_entity.Render(context, pass); // Renders a green bounding rect of the target filter. Entity bounds_entity; bounds_entity.SetContents(SolidColorContents::Make( PathBuilder{}.AddRect(contents->GetCoverage(entity).value()).TakePath(), bounds_color)); bounds_entity.SetTransform(Matrix()); bounds_entity.Render(context, pass); return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, SetBlendMode) { Entity entity; ASSERT_EQ(entity.GetBlendMode(), BlendMode::kSourceOver); entity.SetBlendMode(BlendMode::kClear); ASSERT_EQ(entity.GetBlendMode(), BlendMode::kClear); } TEST_P(EntityTest, ContentsGetBoundsForEmptyPathReturnsNullopt) { Entity entity; entity.SetContents(std::make_shared<SolidColorContents>()); ASSERT_FALSE(entity.GetCoverage().has_value()); } TEST_P(EntityTest, SolidStrokeCoverageIsCorrect) { { auto geometry = Geometry::MakeStrokePath( PathBuilder{}.AddLine({0, 0}, {10, 10}).TakePath(), 4.0, 4.0, Cap::kButt, Join::kBevel); Entity entity; auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(std::move(geometry)); contents->SetColor(Color::Black()); entity.SetContents(std::move(contents)); auto actual = entity.GetCoverage(); auto expected = Rect::MakeLTRB(-2, -2, 12, 12); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } // Cover the Cap::kSquare case. { auto geometry = Geometry::MakeStrokePath( PathBuilder{}.AddLine({0, 0}, {10, 10}).TakePath(), 4.0, 4.0, Cap::kSquare, Join::kBevel); Entity entity; auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(std::move(geometry)); contents->SetColor(Color::Black()); entity.SetContents(std::move(contents)); auto actual = entity.GetCoverage(); auto expected = Rect::MakeLTRB(-sqrt(8), -sqrt(8), 10 + sqrt(8), 10 + sqrt(8)); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } // Cover the Join::kMiter case. { auto geometry = Geometry::MakeStrokePath( PathBuilder{}.AddLine({0, 0}, {10, 10}).TakePath(), 4.0, 2.0, Cap::kSquare, Join::kMiter); Entity entity; auto contents = std::make_unique<SolidColorContents>(); contents->SetGeometry(std::move(geometry)); contents->SetColor(Color::Black()); entity.SetContents(std::move(contents)); auto actual = entity.GetCoverage(); auto expected = Rect::MakeLTRB(-4, -4, 14, 14); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } } TEST_P(EntityTest, BorderMaskBlurCoverageIsCorrect) { auto fill = std::make_shared<SolidColorContents>(); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 300, 400)).TakePath())); fill->SetColor(Color::CornflowerBlue()); auto border_mask_blur = FilterContents::MakeBorderMaskBlur( FilterInput::Make(fill), Radius{3}, Radius{4}); { Entity e; e.SetTransform(Matrix()); auto actual = border_mask_blur->GetCoverage(e); auto expected = Rect::MakeXYWH(-3, -4, 306, 408); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } { Entity e; e.SetTransform(Matrix::MakeRotationZ(Radians{kPi / 4})); auto actual = border_mask_blur->GetCoverage(e); auto expected = Rect::MakeXYWH(-287.792, -4.94975, 504.874, 504.874); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } } TEST_P(EntityTest, DrawAtlasNoColor) { // Draws the image as four squares stiched together. auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); // Divide image into four quadrants. Scalar half_width = size.width / 2; Scalar half_height = size.height / 2; std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, half_width, half_height), Rect::MakeLTRB(half_width, 0, size.width, half_height), Rect::MakeLTRB(0, half_height, half_width, size.height), Rect::MakeLTRB(half_width, half_height, size.width, size.height)}; // Position quadrants adjacent to eachother. std::vector<Matrix> transforms = { Matrix::MakeTranslation({0, 0, 0}), Matrix::MakeTranslation({half_width, 0, 0}), Matrix::MakeTranslation({0, half_height, 0}), Matrix::MakeTranslation({half_width, half_height, 0})}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetBlendMode(BlendMode::kSource); Entity e; e.SetTransform(Matrix::MakeScale(GetContentScale())); e.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(e))); } TEST_P(EntityTest, DrawAtlasWithColorAdvanced) { // Draws the image as four squares stiched together. auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); // Divide image into four quadrants. Scalar half_width = size.width / 2; Scalar half_height = size.height / 2; std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, half_width, half_height), Rect::MakeLTRB(half_width, 0, size.width, half_height), Rect::MakeLTRB(0, half_height, half_width, size.height), Rect::MakeLTRB(half_width, half_height, size.width, size.height)}; // Position quadrants adjacent to eachother. std::vector<Matrix> transforms = { Matrix::MakeTranslation({0, 0, 0}), Matrix::MakeTranslation({half_width, 0, 0}), Matrix::MakeTranslation({0, half_height, 0}), Matrix::MakeTranslation({half_width, half_height, 0})}; std::vector<Color> colors = {Color::Red(), Color::Green(), Color::Blue(), Color::Yellow()}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetColors(colors); contents->SetBlendMode(BlendMode::kModulate); Entity e; e.SetTransform(Matrix::MakeScale(GetContentScale())); e.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(e))); } TEST_P(EntityTest, DrawAtlasWithColorSimple) { // Draws the image as four squares stiched together. Because blend modes // aren't implented this ends up as four solid color blocks. auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); // Divide image into four quadrants. Scalar half_width = size.width / 2; Scalar half_height = size.height / 2; std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, half_width, half_height), Rect::MakeLTRB(half_width, 0, size.width, half_height), Rect::MakeLTRB(0, half_height, half_width, size.height), Rect::MakeLTRB(half_width, half_height, size.width, size.height)}; // Position quadrants adjacent to eachother. std::vector<Matrix> transforms = { Matrix::MakeTranslation({0, 0, 0}), Matrix::MakeTranslation({half_width, 0, 0}), Matrix::MakeTranslation({0, half_height, 0}), Matrix::MakeTranslation({half_width, half_height, 0})}; std::vector<Color> colors = {Color::Red(), Color::Green(), Color::Blue(), Color::Yellow()}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetColors(colors); contents->SetBlendMode(BlendMode::kSourceATop); Entity e; e.SetTransform(Matrix::MakeScale(GetContentScale())); e.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(e))); } TEST_P(EntityTest, DrawAtlasUsesProvidedCullRectForCoverage) { auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); Scalar half_width = size.width / 2; Scalar half_height = size.height / 2; std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, half_width, half_height), Rect::MakeLTRB(half_width, 0, size.width, half_height), Rect::MakeLTRB(0, half_height, half_width, size.height), Rect::MakeLTRB(half_width, half_height, size.width, size.height)}; std::vector<Matrix> transforms = { Matrix::MakeTranslation({0, 0, 0}), Matrix::MakeTranslation({half_width, 0, 0}), Matrix::MakeTranslation({0, half_height, 0}), Matrix::MakeTranslation({half_width, half_height, 0})}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetBlendMode(BlendMode::kSource); auto transform = Matrix::MakeScale(GetContentScale()); Entity e; e.SetTransform(transform); e.SetContents(contents); ASSERT_EQ(contents->GetCoverage(e).value(), Rect::MakeSize(size).TransformBounds(transform)); contents->SetCullRect(Rect::MakeLTRB(0, 0, 10, 10)); ASSERT_EQ(contents->GetCoverage(e).value(), Rect::MakeLTRB(0, 0, 10, 10).TransformBounds(transform)); } TEST_P(EntityTest, DrawAtlasWithOpacity) { // Draws the image as four squares stiched together slightly // opaque auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); // Divide image into four quadrants. Scalar half_width = size.width / 2; Scalar half_height = size.height / 2; std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, half_width, half_height), Rect::MakeLTRB(half_width, 0, size.width, half_height), Rect::MakeLTRB(0, half_height, half_width, size.height), Rect::MakeLTRB(half_width, half_height, size.width, size.height)}; // Position quadrants adjacent to eachother. std::vector<Matrix> transforms = { Matrix::MakeTranslation({0, 0, 0}), Matrix::MakeTranslation({half_width, 0, 0}), Matrix::MakeTranslation({0, half_height, 0}), Matrix::MakeTranslation({half_width, half_height, 0})}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetBlendMode(BlendMode::kSource); contents->SetAlpha(0.5); Entity e; e.SetTransform(Matrix::MakeScale(GetContentScale())); e.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(e))); } TEST_P(EntityTest, DrawAtlasNoColorFullSize) { auto atlas = CreateTextureForFixture("bay_bridge.jpg"); auto size = atlas->GetSize(); std::vector<Rect> texture_coordinates = { Rect::MakeLTRB(0, 0, size.width, size.height)}; std::vector<Matrix> transforms = {Matrix::MakeTranslation({0, 0, 0})}; std::shared_ptr<AtlasContents> contents = std::make_shared<AtlasContents>(); contents->SetTransforms(std::move(transforms)); contents->SetTextureCoordinates(std::move(texture_coordinates)); contents->SetTexture(atlas); contents->SetBlendMode(BlendMode::kSource); Entity e; e.SetTransform(Matrix::MakeScale(GetContentScale())); e.SetContents(contents); ASSERT_TRUE(OpenPlaygroundHere(std::move(e))); } TEST_P(EntityTest, SolidFillCoverageIsCorrect) { // No transform { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); auto expected = Rect::MakeLTRB(100, 110, 200, 220); fill->SetGeometry( Geometry::MakeFillPath(PathBuilder{}.AddRect(expected).TakePath())); auto coverage = fill->GetCoverage({}); ASSERT_TRUE(coverage.has_value()); ASSERT_RECT_NEAR(coverage.value(), expected); } // Entity transform { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(100, 110, 200, 220)).TakePath())); Entity entity; entity.SetTransform(Matrix::MakeTranslation(Vector2(4, 5))); entity.SetContents(std::move(fill)); auto coverage = entity.GetCoverage(); auto expected = Rect::MakeLTRB(104, 115, 204, 225); ASSERT_TRUE(coverage.has_value()); ASSERT_RECT_NEAR(coverage.value(), expected); } // No coverage for fully transparent colors { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::WhiteTransparent()); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(100, 110, 200, 220)).TakePath())); auto coverage = fill->GetCoverage({}); ASSERT_FALSE(coverage.has_value()); } } TEST_P(EntityTest, SolidFillShouldRenderIsCorrect) { // No path. { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); ASSERT_FALSE(fill->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); ASSERT_FALSE( fill->ShouldRender(Entity{}, Rect::MakeLTRB(-100, -100, -50, -50))); } // With path. { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath())); ASSERT_TRUE(fill->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); ASSERT_FALSE( fill->ShouldRender(Entity{}, Rect::MakeLTRB(-100, -100, -50, -50))); } // With paint cover. { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); fill->SetGeometry(Geometry::MakeCover()); ASSERT_TRUE(fill->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); ASSERT_TRUE( fill->ShouldRender(Entity{}, Rect::MakeLTRB(-100, -100, -50, -50))); } } TEST_P(EntityTest, DoesNotCullEntitiesByDefault) { auto fill = std::make_shared<SolidColorContents>(); fill->SetColor(Color::CornflowerBlue()); fill->SetGeometry( Geometry::MakeRect(Rect::MakeLTRB(-1000, -1000, -900, -900))); Entity entity; entity.SetContents(fill); // Even though the entity is offscreen, this should still render because we do // not compute the coverage intersection by default. EXPECT_TRUE(entity.ShouldRender(Rect::MakeLTRB(0, 0, 100, 100))); } TEST_P(EntityTest, ClipContentsShouldRenderIsCorrect) { // For clip ops, `ShouldRender` should always return true. // Clip. { auto clip = std::make_shared<ClipContents>(); ASSERT_TRUE(clip->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); clip->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath())); ASSERT_TRUE(clip->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); ASSERT_TRUE( clip->ShouldRender(Entity{}, Rect::MakeLTRB(-100, -100, -50, -50))); } // Clip restore. { auto restore = std::make_shared<ClipRestoreContents>(); ASSERT_TRUE( restore->ShouldRender(Entity{}, Rect::MakeSize(Size{100, 100}))); ASSERT_TRUE( restore->ShouldRender(Entity{}, Rect::MakeLTRB(-100, -100, -50, -50))); } } TEST_P(EntityTest, ClipContentsGetClipCoverageIsCorrect) { // Intersection: No stencil coverage, no geometry. { auto clip = std::make_shared<ClipContents>(); clip->SetClipOperation(Entity::ClipOperation::kIntersect); auto result = clip->GetClipCoverage(Entity{}, Rect{}); ASSERT_FALSE(result.coverage.has_value()); } // Intersection: No stencil coverage, with geometry. { auto clip = std::make_shared<ClipContents>(); clip->SetClipOperation(Entity::ClipOperation::kIntersect); clip->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 100, 100)).TakePath())); auto result = clip->GetClipCoverage(Entity{}, Rect{}); ASSERT_FALSE(result.coverage.has_value()); } // Intersection: With stencil coverage, no geometry. { auto clip = std::make_shared<ClipContents>(); clip->SetClipOperation(Entity::ClipOperation::kIntersect); auto result = clip->GetClipCoverage(Entity{}, Rect::MakeLTRB(0, 0, 100, 100)); ASSERT_FALSE(result.coverage.has_value()); } // Intersection: With stencil coverage, with geometry. { auto clip = std::make_shared<ClipContents>(); clip->SetClipOperation(Entity::ClipOperation::kIntersect); clip->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 50, 50)).TakePath())); auto result = clip->GetClipCoverage(Entity{}, Rect::MakeLTRB(0, 0, 100, 100)); ASSERT_TRUE(result.coverage.has_value()); ASSERT_RECT_NEAR(result.coverage.value(), Rect::MakeLTRB(0, 0, 50, 50)); ASSERT_EQ(result.type, Contents::ClipCoverage::Type::kAppend); } // Difference: With stencil coverage, with geometry. { auto clip = std::make_shared<ClipContents>(); clip->SetClipOperation(Entity::ClipOperation::kDifference); clip->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 50, 50)).TakePath())); auto result = clip->GetClipCoverage(Entity{}, Rect::MakeLTRB(0, 0, 100, 100)); ASSERT_TRUE(result.coverage.has_value()); ASSERT_RECT_NEAR(result.coverage.value(), Rect::MakeLTRB(0, 0, 100, 100)); ASSERT_EQ(result.type, Contents::ClipCoverage::Type::kAppend); } } TEST_P(EntityTest, RRectShadowTest) { auto callback = [&](ContentContext& context, RenderPass& pass) { static Color color = Color::Red(); static float corner_radius = 100; static float blur_radius = 100; static bool show_coverage = false; static Color coverage_color = Color::Green().WithAlpha(0.2); ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::SliderFloat("Corner radius", &corner_radius, 0, 300); ImGui::SliderFloat("Blur radius", &blur_radius, 0, 300); ImGui::ColorEdit4("Color", reinterpret_cast<Scalar*>(&color)); ImGui::Checkbox("Show coverage", &show_coverage); if (show_coverage) { ImGui::ColorEdit4("Coverage color", reinterpret_cast<Scalar*>(&coverage_color)); } ImGui::End(); static PlaygroundPoint top_left_point(Point(200, 200), 30, Color::White()); static PlaygroundPoint bottom_right_point(Point(600, 400), 30, Color::White()); auto [top_left, bottom_right] = DrawPlaygroundLine(top_left_point, bottom_right_point); auto rect = Rect::MakeLTRB(top_left.x, top_left.y, bottom_right.x, bottom_right.y); auto contents = std::make_unique<SolidRRectBlurContents>(); contents->SetRRect(rect, {corner_radius, corner_radius}); contents->SetColor(color); contents->SetSigma(Radius(blur_radius)); Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); entity.SetContents(std::move(contents)); entity.Render(context, pass); auto coverage = entity.GetCoverage(); if (show_coverage && coverage.has_value()) { auto bounds_contents = std::make_unique<SolidColorContents>(); bounds_contents->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(entity.GetCoverage().value()).TakePath())); bounds_contents->SetColor(coverage_color.Premultiply()); Entity bounds_entity; bounds_entity.SetContents(std::move(bounds_contents)); bounds_entity.Render(context, pass); } return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, ColorMatrixFilterCoverageIsCorrect) { // Set up a simple color background. auto fill = std::make_shared<SolidColorContents>(); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 300, 400)).TakePath())); fill->SetColor(Color::Coral()); // Set the color matrix filter. ColorMatrix matrix = { 1, 1, 1, 1, 1, // 1, 1, 1, 1, 1, // 1, 1, 1, 1, 1, // 1, 1, 1, 1, 1, // }; auto filter = ColorFilterContents::MakeColorMatrix(FilterInput::Make(fill), matrix); Entity e; e.SetTransform(Matrix()); // Confirm that the actual filter coverage matches the expected coverage. auto actual = filter->GetCoverage(e); auto expected = Rect::MakeXYWH(0, 0, 300, 400); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } TEST_P(EntityTest, ColorMatrixFilterEditable) { auto bay_bridge = CreateTextureForFixture("bay_bridge.jpg"); ASSERT_TRUE(bay_bridge); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { // UI state. static ColorMatrix color_matrix = { 1, 0, 0, 0, 0, // 0, 3, 0, 0, 0, // 0, 0, 1, 0, 0, // 0, 0, 0, 1, 0, // }; static float offset[2] = {500, 400}; static float rotation = 0; static float scale[2] = {0.65, 0.65}; static float skew[2] = {0, 0}; // Define the ImGui ImGui::Begin("Color Matrix", nullptr, ImGuiWindowFlags_AlwaysAutoResize); { std::string label = "##1"; for (int i = 0; i < 20; i += 5) { ImGui::InputScalarN(label.c_str(), ImGuiDataType_Float, &(color_matrix.array[i]), 5, nullptr, nullptr, "%.2f", 0); label[2]++; } ImGui::SliderFloat2("Translation", &offset[0], 0, pass.GetRenderTargetSize().width); ImGui::SliderFloat("Rotation", &rotation, 0, kPi * 2); ImGui::SliderFloat2("Scale", &scale[0], 0, 3); ImGui::SliderFloat2("Skew", &skew[0], -3, 3); } ImGui::End(); // Set the color matrix filter. auto filter = ColorFilterContents::MakeColorMatrix( FilterInput::Make(bay_bridge), color_matrix); // Define the entity with the color matrix filter. Entity entity; entity.SetTransform( Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation(Vector3(offset[0], offset[1])) * Matrix::MakeRotationZ(Radians(rotation)) * Matrix::MakeScale(Vector2(scale[0], scale[1])) * Matrix::MakeSkew(skew[0], skew[1]) * Matrix::MakeTranslation(-Point(bay_bridge->GetSize()) / 2)); entity.SetContents(filter); entity.Render(context, pass); return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, LinearToSrgbFilterCoverageIsCorrect) { // Set up a simple color background. auto fill = std::make_shared<SolidColorContents>(); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 300, 400)).TakePath())); fill->SetColor(Color::MintCream()); auto filter = ColorFilterContents::MakeLinearToSrgbFilter(FilterInput::Make(fill)); Entity e; e.SetTransform(Matrix()); // Confirm that the actual filter coverage matches the expected coverage. auto actual = filter->GetCoverage(e); auto expected = Rect::MakeXYWH(0, 0, 300, 400); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } TEST_P(EntityTest, LinearToSrgbFilter) { auto image = CreateTextureForFixture("kalimba.jpg"); ASSERT_TRUE(image); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { auto filtered = ColorFilterContents::MakeLinearToSrgbFilter(FilterInput::Make(image)); // Define the entity that will serve as the control image as a Gaussian blur // filter with no filter at all. Entity entity_left; entity_left.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({100, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); auto unfiltered = FilterContents::MakeGaussianBlur(FilterInput::Make(image), Sigma{0}, Sigma{0}); entity_left.SetContents(unfiltered); // Define the entity that will be filtered from linear to sRGB. Entity entity_right; entity_right.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity_right.SetContents(filtered); return entity_left.Render(context, pass) && entity_right.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, SrgbToLinearFilterCoverageIsCorrect) { // Set up a simple color background. auto fill = std::make_shared<SolidColorContents>(); fill->SetGeometry(Geometry::MakeFillPath( PathBuilder{}.AddRect(Rect::MakeXYWH(0, 0, 300, 400)).TakePath())); fill->SetColor(Color::DeepPink()); auto filter = ColorFilterContents::MakeSrgbToLinearFilter(FilterInput::Make(fill)); Entity e; e.SetTransform(Matrix()); // Confirm that the actual filter coverage matches the expected coverage. auto actual = filter->GetCoverage(e); auto expected = Rect::MakeXYWH(0, 0, 300, 400); ASSERT_TRUE(actual.has_value()); ASSERT_RECT_NEAR(actual.value(), expected); } TEST_P(EntityTest, SrgbToLinearFilter) { auto image = CreateTextureForFixture("embarcadero.jpg"); ASSERT_TRUE(image); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { auto filtered = ColorFilterContents::MakeSrgbToLinearFilter(FilterInput::Make(image)); // Define the entity that will serve as the control image as a Gaussian blur // filter with no filter at all. Entity entity_left; entity_left.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({100, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); auto unfiltered = FilterContents::MakeGaussianBlur(FilterInput::Make(image), Sigma{0}, Sigma{0}); entity_left.SetContents(unfiltered); // Define the entity that will be filtered from sRGB to linear. Entity entity_right; entity_right.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity_right.SetContents(filtered); return entity_left.Render(context, pass) && entity_right.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, AtlasContentsSubAtlas) { auto boston = CreateTextureForFixture("boston.jpg"); { auto contents = std::make_shared<AtlasContents>(); contents->SetBlendMode(BlendMode::kSourceOver); contents->SetTexture(boston); contents->SetColors({ Color::Red(), Color::Red(), Color::Red(), }); contents->SetTextureCoordinates({ Rect::MakeLTRB(0, 0, 10, 10), Rect::MakeLTRB(0, 0, 10, 10), Rect::MakeLTRB(0, 0, 10, 10), }); contents->SetTransforms({ Matrix::MakeTranslation(Vector2(0, 0)), Matrix::MakeTranslation(Vector2(100, 100)), Matrix::MakeTranslation(Vector2(200, 200)), }); // Since all colors and sample rects are the same, there should // only be a single entry in the sub atlas. auto subatlas = contents->GenerateSubAtlas(); ASSERT_EQ(subatlas->sub_texture_coords.size(), 1u); } { auto contents = std::make_shared<AtlasContents>(); contents->SetBlendMode(BlendMode::kSourceOver); contents->SetTexture(boston); contents->SetColors({ Color::Red(), Color::Green(), Color::Blue(), }); contents->SetTextureCoordinates({ Rect::MakeLTRB(0, 0, 10, 10), Rect::MakeLTRB(0, 0, 10, 10), Rect::MakeLTRB(0, 0, 10, 10), }); contents->SetTransforms({ Matrix::MakeTranslation(Vector2(0, 0)), Matrix::MakeTranslation(Vector2(100, 100)), Matrix::MakeTranslation(Vector2(200, 200)), }); // Since all colors are different, there are three entires. auto subatlas = contents->GenerateSubAtlas(); ASSERT_EQ(subatlas->sub_texture_coords.size(), 3u); // The translations are kept but the sample rects point into // different parts of the sub atlas. ASSERT_EQ(subatlas->result_texture_coords[0], Rect::MakeXYWH(0, 0, 10, 10)); ASSERT_EQ(subatlas->result_texture_coords[1], Rect::MakeXYWH(11, 0, 10, 10)); ASSERT_EQ(subatlas->result_texture_coords[2], Rect::MakeXYWH(22, 0, 10, 10)); } } static Vector3 RGBToYUV(Vector3 rgb, YUVColorSpace yuv_color_space) { Vector3 yuv; switch (yuv_color_space) { case YUVColorSpace::kBT601FullRange: yuv.x = rgb.x * 0.299 + rgb.y * 0.587 + rgb.z * 0.114; yuv.y = rgb.x * -0.169 + rgb.y * -0.331 + rgb.z * 0.5 + 0.5; yuv.z = rgb.x * 0.5 + rgb.y * -0.419 + rgb.z * -0.081 + 0.5; break; case YUVColorSpace::kBT601LimitedRange: yuv.x = rgb.x * 0.257 + rgb.y * 0.516 + rgb.z * 0.100 + 0.063; yuv.y = rgb.x * -0.145 + rgb.y * -0.291 + rgb.z * 0.439 + 0.5; yuv.z = rgb.x * 0.429 + rgb.y * -0.368 + rgb.z * -0.071 + 0.5; break; } return yuv; } static std::vector<std::shared_ptr<Texture>> CreateTestYUVTextures( Context* context, YUVColorSpace yuv_color_space) { Vector3 red = {244.0 / 255.0, 67.0 / 255.0, 54.0 / 255.0}; Vector3 green = {76.0 / 255.0, 175.0 / 255.0, 80.0 / 255.0}; Vector3 blue = {33.0 / 255.0, 150.0 / 255.0, 243.0 / 255.0}; Vector3 white = {1.0, 1.0, 1.0}; Vector3 red_yuv = RGBToYUV(red, yuv_color_space); Vector3 green_yuv = RGBToYUV(green, yuv_color_space); Vector3 blue_yuv = RGBToYUV(blue, yuv_color_space); Vector3 white_yuv = RGBToYUV(white, yuv_color_space); std::vector<Vector3> yuvs{red_yuv, green_yuv, blue_yuv, white_yuv}; std::vector<uint8_t> y_data; std::vector<uint8_t> uv_data; for (int i = 0; i < 4; i++) { auto yuv = yuvs[i]; uint8_t y = std::round(yuv.x * 255.0); uint8_t u = std::round(yuv.y * 255.0); uint8_t v = std::round(yuv.z * 255.0); for (int j = 0; j < 16; j++) { y_data.push_back(y); } for (int j = 0; j < 8; j++) { uv_data.push_back(j % 2 == 0 ? u : v); } } impeller::TextureDescriptor y_texture_descriptor; y_texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; y_texture_descriptor.format = PixelFormat::kR8UNormInt; y_texture_descriptor.size = {8, 8}; auto y_texture = context->GetResourceAllocator()->CreateTexture(y_texture_descriptor); auto y_mapping = std::make_shared<fml::DataMapping>(y_data); if (!y_texture->SetContents(y_mapping)) { FML_DLOG(ERROR) << "Could not copy contents into Y texture."; } impeller::TextureDescriptor uv_texture_descriptor; uv_texture_descriptor.storage_mode = impeller::StorageMode::kHostVisible; uv_texture_descriptor.format = PixelFormat::kR8G8UNormInt; uv_texture_descriptor.size = {4, 4}; auto uv_texture = context->GetResourceAllocator()->CreateTexture(uv_texture_descriptor); auto uv_mapping = std::make_shared<fml::DataMapping>(uv_data); if (!uv_texture->SetContents(uv_mapping)) { FML_DLOG(ERROR) << "Could not copy contents into UV texture."; } return {y_texture, uv_texture}; } TEST_P(EntityTest, YUVToRGBFilter) { if (GetParam() == PlaygroundBackend::kOpenGLES) { // TODO(114588) : Support YUV to RGB filter on OpenGLES backend. GTEST_SKIP_("YUV to RGB filter is not supported on OpenGLES backend yet."); } auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { YUVColorSpace yuv_color_space_array[2]{YUVColorSpace::kBT601FullRange, YUVColorSpace::kBT601LimitedRange}; for (int i = 0; i < 2; i++) { auto yuv_color_space = yuv_color_space_array[i]; auto textures = CreateTestYUVTextures(GetContext().get(), yuv_color_space); auto filter_contents = FilterContents::MakeYUVToRGBFilter( textures[0], textures[1], yuv_color_space); Entity filter_entity; filter_entity.SetContents(filter_contents); auto snapshot = filter_contents->RenderToSnapshot(context, filter_entity); Entity entity; auto contents = TextureContents::MakeRect(Rect::MakeLTRB(0, 0, 256, 256)); contents->SetTexture(snapshot->texture); contents->SetSourceRect(Rect::MakeSize(snapshot->texture->GetSize())); entity.SetContents(contents); entity.SetTransform( Matrix::MakeTranslation({static_cast<Scalar>(100 + 400 * i), 300})); entity.Render(context, pass); } return true; }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, RuntimeEffect) { auto runtime_stages = OpenAssetAsRuntimeStage("runtime_stage_example.frag.iplr"); auto runtime_stage = runtime_stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; ASSERT_TRUE(runtime_stage); ASSERT_TRUE(runtime_stage->IsDirty()); bool expect_dirty = true; Pipeline<PipelineDescriptor>* first_pipeline = nullptr; auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { EXPECT_EQ(runtime_stage->IsDirty(), expect_dirty); auto contents = std::make_shared<RuntimeEffectContents>(); contents->SetGeometry(Geometry::MakeCover()); contents->SetRuntimeStage(runtime_stage); struct FragUniforms { Vector2 iResolution; Scalar iTime; } frag_uniforms = { .iResolution = Vector2(GetWindowSize().width, GetWindowSize().height), .iTime = static_cast<Scalar>(GetSecondsElapsed()), }; auto uniform_data = std::make_shared<std::vector<uint8_t>>(); uniform_data->resize(sizeof(FragUniforms)); memcpy(uniform_data->data(), &frag_uniforms, sizeof(FragUniforms)); contents->SetUniformData(uniform_data); Entity entity; entity.SetContents(contents); bool result = contents->Render(context, entity, pass); if (expect_dirty) { EXPECT_NE(first_pipeline, pass.GetCommands().back().pipeline.get()); first_pipeline = pass.GetCommands().back().pipeline.get(); } else { EXPECT_EQ(pass.GetCommands().back().pipeline.get(), first_pipeline); } expect_dirty = false; return result; }; // Simulate some renders and hot reloading of the shader. auto content_context = GetContentContext(); { RenderTarget target; testing::MockRenderPass mock_pass(GetContext(), target); callback(*content_context, mock_pass); callback(*content_context, mock_pass); // Dirty the runtime stage. runtime_stages = OpenAssetAsRuntimeStage("runtime_stage_example.frag.iplr"); runtime_stage = runtime_stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; ASSERT_TRUE(runtime_stage->IsDirty()); expect_dirty = true; callback(*content_context, mock_pass); callback(*content_context, mock_pass); } ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, RuntimeEffectCanSuccessfullyRender) { auto runtime_stages = OpenAssetAsRuntimeStage("runtime_stage_example.frag.iplr"); auto runtime_stage = runtime_stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; ASSERT_TRUE(runtime_stage); ASSERT_TRUE(runtime_stage->IsDirty()); auto contents = std::make_shared<RuntimeEffectContents>(); contents->SetGeometry(Geometry::MakeCover()); contents->SetRuntimeStage(runtime_stage); struct FragUniforms { Vector2 iResolution; Scalar iTime; } frag_uniforms = { .iResolution = Vector2(GetWindowSize().width, GetWindowSize().height), .iTime = static_cast<Scalar>(GetSecondsElapsed()), }; auto uniform_data = std::make_shared<std::vector<uint8_t>>(); uniform_data->resize(sizeof(FragUniforms)); memcpy(uniform_data->data(), &frag_uniforms, sizeof(FragUniforms)); contents->SetUniformData(uniform_data); Entity entity; entity.SetContents(contents); // Create a render target with a depth-stencil, similar to how EntityPass // does. RenderTarget target = GetContentContext()->GetRenderTargetCache()->CreateOffscreenMSAA( *GetContext(), {GetWindowSize().width, GetWindowSize().height}, 1, "RuntimeEffect Texture"); testing::MockRenderPass pass(GetContext(), target); ASSERT_TRUE(contents->Render(*GetContentContext(), entity, pass)); ASSERT_EQ(pass.GetCommands().size(), 1u); const auto& command = pass.GetCommands()[0]; ASSERT_TRUE(command.pipeline->GetDescriptor() .GetDepthStencilAttachmentDescriptor() .has_value()); ASSERT_TRUE(command.pipeline->GetDescriptor() .GetFrontStencilAttachmentDescriptor() .has_value()); } TEST_P(EntityTest, RuntimeEffectSetsRightSizeWhenUniformIsStruct) { if (GetBackend() != PlaygroundBackend::kVulkan) { GTEST_SKIP() << "Test only applies to Vulkan"; } auto runtime_stages = OpenAssetAsRuntimeStage("runtime_stage_example.frag.iplr"); auto runtime_stage = runtime_stages[PlaygroundBackendToRuntimeStageBackend(GetBackend())]; ASSERT_TRUE(runtime_stage); ASSERT_TRUE(runtime_stage->IsDirty()); auto contents = std::make_shared<RuntimeEffectContents>(); contents->SetGeometry(Geometry::MakeCover()); contents->SetRuntimeStage(runtime_stage); struct FragUniforms { Vector2 iResolution; Scalar iTime; } frag_uniforms = { .iResolution = Vector2(GetWindowSize().width, GetWindowSize().height), .iTime = static_cast<Scalar>(GetSecondsElapsed()), }; auto uniform_data = std::make_shared<std::vector<uint8_t>>(); uniform_data->resize(sizeof(FragUniforms)); memcpy(uniform_data->data(), &frag_uniforms, sizeof(FragUniforms)); contents->SetUniformData(uniform_data); Entity entity; entity.SetContents(contents); auto context = GetContentContext(); RenderTarget target; testing::MockRenderPass pass(GetContext(), target); ASSERT_TRUE(contents->Render(*context, entity, pass)); ASSERT_EQ(pass.GetCommands().size(), 1u); const auto& command = pass.GetCommands()[0]; ASSERT_EQ(command.fragment_bindings.buffers.size(), 1u); // 16 bytes: // 8 bytes for iResolution // 4 bytes for iTime // 4 bytes padding EXPECT_EQ(command.fragment_bindings.buffers[0].view.resource.range.length, 16u); } TEST_P(EntityTest, InheritOpacityTest) { Entity entity; // Texture contents can always accept opacity. auto texture_contents = std::make_shared<TextureContents>(); texture_contents->SetOpacity(0.5); ASSERT_TRUE(texture_contents->CanInheritOpacity(entity)); texture_contents->SetInheritedOpacity(0.5); ASSERT_EQ(texture_contents->GetOpacity(), 0.25); texture_contents->SetInheritedOpacity(0.5); ASSERT_EQ(texture_contents->GetOpacity(), 0.25); // Solid color contents can accept opacity if their geometry // doesn't overlap. auto solid_color = std::make_shared<SolidColorContents>(); solid_color->SetGeometry( Geometry::MakeRect(Rect::MakeLTRB(100, 100, 200, 200))); solid_color->SetColor(Color::Blue().WithAlpha(0.5)); ASSERT_TRUE(solid_color->CanInheritOpacity(entity)); solid_color->SetInheritedOpacity(0.5); ASSERT_EQ(solid_color->GetColor().alpha, 0.25); solid_color->SetInheritedOpacity(0.5); ASSERT_EQ(solid_color->GetColor().alpha, 0.25); // Color source contents can accept opacity if their geometry // doesn't overlap. auto tiled_texture = std::make_shared<TiledTextureContents>(); tiled_texture->SetGeometry( Geometry::MakeRect(Rect::MakeLTRB(100, 100, 200, 200))); tiled_texture->SetOpacityFactor(0.5); ASSERT_TRUE(tiled_texture->CanInheritOpacity(entity)); tiled_texture->SetInheritedOpacity(0.5); ASSERT_EQ(tiled_texture->GetOpacityFactor(), 0.25); tiled_texture->SetInheritedOpacity(0.5); ASSERT_EQ(tiled_texture->GetOpacityFactor(), 0.25); // Text contents can accept opacity if the text frames do not // overlap SkFont font = flutter::testing::CreateTestFontOfSize(30); auto blob = SkTextBlob::MakeFromString("A", font); auto frame = MakeTextFrameFromTextBlobSkia(blob); auto lazy_glyph_atlas = std::make_shared<LazyGlyphAtlas>(TypographerContextSkia::Make()); lazy_glyph_atlas->AddTextFrame(*frame, 1.0f); auto text_contents = std::make_shared<TextContents>(); text_contents->SetTextFrame(frame); text_contents->SetColor(Color::Blue().WithAlpha(0.5)); ASSERT_TRUE(text_contents->CanInheritOpacity(entity)); text_contents->SetInheritedOpacity(0.5); ASSERT_EQ(text_contents->GetColor().alpha, 0.25); text_contents->SetInheritedOpacity(0.5); ASSERT_EQ(text_contents->GetColor().alpha, 0.25); // Clips and restores trivially accept opacity. ASSERT_TRUE(ClipContents().CanInheritOpacity(entity)); ASSERT_TRUE(ClipRestoreContents().CanInheritOpacity(entity)); // Runtime effect contents can't accept opacity. auto runtime_effect = std::make_shared<RuntimeEffectContents>(); ASSERT_FALSE(runtime_effect->CanInheritOpacity(entity)); } TEST_P(EntityTest, ColorFilterWithForegroundColorAdvancedBlend) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend( BlendMode::kColorBurn, FilterInput::Make({image}), Color::Red()); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(filter); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, ColorFilterWithForegroundColorClearBlend) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend( BlendMode::kClear, FilterInput::Make({image}), Color::Red()); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(filter); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, ColorFilterWithForegroundColorSrcBlend) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend( BlendMode::kSource, FilterInput::Make({image}), Color::Red()); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(filter); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, ColorFilterWithForegroundColorDstBlend) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend( BlendMode::kDestination, FilterInput::Make({image}), Color::Red()); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(filter); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, ColorFilterWithForegroundColorSrcInBlend) { auto image = CreateTextureForFixture("boston.jpg"); auto filter = ColorFilterContents::MakeBlend( BlendMode::kSourceIn, FilterInput::Make({image}), Color::Red()); auto callback = [&](ContentContext& context, RenderPass& pass) -> bool { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale()) * Matrix::MakeTranslation({500, 300}) * Matrix::MakeScale(Vector2{0.5, 0.5})); entity.SetContents(filter); return entity.Render(context, pass); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(EntityTest, CoverageForStrokePathWithNegativeValuesInTransform) { auto arrow_head = PathBuilder{} .MoveTo({50, 120}) .LineTo({120, 190}) .LineTo({190, 120}) .TakePath(); auto geometry = Geometry::MakeStrokePath(arrow_head, 15.0, 4.0, Cap::kRound, Join::kRound); auto transform = Matrix::MakeTranslation({300, 300}) * Matrix::MakeRotationZ(Radians(kPiOver2)); EXPECT_LT(transform.e[0][0], 0.f); auto coverage = geometry->GetCoverage(transform); ASSERT_RECT_NEAR(coverage.value(), Rect::MakeXYWH(102.5, 342.5, 85, 155)); } TEST_P(EntityTest, SolidColorContentsIsOpaque) { SolidColorContents contents; contents.SetColor(Color::CornflowerBlue()); ASSERT_TRUE(contents.IsOpaque()); contents.SetColor(Color::CornflowerBlue().WithAlpha(0.5)); ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, ConicalGradientContentsIsOpaque) { ConicalGradientContents contents; contents.SetColors({Color::CornflowerBlue()}); ASSERT_FALSE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue().WithAlpha(0.5)}); ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, LinearGradientContentsIsOpaque) { LinearGradientContents contents; contents.SetColors({Color::CornflowerBlue()}); ASSERT_TRUE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue().WithAlpha(0.5)}); ASSERT_FALSE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue()}); contents.SetTileMode(Entity::TileMode::kDecal); ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, RadialGradientContentsIsOpaque) { RadialGradientContents contents; contents.SetColors({Color::CornflowerBlue()}); ASSERT_TRUE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue().WithAlpha(0.5)}); ASSERT_FALSE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue()}); contents.SetTileMode(Entity::TileMode::kDecal); ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, SweepGradientContentsIsOpaque) { RadialGradientContents contents; contents.SetColors({Color::CornflowerBlue()}); ASSERT_TRUE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue().WithAlpha(0.5)}); ASSERT_FALSE(contents.IsOpaque()); contents.SetColors({Color::CornflowerBlue()}); contents.SetTileMode(Entity::TileMode::kDecal); ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, TiledTextureContentsIsOpaque) { auto bay_bridge = CreateTextureForFixture("bay_bridge.jpg"); TiledTextureContents contents; contents.SetTexture(bay_bridge); // This is a placeholder test. Images currently never decompress as opaque // (whether in Flutter or the playground), and so this should currently always // return false in practice. ASSERT_FALSE(contents.IsOpaque()); } TEST_P(EntityTest, PointFieldGeometryDivisions) { // Square always gives 4 divisions. ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(24.0, false), 4u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(2.0, false), 4u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(200.0, false), 4u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(0.5, true), 4u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(1.5, true), 8u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(5.5, true), 24u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(12.5, true), 34u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(22.3, true), 22u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(40.5, true), 40u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(100.0, true), 100u); // Caps at 140. ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(1000.0, true), 140u); ASSERT_EQ(PointFieldGeometry::ComputeCircleDivisions(20000.0, true), 140u); } TEST_P(EntityTest, PointFieldGeometryCoverage) { std::vector<Point> points = {{10, 20}, {100, 200}}; auto geometry = Geometry::MakePointField(points, 5.0, false); ASSERT_EQ(*geometry->GetCoverage(Matrix()), Rect::MakeLTRB(5, 15, 105, 205)); ASSERT_EQ(*geometry->GetCoverage(Matrix::MakeTranslation({30, 0, 0})), Rect::MakeLTRB(35, 15, 135, 205)); } TEST_P(EntityTest, ColorFilterContentsWithLargeGeometry) { Entity entity; entity.SetTransform(Matrix::MakeScale(GetContentScale())); auto src_contents = std::make_shared<SolidColorContents>(); src_contents->SetGeometry( Geometry::MakeRect(Rect::MakeLTRB(-300, -500, 30000, 50000))); src_contents->SetColor(Color::Red()); auto dst_contents = std::make_shared<SolidColorContents>(); dst_contents->SetGeometry( Geometry::MakeRect(Rect::MakeLTRB(300, 500, 20000, 30000))); dst_contents->SetColor(Color::Blue()); auto contents = ColorFilterContents::MakeBlend( BlendMode::kSourceOver, {FilterInput::Make(dst_contents, false), FilterInput::Make(src_contents, false)}); entity.SetContents(std::move(contents)); ASSERT_TRUE(OpenPlaygroundHere(std::move(entity))); } TEST_P(EntityTest, TextContentsCeilsGlyphScaleToDecimal) { ASSERT_EQ(TextFrame::RoundScaledFontSize(0.4321111f, 12), 0.43f); ASSERT_EQ(TextFrame::RoundScaledFontSize(0.5321111f, 12), 0.53f); ASSERT_EQ(TextFrame::RoundScaledFontSize(2.1f, 12), 2.1f); ASSERT_EQ(TextFrame::RoundScaledFontSize(0.0f, 12), 0.0f); } TEST_P(EntityTest, AdvancedBlendCoverageHintIsNotResetByEntityPass) { if (GetContext()->GetCapabilities()->SupportsFramebufferFetch()) { GTEST_SKIP() << "Backends that support framebuffer fetch dont use coverage " "for advanced blends."; } auto contents = std::make_shared<SolidColorContents>(); contents->SetGeometry(Geometry::MakeRect(Rect::MakeXYWH(100, 100, 100, 100))); contents->SetColor(Color::Red()); Entity entity; entity.SetTransform(Matrix::MakeScale(Vector3(2, 2, 1))); entity.SetBlendMode(BlendMode::kColorBurn); entity.SetContents(contents); auto coverage = entity.GetCoverage(); EXPECT_TRUE(coverage.has_value()); auto pass = std::make_unique<EntityPass>(); std::shared_ptr<RenderTargetCache> render_target_allocator = std::make_shared<RenderTargetCache>(GetContext()->GetResourceAllocator()); auto stencil_config = RenderTarget::AttachmentConfig{ .storage_mode = StorageMode::kDevicePrivate, .load_action = LoadAction::kClear, .store_action = StoreAction::kDontCare, .clear_color = Color::BlackTransparent()}; auto rt = render_target_allocator->CreateOffscreen( *GetContext(), ISize::MakeWH(1000, 1000), /*mip_count=*/1, "Offscreen", RenderTarget::kDefaultColorAttachmentConfig, stencil_config); auto content_context = ContentContext( GetContext(), TypographerContextSkia::Make(), render_target_allocator); pass->AddEntity(std::move(entity)); EXPECT_TRUE(pass->Render(content_context, rt)); auto contains_size = [&render_target_allocator](ISize size) -> bool { return std::find_if(render_target_allocator->GetRenderTargetDataBegin(), render_target_allocator->GetRenderTargetDataEnd(), [&size](const auto& data) { return data.config.size == size; }) != render_target_allocator->GetRenderTargetDataEnd(); }; EXPECT_TRUE(contains_size(ISize(1000, 1000))) << "The root texture wasn't allocated"; EXPECT_TRUE(contains_size(ISize(200, 200))) << "The ColorBurned texture wasn't allocated (100x100 scales up 2x)"; } TEST_P(EntityTest, SpecializationConstantsAreAppliedToVariants) { auto content_context = GetContentContext(); auto default_color_burn = content_context->GetBlendColorBurnPipeline({ .color_attachment_pixel_format = PixelFormat::kR8G8B8A8UNormInt, .has_depth_stencil_attachments = false, }); auto alt_color_burn = content_context->GetBlendColorBurnPipeline( {.color_attachment_pixel_format = PixelFormat::kR8G8B8A8UNormInt, .has_depth_stencil_attachments = true}); ASSERT_NE(default_color_burn, alt_color_burn); ASSERT_EQ(default_color_burn->GetDescriptor().GetSpecializationConstants(), alt_color_burn->GetDescriptor().GetSpecializationConstants()); auto decal_supported = static_cast<Scalar>( GetContext()->GetCapabilities()->SupportsDecalSamplerAddressMode()); std::vector<Scalar> expected_constants = {5, decal_supported}; ASSERT_EQ(default_color_burn->GetDescriptor().GetSpecializationConstants(), expected_constants); } TEST_P(EntityTest, DecalSpecializationAppliedToMorphologyFilter) { auto content_context = GetContentContext(); auto default_color_burn = content_context->GetMorphologyFilterPipeline({ .color_attachment_pixel_format = PixelFormat::kR8G8B8A8UNormInt, }); auto decal_supported = static_cast<Scalar>( GetContext()->GetCapabilities()->SupportsDecalSamplerAddressMode()); std::vector<Scalar> expected_constants = {decal_supported}; ASSERT_EQ(default_color_burn->GetDescriptor().GetSpecializationConstants(), expected_constants); } // This doesn't really tell you if the hashes will have frequent // collisions, but since this type is only used to hash a bounded // set of options, we can just compare benchmarks. TEST_P(EntityTest, ContentContextOptionsHasReasonableHashFunctions) { ContentContextOptions opts; auto hash_a = ContentContextOptions::Hash{}(opts); opts.blend_mode = BlendMode::kColorBurn; auto hash_b = ContentContextOptions::Hash{}(opts); opts.has_depth_stencil_attachments = false; auto hash_c = ContentContextOptions::Hash{}(opts); opts.primitive_type = PrimitiveType::kPoint; auto hash_d = ContentContextOptions::Hash{}(opts); EXPECT_NE(hash_a, hash_b); EXPECT_NE(hash_b, hash_c); EXPECT_NE(hash_c, hash_d); } #ifdef FML_OS_LINUX TEST_P(EntityTest, FramebufferFetchVulkanBindingOffsetIsTheSame) { // Using framebuffer fetch on Vulkan requires that we maintain a subpass input // binding that we don't have a good route for configuring with the current // metadata approach. This test verifies that the binding value doesn't change // from the expected constant. // See also: // * impeller/renderer/backend/vulkan/binding_helpers_vk.cc // * impeller/entity/shaders/blending/framebuffer_blend.frag // This test only works on Linux because macOS hosts incorrectly populate the // Vulkan descriptor sets based on the MSL compiler settings. bool expected_layout = false; for (const DescriptorSetLayout& layout : FramebufferBlendColorBurnPipeline:: FragmentShader::kDescriptorSetLayouts) { if (layout.binding == 64 && layout.descriptor_type == DescriptorType::kInputAttachment) { expected_layout = true; } } EXPECT_TRUE(expected_layout); } #endif TEST_P(EntityTest, FillPathGeometryGetPositionBufferReturnsExpectedMode) { RenderTarget target; testing::MockRenderPass mock_pass(GetContext(), target); auto get_result = [this, &mock_pass](const Path& path) { auto geometry = Geometry::MakeFillPath( path, /* inner rect */ Rect::MakeLTRB(0, 0, 100, 100)); return geometry->GetPositionBuffer(*GetContentContext(), {}, mock_pass); }; // Convex path { GeometryResult result = get_result(PathBuilder{} .AddRect(Rect::MakeLTRB(0, 0, 100, 100)) .SetConvexity(Convexity::kConvex) .TakePath()); EXPECT_EQ(result.mode, GeometryResult::Mode::kNormal); } // Concave path { Path path = PathBuilder{} .MoveTo({0, 0}) .LineTo({100, 0}) .LineTo({100, 100}) .LineTo({50, 50}) .Close() .TakePath(); GeometryResult result = get_result(path); if constexpr (ContentContext::kEnableStencilThenCover) { EXPECT_EQ(result.mode, GeometryResult::Mode::kNonZero); } else { EXPECT_EQ(result.mode, GeometryResult::Mode::kNormal); } } } TEST_P(EntityTest, FailOnValidationError) { if (GetParam() != PlaygroundBackend::kVulkan) { GTEST_SKIP() << "Validation is only fatal on Vulkan backend."; } EXPECT_DEATH( // The easiest way to trigger a validation error is to try to compile // a shader with an unsupported pixel format. GetContentContext()->GetBlendColorBurnPipeline({ .color_attachment_pixel_format = PixelFormat::kUnknown, .has_depth_stencil_attachments = false, }), ""); } } // namespace testing } // namespace impeller // NOLINTEND(bugprone-unchecked-optional-access)
engine/impeller/entity/entity_unittests.cc/0
{ "file_path": "engine/impeller/entity/entity_unittests.cc", "repo_id": "engine", "token_count": 47277 }
246
// Copyright 2013 The Flutter Authors. All 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) {} 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 = pass.GetOrthographicTransform() * entity.GetTransform(), }; } // |Geometry| GeometryResult RectGeometry::GetPositionUVBuffer(Rect texture_coverage, Matrix effect_transform, const ContentContext& renderer, const Entity& entity, RenderPass& pass) const { return ComputeUVGeometryForRect(rect_, texture_coverage, effect_transform, renderer, entity, pass); } GeometryVertexType RectGeometry::GetVertexType() const { return GeometryVertexType::kPosition; } std::optional<Rect> 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
engine/impeller/entity/geometry/rect_geometry.cc/0
{ "file_path": "engine/impeller/entity/geometry/rect_geometry.cc", "repo_id": "engine", "token_count": 909 }
247
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <impeller/conversions.glsl> #include <impeller/types.glsl> uniform FrameInfo { mat4 mvp; float texture_sampler_y_coord_scale; } frame_info; in vec2 vertices; in vec2 texture_coords; out vec2 v_texture_coords; void main() { gl_Position = frame_info.mvp * vec4(vertices, 0.0, 1.0); v_texture_coords = IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); }
engine/impeller/entity/shaders/blending/blend.vert/0
{ "file_path": "engine/impeller/entity/shaders/blending/blend.vert", "repo_id": "engine", "token_count": 210 }
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. // 1D (directional) gaussian blur. // // Paths for future optimization: // * Remove the uv bounds multiplier in SampleColor by adding optional // support for SamplerAddressMode::ClampToBorder in the texture sampler. // * Render both blur passes into a smaller texture than the source image // (~1/radius size). // * If doing the small texture render optimization, cache misses can be // reduced in the first pass by sampling the source textures with a mip // level of log2(min_radius). #include <impeller/constants.glsl> #include <impeller/gaussian.glsl> #include <impeller/texture.glsl> #include <impeller/types.glsl> uniform f16sampler2D texture_sampler; uniform BlurInfo { f16vec2 blur_uv_offset; // The blur sigma and radius have a linear relationship which is defined // host-side, but both are useful controls here. Sigma (pixels per standard // deviation) is used to define the gaussian function itself, whereas the // radius is used to limit how much of the function is integrated. float blur_sigma; float16_t blur_radius; float16_t step_size; } blur_info; f16vec4 Sample(f16sampler2D tex, vec2 coords) { #if ENABLE_DECAL_SPECIALIZATION return IPHalfSampleDecal(tex, coords); #else return texture(tex, coords); #endif } in vec2 v_texture_coords; out f16vec4 frag_color; void main() { f16vec4 total_color = f16vec4(0.0hf); float16_t gaussian_integral = 0.0hf; // Step by 2.0 as a performance optimization, relying on bilinear filtering in // the sampler to blend the texels. Typically the space between pixels is // calculated so their blended amounts match the gaussian coefficients. This // just uses 0.5 as an optimization until the gaussian coefficients are // calculated and passed in from the cpu. for (float16_t i = -blur_info.blur_radius; i <= blur_info.blur_radius; i += blur_info.step_size) { // Use the 32 bit Gaussian function because the 16 bit variation results in // quality loss/visible banding. Also, 16 bit variation internally breaks // down at a moderately high (but still reasonable) blur sigma of >255 when // computing sigma^2 due to the exponent only having 5 bits. float16_t gaussian = float16_t(IPGaussian(float(i), blur_info.blur_sigma)); gaussian_integral += gaussian; total_color += gaussian * Sample(texture_sampler, // sampler v_texture_coords + blur_info.blur_uv_offset * i // texture coordinates ); } frag_color = total_color / gaussian_integral; }
engine/impeller/entity/shaders/gaussian_blur/gaussian_blur.glsl/0
{ "file_path": "engine/impeller/entity/shaders/gaussian_blur/gaussian_blur.glsl", "repo_id": "engine", "token_count": 942 }
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/conversions.glsl> #include <impeller/types.glsl> uniform FrameInfo { mat4 mvp; float depth; float texture_sampler_y_coord_scale; float16_t alpha; } frame_info; in vec2 position; in vec2 texture_coords; out vec2 v_texture_coords; IMPELLER_MAYBE_FLAT out float16_t v_alpha; void main() { gl_Position = frame_info.mvp * vec4(position, 0.0, 1.0); gl_Position /= gl_Position.w; gl_Position.z = frame_info.depth; v_alpha = frame_info.alpha; v_texture_coords = IPRemapCoords(texture_coords, frame_info.texture_sampler_y_coord_scale); }
engine/impeller/entity/shaders/texture_fill.vert/0
{ "file_path": "engine/impeller/entity/shaders/texture_fill.vert", "repo_id": "engine", "token_count": 281 }
250
// Copyright 2013 The Flutter 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); } }
engine/impeller/fixtures/impeller.frag/0
{ "file_path": "engine/impeller/fixtures/impeller.frag", "repo_id": "engine", "token_count": 6190 }
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 "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); }
engine/impeller/fixtures/sa%m#ple.vert/0
{ "file_path": "engine/impeller/fixtures/sa%m#ple.vert", "repo_id": "engine", "token_count": 221 }
252
// Copyright 2013 The Flutter Authors. All rights 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/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 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(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(Point p1, Point cp, Point p2); /// @brief Move to point `p1`, then insert a cubic curve from `p1` to `p2` /// with control points `cp1` and `cp2`. PathBuilder& AddCubicCurve(Point p1, Point cp1, Point cp2, 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); struct RoundingRadii { Point top_left; Point bottom_left; Point top_right; Point bottom_right; RoundingRadii() = default; RoundingRadii(Scalar p_top_left, Scalar p_bottom_left, Scalar p_top_right, Scalar p_bottom_right) : top_left(p_top_left, p_top_left), bottom_left(p_bottom_left, p_bottom_left), top_right(p_top_right, p_top_right), bottom_right(p_bottom_right, p_bottom_right) {} explicit RoundingRadii(Scalar radius) : top_left(radius, radius), bottom_left(radius, radius), top_right(radius, radius), bottom_right(radius, radius) {} explicit RoundingRadii(Point radii) : top_left(radii), bottom_left(radii), top_right(radii), bottom_right(radii) {} explicit RoundingRadii(Size radii) : top_left(radii), bottom_left(radii), top_right(radii), bottom_right(radii) {} bool AreAllZero() const { return top_left.IsZero() && // bottom_left.IsZero() && // top_right.IsZero() && // bottom_right.IsZero(); } }; PathBuilder& AddRoundedRect(Rect rect, RoundingRadii radii); PathBuilder& AddRoundedRect(Rect rect, Size radii); PathBuilder& AddRoundedRect(Rect rect, Scalar radius); PathBuilder& AddPath(const Path& path); private: Point subpath_start_; Point current_; 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 AddQuadraticComponent(const Point& p1, const Point& cp, const Point& p2); 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<std::pair<Point, Point>> GetMinMaxCoveragePoints() const; PathBuilder(const PathBuilder&) = delete; PathBuilder& operator=(const PathBuilder&&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_GEOMETRY_PATH_BUILDER_H_
engine/impeller/geometry/path_builder.h/0
{ "file_path": "engine/impeller/geometry/path_builder.h", "repo_id": "engine", "token_count": 2459 }
253
// Copyright 2013 The Flutter Authors. All 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 <sstream> 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
engine/impeller/geometry/sigma.cc/0
{ "file_path": "engine/impeller/geometry/sigma.cc", "repo_id": "engine", "token_count": 172 }
254
// Copyright 2013 The Flutter Authors. All rights 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 <memory> #include "flutter/impeller/aiks/aiks_context.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<PlaygroundBackend> { public: using AiksPlaygroundCallback = std::function<std::optional<Picture>(AiksContext& renderer)>; GoldenPlaygroundTest(); ~GoldenPlaygroundTest() override; void SetUp(); void TearDown(); PlaygroundBackend GetBackend() const; void SetTypographerContext( std::shared_ptr<TypographerContext> typographer_context); bool OpenPlaygroundHere(Picture picture); bool OpenPlaygroundHere(AiksPlaygroundCallback callback); static bool ImGuiBegin(const char* name, bool* p_open, ImGuiWindowFlags flags); std::shared_ptr<Texture> CreateTextureForFixture( const char* fixture_name, bool enable_mipmapping = false) const; RuntimeStage::Map OpenAssetAsRuntimeStage(const char* asset_name) const; std::shared_ptr<Context> GetContext() const; std::shared_ptr<Context> MakeContext() const; Point GetContentScale() const; Scalar GetSecondsElapsed() const; ISize GetWindowSize() const; [[nodiscard]] fml::Status SetCapabilities( const std::shared_ptr<Capabilities>& capabilities); /// TODO(https://github.com/flutter/flutter/issues/139950): Remove this. /// 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<TypographerContext> typographer_context_; struct GoldenPlaygroundTestImpl; // This is only a shared_ptr so it can work with a forward declared type. std::shared_ptr<GoldenPlaygroundTestImpl> pimpl_; GoldenPlaygroundTest(const GoldenPlaygroundTest&) = delete; GoldenPlaygroundTest& operator=(const GoldenPlaygroundTest&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_GOLDEN_TESTS_GOLDEN_PLAYGROUND_TEST_H_
engine/impeller/golden_tests/golden_playground_test.h/0
{ "file_path": "engine/impeller/golden_tests/golden_playground_test.h", "repo_id": "engine", "token_count": 958 }
255
# 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.
engine/impeller/playground/README.md/0
{ "file_path": "engine/impeller/playground/README.md", "repo_id": "engine", "token_count": 121 }
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. #ifndef FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_ #define FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/fml/mapping.h" #include "impeller/geometry/size.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<const fml::Mapping> source_; explicit CompressedImage(std::shared_ptr<const fml::Mapping> allocation); }; } // namespace impeller #endif // FLUTTER_IMPELLER_PLAYGROUND_IMAGE_COMPRESSED_IMAGE_H_
engine/impeller/playground/image/compressed_image.h/0
{ "file_path": "engine/impeller/playground/image/compressed_image.h", "repo_id": "engine", "token_count": 313 }
257
// Copyright 2013 The Flutter Authors. All 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<Point, Point> 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
engine/impeller/playground/widgets.cc/0
{ "file_path": "engine/impeller/playground/widgets.cc", "repo_id": "engine", "token_count": 1063 }
258
// Copyright 2013 The Flutter Authors. All rights 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 "flutter/fml/macros.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; ReactorGLES::Ref reactor_; bool is_valid_ = false; CommandBufferGLES(std::weak_ptr<const Context> context, ReactorGLES::Ref reactor); // |CommandBuffer| void SetLabel(const std::string& label) const override; // |CommandBuffer| bool IsValid() const override; // |CommandBuffer| bool OnSubmitCommands(CompletionCallback callback) override; // |CommandBuffer| void OnWaitUntilScheduled() override; // |CommandBuffer| std::shared_ptr<RenderPass> OnCreateRenderPass(RenderTarget target) override; // |CommandBuffer| std::shared_ptr<BlitPass> OnCreateBlitPass() override; // |CommandBuffer| std::shared_ptr<ComputePass> OnCreateComputePass() override; CommandBufferGLES(const CommandBufferGLES&) = delete; CommandBufferGLES& operator=(const CommandBufferGLES&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_GLES_COMMAND_BUFFER_GLES_H_
engine/impeller/renderer/backend/gles/command_buffer_gles.h/0
{ "file_path": "engine/impeller/renderer/backend/gles/command_buffer_gles.h", "repo_id": "engine", "token_count": 553 }
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/gles/pipeline_library_gles.h" #include <sstream> #include <string> #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(ReactorGLES::Ref 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<char*>(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<char*>(malloc(10240)); GLsizei length; gl.GetShaderSource(shader, 10240, &length, data); auto result = std::string{data, static_cast<size_t>(length)}; free(data); return result; } static void LogShaderCompilationFailure(const ProcTableGLES& gl, GLuint shader, const std::string& 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<PipelineGLES>& pipeline, const std::shared_ptr<const ShaderFunction>& vert_function, const std::shared_ptr<const ShaderFunction>& 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().c_str())); gl.SetDebugLabel( DebugResourceType::kShader, frag_shader, SPrintF("%s Fragment Shader", descriptor.GetLabel().c_str())); 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<GLuint>(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; } // |PipelineLibrary| PipelineFuture<PipelineDescriptor> PipelineLibraryGLES::GetPipeline( PipelineDescriptor descriptor) { if (auto found = pipelines_.find(descriptor); found != pipelines_.end()) { return found->second; } if (!reactor_) { return { descriptor, RealizedFuture<std::shared_ptr<Pipeline<PipelineDescriptor>>>(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<std::shared_ptr<Pipeline<PipelineDescriptor>>>(nullptr)}; } auto promise = std::make_shared< std::promise<std::shared_ptr<Pipeline<PipelineDescriptor>>>>(); auto pipeline_future = PipelineFuture<PipelineDescriptor>{descriptor, promise->get_future()}; pipelines_[descriptor] = pipeline_future; auto weak_this = weak_from_this(); auto result = reactor_->AddOperation( [promise, weak_this, reactor_ptr = reactor_, descriptor, vert_function, frag_function](const ReactorGLES& reactor) { auto strong_this = weak_this.lock(); if (!strong_this) { promise->set_value(nullptr); VALIDATION_LOG << "Library was collected before a pending pipeline " "creation could finish."; return; } auto pipeline = std::shared_ptr<PipelineGLES>( new PipelineGLES(reactor_ptr, strong_this, descriptor)); auto program = reactor.GetGLHandle(pipeline->GetProgramHandle()); if (!program.has_value()) { promise->set_value(nullptr); VALIDATION_LOG << "Could not obtain program handle."; return; } const auto link_result = LinkProgram(reactor, // pipeline, // vert_function, // frag_function // ); if (!link_result) { promise->set_value(nullptr); VALIDATION_LOG << "Could not link pipeline program."; return; } if (!pipeline->BuildVertexDescriptor(reactor.GetProcTable(), program.value())) { promise->set_value(nullptr); VALIDATION_LOG << "Could not build pipeline vertex descriptors."; return; } if (!pipeline->IsValid()) { promise->set_value(nullptr); VALIDATION_LOG << "Pipeline validation checks failed."; return; } promise->set_value(std::move(pipeline)); }); FML_CHECK(result); return pipeline_future; } // |PipelineLibrary| PipelineFuture<ComputePipelineDescriptor> PipelineLibraryGLES::GetPipeline( ComputePipelineDescriptor descriptor) { auto promise = std::make_shared< std::promise<std::shared_ptr<Pipeline<ComputePipelineDescriptor>>>>(); // TODO(dnfield): implement compute for GLES. promise->set_value(nullptr); return {descriptor, promise->get_future()}; } // |PipelineLibrary| void PipelineLibraryGLES::RemovePipelinesWithEntryPoint( std::shared_ptr<const ShaderFunction> function) { fml::erase_if(pipelines_, [&](auto item) { return item->first.GetEntrypointForStage(function->GetStage()) ->IsEqual(*function); }); } // |PipelineLibrary| PipelineLibraryGLES::~PipelineLibraryGLES() = default; } // namespace impeller
engine/impeller/renderer/backend/gles/pipeline_library_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/pipeline_library_gles.cc", "repo_id": "engine", "token_count": 4046 }
260
// Copyright 2013 The Flutter Authors. All 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<Surface> SurfaceGLES::WrapFBO( const std::shared_ptr<Context>& 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 = std::make_shared<TextureGLES>( gl_context.GetReactor(), color0_tex, TextureGLES::IsWrapped::kWrapped); 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 = std::make_shared<TextureGLES>( gl_context.GetReactor(), depth_stencil_texture_desc, TextureGLES::IsWrapped::kWrapped); 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 return std::unique_ptr<SurfaceGLES>( 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
engine/impeller/renderer/backend/gles/surface_gles.cc/0
{ "file_path": "engine/impeller/renderer/backend/gles/surface_gles.cc", "repo_id": "engine", "token_count": 1111 }
261
// Copyright 2013 The Flutter Authors. All rights 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_COMMAND_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_COMMAND_MTL_H_ #include <Metal/Metal.h> #include "impeller/base/backend_cast.h" #include "impeller/renderer/blit_command.h" namespace impeller { /// Mixin for dispatching Metal commands. struct BlitEncodeMTL : BackendCast<BlitEncodeMTL, BlitCommand> { virtual ~BlitEncodeMTL(); virtual std::string GetLabel() const = 0; [[nodiscard]] virtual bool Encode( id<MTLBlitCommandEncoder> encoder) const = 0; }; struct BlitCopyTextureToTextureCommandMTL : public BlitCopyTextureToTextureCommand, public BlitEncodeMTL { ~BlitCopyTextureToTextureCommandMTL() override; std::string GetLabel() const override; [[nodiscard]] bool Encode(id<MTLBlitCommandEncoder> encoder) const override; }; struct BlitCopyTextureToBufferCommandMTL : public BlitCopyTextureToBufferCommand, public BlitEncodeMTL { ~BlitCopyTextureToBufferCommandMTL() override; std::string GetLabel() const override; [[nodiscard]] bool Encode(id<MTLBlitCommandEncoder> encoder) const override; }; struct BlitGenerateMipmapCommandMTL : public BlitGenerateMipmapCommand, public BlitEncodeMTL { ~BlitGenerateMipmapCommandMTL() override; std::string GetLabel() const override; [[nodiscard]] bool Encode(id<MTLBlitCommandEncoder> encoder) const override; }; struct BlitCopyBufferToTextureCommandMTL : public BlitCopyBufferToTextureCommand, public BlitEncodeMTL { ~BlitCopyBufferToTextureCommandMTL() override; std::string GetLabel() const override; [[nodiscard]] bool Encode(id<MTLBlitCommandEncoder> encoder) const override; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_BLIT_COMMAND_MTL_H_
engine/impeller/renderer/backend/metal/blit_command_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/blit_command_mtl.h", "repo_id": "engine", "token_count": 727 }
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_BACKEND_METAL_FORMATS_MTL_H_ #define FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_FORMATS_MTL_H_ #include <Metal/Metal.h> #include <optional> #include "flutter/fml/build_config.h" #include "flutter/fml/macros.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; } 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::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<DepthAttachmentDescriptor> depth, std::optional<StencilAttachmentDescriptor> front, std::optional<StencilAttachmentDescriptor> back); MTLTextureDescriptor* ToMTLTextureDescriptor(const TextureDescriptor& desc); } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_FORMATS_MTL_H_
engine/impeller/renderer/backend/metal/formats_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/formats_mtl.h", "repo_id": "engine", "token_count": 4907 }
263
// Copyright 2013 The Flutter Authors. All rights 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 <Metal/Metal.h> #include "flutter/fml/macros.h" #include "impeller/base/backend_cast.h" #include "impeller/core/sampler.h" namespace impeller { class SamplerLibraryMTL; class SamplerMTL final : public Sampler, public BackendCast<SamplerMTL, Sampler> { public: SamplerMTL(); // |Sampler| ~SamplerMTL() override; id<MTLSamplerState> GetMTLSamplerState() const; private: friend SamplerLibraryMTL; id<MTLSamplerState> state_ = nullptr; SamplerMTL(SamplerDescriptor desc, id<MTLSamplerState> state); SamplerMTL(const SamplerMTL&) = delete; SamplerMTL& operator=(const SamplerMTL&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_METAL_SAMPLER_MTL_H_
engine/impeller/renderer/backend/metal/sampler_mtl.h/0
{ "file_path": "engine/impeller/renderer/backend/metal/sampler_mtl.h", "repo_id": "engine", "token_count": 413 }
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/allocator_vk.h" #include <memory> #include "flutter/fml/memory/ref_ptr.h" #include "flutter/fml/trace_event.h" #include "impeller/core/formats.h" #include "impeller/renderer/backend/vulkan/device_buffer_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<vk::MemoryPropertyFlagBits> 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<vk::BufferCreateInfo::NativeType>(buffer_info); VmaAllocationCreateInfo allocation_info = {}; allocation_info.usage = VMA_MEMORY_USAGE_AUTO; allocation_info.preferredFlags = static_cast<VkMemoryPropertyFlags>( 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; 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> context, uint32_t vulkan_api_version, const vk::PhysicalDevice& physical_device, const std::shared_ptr<DeviceHolderVK>& 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; 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<int32_t>(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<vk::MemoryPropertyFlagBits> 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(std::weak_ptr<ResourceManagerVK> resource_manager, const TextureDescriptor& desc, VmaAllocator allocator, vk::Device device, bool supports_memoryless_textures) : TextureSourceVK(desc), resource_(std::move(resource_manager)) { FML_DCHECK(desc.format != PixelFormat::kUnknown); vk::ImageCreateInfo image_info; image_info.flags = ToVKImageCreateFlags(desc.type); image_info.imageType = vk::ImageType::e2D; image_info.format = ToVKImageFormat(desc.format); image_info.extent = VkExtent3D{ static_cast<uint32_t>(desc.size.width), // width static_cast<uint32_t>(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; VmaAllocationCreateInfo alloc_nfo = {}; alloc_nfo.usage = ToVMAMemoryUsage(); alloc_nfo.preferredFlags = static_cast<VkMemoryPropertyFlags>(ToVKTextureMemoryPropertyFlags( desc.storage_mode, supports_memoryless_textures)); alloc_nfo.flags = ToVmaAllocationCreateFlags(desc.storage_mode); auto create_info_native = static_cast<vk::ImageCreateInfo::NativeType>(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))); 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 { 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) : 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<ImageResource> resource_; bool is_valid_ = false; AllocatedTextureSourceVK(const AllocatedTextureSourceVK&) = delete; AllocatedTextureSourceVK& operator=(const AllocatedTextureSourceVK&) = delete; }; // |Allocator| std::shared_ptr<Texture> 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<AllocatedTextureSourceVK>( ContextVK::Cast(*context).GetResourceManager(), // desc, // allocator_.get(), // device_holder->GetDevice(), // supports_memoryless_textures_ // ); if (!source->IsValid()) { return nullptr; } return std::make_shared<TextureVK>(context_, std::move(source)); } // |Allocator| std::shared_ptr<DeviceBuffer> 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<vk::BufferCreateInfo::NativeType>(buffer_info); VmaAllocationCreateInfo allocation_info = {}; allocation_info.usage = ToVMAMemoryUsage(); allocation_info.preferredFlags = static_cast<VkMemoryPropertyFlags>( 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 // )}; if (result != vk::Result::eSuccess) { VALIDATION_LOG << "Unable to allocate a device buffer: " << vk::to_string(result); return {}; } return std::make_shared<DeviceBufferVK>( desc, // context_, // UniqueBufferVMA{BufferVMA{allocator_.get(), // buffer_allocation, // vk::Buffer{buffer}}}, // buffer_allocation_info // ); } size_t AllocatorVK::DebugGetHeapUsage() const { auto count = memory_properties_.memoryHeapCount; std::vector<VmaBudget> 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; } // Convert bytes to MB. total_usage *= 1e-6; return total_usage; } void AllocatorVK::DebugTraceMemoryStatistics() const { #ifdef IMPELLER_DEBUG FML_TRACE_COUNTER("flutter", "AllocatorVK", reinterpret_cast<int64_t>(this), // Trace Counter ID "MemoryBudgetUsageMB", DebugGetHeapUsage()); #endif // IMPELLER_DEBUG } } // namespace impeller
engine/impeller/renderer/backend/vulkan/allocator_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/allocator_vk.cc", "repo_id": "engine", "token_count": 8637 }
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. #include "impeller/renderer/backend/vulkan/command_encoder_vk.h" #include <string> #include "flutter/fml/closure.h" #include "fml/status.h" #include "fml/status_or.h" #include "impeller/renderer/backend/vulkan/context_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/texture_vk.h" #include "impeller/renderer/backend/vulkan/tracked_objects_vk.h" namespace impeller { CommandEncoderFactoryVK::CommandEncoderFactoryVK( const std::weak_ptr<const ContextVK>& context) : context_(context) {} void CommandEncoderFactoryVK::SetLabel(const std::string& label) { label_ = label; } std::shared_ptr<CommandEncoderVK> CommandEncoderFactoryVK::Create() { auto context = context_.lock(); if (!context) { return nullptr; } auto recycler = context->GetCommandPoolRecycler(); if (!recycler) { return nullptr; } auto tls_pool = recycler->Get(); if (!tls_pool) { return nullptr; } auto tracked_objects = std::make_shared<TrackedObjectsVK>( context, tls_pool, context->GetGPUTracer()->CreateGPUProbe()); auto queue = context->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; } if (label_.has_value()) { context->SetDebugName(tracked_objects->GetCommandBuffer(), label_.value()); } tracked_objects->GetGPUProbe().RecordCmdBufferStart( tracked_objects->GetCommandBuffer()); return std::make_shared<CommandEncoderVK>(context->GetDeviceHolder(), tracked_objects, queue, context->GetFenceWaiter()); } CommandEncoderVK::CommandEncoderVK( std::weak_ptr<const DeviceHolderVK> device_holder, std::shared_ptr<TrackedObjectsVK> tracked_objects, const std::shared_ptr<QueueVK>& queue, std::shared_ptr<FenceWaiterVK> fence_waiter) : device_holder_(std::move(device_holder)), tracked_objects_(std::move(tracked_objects)), queue_(queue), fence_waiter_(std::move(fence_waiter)) {} CommandEncoderVK::~CommandEncoderVK() = default; bool CommandEncoderVK::IsValid() const { return is_valid_; } bool CommandEncoderVK::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 CommandEncoderVK::GetCommandBuffer() const { if (tracked_objects_) { return tracked_objects_->GetCommandBuffer(); } return {}; } void CommandEncoderVK::Reset() { tracked_objects_.reset(); queue_ = nullptr; is_valid_ = false; } bool CommandEncoderVK::Track(std::shared_ptr<SharedObjectVK> object) { if (!IsValid()) { return false; } tracked_objects_->Track(std::move(object)); return true; } bool CommandEncoderVK::Track(std::shared_ptr<const DeviceBuffer> buffer) { if (!IsValid()) { return false; } tracked_objects_->Track(std::move(buffer)); return true; } bool CommandEncoderVK::IsTracking( const std::shared_ptr<const DeviceBuffer>& buffer) const { if (!IsValid()) { return false; } return tracked_objects_->IsTracking(buffer); } bool CommandEncoderVK::Track(std::shared_ptr<const TextureSourceVK> texture) { if (!IsValid()) { return false; } tracked_objects_->Track(std::move(texture)); return true; } bool CommandEncoderVK::Track(const std::shared_ptr<const Texture>& texture) { if (!IsValid()) { return false; } if (!texture) { return true; } return Track(TextureVK::Cast(*texture).GetTextureSource()); } bool CommandEncoderVK::IsTracking( const std::shared_ptr<const Texture>& texture) const { if (!IsValid()) { return false; } std::shared_ptr<const TextureSourceVK> source = TextureVK::Cast(*texture).GetTextureSource(); return tracked_objects_->IsTracking(source); } fml::StatusOr<vk::DescriptorSet> CommandEncoderVK::AllocateDescriptorSets( const vk::DescriptorSetLayout& layout, const ContextVK& context) { if (!IsValid()) { return fml::Status(fml::StatusCode::kUnknown, "command encoder invalid"); } return tracked_objects_->GetDescriptorPool().AllocateDescriptorSets(layout, context); } void CommandEncoderVK::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 CommandEncoderVK::PopDebugGroup() const { if (!HasValidationLayers()) { return; } if (auto command_buffer = GetCommandBuffer()) { command_buffer.endDebugUtilsLabelEXT(); } } void CommandEncoderVK::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); } if (queue_) { queue_->InsertDebugMarker(label); } } } // namespace impeller
engine/impeller/renderer/backend/vulkan/command_encoder_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/command_encoder_vk.cc", "repo_id": "engine", "token_count": 2171 }
266
// Copyright 2013 The Flutter Authors. All rights 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 "flutter/fml/macros.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 VkDebugUtilsMessengerCallbackDataEXT* data); static VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsMessengerCallback( VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* 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_
engine/impeller/renderer/backend/vulkan/debug_report_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/debug_report_vk.h", "repo_id": "engine", "token_count": 535 }
267
// Copyright 2013 The Flutter Authors. All rights 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 <memory> #include <thread> #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: /// <meta-data /// android:name="io.flutter.embedding.android.EnableVulkanGPUTracing" /// android:value="false" /> class GPUTracerVK : public std::enable_shared_from_this<GPUTracerVK> { public: GPUTracerVK(std::weak_ptr<ContextVK> 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<GPUProbe> 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<ContextVK> 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<size_t> 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<GPUTracerVK>& 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<GPUTracerVK> tracer_; std::optional<size_t> index_ = std::nullopt; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_GPU_TRACER_VK_H_
engine/impeller/renderer/backend/vulkan/gpu_tracer_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/gpu_tracer_vk.h", "repo_id": "engine", "token_count": 1406 }
268
// Copyright 2013 The Flutter Authors. All rights 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 <condition_variable> #include <memory> #include <mutex> #include <thread> #include <vector> #include "flutter/fml/macros.h" 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<SomeResource>(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<ResourceManagerVK> { 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<ResourceManagerVK> 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<ResourceVK> 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<std::unique_ptr<ResourceVK>>; 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 ResourceType_> 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 ResourceType_> 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<ResourceManagerVK> 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<ResourceManagerVK> resource_manager, ResourceType&& resource) : resource_manager_(std::move(resource_manager)), resource_( std::make_unique<ResourceVKT<ResourceType>>(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<ResourceVKT<ResourceType>>(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<ResourceManagerVK> resource_manager_; std::unique_ptr<ResourceVKT<ResourceType>> resource_; UniqueResourceVKT(const UniqueResourceVKT&) = delete; UniqueResourceVKT& operator=(const UniqueResourceVKT&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_BACKEND_VULKAN_RESOURCE_MANAGER_VK_H_
engine/impeller/renderer/backend/vulkan/resource_manager_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/resource_manager_vk.h", "repo_id": "engine", "token_count": 2248 }
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/renderer/backend/vulkan/swapchain/khr/khr_surface_vk.h" #include "impeller/core/formats.h" #include "impeller/renderer/backend/vulkan/swapchain/khr/khr_swapchain_image_vk.h" #include "impeller/renderer/backend/vulkan/texture_vk.h" #include "impeller/renderer/surface.h" namespace impeller { std::unique_ptr<KHRSurfaceVK> KHRSurfaceVK::WrapSwapchainImage( const std::shared_ptr<Context>& context, std::shared_ptr<KHRSwapchainImageVK>& swapchain_image, SwapCallback swap_callback, bool enable_msaa) { if (!context || !swapchain_image || !swap_callback) { return nullptr; } std::shared_ptr<Texture> msaa_tex; if (enable_msaa) { TextureDescriptor msaa_tex_desc; msaa_tex_desc.storage_mode = StorageMode::kDeviceTransient; msaa_tex_desc.type = TextureType::kTexture2DMultisample; msaa_tex_desc.sample_count = SampleCount::kCount4; msaa_tex_desc.format = swapchain_image->GetPixelFormat(); msaa_tex_desc.size = swapchain_image->GetSize(); msaa_tex_desc.usage = TextureUsage::kRenderTarget; if (!swapchain_image->GetMSAATexture()) { msaa_tex = context->GetResourceAllocator()->CreateTexture(msaa_tex_desc); msaa_tex->SetLabel("ImpellerOnscreenColorMSAA"); if (!msaa_tex) { VALIDATION_LOG << "Could not allocate MSAA color texture."; return nullptr; } } else { msaa_tex = swapchain_image->GetMSAATexture(); } } TextureDescriptor resolve_tex_desc; resolve_tex_desc.type = TextureType::kTexture2D; resolve_tex_desc.format = swapchain_image->GetPixelFormat(); resolve_tex_desc.size = swapchain_image->GetSize(); resolve_tex_desc.usage = TextureUsage::kRenderTarget; resolve_tex_desc.sample_count = SampleCount::kCount1; resolve_tex_desc.storage_mode = StorageMode::kDevicePrivate; std::shared_ptr<Texture> resolve_tex = std::make_shared<TextureVK>(context, // swapchain_image // ); if (!resolve_tex) { VALIDATION_LOG << "Could not wrap resolve texture."; return nullptr; } resolve_tex->SetLabel("ImpellerOnscreenResolve"); ColorAttachment color0; color0.clear_color = Color::DarkSlateGray(); color0.load_action = LoadAction::kClear; if (enable_msaa) { color0.texture = msaa_tex; 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_image->GetSize(), // /*msaa=*/enable_msaa, // /*label=*/"Onscreen", // /*stencil_attachment_config=*/ RenderTarget::kDefaultStencilAttachmentConfig, // /*depth_stencil_texture=*/swapchain_image->GetDepthStencilTexture() // ); // The constructor is private. So make_unique may not be used. return std::unique_ptr<KHRSurfaceVK>( new KHRSurfaceVK(render_target_desc, std::move(swap_callback))); } KHRSurfaceVK::KHRSurfaceVK(const RenderTarget& target, SwapCallback swap_callback) : Surface(target), swap_callback_(std::move(swap_callback)) {} KHRSurfaceVK::~KHRSurfaceVK() = default; bool KHRSurfaceVK::Present() const { return swap_callback_ ? swap_callback_() : false; } } // namespace impeller
engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_surface_vk.cc/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/swapchain/khr/khr_surface_vk.cc", "repo_id": "engine", "token_count": 1557 }
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_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<TextureVK, Texture> { public: TextureVK(std::weak_ptr<Context> context, std::shared_ptr<TextureSourceVK> 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<const TextureSourceVK> GetTextureSource() const; // |Texture| ISize GetSize() const override; void SetMipMapGenerated(); bool IsSwapchainImage() const; std::shared_ptr<SamplerVK> 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<vk::Framebuffer>& 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<vk::RenderPass>& render_pass); /// Retrieve the last framebuffer object used with this texture. /// /// May be nullptr if no previous framebuffer existed. SharedHandleVK<vk::Framebuffer> GetCachedFramebuffer() const; /// Retrieve the last render pass object used with this texture. /// /// May be nullptr if no previous render pass existed. SharedHandleVK<vk::RenderPass> GetCachedRenderPass() const; private: std::weak_ptr<Context> context_; std::shared_ptr<TextureSourceVK> source_; // |Texture| void SetLabel(std::string_view label) override; // |Texture| bool OnSetContents(const uint8_t* contents, size_t length, size_t slice) override; // |Texture| bool OnSetContents(std::shared_ptr<const fml::Mapping> 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_
engine/impeller/renderer/backend/vulkan/texture_vk.h/0
{ "file_path": "engine/impeller/renderer/backend/vulkan/texture_vk.h", "repo_id": "engine", "token_count": 1109 }
271
// Copyright 2013 The Flutter Authors. 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/base/validation.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 BlitPassTest = PlaygroundTest; 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}; 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_TRUE(blit_pass->AddCopy(src, dst)); } } // namespace testing } // namespace impeller
engine/impeller/renderer/blit_pass_unittests.cc/0
{ "file_path": "engine/impeller/renderer/blit_pass_unittests.cc", "repo_id": "engine", "token_count": 947 }
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. #include <future> #include <numeric> #include "compute_tessellator.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/time/time_point.h" #include "flutter/testing/testing.h" #include "gmock/gmock.h" #include "impeller/base/strings.h" #include "impeller/core/formats.h" #include "impeller/core/host_buffer.h" #include "impeller/display_list/skia_conversions.h" #include "impeller/entity/contents/content_context.h" #include "impeller/fixtures/golden_paths.h" #include "impeller/fixtures/sample.comp.h" #include "impeller/fixtures/stage1.comp.h" #include "impeller/fixtures/stage2.comp.h" #include "impeller/geometry/path.h" #include "impeller/geometry/path_builder.h" #include "impeller/geometry/path_component.h" #include "impeller/playground/compute_playground_test.h" #include "impeller/renderer/command_buffer.h" #include "impeller/renderer/compute_pipeline_builder.h" #include "impeller/renderer/compute_tessellator.h" #include "impeller/renderer/path_polyline.comp.h" #include "impeller/renderer/pipeline_library.h" #include "impeller/renderer/render_pass.h" #include "impeller/renderer/stroke.comp.h" #include "third_party/imgui/imgui.h" #include "third_party/skia/include/utils/SkParsePath.h" namespace impeller { namespace testing { using ComputeSubgroupTest = ComputePlaygroundTest; INSTANTIATE_COMPUTE_SUITE(ComputeSubgroupTest); TEST_P(ComputeSubgroupTest, CapabilitiesSuportSubgroups) { auto context = GetContext(); ASSERT_TRUE(context); ASSERT_TRUE(context->GetCapabilities()->SupportsComputeSubgroups()); } TEST_P(ComputeSubgroupTest, PathPlayground) { // Renders stroked SVG paths in an interactive playground. using SS = StrokeComputeShader; auto context = GetContext(); ASSERT_TRUE(context); ASSERT_TRUE(context->GetCapabilities()->SupportsComputeSubgroups()); char svg_path_data[16384] = "M140 20 " "C73 20 20 74 20 140 " "c0 135 136 170 228 303 " "88-132 229-173 229-303 " "0-66-54-120-120-120 " "-48 0-90 28-109 69 " "-19-41-60-69-108-69z"; size_t vertex_count = 0; Scalar stroke_width = 1.0; auto vertex_buffer = CreateHostVisibleDeviceBuffer<SS::VertexBuffer<2048>>( context, "VertexBuffer"); auto vertex_buffer_count = CreateHostVisibleDeviceBuffer<SS::VertexBufferCount>(context, "VertexCount"); auto callback = [&](RenderPass& pass) -> bool { ::memset(vertex_buffer_count->OnGetContents(), 0, sizeof(SS::VertexBufferCount)); ::memset(vertex_buffer->OnGetContents(), 0, sizeof(SS::VertexBuffer<2048>)); const auto* main_viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos( ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20)); ImGui::Begin("Path data", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::InputTextMultiline("Path", svg_path_data, IM_ARRAYSIZE(svg_path_data)); ImGui::DragFloat("Stroke width", &stroke_width, .1, 0.0, 25.0); SkPath sk_path; if (SkParsePath::FromSVGString(svg_path_data, &sk_path)) { std::promise<bool> promise; auto future = promise.get_future(); auto path = skia_conversions::ToPath(sk_path); auto host_buffer = HostBuffer::Create(context->GetResourceAllocator()); auto status = ComputeTessellator{} .SetStrokeWidth(stroke_width) .Tessellate(path, *host_buffer, context, DeviceBuffer::AsBufferView(vertex_buffer), DeviceBuffer::AsBufferView(vertex_buffer_count), [vertex_buffer_count, &vertex_count, &promise](CommandBuffer::Status status) { vertex_count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; promise.set_value( status == CommandBuffer::Status::kCompleted); }); switch (status) { case ComputeTessellator::Status::kCommandInvalid: ImGui::Text("Failed to submit compute job (invalid command)"); break; case ComputeTessellator::Status::kTooManyComponents: ImGui::Text("Failed to submit compute job (too many components) "); break; case ComputeTessellator::Status::kOk: break; } if (!future.get()) { ImGui::Text("Failed to submit compute job."); return false; } if (vertex_count > 0) { ImGui::Text("Vertex count: %zu", vertex_count); } } else { ImGui::Text("Failed to parse path data"); } ImGui::End(); ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } using VS = SolidFillPipeline::VertexShader; pass.SetCommandLabel("Draw Stroke"); pass.SetStencilReference(0); ContentContextOptions options; options.sample_count = pass.GetRenderTarget().GetSampleCount(); options.color_attachment_pixel_format = pass.GetRenderTarget().GetRenderTargetPixelFormat(); options.has_depth_stencil_attachments = pass.GetRenderTarget().GetStencilAttachment().has_value(); options.blend_mode = BlendMode::kSourceIn; options.primitive_type = PrimitiveType::kTriangleStrip; options.stencil_mode = ContentContextOptions::StencilMode::kLegacyClipIncrement; pass.SetPipeline(renderer.GetSolidFillPipeline(options)); auto count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; pass.SetVertexBuffer( VertexBuffer{.vertex_buffer = DeviceBuffer::AsBufferView(vertex_buffer), .vertex_count = count, .index_type = IndexType::kNone}); VS::FrameInfo frame_info; frame_info.depth = 0.0; auto world_matrix = Matrix::MakeScale(GetContentScale()); frame_info.mvp = pass.GetOrthographicTransform() * world_matrix; frame_info.color = Color::Red().Premultiply(); VS::BindFrameInfo( pass, renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); return pass.Draw().ok(); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(ComputeSubgroupTest, LargePath) { // The path in here is large enough to highlight issues around exceeding // subgroup size. using SS = StrokeComputeShader; auto context = GetContext(); ASSERT_TRUE(context); ASSERT_TRUE(context->GetCapabilities()->SupportsComputeSubgroups()); size_t vertex_count = 0; Scalar stroke_width = 1.0; auto vertex_buffer = CreateHostVisibleDeviceBuffer<SS::VertexBuffer<2048>>( context, "VertexBuffer"); auto vertex_buffer_count = CreateHostVisibleDeviceBuffer<SS::VertexBufferCount>(context, "VertexCount"); auto complex_path = PathBuilder{} .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}) .Close() .TakePath(); auto callback = [&](RenderPass& pass) -> bool { ::memset(vertex_buffer_count->OnGetContents(), 0, sizeof(SS::VertexBufferCount)); ::memset(vertex_buffer->OnGetContents(), 0, sizeof(SS::VertexBuffer<2048>)); ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } ComputeTessellator{} .SetStrokeWidth(stroke_width) .Tessellate( complex_path, renderer.GetTransientsBuffer(), context, DeviceBuffer::AsBufferView(vertex_buffer), DeviceBuffer::AsBufferView(vertex_buffer_count), [vertex_buffer_count, &vertex_count](CommandBuffer::Status status) { vertex_count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; }); using VS = SolidFillPipeline::VertexShader; pass.SetCommandLabel("Draw Stroke"); pass.SetStencilReference(0); ContentContextOptions options; options.sample_count = pass.GetRenderTarget().GetSampleCount(); options.color_attachment_pixel_format = pass.GetRenderTarget().GetRenderTargetPixelFormat(); options.has_depth_stencil_attachments = pass.GetRenderTarget().GetStencilAttachment().has_value(); options.blend_mode = BlendMode::kSourceIn; options.primitive_type = PrimitiveType::kTriangleStrip; options.stencil_mode = ContentContextOptions::StencilMode::kLegacyClipIncrement; pass.SetPipeline(renderer.GetSolidFillPipeline(options)); auto count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; pass.SetVertexBuffer( VertexBuffer{.vertex_buffer = DeviceBuffer::AsBufferView(vertex_buffer), .vertex_count = count, .index_type = IndexType::kNone}); VS::FrameInfo frame_info; frame_info.depth = 0.0; auto world_matrix = Matrix::MakeScale(GetContentScale()); frame_info.mvp = pass.GetOrthographicTransform() * world_matrix; frame_info.color = Color::Red().Premultiply(); VS::BindFrameInfo( pass, renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); return pass.Draw().ok(); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); } TEST_P(ComputeSubgroupTest, QuadAndCubicInOnePath) { using SS = StrokeComputeShader; auto context = GetContext(); ASSERT_TRUE(context); ASSERT_TRUE(context->GetCapabilities()->SupportsComputeSubgroups()); auto vertex_buffer = CreateHostVisibleDeviceBuffer<SS::VertexBuffer<2048>>( context, "VertexBuffer"); auto vertex_buffer_count = CreateHostVisibleDeviceBuffer<SS::VertexBufferCount>(context, "VertexBufferCount"); auto path = PathBuilder{} .AddCubicCurve({140, 20}, {73, 20}, {20, 74}, {20, 140}) .AddQuadraticCurve({20, 140}, {93, 90}, {100, 42}) .TakePath(); auto tessellator = ComputeTessellator{}; fml::AutoResetWaitableEvent latch; auto host_buffer = HostBuffer::Create(context->GetResourceAllocator()); auto status = tessellator.Tessellate( path, *host_buffer, context, DeviceBuffer::AsBufferView(vertex_buffer), DeviceBuffer::AsBufferView(vertex_buffer_count), [&latch](CommandBuffer::Status status) { EXPECT_EQ(status, CommandBuffer::Status::kCompleted); latch.Signal(); }); ASSERT_EQ(status, ComputeTessellator::Status::kOk); auto callback = [&](RenderPass& pass) -> bool { ContentContext renderer(context, nullptr); if (!renderer.IsValid()) { return false; } using VS = SolidFillPipeline::VertexShader; pass.SetCommandLabel("Draw Stroke"); pass.SetStencilReference(0); ContentContextOptions options; options.sample_count = pass.GetRenderTarget().GetSampleCount(); options.color_attachment_pixel_format = pass.GetRenderTarget().GetRenderTargetPixelFormat(); options.has_depth_stencil_attachments = pass.GetRenderTarget().GetStencilAttachment().has_value(); options.blend_mode = BlendMode::kSourceIn; options.primitive_type = PrimitiveType::kTriangleStrip; options.stencil_mode = ContentContextOptions::StencilMode::kLegacyClipIncrement; pass.SetPipeline(renderer.GetSolidFillPipeline(options)); auto count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; pass.SetVertexBuffer( VertexBuffer{.vertex_buffer = DeviceBuffer::AsBufferView(vertex_buffer), .vertex_count = count, .index_type = IndexType::kNone}); VS::FrameInfo frame_info; frame_info.depth = 0.0; auto world_matrix = Matrix::MakeScale(GetContentScale()); frame_info.mvp = pass.GetOrthographicTransform() * world_matrix; frame_info.color = Color::Red().Premultiply(); VS::BindFrameInfo( pass, renderer.GetTransientsBuffer().EmplaceUniform(frame_info)); return pass.Draw().ok(); }; ASSERT_TRUE(OpenPlaygroundHere(callback)); // The latch is down here because it's expected that on Metal the backend // will take care of synchronizing the buffer between the compute and render // pass usages, since it's not MTLHeap allocated. However, if playgrounds // are disabled, no render pass actually gets submitted and we need to do a // CPU latch here. latch.Wait(); auto vertex_count = reinterpret_cast<SS::VertexBufferCount*>( vertex_buffer_count->OnGetContents()) ->count; EXPECT_EQ(vertex_count, golden_cubic_and_quad_points.size()); auto vertex_buffer_data = reinterpret_cast<SS::VertexBuffer<2048>*>(vertex_buffer->OnGetContents()); for (size_t i = 0; i < vertex_count; i++) { EXPECT_LT(std::abs(golden_cubic_and_quad_points[i].x - vertex_buffer_data->position[i].x), 1e-3); EXPECT_LT(std::abs(golden_cubic_and_quad_points[i].y - vertex_buffer_data->position[i].y), 1e-3); } } } // namespace testing } // namespace impeller
engine/impeller/renderer/compute_subgroup_unittests.cc/0
{ "file_path": "engine/impeller/renderer/compute_subgroup_unittests.cc", "repo_id": "engine", "token_count": 9466 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_ #define FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_ #include <optional> #include "compute_pipeline_descriptor.h" #include "flutter/fml/macros.h" #include "impeller/renderer/pipeline.h" #include "impeller/renderer/pipeline_descriptor.h" namespace impeller { class Context; using PipelineMap = std::unordered_map<PipelineDescriptor, PipelineFuture<PipelineDescriptor>, ComparableHash<PipelineDescriptor>, ComparableEqual<PipelineDescriptor>>; using ComputePipelineMap = std::unordered_map<ComputePipelineDescriptor, PipelineFuture<ComputePipelineDescriptor>, ComparableHash<ComputePipelineDescriptor>, ComparableEqual<ComputePipelineDescriptor>>; class PipelineLibrary : public std::enable_shared_from_this<PipelineLibrary> { public: virtual ~PipelineLibrary(); PipelineFuture<PipelineDescriptor> GetPipeline( std::optional<PipelineDescriptor> descriptor); PipelineFuture<ComputePipelineDescriptor> GetPipeline( std::optional<ComputePipelineDescriptor> descriptor); virtual bool IsValid() const = 0; virtual PipelineFuture<PipelineDescriptor> GetPipeline( PipelineDescriptor descriptor) = 0; virtual PipelineFuture<ComputePipelineDescriptor> GetPipeline( ComputePipelineDescriptor descriptor) = 0; virtual void RemovePipelinesWithEntryPoint( std::shared_ptr<const ShaderFunction> function) = 0; protected: PipelineLibrary(); private: PipelineLibrary(const PipelineLibrary&) = delete; PipelineLibrary& operator=(const PipelineLibrary&) = delete; }; } // namespace impeller #endif // FLUTTER_IMPELLER_RENDERER_PIPELINE_LIBRARY_H_
engine/impeller/renderer/pipeline_library.h/0
{ "file_path": "engine/impeller/renderer/pipeline_library.h", "repo_id": "engine", "token_count": 807 }
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. #ifndef FLUTTER_IMPELLER_RENDERER_VERTEX_DESCRIPTOR_H_ #define FLUTTER_IMPELLER_RENDERER_VERTEX_DESCRIPTOR_H_ #include <vector> #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<VS, FS>`. /// class VertexDescriptor final : public Comparable<VertexDescriptor> { public: static constexpr size_t kReservedVertexBufferIndex = 30u; // The final slot available. Regular buffer indices go up from 0. VertexDescriptor(); // |Comparable<PipelineVertexDescriptor>| virtual ~VertexDescriptor(); template <size_t Size, size_t LayoutSize> void SetStageInputs( const std::array<const ShaderStageIOSlot*, Size>& inputs, const std::array<const ShaderStageBufferLayout*, LayoutSize>& layout) { return SetStageInputs(inputs.data(), inputs.size(), layout.data(), layout.size()); } void SetStageInputs(const std::vector<ShaderStageIOSlot>& inputs, const std::vector<ShaderStageBufferLayout>& layout); template <size_t Size> void RegisterDescriptorSetLayouts( const std::array<DescriptorSetLayout, Size>& 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<ShaderStageIOSlot>& GetStageInputs() const; const std::vector<ShaderStageBufferLayout>& GetStageLayouts() const; const std::vector<DescriptorSetLayout>& GetDescriptorSetLayouts() const; // |Comparable<VertexDescriptor>| std::size_t GetHash() const override; // |Comparable<VertexDescriptor>| bool IsEqual(const VertexDescriptor& other) const override; bool UsesInputAttacments() const; private: std::vector<ShaderStageIOSlot> inputs_; std::vector<ShaderStageBufferLayout> layouts_; std::vector<DescriptorSetLayout> 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_
engine/impeller/renderer/vertex_descriptor.h/0
{ "file_path": "engine/impeller/renderer/vertex_descriptor.h", "repo_id": "engine", "token_count": 1124 }
275
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_PLAYER_H_ #define FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_PLAYER_H_ #include <map> #include <memory> #include <optional> #include <vector> #include "flutter/fml/hash_combine.h" #include "flutter/fml/macros.h" #include "flutter/fml/time/time_delta.h" #include "impeller/base/timing.h" #include "impeller/geometry/matrix.h" #include "impeller/geometry/matrix_decomposition.h" #include "impeller/scene/animation/animation_clip.h" namespace impeller { namespace scene { class Node; class AnimationPlayer final { public: AnimationPlayer(); ~AnimationPlayer(); AnimationPlayer(AnimationPlayer&&); AnimationPlayer& operator=(AnimationPlayer&&); AnimationClip* AddAnimation(const std::shared_ptr<Animation>& animation, Node* bind_target); AnimationClip* GetClip(const std::string& name) const; /// @brief Advanced all clips and updates animated properties in the scene. void Update(); private: std::unordered_map<Node*, AnimationTransforms> target_transforms_; std::map<std::string, AnimationClip> clips_; std::optional<TimePoint> previous_time_; AnimationPlayer(const AnimationPlayer&) = delete; AnimationPlayer& operator=(const AnimationPlayer&) = delete; }; } // namespace scene } // namespace impeller #endif // FLUTTER_IMPELLER_SCENE_ANIMATION_ANIMATION_PLAYER_H_
engine/impeller/scene/animation/animation_player.h/0
{ "file_path": "engine/impeller/scene/animation/animation_player.h", "repo_id": "engine", "token_count": 532 }
276
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "impeller/scene/importer/switches.h" #include <algorithm> #include <cctype> #include <filesystem> #include <map> #include "flutter/fml/file.h" #include "impeller/compiler/utilities.h" #include "impeller/scene/importer/types.h" namespace impeller { namespace scene { namespace importer { static const std::map<std::string, SourceType> kKnownSourceTypes = { {"gltf", SourceType::kGLTF}, }; void Switches::PrintHelp(std::ostream& stream) { stream << std::endl; stream << "SceneC is an offline 3D geometry file parser." << std::endl; stream << "---------------------------------------------------------------" << std::endl; stream << "Valid Argument are:" << std::endl; stream << "--input=<source_file>" << std::endl; stream << "[optional] --input-kind={"; for (const auto& source_type : kKnownSourceTypes) { stream << source_type.first << ", "; } stream << "} (default: gltf)" << std::endl; stream << "--output=<output_file>" << std::endl; } Switches::Switches() = default; Switches::~Switches() = default; static SourceType SourceTypeFromCommandLine( const fml::CommandLine& command_line) { auto source_type_option = command_line.GetOptionValueWithDefault("input-type", "gltf"); 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::UniqueFD>(fml::OpenDirectory( compiler::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)), output_file_name(command_line.GetOptionValueWithDefault("output", "")) { if (!working_directory || !working_directory->is_valid()) { return; } } bool Switches::AreValid(std::ostream& explain) const { bool valid = true; if (input_type == SourceType::kUnknown) { explain << "Unknown input type." << std::endl; valid = false; } if (!working_directory || !working_directory->is_valid()) { explain << "Could not figure out working directory." << std::endl; valid = false; } if (source_file_name.empty()) { explain << "Input file name was empty." << std::endl; valid = false; } if (output_file_name.empty()) { explain << "Target output file name was empty." << std::endl; valid = false; } return valid; } } // namespace importer } // namespace scene } // namespace impeller
engine/impeller/scene/importer/switches.cc/0
{ "file_path": "engine/impeller/scene/importer/switches.cc", "repo_id": "engine", "token_count": 987 }
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 "flutter/fml/macros.h" #include "flutter/fml/logging.h" #include "impeller/renderer/command.h" #include "impeller/renderer/render_target.h" #include "impeller/scene/scene_context.h" #include "impeller/scene/scene_encoder.h" namespace impeller { namespace scene { SceneEncoder::SceneEncoder() = default; void SceneEncoder::Add(const SceneCommand& command) { // TODO(bdero): Manage multi-pass translucency ordering. commands_.push_back(command); } static void EncodeCommand(const SceneContext& scene_context, const Matrix& view_transform, RenderPass& render_pass, const SceneCommand& scene_command) { auto& host_buffer = scene_context.GetTransientsBuffer(); render_pass.SetCommandLabel(scene_command.label); // TODO(bdero): Configurable stencil ref per-command. render_pass.SetStencilReference(0); render_pass.SetPipeline(scene_context.GetPipeline( PipelineKey{scene_command.geometry->GetGeometryType(), scene_command.material->GetMaterialType()}, scene_command.material->GetContextOptions(render_pass))); scene_command.geometry->BindToCommand( scene_context, host_buffer, view_transform * scene_command.transform, render_pass); scene_command.material->BindToCommand(scene_context, host_buffer, render_pass); render_pass.Draw(); ; } std::shared_ptr<CommandBuffer> SceneEncoder::BuildSceneCommandBuffer( const SceneContext& scene_context, const Matrix& camera_transform, RenderTarget render_target) const { { TextureDescriptor ds_texture; ds_texture.type = TextureType::kTexture2DMultisample; ds_texture.format = PixelFormat::kD32FloatS8UInt; ds_texture.size = render_target.GetRenderTargetSize(); ds_texture.usage = TextureUsage::kRenderTarget; ds_texture.sample_count = SampleCount::kCount4; ds_texture.storage_mode = StorageMode::kDeviceTransient; auto texture = scene_context.GetContext()->GetResourceAllocator()->CreateTexture( ds_texture); DepthAttachment depth; depth.load_action = LoadAction::kClear; depth.store_action = StoreAction::kDontCare; depth.clear_depth = 1.0; depth.texture = texture; render_target.SetDepthAttachment(depth); // The stencil and depth buffers must be the same texture for MacOS ARM // and Vulkan. StencilAttachment stencil; stencil.load_action = LoadAction::kClear; stencil.store_action = StoreAction::kDontCare; stencil.clear_stencil = 0u; stencil.texture = texture; render_target.SetStencilAttachment(stencil); } auto command_buffer = scene_context.GetContext()->CreateCommandBuffer(); if (!command_buffer) { FML_LOG(ERROR) << "Failed to create command buffer."; return nullptr; } auto render_pass = command_buffer->CreateRenderPass(render_target); if (!render_pass) { FML_LOG(ERROR) << "Failed to create render pass."; return nullptr; } for (auto& command : commands_) { EncodeCommand(scene_context, camera_transform, *render_pass, command); } if (!render_pass->EncodeCommands()) { FML_LOG(ERROR) << "Failed to encode render pass commands."; return nullptr; } return command_buffer; } } // namespace scene } // namespace impeller
engine/impeller/scene/scene_encoder.cc/0
{ "file_path": "engine/impeller/scene/scene_encoder.cc", "repo_id": "engine", "token_count": 1282 }
278
// Copyright 2013 The Flutter 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";
engine/impeller/shader_archive/shader_archive.fbs/0
{ "file_path": "engine/impeller/shader_archive/shader_archive.fbs", "repo_id": "engine", "token_count": 147 }
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 "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" namespace impeller { namespace testing { TEST(TessellatorTest, TessellatorBuilderReturnsCorrectResultStatus) { // Zero points. { Tessellator t; auto path = PathBuilder{}.TakePath(FillType::kOdd); Tessellator::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, Tessellator::Result::kInputError); } // One point. { Tessellator t; auto path = PathBuilder{}.LineTo({0, 0}).TakePath(FillType::kOdd); Tessellator::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, Tessellator::Result::kSuccess); } // Two points. { Tessellator t; auto path = PathBuilder{}.AddLine({0, 0}, {0, 1}).TakePath(FillType::kOdd); Tessellator::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, Tessellator::Result::kSuccess); } // Many points. { Tessellator 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); Tessellator::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, Tessellator::Result::kSuccess); } // Closure fails. { Tessellator t; auto path = PathBuilder{}.AddLine({0, 0}, {0, 1}).TakePath(FillType::kOdd); Tessellator::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, Tessellator::Result::kInputError); } // More than uint16 points, odd fill mode. { Tessellator t; PathBuilder builder = {}; for (auto i = 0; i < 1000; i++) { builder.AddCircle(Point(i, i), 4); } auto path = builder.TakePath(FillType::kOdd); bool no_indices = false; size_t count = 0u; Tessellator::Result result = t.Tessellate( path, 1.0f, [&no_indices, &count](const float* vertices, size_t vertices_count, const uint16_t* indices, size_t indices_count) { no_indices = indices == nullptr; count = vertices_count; return true; }); ASSERT_TRUE(no_indices); ASSERT_TRUE(count >= USHRT_MAX); ASSERT_EQ(result, Tessellator::Result::kSuccess); } } TEST(TessellatorTest, TessellateConvex) { { Tessellator t; // Sanity check simple rectangle. auto pts = t.TessellateConvex( PathBuilder{}.AddRect(Rect::MakeLTRB(0, 0, 10, 10)).TakePath(), 1.0); std::vector<Point> expected = {{0, 0}, {10, 0}, {0, 10}, {10, 10}}; EXPECT_EQ(pts, expected); } { Tessellator t; auto pts = t.TessellateConvex(PathBuilder{} .AddRect(Rect::MakeLTRB(0, 0, 10, 10)) .AddRect(Rect::MakeLTRB(20, 20, 30, 30)) .TakePath(), 1.0); std::vector<Point> expected = {{0, 0}, {10, 0}, {0, 10}, {10, 10}, {10, 10}, {20, 20}, {20, 20}, {30, 20}, {20, 30}, {30, 30}}; EXPECT_EQ(pts, expected); } } TEST(TessellatorTest, CircleVertexCounts) { auto tessellator = std::make_shared<Tessellator>(); 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<Scalar>(cos(angle) * radius), static_cast<Scalar>(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<Tessellator>(); 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<Point>(); 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; double rcos = 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<Tessellator>(); 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<Point>(); 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); double rcos = 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); double rcos = 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<Tessellator>(); 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<Point>(); 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; Point relative_along = along * 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<Tessellator>(); 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<Point>(); 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 rcos = 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<Tessellator>(); 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<Point>(); 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 rcos = 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}); } #if !NDEBUG TEST(TessellatorTest, ChecksConcurrentPolylineUsage) { auto tessellator = std::make_shared<Tessellator>(); 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
engine/impeller/tessellator/tessellator_unittests.cc/0
{ "file_path": "engine/impeller/tessellator/tessellator_unittests.cc", "repo_id": "engine", "token_count": 8893 }
280
// Copyright 2013 The Flutter Authors. All rights 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<GLTexture, GLTextureTraits>; } // namespace impeller #endif // FLUTTER_IMPELLER_TOOLKIT_GLES_TEXTURE_H_
engine/impeller/toolkit/gles/texture.h/0
{ "file_path": "engine/impeller/toolkit/gles/texture.h", "repo_id": "engine", "token_count": 371 }
281
// Copyright 2013 The Flutter Authors. All 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<SkTypeface> 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<size_t>(typeface_.get()); } bool TypefaceSkia::IsEqual(const Typeface& other) const { auto sk_other = reinterpret_cast<const TypefaceSkia*>(&other); return sk_other->typeface_ == typeface_; } const sk_sp<SkTypeface>& TypefaceSkia::GetSkiaTypeface() const { return typeface_; } } // namespace impeller
engine/impeller/typographer/backends/skia/typeface_skia.cc/0
{ "file_path": "engine/impeller/typographer/backends/skia/typeface_skia.cc", "repo_id": "engine", "token_count": 308 }
282
// Copyright 2013 The Flutter Authors. All rights 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 <optional> #include <unordered_map> #include <unordered_set> #include <vector> #include "flutter/fml/macros.h" #include "impeller/geometry/size.h" #include "impeller/typographer/font.h" #include "impeller/typographer/glyph.h" namespace impeller { //------------------------------------------------------------------------------ /// @brief A font and a scale. Used as a key that represents a typeface /// within a glyph atlas. /// struct ScaledFont { Font font; Scalar scale; }; using FontGlyphMap = std::unordered_map<ScaledFont, std::unordered_set<Glyph>>; //------------------------------------------------------------------------------ /// @brief A font along with a glyph in that font rendered at a particular /// scale. /// struct FontGlyphPair { FontGlyphPair(const ScaledFont& sf, const Glyph& g) : scaled_font(sf), glyph(g) {} const ScaledFont& scaled_font; const Glyph& glyph; }; } // namespace impeller template <> struct std::hash<impeller::ScaledFont> { constexpr std::size_t operator()(const impeller::ScaledFont& sf) const { return fml::HashCombine(sf.font.GetHash(), sf.scale); } }; template <> struct std::equal_to<impeller::ScaledFont> { constexpr bool operator()(const impeller::ScaledFont& lhs, const impeller::ScaledFont& rhs) const { return lhs.font.IsEqual(rhs.font) && lhs.scale == rhs.scale; } }; #endif // FLUTTER_IMPELLER_TYPOGRAPHER_FONT_GLYPH_PAIR_H_
engine/impeller/typographer/font_glyph_pair.h/0
{ "file_path": "engine/impeller/typographer/font_glyph_pair.h", "repo_id": "engine", "token_count": 656 }
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_TYPOGRAPHER_TYPOGRAPHER_CONTEXT_H_ #define FLUTTER_IMPELLER_TYPOGRAPHER_TYPOGRAPHER_CONTEXT_H_ #include <memory> #include "flutter/fml/macros.h" #include "impeller/renderer/context.h" #include "impeller/typographer/glyph_atlas.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<GlyphAtlasContext> CreateGlyphAtlasContext() const = 0; // TODO(dnfield): Callers should not need to know which type of atlas to // create. https://github.com/flutter/flutter/issues/111640 virtual std::shared_ptr<GlyphAtlas> CreateGlyphAtlas( Context& context, GlyphAtlas::Type type, const std::shared_ptr<GlyphAtlasContext>& atlas_context, const FontGlyphMap& font_glyph_map) 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_
engine/impeller/typographer/typographer_context.h/0
{ "file_path": "engine/impeller/typographer/typographer_context.h", "repo_id": "engine", "token_count": 583 }
284
// Copyright 2013 The Flutter Authors. 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/lib/gpu/host_buffer.h" #include <optional> #include "dart_api.h" #include "impeller/core/host_buffer.h" #include "impeller/core/platform.h" #include "third_party/tonic/typed_data/dart_byte_data.h" namespace flutter { namespace gpu { IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, HostBuffer); HostBuffer::HostBuffer(Context* context) : host_buffer_(impeller::HostBuffer::Create( context->GetContext()->GetResourceAllocator())) {} HostBuffer::~HostBuffer() = default; std::shared_ptr<impeller::HostBuffer> HostBuffer::GetBuffer() { return host_buffer_; } size_t HostBuffer::EmplaceBytes(const tonic::DartByteData& byte_data) { auto view = host_buffer_->Emplace(byte_data.data(), byte_data.length_in_bytes(), impeller::DefaultUniformAlignment()); emplacements_[current_offset_] = view; size_t previous_offset = current_offset_; current_offset_ += view.range.length; return previous_offset; } std::optional<impeller::BufferView> HostBuffer::GetBufferViewForOffset( size_t offset) { return emplacements_[offset]; } } // namespace gpu } // namespace flutter //---------------------------------------------------------------------------- /// Exports /// void InternalFlutterGpu_HostBuffer_Initialize(Dart_Handle wrapper, flutter::gpu::Context* context) { auto res = fml::MakeRefCounted<flutter::gpu::HostBuffer>(context); res->AssociateWithDartWrapper(wrapper); } size_t InternalFlutterGpu_HostBuffer_EmplaceBytes( flutter::gpu::HostBuffer* wrapper, Dart_Handle byte_data) { return wrapper->EmplaceBytes(tonic::DartByteData(byte_data)); }
engine/lib/gpu/host_buffer.cc/0
{ "file_path": "engine/lib/gpu/host_buffer.cc", "repo_id": "engine", "token_count": 666 }
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 "flutter/lib/gpu/render_pipeline.h" #include "flutter/lib/gpu/shader.h" #include "impeller/renderer/pipeline_descriptor.h" namespace flutter { namespace gpu { IMPLEMENT_WRAPPERTYPEINFO(flutter_gpu, RenderPipeline); RenderPipeline::RenderPipeline( fml::RefPtr<flutter::gpu::Shader> vertex_shader, fml::RefPtr<flutter::gpu::Shader> fragment_shader) : vertex_shader_(std::move(vertex_shader)), fragment_shader_(std::move(fragment_shader)) {} void RenderPipeline::BindToPipelineDescriptor( impeller::ShaderLibrary& library, impeller::PipelineDescriptor& desc) { desc.SetVertexDescriptor(vertex_shader_->GetVertexDescriptor()); desc.AddStageEntrypoint(vertex_shader_->GetFunctionFromLibrary(library)); desc.AddStageEntrypoint(fragment_shader_->GetFunctionFromLibrary(library)); } RenderPipeline::~RenderPipeline() = default; } // namespace gpu } // namespace flutter //---------------------------------------------------------------------------- /// Exports /// Dart_Handle InternalFlutterGpu_RenderPipeline_Initialize( Dart_Handle wrapper, flutter::gpu::Context* gpu_context, flutter::gpu::Shader* vertex_shader, flutter::gpu::Shader* fragment_shader) { // Lazily register the shaders synchronously if they haven't been already. vertex_shader->RegisterSync(*gpu_context); fragment_shader->RegisterSync(*gpu_context); auto res = fml::MakeRefCounted<flutter::gpu::RenderPipeline>( fml::RefPtr<flutter::gpu::Shader>(vertex_shader), // fml::RefPtr<flutter::gpu::Shader>(fragment_shader)); res->AssociateWithDartWrapper(wrapper); return Dart_Null(); }
engine/lib/gpu/render_pipeline.cc/0
{ "file_path": "engine/lib/gpu/render_pipeline.cc", "repo_id": "engine", "token_count": 625 }
286
# Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. dart_ui_files = [ "//flutter/lib/ui/annotations.dart", "//flutter/lib/ui/channel_buffers.dart", "//flutter/lib/ui/compositing.dart", "//flutter/lib/ui/geometry.dart", "//flutter/lib/ui/hash_codes.dart", "//flutter/lib/ui/hooks.dart", "//flutter/lib/ui/isolate_name_server.dart", "//flutter/lib/ui/key.dart", "//flutter/lib/ui/lerp.dart", "//flutter/lib/ui/math.dart", "//flutter/lib/ui/natives.dart", "//flutter/lib/ui/painting.dart", "//flutter/lib/ui/platform_dispatcher.dart", "//flutter/lib/ui/platform_isolate.dart", "//flutter/lib/ui/plugins.dart", "//flutter/lib/ui/pointer.dart", "//flutter/lib/ui/semantics.dart", "//flutter/lib/ui/text.dart", "//flutter/lib/ui/ui.dart", "//flutter/lib/ui/window.dart", ] dart_ui_path = "//flutter/lib/ui/ui.dart" dart_ui_web_files = [ "$root_out_dir/flutter_web_sdk/lib/ui_web/ui_web/url_strategy.dart", "$root_out_dir/flutter_web_sdk/lib/ui_web/ui_web.dart", ] dart_ui_web_path = "//flutter/lib/web_ui/lib/ui_web/src/ui_web.dart"
engine/lib/ui/dart_ui.gni/0
{ "file_path": "engine/lib/ui/dart_ui.gni", "repo_id": "engine", "token_count": 538 }
287
# Copyright 2013 The Flutter 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") if (enable_unittests) { group("shaders") { testonly = true deps = [ ":fixtures", "//flutter/lib/ui/fixtures/shaders/general_shaders", "//flutter/lib/ui/fixtures/shaders/supported_glsl_op_shaders", "//flutter/lib/ui/fixtures/shaders/supported_op_shaders", ] } impellerc("ink_sparkle") { shaders = [ "//flutter/impeller/fixtures/ink_sparkle.frag" ] shader_target_flags = [ "--sksl" ] intermediates_subdir = "iplr" sl_file_extension = "iplr" iplr = true } impellerc("ink_sparkle_web") { shaders = [ "//flutter/impeller/fixtures/ink_sparkle.frag" ] shader_target_flags = [ "--sksl" ] intermediates_subdir = "iplr-json" sl_file_extension = "iplr" iplr = true json = true } impellerc("sampler_order_fixture") { shaders = [ "//flutter/impeller/fixtures/ordering/shader_with_samplers.frag", "//flutter/third_party/test_shaders/selman/glow_shader.frag", ] shader_target_flags = [ "--runtime-stage-metal", "--runtime-stage-gles", "--runtime-stage-vulkan", ] intermediates_subdir = "iplr-remap" sl_file_extension = "iplr" iplr = true } test_fixtures("fixtures") { deps = [ ":ink_sparkle", ":ink_sparkle_web", ":sampler_order_fixture", ] fixtures = get_target_outputs(":ink_sparkle") dest = "$root_gen_dir/flutter/lib/ui" } }
engine/lib/ui/fixtures/shaders/BUILD.gn/0
{ "file_path": "engine/lib/ui/fixtures/shaders/BUILD.gn", "repo_id": "engine", "token_count": 741 }
288
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "flutter/common/task_runners.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/common/shell_test.h" #include "flutter/shell/common/thread_host.h" #include "flutter/testing/testing.h" #include "third_party/dart/runtime/include/dart_api.h" // CREATE_NATIVE_ENTRY is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) namespace flutter { namespace testing { using HooksTest = ShellTest; #define CHECK_DART_ERROR(name) \ EXPECT_FALSE(Dart_IsError(name)) << Dart_GetError(name) TEST_F(HooksTest, HooksUnitTests) { auto settings = CreateSettingsForFixture(); TaskRunners task_runners(GetCurrentTestName(), // label GetCurrentTaskRunner(), // platform CreateNewThread("raster"), // raster CreateNewThread("ui"), // ui CreateNewThread("io") // io ); auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto call_hook = [](Dart_NativeArguments args) { Dart_Handle hook_name = Dart_GetNativeArgument(args, 0); CHECK_DART_ERROR(hook_name); Dart_Handle ui_library = Dart_LookupLibrary(tonic::ToDart("dart:ui")); CHECK_DART_ERROR(ui_library); Dart_Handle hook = Dart_GetField(ui_library, hook_name); CHECK_DART_ERROR(hook); Dart_Handle arg_count_handle = Dart_GetNativeArgument(args, 1); CHECK_DART_ERROR(arg_count_handle); int64_t arg_count; Dart_IntegerToInt64(arg_count_handle, &arg_count); std::vector<Dart_Handle> hook_args; for (int i = 0; i < static_cast<int>(arg_count); i++) { hook_args.push_back(Dart_GetNativeArgument(args, 2 + i)); CHECK_DART_ERROR(hook_args.back()); } Dart_Handle hook_result = Dart_InvokeClosure(hook, hook_args.size(), hook_args.data()); CHECK_DART_ERROR(hook_result); }; auto finished = [&message_latch](Dart_NativeArguments args) { message_latch->Signal(); }; AddNativeCallback("CallHook", CREATE_NATIVE_ENTRY(call_hook)); AddNativeCallback("Finish", CREATE_NATIVE_ENTRY(finished)); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("hooksTests"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/lib/ui/hooks_unittests.cc/0
{ "file_path": "engine/lib/ui/hooks_unittests.cc", "repo_id": "engine", "token_count": 1114 }
289
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_CODEC_H_ #define FLUTTER_LIB_UI_PAINTING_CODEC_H_ #include "flutter/lib/ui/dart_wrapper.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/skia/include/codec/SkCodec.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImage.h" namespace flutter { // A handle to an SkCodec object. // // Doesn't mirror SkCodec's API but provides a simple sequential access API. class Codec : public RefCountedDartWrappable<Codec> { DEFINE_WRAPPERTYPEINFO(); public: virtual int frameCount() const = 0; virtual int repetitionCount() const = 0; virtual Dart_Handle getNextFrame(Dart_Handle callback_handle) = 0; void dispose(); }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_CODEC_H_
engine/lib/ui/painting/codec.h/0
{ "file_path": "engine/lib/ui/painting/codec.h", "repo_id": "engine", "token_count": 341 }
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. #ifndef FLUTTER_LIB_UI_PAINTING_GRADIENT_H_ #define FLUTTER_LIB_UI_PAINTING_GRADIENT_H_ #include "flutter/display_list/effects/dl_color_source.h" #include "flutter/lib/ui/painting/matrix.h" #include "flutter/lib/ui/painting/shader.h" #include "third_party/tonic/typed_data/typed_list.h" namespace flutter { class CanvasGradient : public Shader { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(CanvasGradient); public: ~CanvasGradient() override; static void Create(Dart_Handle wrapper); void initLinear(const tonic::Float32List& end_points, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4); void initRadial(double center_x, double center_y, double radius, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4); void initSweep(double center_x, double center_y, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, double start_angle, double end_angle, const tonic::Float64List& matrix4); void initTwoPointConical(double start_x, double start_y, double start_radius, double end_x, double end_y, double end_radius, const tonic::Int32List& colors, const tonic::Float32List& color_stops, DlTileMode tile_mode, const tonic::Float64List& matrix4); std::shared_ptr<DlColorSource> shader(DlImageSampling sampling) override { // Gradient color sources do not have image sampling variants... return dl_shader_; } private: CanvasGradient(); std::shared_ptr<DlColorSource> dl_shader_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_GRADIENT_H_
engine/lib/ui/painting/gradient.h/0
{ "file_path": "engine/lib/ui/painting/gradient.h", "repo_id": "engine", "token_count": 1180 }
291
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_H_ #define FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_H_ #include "third_party/skia/include/core/SkImage.h" #include "third_party/tonic/dart_library_natives.h" namespace flutter { class CanvasImage; // This must be kept in sync with the enum in painting.dart enum ImageByteFormat { kRawRGBA, kRawStraightRGBA, kRawUnmodified, kRawExtendedRgba128, kPNG, }; Dart_Handle EncodeImage(CanvasImage* canvas_image, int format, Dart_Handle callback_handle); sk_sp<SkData> EncodeImage(const sk_sp<SkImage>& raster_image, ImageByteFormat format); } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_IMAGE_ENCODING_H_
engine/lib/ui/painting/image_encoding.h/0
{ "file_path": "engine/lib/ui/painting/image_encoding.h", "repo_id": "engine", "token_count": 382 }
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 "flutter/lib/ui/painting/image_shader.h" #include "flutter/lib/ui/painting/image_filter.h" #include "flutter/lib/ui/painting/display_list_image_gpu.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" using tonic::ToDart; namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, ImageShader); void ImageShader::Create(Dart_Handle wrapper) { auto res = fml::MakeRefCounted<ImageShader>(); res->AssociateWithDartWrapper(wrapper); } Dart_Handle ImageShader::initWithImage(CanvasImage* image, DlTileMode tmx, DlTileMode tmy, int filter_quality_index, Dart_Handle matrix_handle) { // CanvasImage should have already checked for a UI thread safe image. if (!image || !image->image()->isUIThreadSafe()) { return ToDart("ImageShader constructor called with non-genuine Image."); } image_ = image->image(); tonic::Float64List matrix4(matrix_handle); SkMatrix local_matrix = ToSkMatrix(matrix4); matrix4.Release(); sampling_is_locked_ = filter_quality_index >= 0; DlImageSampling sampling = sampling_is_locked_ ? ImageFilter::SamplingFromIndex(filter_quality_index) : DlImageSampling::kLinear; cached_shader_ = std::make_shared<DlImageColorSource>( image_, tmx, tmy, sampling, &local_matrix); FML_DCHECK(cached_shader_->isUIThreadSafe()); return Dart_Null(); } std::shared_ptr<DlColorSource> ImageShader::shader(DlImageSampling sampling) { if (sampling_is_locked_ || sampling == cached_shader_->sampling()) { return cached_shader_; } return cached_shader_->with_sampling(sampling); } int ImageShader::width() { return image_->width(); } int ImageShader::height() { return image_->height(); } void ImageShader::dispose() { cached_shader_.reset(); image_.reset(); ClearDartWrapper(); } ImageShader::ImageShader() = default; ImageShader::~ImageShader() = default; } // namespace flutter
engine/lib/ui/painting/image_shader.cc/0
{ "file_path": "engine/lib/ui/painting/image_shader.cc", "repo_id": "engine", "token_count": 968 }
293
// Copyright 2013 The Flutter Authors. 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/lib/ui/painting/picture.h" #include <memory> #include <utility> #include "flutter/fml/make_copyable.h" #include "flutter/lib/ui/painting/canvas.h" #include "flutter/lib/ui/painting/display_list_deferred_image_gpu_skia.h" #include "flutter/lib/ui/ui_dart_state.h" #if IMPELLER_SUPPORTS_RENDERING #include "flutter/lib/ui/painting/display_list_deferred_image_gpu_impeller.h" #endif // IMPELLER_SUPPORTS_RENDERING #include "flutter/lib/ui/painting/display_list_image_gpu.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_args.h" #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_library_natives.h" #include "third_party/tonic/dart_persistent_value.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, Picture); void Picture::CreateAndAssociateWithDartWrapper( Dart_Handle dart_handle, sk_sp<DisplayList> display_list) { FML_DCHECK(display_list->isUIThreadSafe()); auto canvas_picture = fml::MakeRefCounted<Picture>(std::move(display_list)); canvas_picture->AssociateWithDartWrapper(dart_handle); } Picture::Picture(sk_sp<DisplayList> display_list) : display_list_(std::move(display_list)) {} Picture::~Picture() = default; Dart_Handle Picture::toImage(uint32_t width, uint32_t height, Dart_Handle raw_image_callback) { if (!display_list_) { return tonic::ToDart("Picture is null"); } return RasterizeToImage(display_list_, width, height, raw_image_callback); } void Picture::toImageSync(uint32_t width, uint32_t height, Dart_Handle raw_image_handle) { FML_DCHECK(display_list_); RasterizeToImageSync(display_list_, width, height, raw_image_handle); } static sk_sp<DlImage> CreateDeferredImage( bool impeller, sk_sp<DisplayList> display_list, uint32_t width, uint32_t height, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, fml::RefPtr<fml::TaskRunner> raster_task_runner, fml::RefPtr<SkiaUnrefQueue> unref_queue) { #if IMPELLER_SUPPORTS_RENDERING if (impeller) { return DlDeferredImageGPUImpeller::Make( std::move(display_list), SkISize::Make(width, height), std::move(snapshot_delegate), std::move(raster_task_runner)); } #endif // IMPELLER_SUPPORTS_RENDERING const SkImageInfo image_info = SkImageInfo::Make( width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType); return DlDeferredImageGPUSkia::Make( image_info, std::move(display_list), std::move(snapshot_delegate), raster_task_runner, std::move(unref_queue)); } // static void Picture::RasterizeToImageSync(sk_sp<DisplayList> display_list, uint32_t width, uint32_t height, Dart_Handle raw_image_handle) { auto* dart_state = UIDartState::Current(); if (!dart_state) { return; } auto unref_queue = dart_state->GetSkiaUnrefQueue(); auto snapshot_delegate = dart_state->GetSnapshotDelegate(); auto raster_task_runner = dart_state->GetTaskRunners().GetRasterTaskRunner(); auto image = CanvasImage::Create(); auto dl_image = CreateDeferredImage( dart_state->IsImpellerEnabled(), std::move(display_list), width, height, std::move(snapshot_delegate), std::move(raster_task_runner), std::move(unref_queue)); image->set_image(dl_image); image->AssociateWithDartWrapper(raw_image_handle); } void Picture::dispose() { display_list_.reset(); ClearDartWrapper(); } size_t Picture::GetAllocationSize() const { if (display_list_) { return display_list_->bytes() + sizeof(Picture); } else { return sizeof(Picture); } } Dart_Handle Picture::RasterizeToImage(const sk_sp<DisplayList>& display_list, uint32_t width, uint32_t height, Dart_Handle raw_image_callback) { return DoRasterizeToImage(display_list, nullptr, width, height, raw_image_callback); } Dart_Handle Picture::RasterizeLayerTreeToImage( std::unique_ptr<LayerTree> layer_tree, Dart_Handle raw_image_callback) { FML_DCHECK(layer_tree != nullptr); auto frame_size = layer_tree->frame_size(); return DoRasterizeToImage(nullptr, std::move(layer_tree), frame_size.width(), frame_size.height(), raw_image_callback); } Dart_Handle Picture::DoRasterizeToImage(const sk_sp<DisplayList>& display_list, std::unique_ptr<LayerTree> layer_tree, uint32_t width, uint32_t height, Dart_Handle raw_image_callback) { // Either display_list or layer_tree should be provided. FML_DCHECK((display_list == nullptr) != (layer_tree == nullptr)); if (Dart_IsNull(raw_image_callback) || !Dart_IsClosure(raw_image_callback)) { return tonic::ToDart("Image callback was invalid"); } if (width == 0 || height == 0) { return tonic::ToDart("Image dimensions for scene were invalid."); } auto* dart_state = UIDartState::Current(); auto image_callback = std::make_unique<tonic::DartPersistentValue>( dart_state, raw_image_callback); auto unref_queue = dart_state->GetSkiaUnrefQueue(); auto ui_task_runner = dart_state->GetTaskRunners().GetUITaskRunner(); auto raster_task_runner = dart_state->GetTaskRunners().GetRasterTaskRunner(); auto snapshot_delegate = dart_state->GetSnapshotDelegate(); // We can't create an image on this task runner because we don't have a // graphics context. Even if we did, it would be slow anyway. Also, this // thread owns the sole reference to the layer tree. So we do it in the // raster thread. auto ui_task = // The static leak checker gets confused by the use of fml::MakeCopyable. // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) fml::MakeCopyable([image_callback = std::move(image_callback), unref_queue](sk_sp<DlImage> image) mutable { auto dart_state = image_callback->dart_state().lock(); if (!dart_state) { // The root isolate could have died in the meantime. return; } tonic::DartState::Scope scope(dart_state); if (!image) { tonic::DartInvoke(image_callback->Get(), {Dart_Null()}); return; } if (!image->isUIThreadSafe()) { // All images with impeller textures should already be safe. FML_DCHECK(image->impeller_texture() == nullptr); image = DlImageGPU::Make({image->skia_image(), std::move(unref_queue)}); } auto dart_image = CanvasImage::Create(); dart_image->set_image(image); auto* raw_dart_image = tonic::ToDart(dart_image); // All done! tonic::DartInvoke(image_callback->Get(), {raw_dart_image}); // image_callback is associated with the Dart isolate and must be // deleted on the UI thread. image_callback.reset(); }); // Kick things off on the raster rask runner. fml::TaskRunner::RunNowOrPostTask( raster_task_runner, fml::MakeCopyable([ui_task_runner, snapshot_delegate, display_list, width, height, ui_task, layer_tree = std::move(layer_tree)]() mutable { auto picture_bounds = SkISize::Make(width, height); sk_sp<DlImage> image; if (layer_tree) { FML_DCHECK(picture_bounds == layer_tree->frame_size()); auto display_list = layer_tree->Flatten(SkRect::MakeWH(width, height), snapshot_delegate->GetTextureRegistry(), snapshot_delegate->GetGrContext()); image = snapshot_delegate->MakeRasterSnapshot(display_list, picture_bounds); } else { image = snapshot_delegate->MakeRasterSnapshot(display_list, picture_bounds); } fml::TaskRunner::RunNowOrPostTask( ui_task_runner, [ui_task, image]() { ui_task(image); }); })); return Dart_Null(); } } // namespace flutter
engine/lib/ui/painting/picture.cc/0
{ "file_path": "engine/lib/ui/painting/picture.cc", "repo_id": "engine", "token_count": 3774 }
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. #ifndef FLUTTER_LIB_UI_PAINTING_VERTICES_H_ #define FLUTTER_LIB_UI_PAINTING_VERTICES_H_ #include "flutter/display_list/dl_vertices.h" #include "flutter/lib/ui/dart_wrapper.h" #include "third_party/skia/include/core/SkVertices.h" #include "third_party/tonic/typed_data/typed_list.h" namespace flutter { class Vertices : public RefCountedDartWrappable<Vertices> { DEFINE_WRAPPERTYPEINFO(); FML_FRIEND_MAKE_REF_COUNTED(Vertices); public: ~Vertices() override; static bool init(Dart_Handle vertices_handle, DlVertexMode vertex_mode, Dart_Handle positions_handle, Dart_Handle texture_coordinates_handle, Dart_Handle colors_handle, Dart_Handle indices_handle); const DlVertices* vertices() const { return vertices_.get(); } void dispose(); private: Vertices(); std::shared_ptr<DlVertices> vertices_; }; } // namespace flutter #endif // FLUTTER_LIB_UI_PAINTING_VERTICES_H_
engine/lib/ui/painting/vertices.h/0
{ "file_path": "engine/lib/ui/painting/vertices.h", "repo_id": "engine", "token_count": 467 }
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. #include "flutter/lib/ui/semantics/semantics_update_builder.h" #include "flutter/shell/common/shell_test.h" #include "gtest/gtest.h" namespace flutter { namespace testing { using SemanticsUpdateBuilderTest = ShellTest; TEST_F(SemanticsUpdateBuilderTest, CanHandleAttributedStrings) { auto message_latch = std::make_shared<fml::AutoResetWaitableEvent>(); auto nativeSemanticsUpdate = [message_latch](Dart_NativeArguments args) { auto handle = Dart_GetNativeArgument(args, 0); intptr_t peer = 0; Dart_Handle result = Dart_GetNativeInstanceField( handle, tonic::DartWrappable::kPeerIndex, &peer); ASSERT_FALSE(Dart_IsError(result)); SemanticsUpdate* update = reinterpret_cast<SemanticsUpdate*>(peer); SemanticsNodeUpdates nodes = update->takeNodes(); ASSERT_EQ(nodes.size(), (size_t)1); auto node = nodes.find(0)->second; // Should match the updateNode in ui_test.dart. ASSERT_EQ(node.label, "label"); ASSERT_EQ(node.labelAttributes.size(), (size_t)1); ASSERT_EQ(node.labelAttributes[0]->start, 1); ASSERT_EQ(node.labelAttributes[0]->end, 2); ASSERT_EQ(node.labelAttributes[0]->type, StringAttributeType::kSpellOut); ASSERT_EQ(node.value, "value"); ASSERT_EQ(node.valueAttributes.size(), (size_t)1); ASSERT_EQ(node.valueAttributes[0]->start, 2); ASSERT_EQ(node.valueAttributes[0]->end, 3); ASSERT_EQ(node.valueAttributes[0]->type, StringAttributeType::kSpellOut); ASSERT_EQ(node.hint, "hint"); ASSERT_EQ(node.hintAttributes.size(), (size_t)1); ASSERT_EQ(node.hintAttributes[0]->start, 0); ASSERT_EQ(node.hintAttributes[0]->end, 1); ASSERT_EQ(node.hintAttributes[0]->type, StringAttributeType::kLocale); auto local_attribute = std::static_pointer_cast<LocaleStringAttribute>(node.hintAttributes[0]); ASSERT_EQ(local_attribute->locale, "en-MX"); ASSERT_EQ(node.increasedValue, "increasedValue"); ASSERT_EQ(node.increasedValueAttributes.size(), (size_t)1); ASSERT_EQ(node.increasedValueAttributes[0]->start, 4); ASSERT_EQ(node.increasedValueAttributes[0]->end, 5); ASSERT_EQ(node.increasedValueAttributes[0]->type, StringAttributeType::kSpellOut); ASSERT_EQ(node.decreasedValue, "decreasedValue"); ASSERT_EQ(node.decreasedValueAttributes.size(), (size_t)1); ASSERT_EQ(node.decreasedValueAttributes[0]->start, 5); ASSERT_EQ(node.decreasedValueAttributes[0]->end, 6); ASSERT_EQ(node.decreasedValueAttributes[0]->type, StringAttributeType::kSpellOut); message_latch->Signal(); }; Settings settings = CreateSettingsForFixture(); TaskRunners task_runners("test", // label GetCurrentTaskRunner(), // platform CreateNewThread(), // raster CreateNewThread(), // ui CreateNewThread() // io ); AddNativeCallback("SemanticsUpdate", CREATE_NATIVE_ENTRY(nativeSemanticsUpdate)); std::unique_ptr<Shell> shell = CreateShell(settings, task_runners); ASSERT_TRUE(shell->IsSetup()); auto configuration = RunConfiguration::InferFromSettings(settings); configuration.SetEntrypoint("sendSemanticsUpdate"); shell->RunEngine(std::move(configuration), [](auto result) { ASSERT_EQ(result, Engine::RunStatus::Success); }); message_latch->Wait(); DestroyShell(std::move(shell), task_runners); } } // namespace testing } // namespace flutter
engine/lib/ui/semantics/semantics_update_builder_unittests.cc/0
{ "file_path": "engine/lib/ui/semantics/semantics_update_builder_unittests.cc", "repo_id": "engine", "token_count": 1465 }
296
// Copyright 2013 The Flutter Authors. 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/lib/ui/ui_dart_state.h" #include <iostream> #include <utility> #include "flutter/fml/message_loop.h" #include "flutter/lib/ui/window/platform_configuration.h" #include "flutter/lib/ui/window/platform_message.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/dart_message_handler.h" #if defined(FML_OS_ANDROID) #include <android/log.h> #elif defined(FML_OS_IOS) extern "C" { // Cannot import the syslog.h header directly because of macro collision. extern void syslog(int, const char*, ...); } #endif using tonic::ToDart; namespace flutter { UIDartState::Context::Context(const TaskRunners& task_runners) : task_runners(task_runners) {} UIDartState::Context::Context( const TaskRunners& task_runners, fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> snapshot_delegate, fml::WeakPtr<IOManager> io_manager, fml::RefPtr<SkiaUnrefQueue> unref_queue, fml::WeakPtr<ImageDecoder> image_decoder, fml::WeakPtr<ImageGeneratorRegistry> image_generator_registry, std::string advisory_script_uri, std::string advisory_script_entrypoint, std::shared_ptr<VolatilePathTracker> volatile_path_tracker, std::shared_ptr<fml::ConcurrentTaskRunner> concurrent_task_runner, bool enable_impeller, impeller::RuntimeStageBackend runtime_stage_backend) : task_runners(task_runners), snapshot_delegate(std::move(snapshot_delegate)), io_manager(std::move(io_manager)), unref_queue(std::move(unref_queue)), image_decoder(std::move(image_decoder)), image_generator_registry(std::move(image_generator_registry)), advisory_script_uri(std::move(advisory_script_uri)), advisory_script_entrypoint(std::move(advisory_script_entrypoint)), volatile_path_tracker(std::move(volatile_path_tracker)), concurrent_task_runner(std::move(concurrent_task_runner)), enable_impeller(enable_impeller), runtime_stage_backend(runtime_stage_backend) {} UIDartState::UIDartState( TaskObserverAdd add_callback, TaskObserverRemove remove_callback, std::string logger_prefix, UnhandledExceptionCallback unhandled_exception_callback, LogMessageCallback log_message_callback, std::shared_ptr<IsolateNameServer> isolate_name_server, bool is_root_isolate, const UIDartState::Context& context) : add_callback_(std::move(add_callback)), remove_callback_(std::move(remove_callback)), logger_prefix_(std::move(logger_prefix)), is_root_isolate_(is_root_isolate), unhandled_exception_callback_(std::move(unhandled_exception_callback)), log_message_callback_(std::move(log_message_callback)), isolate_name_server_(std::move(isolate_name_server)), context_(context) { AddOrRemoveTaskObserver(true /* add */); } UIDartState::~UIDartState() { AddOrRemoveTaskObserver(false /* remove */); } const std::string& UIDartState::GetAdvisoryScriptURI() const { return context_.advisory_script_uri; } bool UIDartState::IsImpellerEnabled() const { return context_.enable_impeller; } impeller::RuntimeStageBackend UIDartState::GetRuntimeStageBackend() const { return context_.runtime_stage_backend; } void UIDartState::DidSetIsolate() { main_port_ = Dart_GetMainPortId(); std::ostringstream debug_name; // main.dart$main-1234 debug_name << context_.advisory_script_uri << "$" << context_.advisory_script_entrypoint << "-" << main_port_; SetDebugName(debug_name.str()); } void UIDartState::ThrowIfUIOperationsProhibited() { if (!UIDartState::Current()->IsRootIsolate()) { Dart_EnterScope(); Dart_ThrowException( tonic::ToDart("UI actions are only available on root isolate.")); } } void UIDartState::SetDebugName(const std::string& debug_name) { debug_name_ = debug_name; if (platform_configuration_) { platform_configuration_->client()->UpdateIsolateDescription(debug_name_, main_port_); } } UIDartState* UIDartState::Current() { return static_cast<UIDartState*>(DartState::Current()); } void UIDartState::SetPlatformConfiguration( std::unique_ptr<PlatformConfiguration> platform_configuration) { FML_DCHECK(IsRootIsolate()); platform_configuration_ = std::move(platform_configuration); if (platform_configuration_) { platform_configuration_->client()->UpdateIsolateDescription(debug_name_, main_port_); } } void UIDartState::SetPlatformMessageHandler( std::weak_ptr<PlatformMessageHandler> handler) { FML_DCHECK(!IsRootIsolate()); platform_message_handler_ = std::move(handler); } const TaskRunners& UIDartState::GetTaskRunners() const { return context_.task_runners; } fml::WeakPtr<IOManager> UIDartState::GetIOManager() const { return context_.io_manager; } fml::RefPtr<flutter::SkiaUnrefQueue> UIDartState::GetSkiaUnrefQueue() const { return context_.unref_queue; } std::shared_ptr<VolatilePathTracker> UIDartState::GetVolatilePathTracker() const { return context_.volatile_path_tracker; } std::shared_ptr<fml::ConcurrentTaskRunner> UIDartState::GetConcurrentTaskRunner() const { return context_.concurrent_task_runner; } void UIDartState::ScheduleMicrotask(Dart_Handle closure) { if (tonic::CheckAndHandleError(closure) || !Dart_IsClosure(closure)) { return; } microtask_queue_.ScheduleMicrotask(closure); } void UIDartState::FlushMicrotasksNow() { microtask_queue_.RunMicrotasks(); } void UIDartState::AddOrRemoveTaskObserver(bool add) { auto task_runner = context_.task_runners.GetUITaskRunner(); if (!task_runner) { // This may happen in case the isolate has no thread affinity (for example, // the service isolate). return; } FML_DCHECK(add_callback_ && remove_callback_); if (add) { add_callback_(reinterpret_cast<intptr_t>(this), [this]() { this->FlushMicrotasksNow(); }); } else { remove_callback_(reinterpret_cast<intptr_t>(this)); } } fml::TaskRunnerAffineWeakPtr<SnapshotDelegate> UIDartState::GetSnapshotDelegate() const { return context_.snapshot_delegate; } fml::WeakPtr<ImageDecoder> UIDartState::GetImageDecoder() const { return context_.image_decoder; } fml::WeakPtr<ImageGeneratorRegistry> UIDartState::GetImageGeneratorRegistry() const { return context_.image_generator_registry; } std::shared_ptr<IsolateNameServer> UIDartState::GetIsolateNameServer() const { return isolate_name_server_; } tonic::DartErrorHandleType UIDartState::GetLastError() { tonic::DartErrorHandleType error = message_handler().isolate_last_error(); if (error == tonic::kNoError) { error = microtask_queue_.GetLastError(); } return error; } void UIDartState::LogMessage(const std::string& tag, const std::string& message) const { if (log_message_callback_) { log_message_callback_(tag, message); } else { // Fall back to previous behavior if unspecified. #if defined(FML_OS_ANDROID) __android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%.*s", static_cast<int>(message.size()), message.c_str()); #elif defined(FML_OS_IOS) std::stringstream stream; if (!tag.empty()) { stream << tag << ": "; } stream << message; std::string log = stream.str(); syslog(1 /* LOG_ALERT */, "%.*s", static_cast<int>(log.size()), log.c_str()); #else if (!tag.empty()) { std::cout << tag << ": "; } std::cout << message << std::endl; #endif } } Dart_Handle UIDartState::HandlePlatformMessage( std::unique_ptr<PlatformMessage> message) { if (platform_configuration_) { platform_configuration_->client()->HandlePlatformMessage( std::move(message)); } else { std::shared_ptr<PlatformMessageHandler> handler = platform_message_handler_.lock(); if (handler) { handler->HandlePlatformMessage(std::move(message)); } else { return tonic::ToDart( "No platform channel handler registered for background isolate."); } } return Dart_Null(); } int64_t UIDartState::GetRootIsolateToken() const { return IsRootIsolate() ? reinterpret_cast<int64_t>(this) : 0; } Dart_Isolate UIDartState::CreatePlatformIsolate(Dart_Handle entry_point, char** error) { FML_UNREACHABLE(); return nullptr; } } // namespace flutter
engine/lib/ui/ui_dart_state.cc/0
{ "file_path": "engine/lib/ui/ui_dart_state.cc", "repo_id": "engine", "token_count": 3226 }
297
// Copyright 2013 The Flutter Authors. 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/lib/ui/window/viewport_metrics.h" #include "flutter/fml/logging.h" namespace flutter { ViewportMetrics::ViewportMetrics() = default; ViewportMetrics::ViewportMetrics(double p_device_pixel_ratio, double p_physical_width, double p_physical_height, double p_physical_touch_slop, size_t p_display_id) : device_pixel_ratio(p_device_pixel_ratio), physical_width(p_physical_width), physical_height(p_physical_height), physical_touch_slop(p_physical_touch_slop), display_id(p_display_id) {} ViewportMetrics::ViewportMetrics( double p_device_pixel_ratio, double p_physical_width, double p_physical_height, double p_physical_padding_top, double p_physical_padding_right, double p_physical_padding_bottom, double p_physical_padding_left, double p_physical_view_inset_top, double p_physical_view_inset_right, double p_physical_view_inset_bottom, double p_physical_view_inset_left, double p_physical_system_gesture_inset_top, double p_physical_system_gesture_inset_right, double p_physical_system_gesture_inset_bottom, double p_physical_system_gesture_inset_left, double p_physical_touch_slop, const std::vector<double>& p_physical_display_features_bounds, const std::vector<int>& p_physical_display_features_type, const std::vector<int>& p_physical_display_features_state, size_t p_display_id) : device_pixel_ratio(p_device_pixel_ratio), physical_width(p_physical_width), physical_height(p_physical_height), physical_padding_top(p_physical_padding_top), physical_padding_right(p_physical_padding_right), physical_padding_bottom(p_physical_padding_bottom), physical_padding_left(p_physical_padding_left), physical_view_inset_top(p_physical_view_inset_top), physical_view_inset_right(p_physical_view_inset_right), physical_view_inset_bottom(p_physical_view_inset_bottom), physical_view_inset_left(p_physical_view_inset_left), physical_system_gesture_inset_top(p_physical_system_gesture_inset_top), physical_system_gesture_inset_right( p_physical_system_gesture_inset_right), physical_system_gesture_inset_bottom( p_physical_system_gesture_inset_bottom), physical_system_gesture_inset_left(p_physical_system_gesture_inset_left), physical_touch_slop(p_physical_touch_slop), physical_display_features_bounds(p_physical_display_features_bounds), physical_display_features_type(p_physical_display_features_type), physical_display_features_state(p_physical_display_features_state), display_id(p_display_id) {} bool operator==(const ViewportMetrics& a, const ViewportMetrics& b) { return a.device_pixel_ratio == b.device_pixel_ratio && a.physical_width == b.physical_width && a.physical_height == b.physical_height && a.physical_padding_top == b.physical_padding_top && a.physical_padding_right == b.physical_padding_right && a.physical_padding_bottom == b.physical_padding_bottom && a.physical_padding_left == b.physical_padding_left && a.physical_view_inset_top == b.physical_view_inset_top && a.physical_view_inset_right == b.physical_view_inset_right && a.physical_view_inset_bottom == b.physical_view_inset_bottom && a.physical_view_inset_left == b.physical_view_inset_left && a.physical_system_gesture_inset_top == b.physical_system_gesture_inset_top && a.physical_system_gesture_inset_right == b.physical_system_gesture_inset_right && a.physical_system_gesture_inset_bottom == b.physical_system_gesture_inset_bottom && a.physical_system_gesture_inset_left == b.physical_system_gesture_inset_left && a.physical_touch_slop == b.physical_touch_slop && a.physical_display_features_bounds == b.physical_display_features_bounds && a.physical_display_features_type == b.physical_display_features_type && a.physical_display_features_state == b.physical_display_features_state && a.display_id == b.display_id; } std::ostream& operator<<(std::ostream& os, const ViewportMetrics& a) { os << "DPR: " << a.device_pixel_ratio << " " << "Size: [" << a.physical_width << "W " << a.physical_height << "H] " << "Padding: [" << a.physical_padding_top << "T " << a.physical_padding_right << "R " << a.physical_padding_bottom << "B " << a.physical_padding_left << "L] " << "Insets: [" << a.physical_view_inset_top << "T " << a.physical_view_inset_right << "R " << a.physical_view_inset_bottom << "B " << a.physical_view_inset_left << "L] " << "Gesture Insets: [" << a.physical_system_gesture_inset_top << "T " << a.physical_system_gesture_inset_right << "R " << a.physical_system_gesture_inset_bottom << "B " << a.physical_system_gesture_inset_left << "L] " << "Display Features: " << a.physical_display_features_type.size() << " " << "Display ID: " << a.display_id; return os; } } // namespace flutter
engine/lib/ui/window/viewport_metrics.cc/0
{ "file_path": "engine/lib/ui/window/viewport_metrics.cc", "repo_id": "engine", "token_count": 2273 }
298
// Copyright 2013 The Flutter 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 'dart:io' as io; import 'package:path/path.dart' as path; import 'utils.dart'; // Determine if a `package` tagged with version:`versionTag` already exists in CIPD. Future<bool> cipdKnowsPackageVersion({ required String package, required String versionTag, bool isVerbose = false, }) async { // $ cipd search $package -tag version:$versionTag // Instances: // $package:CIPD_PACKAGE_ID // or: // No matching instances. final String logLevel = isVerbose ? 'debug' : 'warning'; final String stdout = await evalProcess('cipd', <String>[ 'search', package, '--tag', 'version:$versionTag', '--log-level', logLevel, ]); return stdout.contains('Instances:') && stdout.contains(package); } // Runs a CIPD command to upload a package defined by its `config` file. Future<int> uploadDirectoryToCipd({ required io.Directory directory, required String packageName, required String configFileName, required String description, required String root, required String version, bool isDryRun = false, bool isVerbose = false, }) async { final String cipdConfig = ''' package: $packageName description: $description preserve_writable: true root: $root data: - dir: . '''; // Create the config manifest to upload to CIPD final io.File configFile = io.File(path.join(directory.path, configFileName)); await configFile.writeAsString(cipdConfig); final String cipdCommand = isDryRun ? 'pkg-build' : 'create'; // CIPD won't fully shut up even in 'error' mode final String logLevel = isVerbose ? 'debug' : 'warning'; return runProcess('cipd', <String>[ cipdCommand, '--pkg-def', path.basename(configFile.path), '--json-output', '${path.basenameWithoutExtension(configFile.path)}.json', '--log-level', logLevel, if (!isDryRun) ...<String>[ '--tag', 'version:$version', '--ref', version, ], if (isDryRun) ...<String>[ '--out', '${path.basenameWithoutExtension(configFile.path)}.zip', ], ], workingDirectory: directory.path); }
engine/lib/web_ui/dev/cipd.dart/0
{ "file_path": "engine/lib/web_ui/dev/cipd.dart", "repo_id": "engine", "token_count": 787 }
299
# Please refer to the "Upgrade Browser Version" section in the README.md for # more details on how to update browser version numbers. chrome: version: '119.0.6045.9' firefox: version: '106.0' edge: launcher_version: '1.2.0.0' esbuild: version: '0.19.5'
engine/lib/web_ui/dev/package_lock.yaml/0
{ "file_path": "engine/lib/web_ui/dev/package_lock.yaml", "repo_id": "engine", "token_count": 97 }
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. export const baseUri = ensureTrailingSlash(getBaseURI()); function getBaseURI() { const base = document.querySelector("base"); return (base && base.getAttribute("href")) || ""; } function ensureTrailingSlash(uri) { if (uri === "") { return uri; } return uri.endsWith("/") ? uri : `${uri}/`; }
engine/lib/web_ui/flutter_js/src/base_uri.js/0
{ "file_path": "engine/lib/web_ui/flutter_js/src/base_uri.js", "repo_id": "engine", "token_count": 154 }
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. import 'package:meta/meta.dart'; import 'dom.dart'; // iOS 15 launched WebGL 2.0, but there's something broken about it, which // leads to apps failing to load. For now, we're forcing WebGL 1 on iOS. // // TODO(yjbanov): https://github.com/flutter/flutter/issues/91333 bool get _workAroundBug91333 => operatingSystem == OperatingSystem.iOs; /// The HTML engine used by the current browser. enum BrowserEngine { /// The engine that powers Chrome, Samsung Internet Browser, UC Browser, /// Microsoft Edge, Opera, and others. /// /// Blink is assumed in case when a more precise browser engine wasn't /// detected. blink, /// The engine that powers Safari. webkit, /// The engine that powers Firefox. firefox, } /// The signature of [getUserAgent]. typedef UserAgentGetter = String Function(); /// Returns the current user agent string. /// /// This function is read-writable, so it can be overridden in tests. UserAgentGetter getUserAgent = defaultGetUserAgent; /// The default implementation of [getUserAgent]. String defaultGetUserAgent() { return domWindow.navigator.userAgent; } /// html webgl version qualifier constants. abstract class WebGLVersion { /// WebGL 1.0 is based on OpenGL ES 2.0 / GLSL 1.00 static const int webgl1 = 1; /// WebGL 2.0 is based on OpenGL ES 3.0 / GLSL 3.00 static const int webgl2 = 2; } /// Lazily initialized current browser engine. final BrowserEngine _browserEngine = _detectBrowserEngine(); /// Override the value of [browserEngine]. /// /// Setting this to `null` lets [browserEngine] detect the browser that the /// app is running on. /// /// This is intended to be used for testing and debugging only. BrowserEngine? debugBrowserEngineOverride; /// Returns the [BrowserEngine] used by the current browser. /// /// This is used to implement browser-specific behavior. BrowserEngine get browserEngine { return debugBrowserEngineOverride ?? _browserEngine; } BrowserEngine _detectBrowserEngine() { final String vendor = domWindow.navigator.vendor; final String agent = domWindow.navigator.userAgent.toLowerCase(); return detectBrowserEngineByVendorAgent(vendor, agent); } /// Detects browser engine for a given vendor and agent string. /// /// Used for testing this library. @visibleForTesting BrowserEngine detectBrowserEngineByVendorAgent(String vendor, String agent) { if (vendor == 'Google Inc.') { return BrowserEngine.blink; } else if (vendor == 'Apple Computer, Inc.') { return BrowserEngine.webkit; } else if (agent.contains('Edg/')) { // Chromium based Microsoft Edge has `Edg` in the user-agent. // https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string return BrowserEngine.blink; } else if (vendor == '' && agent.contains('firefox')) { // An empty string means firefox: // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/vendor return BrowserEngine.firefox; } // Assume Blink otherwise, but issue a warning. print( 'WARNING: failed to detect current browser engine. Assuming this is a Chromium-compatible browser.'); return BrowserEngine.blink; } /// Operating system where the current browser runs. /// /// Taken from the navigator platform. /// <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform> enum OperatingSystem { /// iOS: <http://www.apple.com/ios/> iOs, /// Android: <https://www.android.com/> android, /// Linux: <https://www.linux.org/> linux, /// Windows: <https://www.microsoft.com/windows/> windows, /// MacOs: <https://www.apple.com/macos/> macOs, /// We were unable to detect the current operating system. unknown, } /// Lazily initialized current operating system. final OperatingSystem _operatingSystem = detectOperatingSystem(); /// Returns the [OperatingSystem] the current browsers works on. /// /// This is used to implement operating system specific behavior such as /// soft keyboards. OperatingSystem get operatingSystem { return debugOperatingSystemOverride ?? _operatingSystem; } /// Override the value of [operatingSystem]. /// /// Setting this to `null` lets [operatingSystem] detect the real OS that the /// app is running on. /// /// This is intended to be used for testing and debugging only. OperatingSystem? debugOperatingSystemOverride; /// Detects operating system using platform and UA used for unit testing. @visibleForTesting OperatingSystem detectOperatingSystem({ String? overridePlatform, int? overrideMaxTouchPoints, }) { final String platform = overridePlatform ?? domWindow.navigator.platform!; final String userAgent = getUserAgent(); if (platform.startsWith('Mac')) { // iDevices requesting a "desktop site" spoof their UA so it looks like a Mac. // This checks if we're in a touch device, or on a real mac. final int maxTouchPoints = overrideMaxTouchPoints ?? domWindow.navigator.maxTouchPoints?.toInt() ?? 0; if (maxTouchPoints > 2) { return OperatingSystem.iOs; } return OperatingSystem.macOs; } else if (platform.toLowerCase().contains('iphone') || platform.toLowerCase().contains('ipad') || platform.toLowerCase().contains('ipod')) { return OperatingSystem.iOs; } else if (userAgent.contains('Android')) { // The Android OS reports itself as "Linux armv8l" in // [domWindow.navigator.platform]. So we have to check the user-agent to // determine if the OS is Android or not. return OperatingSystem.android; } else if (platform.startsWith('Linux')) { return OperatingSystem.linux; } else if (platform.startsWith('Win')) { return OperatingSystem.windows; } else { return OperatingSystem.unknown; } } /// List of Operating Systems we know to be working on laptops/desktops. /// /// These devices tend to behave differently on many core issues such as events, /// screen readers, input devices. const Set<OperatingSystem> _desktopOperatingSystems = <OperatingSystem>{ OperatingSystem.macOs, OperatingSystem.linux, OperatingSystem.windows, }; /// A flag to check if the current operating system is a laptop/desktop /// operating system. /// /// See [_desktopOperatingSystems]. bool get isDesktop => _desktopOperatingSystems.contains(operatingSystem); /// A flag to check if the current browser is running on a mobile device. /// /// See [_desktopOperatingSystems]. /// See [isDesktop]. bool get isMobile => !isDesktop; /// Whether the browser is running on macOS or iOS. /// /// - See [operatingSystem]. /// - See [OperatingSystem]. bool get isMacOrIOS => operatingSystem == OperatingSystem.iOs || operatingSystem == OperatingSystem.macOs; /// Detect iOS 15. bool get isIOS15 { if (debugIsIOS15 != null) { return debugIsIOS15!; } return operatingSystem == OperatingSystem.iOs && domWindow.navigator.userAgent.contains('OS 15_'); } /// Detect if running on Chrome version 110 or older. /// /// These versions of Chrome have a bug which causes rendering to be flipped /// upside down when using `createImageBitmap`: see /// https://chromium.googlesource.com/chromium/src/+/a7f9b00e422a1755918f8ca5500380f98b6fddf2 // TODO(harryterkelsen): Remove this check once we stop supporting Chrome 110 // and earlier, https://github.com/flutter/flutter/issues/139186. bool get isChrome110OrOlder { if (debugIsChrome110OrOlder != null) { return debugIsChrome110OrOlder!; } if (_cachedIsChrome110OrOlder != null) { return _cachedIsChrome110OrOlder!; } final RegExp chromeRegexp = RegExp(r'Chrom(e|ium)\/([0-9]+)\.'); final RegExpMatch? match = chromeRegexp.firstMatch(domWindow.navigator.userAgent); if (match != null) { final int chromeVersion = int.parse(match.group(2)!); return _cachedIsChrome110OrOlder = chromeVersion <= 110; } return _cachedIsChrome110OrOlder = false; } // Cache the result of checking if the app is running on Chrome 110 on Windows // since we check this on every frame. bool? _cachedIsChrome110OrOlder; /// If set to true pretends that the current browser is iOS Safari. /// /// Useful for tests. Do not use in production code. @visibleForTesting bool debugEmulateIosSafari = false; /// Returns true if the browser is iOS Safari, false otherwise. bool get isIosSafari => debugEmulateIosSafari || _isActualIosSafari; bool get _isActualIosSafari => browserEngine == BrowserEngine.webkit && operatingSystem == OperatingSystem.iOs; /// Whether the current browser is Safari. bool get isSafari => browserEngine == BrowserEngine.webkit; /// Whether the current browser is Firefox. bool get isFirefox => browserEngine == BrowserEngine.firefox; /// Whether the current browser is Edge. bool get isEdge => domWindow.navigator.userAgent.contains('Edg/'); /// Whether we are running from a wasm module compiled with dart2wasm. /// Note: Currently the ffi library is available from dart2wasm but not dart2js /// or dartdevc. bool get isWasm => const bool.fromEnvironment('dart.library.ffi'); /// Use in tests to simulate the detection of iOS 15. bool? debugIsIOS15; /// Use in tests to simulated the detection of Chrome 110 or older on Windows. bool? debugIsChrome110OrOlder; int? _cachedWebGLVersion; /// The highest WebGL version supported by the current browser, or -1 if WebGL /// is not supported. int get webGLVersion => _cachedWebGLVersion ?? (_cachedWebGLVersion = _detectWebGLVersion()); /// Detects the highest WebGL version supported by the current browser, or /// -1 if WebGL is not supported. /// /// Chrome reports that `WebGL2RenderingContext` is available even when WebGL 2 is /// disabled due hardware-specific issues. This happens, for example, on Chrome on /// Moto E5. Therefore checking for the presence of `WebGL2RenderingContext` or /// using the current [browserEngine] is insufficient. /// /// Our CanvasKit backend is affected due to: https://github.com/emscripten-core/emscripten/issues/11819 int _detectWebGLVersion() { final DomCanvasElement canvas = createDomCanvasElement( width: 1, height: 1, ); if (canvas.getContext('webgl2') != null) { if (_workAroundBug91333) { return WebGLVersion.webgl1; } return WebGLVersion.webgl2; } if (canvas.getContext('webgl') != null) { return WebGLVersion.webgl1; } return -1; } /// Whether the current browser supports the Chromium variant of CanvasKit. bool get browserSupportsCanvaskitChromium => domIntl.v8BreakIterator != null && domIntl.Segmenter != null;
engine/lib/web_ui/lib/src/engine/browser_detection.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/browser_detection.dart", "repo_id": "engine", "token_count": 3220 }
302
// Copyright 2013 The Flutter 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 'package:ui/ui.dart' as ui; import 'canvaskit_api.dart'; import 'native_memory.dart'; /// The CanvasKit implementation of [ui.MaskFilter]. class CkMaskFilter { CkMaskFilter.blur(ui.BlurStyle blurStyle, double sigma) : _blurStyle = blurStyle, _sigma = sigma { final SkMaskFilter skMaskFilter = canvasKit.MaskFilter.MakeBlur( toSkBlurStyle(_blurStyle), _sigma, true, )!; _ref = UniqueRef<SkMaskFilter>(this, skMaskFilter, 'MaskFilter'); } final ui.BlurStyle _blurStyle; final double _sigma; late final UniqueRef<SkMaskFilter> _ref; SkMaskFilter get skiaObject => _ref.nativeObject; }
engine/lib/web_ui/lib/src/engine/canvaskit/mask_filter.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/mask_filter.dart", "repo_id": "engine", "token_count": 300 }
303
// Copyright 2013 The Flutter 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 'dart:math' as math; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:ui/ui.dart' as ui; import '../validators.dart'; import 'canvaskit_api.dart'; import 'image.dart'; import 'native_memory.dart'; /// Refines the generic [ui.Shader] interface with CanvasKit-specific features. abstract class CkShader implements ui.Shader { /// Returns a Skia shader at requested filter quality, if that shader supports /// altering its filter quality. /// /// If the implementation supports changing filter quality, and the value of /// [contextualQuality] is the same as a previously passed value, the /// implementation may return the same object as before. If a new Skia object /// is created, the previous object is released and cannot be used again. For /// this reason, do not store the returned value long-term to prevent dangling /// pointer errors. SkShader getSkShader(ui.FilterQuality contextualQuality); } /// Base class for shader implementations with a simple memory model that do not /// support contextual filter quality. /// /// Provides common memory mangement logic for shaders that map one-to-one to a /// [SkShader] object. The lifetime of this shader is hard-linked to the /// lifetime of the [SkShader]. [getSkShader] always returns the one and only /// [SkShader] object, ignoring contextual filter quality. abstract class SimpleCkShader implements CkShader { SimpleCkShader() { _ref = UniqueRef<SkShader>(this, createSkiaObject(), debugOwnerLabel); } late final UniqueRef<SkShader> _ref; @override SkShader getSkShader(ui.FilterQuality contextualQuality) => _ref.nativeObject; String get debugOwnerLabel; SkShader createSkiaObject(); @override bool get debugDisposed => _ref.isDisposed; @override void dispose() { _ref.dispose(); } @override String toString() => 'Gradient()'; } class CkGradientSweep extends SimpleCkShader implements ui.Gradient { CkGradientSweep(this.center, this.colors, this.colorStops, this.tileMode, this.startAngle, this.endAngle, this.matrix4) : assert(offsetIsValid(center)), assert(startAngle < endAngle), assert(matrix4 == null || matrix4IsValid(matrix4)) { validateColorStops(colors, colorStops); } @override String get debugOwnerLabel => 'Gradient.sweep'; final ui.Offset center; final List<ui.Color> colors; final List<double>? colorStops; final ui.TileMode tileMode; final double startAngle; final double endAngle; final Float32List? matrix4; @override SkShader createSkiaObject() { const double toDegrees = 180.0 / math.pi; return canvasKit.Shader.MakeSweepGradient( center.dx, center.dy, toFlatColors(colors), toSkColorStops(colorStops), toSkTileMode(tileMode), matrix4 != null ? toSkMatrixFromFloat32(matrix4!) : null, 0, toDegrees * startAngle, toDegrees * endAngle, ); } } class CkGradientLinear extends SimpleCkShader implements ui.Gradient { CkGradientLinear( this.from, this.to, this.colors, this.colorStops, this.tileMode, Float32List? matrix, ) : assert(offsetIsValid(from)), assert(offsetIsValid(to)), matrix4 = matrix { assert(matrix4 == null || matrix4IsValid(matrix4!)); // ignore: prefer_asserts_in_initializer_lists assert(() { validateColorStops(colors, colorStops); return true; }()); } final ui.Offset from; final ui.Offset to; final List<ui.Color> colors; final List<double>? colorStops; final ui.TileMode tileMode; final Float32List? matrix4; @override String get debugOwnerLabel => 'Gradient.linear'; @override SkShader createSkiaObject() { return canvasKit.Shader.MakeLinearGradient( toSkPoint(from), toSkPoint(to), toFlatColors(colors), toSkColorStops(colorStops), toSkTileMode(tileMode), matrix4 != null ? toSkMatrixFromFloat32(matrix4!) : null, ); } @override String toString() => 'Gradient()'; } class CkGradientRadial extends SimpleCkShader implements ui.Gradient { CkGradientRadial(this.center, this.radius, this.colors, this.colorStops, this.tileMode, this.matrix4); final ui.Offset center; final double radius; final List<ui.Color> colors; final List<double>? colorStops; final ui.TileMode tileMode; final Float32List? matrix4; @override String get debugOwnerLabel => 'Gradient.radial'; @override SkShader createSkiaObject() { return canvasKit.Shader.MakeRadialGradient( toSkPoint(center), radius, toFlatColors(colors), toSkColorStops(colorStops), toSkTileMode(tileMode), matrix4 != null ? toSkMatrixFromFloat32(matrix4!) : null, 0, ); } @override String toString() => 'Gradient()'; } class CkGradientConical extends SimpleCkShader implements ui.Gradient { CkGradientConical(this.focal, this.focalRadius, this.center, this.radius, this.colors, this.colorStops, this.tileMode, this.matrix4); final ui.Offset focal; final double focalRadius; final ui.Offset center; final double radius; final List<ui.Color> colors; final List<double>? colorStops; final ui.TileMode tileMode; final Float32List? matrix4; @override String get debugOwnerLabel => 'Gradient.radial(conical)'; @override SkShader createSkiaObject() { return canvasKit.Shader.MakeTwoPointConicalGradient( toSkPoint(focal), focalRadius, toSkPoint(center), radius, toFlatColors(colors), toSkColorStops(colorStops), toSkTileMode(tileMode), matrix4 != null ? toSkMatrixFromFloat32(matrix4!) : null, 0, ); } } /// Implements [ui.ImageShader] for CanvasKit. /// /// The memory management model is different from other shaders (backed by /// [SimpleCkShader]) in that this object is not one-to-one to its Skia /// counterpart [SkShader]. During initialization a default [SkShader] is /// created based on the [filterQuality] specified in the constructor. However, /// when [withQuality] is called with a different [ui.FilterQuality] value the /// previous [SkShader] is discarded and a new [SkShader] is created. Therefore, /// over the lifetime of this object, multiple [SkShader] instances may be /// generated depending on the _usage_ of this object in [ui.Paint] and other /// scenarios that want a shader at different filter quality levels. class CkImageShader implements ui.ImageShader, CkShader { CkImageShader(ui.Image image, this.tileModeX, this.tileModeY, this.matrix4, this.filterQuality) : _image = image as CkImage { _initializeSkImageShader(filterQuality ?? ui.FilterQuality.none); } final ui.TileMode tileModeX; final ui.TileMode tileModeY; final Float64List matrix4; final ui.FilterQuality? filterQuality; final CkImage _image; /// Owns the reference to the currently [SkShader]. /// /// This reference changes when [withQuality] is called with different filter /// quality levels. @visibleForTesting UniqueRef<SkShader>? ref; /// The filter quality at which the latest [SkShader] was initialized. @visibleForTesting late ui.FilterQuality currentQuality; int get imageWidth => _image.width; int get imageHeight => _image.height; @override SkShader getSkShader(ui.FilterQuality contextualQuality) { assert(!debugDisposed, 'Cannot make a copy of a disposed ImageShader.'); final ui.FilterQuality quality = filterQuality ?? contextualQuality; if (currentQuality != quality) { _initializeSkImageShader(quality); } return ref!.nativeObject; } void _initializeSkImageShader(ui.FilterQuality quality) { final SkShader skShader; if (quality == ui.FilterQuality.high) { skShader = _image.skImage.makeShaderCubic( toSkTileMode(tileModeX), toSkTileMode(tileModeY), 1.0 / 3.0, 1.0 / 3.0, toSkMatrixFromFloat64(matrix4), ); } else { skShader = _image.skImage.makeShaderOptions( toSkTileMode(tileModeX), toSkTileMode(tileModeY), toSkFilterMode(quality), toSkMipmapMode(quality), toSkMatrixFromFloat64(matrix4), ); } currentQuality = quality; ref?.dispose(); ref = UniqueRef<SkShader>(this, skShader, 'ImageShader'); } bool _isDisposed = false; @override bool get debugDisposed => _isDisposed; @override void dispose() { assert(!_isDisposed, 'Cannot dispose ImageShader more than once.'); _isDisposed = true; _image.dispose(); ref?.dispose(); ref = null; } }
engine/lib/web_ui/lib/src/engine/canvaskit/shader.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/canvaskit/shader.dart", "repo_id": "engine", "token_count": 3132 }
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. /// A monotonically increasing frame number being rendered. /// /// Used for debugging only. int debugFrameNumber = 1; List<FrameReference<dynamic>> frameReferences = <FrameReference<dynamic>>[]; /// A temporary reference to a value of type [V]. /// /// The value automatically gets set to null after the current frame is /// rendered. /// /// It is useful to think of this as a weak reference that's scoped to a /// single frame. class FrameReference<V> { /// Creates a frame reference to a value. FrameReference([this.value]) { frameReferences.add(this); } /// The current value of this reference. V? value; } /// Cache where items cached before frame(N) is committed, can be reused in /// frame(N+1) and are evicted if not. /// /// A typical use case is image elements. As images are created and added to /// DOM when painting a scene they are cached and if possible reused on next /// update. If the next update does not reuse the element, it is evicted. /// /// Maps are lazily allocated since many pictures don't contain cachable images /// at all. class CrossFrameCache<T> { // Cached items in a scene. Map<String, List<_CrossFrameCacheItem<T>>>? _cache; // Cached items that have been committed, ready for reuse on next frame. Map<String, List<_CrossFrameCacheItem<T>>>? _reusablePool; // Called when a scene or picture update is committed. void commitFrame() { // Evict unused items from prior frame. if (_reusablePool != null) { for (final List<_CrossFrameCacheItem<T>> items in _reusablePool!.values) { for (final _CrossFrameCacheItem<T> item in items) { item.evict(); } } } // Move cached items to reusable pool. _reusablePool = _cache; _cache = null; } /// Caches an item for reuse on next update frame. /// /// Duplicate keys are allowed. For example the same image url may be used /// to create multiple instances of [ImageElement] to be reused in the future. void cache(String key, T value, [CrossFrameCacheEvictCallback<T>? callback]) { _addToCache(key, _CrossFrameCacheItem<T>(value, callback)); } void _addToCache(String key, _CrossFrameCacheItem<T> item) { _cache ??= <String, List<_CrossFrameCacheItem<T>>>{}; (_cache![key] ??= <_CrossFrameCacheItem<T>>[]).add(item); } /// Given a key, consumes an item that has been cached in a prior frame. T? reuse(String key) { if (_reusablePool == null) { return null; } final List<_CrossFrameCacheItem<T>>? items = _reusablePool![key]; if (items == null || items.isEmpty) { return null; } final _CrossFrameCacheItem<T> item = items.removeAt(0); _addToCache(key, item); return item.value; } } class _CrossFrameCacheItem<T> { _CrossFrameCacheItem(this.value, this.evictCallback); final T value; final CrossFrameCacheEvictCallback<T>? evictCallback; void evict() { if (evictCallback != null) { evictCallback!(value); } } } typedef CrossFrameCacheEvictCallback<T> = void Function(T value);
engine/lib/web_ui/lib/src/engine/frame_reference.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/frame_reference.dart", "repo_id": "engine", "token_count": 1031 }
305
// Copyright 2013 The Flutter 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 'dart:typed_data'; import 'package:ui/ui.dart' as ui; import 'path_ref.dart'; import 'path_utils.dart'; // Iterates through path including generating closing segments. class PathIterator { PathIterator(this.pathRef, bool forceClose) : _forceClose = forceClose, _verbCount = pathRef.countVerbs() { _pointIndex = 0; if (!pathRef.isFinite) { // Don't allow iteration through non-finite points, prepare to return // done verb. _verbIndex = pathRef.countVerbs(); } } final PathRef pathRef; final bool _forceClose; final int _verbCount; bool _needClose = false; int _segmentState = SPathSegmentState.kEmptyContour; int _conicWeightIndex = -1; double _lastPointX = 0; double _lastPointY = 0; double _moveToX = 0; double _moveToY = 0; int _verbIndex = 0; int _pointIndex = 0; int get pathVerbIndex => _verbIndex; int get conicWeightIndex => _conicWeightIndex; /// Maximum buffer size required for points in [next] calls. static const int kMaxBufferSize = 8; /// Returns true if first contour on path is closed. bool isClosedContour() { if (_verbCount == 0 || _verbIndex == _verbCount) { return false; } if (_forceClose) { return true; } int verbIndex = 0; // Skip starting moveTo. if (pathRef.atVerb(verbIndex) == SPath.kMoveVerb) { ++verbIndex; } while (verbIndex < _verbCount) { final int verb = pathRef.atVerb(verbIndex++); if (SPath.kMoveVerb == verb) { break; } if (SPath.kCloseVerb == verb) { return true; } } return false; } int _autoClose(Float32List outPts) { if (_lastPointX != _moveToX || _lastPointY != _moveToY) { // Handle special case where comparison above will return true for // NaN != NaN although it should be false. if (_lastPointX.isNaN || _lastPointY.isNaN || _moveToX.isNaN || _moveToY.isNaN) { return SPath.kCloseVerb; } outPts[0] = _lastPointX; outPts[1] = _lastPointY; outPts[2] = _moveToX; outPts[3] = _moveToY; _lastPointX = _moveToX; _lastPointY = _moveToY; return SPath.kLineVerb; } else { outPts[0] = _moveToX; outPts[1] = _moveToY; return SPath.kCloseVerb; } } // Returns true if caller should use moveTo, false if last point of // previous primitive. ui.Offset _constructMoveTo() { if (_segmentState == SPathSegmentState.kAfterMove) { // Set the first return point to move point. _segmentState = SPathSegmentState.kAfterPrimitive; return ui.Offset(_moveToX, _moveToY); } return ui.Offset( pathRef.points[_pointIndex - 2], pathRef.points[_pointIndex - 1]); } int peek() { if (_verbIndex < pathRef.countVerbs()) { return pathRef.atVerb(_verbIndex); } if (_needClose && _segmentState == SPathSegmentState.kAfterPrimitive) { return (_lastPointX != _moveToX || _lastPointY != _moveToY) ? SPath.kLineVerb : SPath.kCloseVerb; } return SPath.kDoneVerb; } // Returns next verb and reads associated points into [outPts]. int next(Float32List outPts) { if (_verbIndex == pathRef.countVerbs()) { // Close the curve if requested and if there is some curve to close if (_needClose && _segmentState == SPathSegmentState.kAfterPrimitive) { if (SPath.kLineVerb == _autoClose(outPts)) { return SPath.kLineVerb; } _needClose = false; return SPath.kCloseVerb; } return SPath.kDoneVerb; } int verb = pathRef.atVerb(_verbIndex++); switch (verb) { case SPath.kMoveVerb: if (_needClose) { // Move back one verb. _verbIndex--; final int autoVerb = _autoClose(outPts); if (autoVerb == SPath.kCloseVerb) { _needClose = false; } return autoVerb; } if (_verbIndex == _verbCount) { return SPath.kDoneVerb; } final double offsetX = pathRef.points[_pointIndex++]; final double offsetY = pathRef.points[_pointIndex++]; _moveToX = offsetX; _moveToY = offsetY; outPts[0] = offsetX; outPts[1] = offsetY; _segmentState = SPathSegmentState.kAfterMove; _lastPointX = _moveToX; _lastPointY = _moveToY; _needClose = _forceClose; case SPath.kLineVerb: final ui.Offset start = _constructMoveTo(); final double offsetX = pathRef.points[_pointIndex++]; final double offsetY = pathRef.points[_pointIndex++]; outPts[0] = start.dx; outPts[1] = start.dy; outPts[2] = offsetX; outPts[3] = offsetY; _lastPointX = offsetX; _lastPointY = offsetY; case SPath.kConicVerb: _conicWeightIndex++; final ui.Offset start = _constructMoveTo(); outPts[0] = start.dx; outPts[1] = start.dy; outPts[2] = pathRef.points[_pointIndex++]; outPts[3] = pathRef.points[_pointIndex++]; _lastPointX = outPts[4] = pathRef.points[_pointIndex++]; _lastPointY = outPts[5] = pathRef.points[_pointIndex++]; case SPath.kQuadVerb: final ui.Offset start = _constructMoveTo(); outPts[0] = start.dx; outPts[1] = start.dy; outPts[2] = pathRef.points[_pointIndex++]; outPts[3] = pathRef.points[_pointIndex++]; _lastPointX = outPts[4] = pathRef.points[_pointIndex++]; _lastPointY = outPts[5] = pathRef.points[_pointIndex++]; case SPath.kCubicVerb: final ui.Offset start = _constructMoveTo(); outPts[0] = start.dx; outPts[1] = start.dy; outPts[2] = pathRef.points[_pointIndex++]; outPts[3] = pathRef.points[_pointIndex++]; outPts[4] = pathRef.points[_pointIndex++]; outPts[5] = pathRef.points[_pointIndex++]; _lastPointX = outPts[6] = pathRef.points[_pointIndex++]; _lastPointY = outPts[7] = pathRef.points[_pointIndex++]; case SPath.kCloseVerb: verb = _autoClose(outPts); if (verb == SPath.kLineVerb) { // Move back one verb since we constructed line for this close verb. _verbIndex--; } else { _needClose = false; _segmentState = SPathSegmentState.kEmptyContour; } _lastPointX = _moveToX; _lastPointY = _moveToY; case SPath.kDoneVerb: assert(_verbIndex == pathRef.countVerbs()); default: throw FormatException('Unsupport Path verb $verb'); } return verb; } double get conicWeight => pathRef.atWeight(_conicWeightIndex); }
engine/lib/web_ui/lib/src/engine/html/path/path_iterator.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/path/path_iterator.dart", "repo_id": "engine", "token_count": 3060 }
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. import 'package:ui/ui.dart' as ui; import '../browser_detection.dart'; import '../dom.dart'; import 'bitmap_canvas.dart'; import 'color_filter.dart'; import 'resource_manager.dart'; import 'shaders/shader.dart'; import 'surface.dart'; /// A surface that applies a shader to its children. /// /// Currently there are 2 types of shaders: /// - Gradients /// - ImageShader /// /// Gradients /// The gradients can be applied to the child tree by rendering the gradient /// into an image and referencing the image in an svg filter to apply /// to DOM tree. /// class PersistedShaderMask extends PersistedContainerSurface implements ui.ShaderMaskEngineLayer { PersistedShaderMask( PersistedShaderMask? super.oldLayer, this.shader, this.maskRect, this.blendMode, this.filterQuality, ); DomElement? _childContainer; final ui.Shader shader; final ui.Rect maskRect; final ui.BlendMode blendMode; final ui.FilterQuality filterQuality; DomElement? _shaderElement; final bool isWebKit = browserEngine == BrowserEngine.webkit; @override void adoptElements(PersistedShaderMask oldSurface) { super.adoptElements(oldSurface); _childContainer = oldSurface._childContainer; _shaderElement = oldSurface._shaderElement; oldSurface._childContainer = null; oldSurface._shaderElement = null; } @override DomElement? get childContainer => _childContainer; @override void discard() { super.discard(); ResourceManager.instance.removeResource(_shaderElement); _shaderElement = null; // Do not detach the child container from the root. It is permanently // attached. The elements are reused together and are detached from the DOM // together. _childContainer = null; } @override void preroll(PrerollSurfaceContext prerollContext) { ++prerollContext.activeShaderMaskCount; super.preroll(prerollContext); --prerollContext.activeShaderMaskCount; } @override DomElement createElement() { final DomElement element = defaultCreateElement('flt-shader-mask'); final DomElement container = createDomElement('flt-mask-interior'); container.style.position = 'absolute'; _childContainer = container; element.append(_childContainer!); return element; } @override void apply() { ResourceManager.instance.removeResource(_shaderElement); _shaderElement = null; if (shader is ui.Gradient) { rootElement!.style ..left = '${maskRect.left}px' ..top = '${maskRect.top}px' ..width = '${maskRect.width}px' ..height = '${maskRect.height}px'; _childContainer!.style ..left = '${-maskRect.left}px' ..top = '${-maskRect.top}px'; // Prevent ShaderMask from failing inside animations that size // area to empty. if (maskRect.width > 0 && maskRect.height > 0) { _applyGradientShader(); } return; } // TODO(ferhat): Implement _applyImageShader(); throw Exception('Shader type not supported for ShaderMask'); } void _applyGradientShader() { if (shader is EngineGradient) { final EngineGradient gradientShader = shader as EngineGradient; // The gradient shader's bounds are in the context of the element itself, // rather than the global position, so translate it back to the origin. final ui.Rect translatedRect = maskRect.translate(-maskRect.left, -maskRect.top); final String imageUrl = gradientShader.createImageBitmap(translatedRect, 1, true) as String; ui.BlendMode blendModeTemp = blendMode; switch (blendModeTemp) { case ui.BlendMode.clear: case ui.BlendMode.dstOut: case ui.BlendMode.srcOut: childContainer?.style.visibility = 'hidden'; return; case ui.BlendMode.dst: case ui.BlendMode.dstIn: // Noop. Should render existing destination. rootElement!.style.filter = ''; return; case ui.BlendMode.srcOver: // Uses source filter color. // Since we don't have a size, we can't use background color. // Use svg filter srcIn instead. blendModeTemp = ui.BlendMode.srcIn; case ui.BlendMode.src: case ui.BlendMode.dstOver: case ui.BlendMode.srcIn: case ui.BlendMode.srcATop: case ui.BlendMode.dstATop: case ui.BlendMode.xor: case ui.BlendMode.plus: case ui.BlendMode.modulate: case ui.BlendMode.screen: case ui.BlendMode.overlay: case ui.BlendMode.darken: case ui.BlendMode.lighten: case ui.BlendMode.colorDodge: case ui.BlendMode.colorBurn: case ui.BlendMode.hardLight: case ui.BlendMode.softLight: case ui.BlendMode.difference: case ui.BlendMode.exclusion: case ui.BlendMode.multiply: case ui.BlendMode.hue: case ui.BlendMode.saturation: case ui.BlendMode.color: case ui.BlendMode.luminosity: break; } final SvgFilter svgFilter = svgMaskFilterFromImageAndBlendMode( imageUrl, blendModeTemp, maskRect.width, maskRect.height); _shaderElement = svgFilter.element; if (isWebKit) { _childContainer!.style.filter = 'url(#${svgFilter.id})'; } else { rootElement!.style.filter = 'url(#${svgFilter.id})'; } ResourceManager.instance.addResource(_shaderElement!); } } @override void update(PersistedShaderMask oldSurface) { super.update(oldSurface); if (shader != oldSurface.shader || maskRect != oldSurface.maskRect || blendMode != oldSurface.blendMode) { apply(); } } } SvgFilter svgMaskFilterFromImageAndBlendMode( String imageUrl, ui.BlendMode blendMode, double width, double height) { final SvgFilter svgFilter; switch (blendMode) { case ui.BlendMode.src: svgFilter = _srcImageToSvg(imageUrl, width, height); case ui.BlendMode.srcIn: case ui.BlendMode.srcATop: svgFilter = _srcInImageToSvg(imageUrl, width, height); case ui.BlendMode.srcOut: svgFilter = _srcOutImageToSvg(imageUrl, width, height); case ui.BlendMode.xor: svgFilter = _xorImageToSvg(imageUrl, width, height); case ui.BlendMode.plus: // Porter duff source + destination. svgFilter = _compositeImageToSvg(imageUrl, 0, 1, 1, 0, width, height); case ui.BlendMode.modulate: // Porter duff source * destination but preserves alpha. svgFilter = _modulateImageToSvg(imageUrl, width, height); case ui.BlendMode.overlay: // Since overlay is the same as hard-light by swapping layers, // pass hard-light blend function. svgFilter = _blendImageToSvg( imageUrl, blendModeToSvgEnum(ui.BlendMode.hardLight)!, width, height, swapLayers: true, ); // Several of the filters below (although supported) do not render the // same (close but not exact) as native flutter when used as blend mode // for a background-image with a background color. They only look // identical when feBlend is used within an svg filter definition. // // Saturation filter uses destination when source is transparent. // cMax = math.max(r, math.max(b, g)); // cMin = math.min(r, math.min(b, g)); // delta = cMax - cMin; // lightness = (cMax + cMin) / 2.0; // saturation = delta / (1.0 - (2 * lightness - 1.0).abs()); case ui.BlendMode.saturation: case ui.BlendMode.colorDodge: case ui.BlendMode.colorBurn: case ui.BlendMode.hue: case ui.BlendMode.color: case ui.BlendMode.luminosity: case ui.BlendMode.multiply: case ui.BlendMode.screen: case ui.BlendMode.darken: case ui.BlendMode.lighten: case ui.BlendMode.hardLight: case ui.BlendMode.softLight: case ui.BlendMode.difference: case ui.BlendMode.exclusion: svgFilter = _blendImageToSvg( imageUrl, blendModeToSvgEnum(blendMode)!, width, height); case ui.BlendMode.dst: case ui.BlendMode.dstATop: case ui.BlendMode.dstIn: case ui.BlendMode.dstOut: case ui.BlendMode.dstOver: case ui.BlendMode.clear: case ui.BlendMode.srcOver: throw UnsupportedError( 'Invalid svg filter request for blend-mode $blendMode'); } return svgFilter; } // The color matrix for feColorMatrix element changes colors based on // the following: // // | R' | | r1 r2 r3 r4 r5 | | R | // | G' | | g1 g2 g3 g4 g5 | | G | // | B' | = | b1 b2 b3 b4 b5 | * | B | // | A' | | a1 a2 a3 a4 a5 | | A | // | 1 | | 0 0 0 0 1 | | 1 | // // R' = r1*R + r2*G + r3*B + r4*A + r5 // G' = g1*R + g2*G + g3*B + g4*A + g5 // B' = b1*R + b2*G + b3*B + b4*A + b5 // A' = a1*R + a2*G + a3*B + a4*A + a5 SvgFilter _srcInImageToSvg(String imageUrl, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeColorMatrix( const <double>[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, ], result: 'destalpha', ); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); builder.setFeComposite( in1: 'image', in2: 'destalpha', operator: kOperatorArithmetic, k1: 1, k2: 0, k3: 0, k4: 0, result: 'comp', ); return builder.build(); } SvgFilter _srcImageToSvg(String imageUrl, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'comp', width: width, height: height, ); return builder.build(); } SvgFilter _srcOutImageToSvg(String imageUrl, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); builder.setFeComposite( in1: 'image', in2: 'SourceGraphic', operator: kOperatorOut, result: 'comp', ); return builder.build(); } SvgFilter _xorImageToSvg(String imageUrl, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); builder.setFeComposite( in1: 'image', in2: 'SourceGraphic', operator: kOperatorXor, result: 'comp', ); return builder.build(); } // The source image and color are composited using : // result = k1 *in*in2 + k2*in + k3*in2 + k4. SvgFilter _compositeImageToSvg(String imageUrl, double k1, double k2, double k3, double k4, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); builder.setFeComposite( in1: 'image', in2: 'SourceGraphic', operator: kOperatorArithmetic, k1: k1, k2: k2, k3: k3, k4: k4, result: 'comp', ); return builder.build(); } // Porter duff source * destination , keep source alpha. // First apply color filter to source to change it to [color], then // composite using multiplication. SvgFilter _modulateImageToSvg(String imageUrl, double width, double height) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); builder.setFeComposite( in1: 'image', in2: 'SourceGraphic', operator: kOperatorArithmetic, k1: 1, k2: 0, k3: 0, k4: 0, result: 'comp', ); return builder.build(); } // Uses feBlend element to blend source image with a color. SvgFilter _blendImageToSvg( String imageUrl, SvgBlendMode svgBlendMode, double width, double height, {bool swapLayers = false}) { final SvgFilterBuilder builder = SvgFilterBuilder(); builder.setFeImage( href: imageUrl, result: 'image', width: width, height: height, ); if (swapLayers) { builder.setFeBlend( in1: 'SourceGraphic', in2: 'image', mode: svgBlendMode.blendMode, ); } else { builder.setFeBlend( in1: 'image', in2: 'SourceGraphic', mode: svgBlendMode.blendMode, ); } return builder.build(); }
engine/lib/web_ui/lib/src/engine/html/shader_mask.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/html/shader_mask.dart", "repo_id": "engine", "token_count": 5112 }
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. // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by dev/tools/gen_keycodes/bin/gen_keycodes.dart and // should not be edited directly. // // Edit the template dev/tools/gen_keycodes/data/web_key_map_dart.tmpl instead. // See dev/tools/gen_keycodes/README.md for more information. /// Maps Web KeyboardEvent keys to the matching LogicalKeyboardKey id. const Map<String, int> kWebToLogicalKey = <String, int>{ 'AVRInput': 0x00100000d08, 'AVRPower': 0x00100000d09, 'Accel': 0x00100000101, 'Accept': 0x00100000501, 'Again': 0x00100000502, 'AllCandidates': 0x00100000701, 'Alphanumeric': 0x00100000702, 'AltGraph': 0x00100000103, 'AppSwitch': 0x00100001001, 'ArrowDown': 0x00100000301, 'ArrowLeft': 0x00100000302, 'ArrowRight': 0x00100000303, 'ArrowUp': 0x00100000304, 'Attn': 0x00100000503, 'AudioBalanceLeft': 0x00100000d01, 'AudioBalanceRight': 0x00100000d02, 'AudioBassBoostDown': 0x00100000d03, 'AudioBassBoostToggle': 0x00100000e02, 'AudioBassBoostUp': 0x00100000d04, 'AudioFaderFront': 0x00100000d05, 'AudioFaderRear': 0x00100000d06, 'AudioSurroundModeNext': 0x00100000d07, 'AudioTrebleDown': 0x00100000e04, 'AudioTrebleUp': 0x00100000e05, 'AudioVolumeDown': 0x00100000a0f, 'AudioVolumeMute': 0x00100000a11, 'AudioVolumeUp': 0x00100000a10, 'Backspace': 0x00100000008, 'BrightnessDown': 0x00100000601, 'BrightnessUp': 0x00100000602, 'BrowserBack': 0x00100000c01, 'BrowserFavorites': 0x00100000c02, 'BrowserForward': 0x00100000c03, 'BrowserHome': 0x00100000c04, 'BrowserRefresh': 0x00100000c05, 'BrowserSearch': 0x00100000c06, 'BrowserStop': 0x00100000c07, 'Call': 0x00100001002, 'Camera': 0x00100000603, 'CameraFocus': 0x00100001003, 'Cancel': 0x00100000504, 'CapsLock': 0x00100000104, 'ChannelDown': 0x00100000d0a, 'ChannelUp': 0x00100000d0b, 'Clear': 0x00100000401, 'Close': 0x00100000a01, 'ClosedCaptionToggle': 0x00100000d12, 'CodeInput': 0x00100000703, 'ColorF0Red': 0x00100000d0c, 'ColorF1Green': 0x00100000d0d, 'ColorF2Yellow': 0x00100000d0e, 'ColorF3Blue': 0x00100000d0f, 'ColorF4Grey': 0x00100000d10, 'ColorF5Brown': 0x00100000d11, 'Compose': 0x00100000704, 'ContextMenu': 0x00100000505, 'Convert': 0x00100000705, 'Copy': 0x00100000402, 'CrSel': 0x00100000403, 'Cut': 0x00100000404, 'DVR': 0x00100000d4f, 'Delete': 0x0010000007f, 'Dimmer': 0x00100000d13, 'DisplaySwap': 0x00100000d14, 'Eisu': 0x00100000714, 'Eject': 0x00100000604, 'End': 0x00100000305, 'EndCall': 0x00100001004, 'Enter': 0x0010000000d, 'EraseEof': 0x00100000405, 'Esc': 0x0010000001b, 'Escape': 0x0010000001b, 'ExSel': 0x00100000406, 'Execute': 0x00100000506, 'Exit': 0x00100000d15, 'F1': 0x00100000801, 'F10': 0x0010000080a, 'F11': 0x0010000080b, 'F12': 0x0010000080c, 'F13': 0x0010000080d, 'F14': 0x0010000080e, 'F15': 0x0010000080f, 'F16': 0x00100000810, 'F17': 0x00100000811, 'F18': 0x00100000812, 'F19': 0x00100000813, 'F2': 0x00100000802, 'F20': 0x00100000814, 'F21': 0x00100000815, 'F22': 0x00100000816, 'F23': 0x00100000817, 'F24': 0x00100000818, 'F3': 0x00100000803, 'F4': 0x00100000804, 'F5': 0x00100000805, 'F6': 0x00100000806, 'F7': 0x00100000807, 'F8': 0x00100000808, 'F9': 0x00100000809, 'FavoriteClear0': 0x00100000d16, 'FavoriteClear1': 0x00100000d17, 'FavoriteClear2': 0x00100000d18, 'FavoriteClear3': 0x00100000d19, 'FavoriteRecall0': 0x00100000d1a, 'FavoriteRecall1': 0x00100000d1b, 'FavoriteRecall2': 0x00100000d1c, 'FavoriteRecall3': 0x00100000d1d, 'FavoriteStore0': 0x00100000d1e, 'FavoriteStore1': 0x00100000d1f, 'FavoriteStore2': 0x00100000d20, 'FavoriteStore3': 0x00100000d21, 'FinalMode': 0x00100000706, 'Find': 0x00100000507, 'Fn': 0x00100000106, 'FnLock': 0x00100000107, 'GoBack': 0x00100001005, 'GoHome': 0x00100001006, 'GroupFirst': 0x00100000707, 'GroupLast': 0x00100000708, 'GroupNext': 0x00100000709, 'GroupPrevious': 0x0010000070a, 'Guide': 0x00100000d22, 'GuideNextDay': 0x00100000d23, 'GuidePreviousDay': 0x00100000d24, 'HangulMode': 0x00100000711, 'HanjaMode': 0x00100000712, 'Hankaku': 0x00100000715, 'HeadsetHook': 0x00100001007, 'Help': 0x00100000508, 'Hibernate': 0x00100000609, 'Hiragana': 0x00100000716, 'HiraganaKatakana': 0x00100000717, 'Home': 0x00100000306, 'Hyper': 0x00100000108, 'Info': 0x00100000d25, 'Insert': 0x00100000407, 'InstantReplay': 0x00100000d26, 'JunjaMode': 0x00100000713, 'KanaMode': 0x00100000718, 'KanjiMode': 0x00100000719, 'Katakana': 0x0010000071a, 'Key11': 0x00100001201, 'Key12': 0x00100001202, 'LastNumberRedial': 0x00100001008, 'LaunchApplication1': 0x00100000b06, 'LaunchApplication2': 0x00100000b01, 'LaunchAssistant': 0x00100000b0e, 'LaunchCalendar': 0x00100000b02, 'LaunchContacts': 0x00100000b0c, 'LaunchControlPanel': 0x00100000b0f, 'LaunchMail': 0x00100000b03, 'LaunchMediaPlayer': 0x00100000b04, 'LaunchMusicPlayer': 0x00100000b05, 'LaunchPhone': 0x00100000b0d, 'LaunchScreenSaver': 0x00100000b07, 'LaunchSpreadsheet': 0x00100000b08, 'LaunchWebBrowser': 0x00100000b09, 'LaunchWebCam': 0x00100000b0a, 'LaunchWordProcessor': 0x00100000b0b, 'Link': 0x00100000d27, 'ListProgram': 0x00100000d28, 'LiveContent': 0x00100000d29, 'Lock': 0x00100000d2a, 'LogOff': 0x00100000605, 'MailForward': 0x00100000a02, 'MailReply': 0x00100000a03, 'MailSend': 0x00100000a04, 'MannerMode': 0x0010000100a, 'MediaApps': 0x00100000d2b, 'MediaAudioTrack': 0x00100000d50, 'MediaClose': 0x00100000d5b, 'MediaFastForward': 0x00100000d2c, 'MediaLast': 0x00100000d2d, 'MediaPause': 0x00100000d2e, 'MediaPlay': 0x00100000d2f, 'MediaPlayPause': 0x00100000a05, 'MediaRecord': 0x00100000d30, 'MediaRewind': 0x00100000d31, 'MediaSkip': 0x00100000d32, 'MediaSkipBackward': 0x00100000d51, 'MediaSkipForward': 0x00100000d52, 'MediaStepBackward': 0x00100000d53, 'MediaStepForward': 0x00100000d54, 'MediaStop': 0x00100000a07, 'MediaTopMenu': 0x00100000d55, 'MediaTrackNext': 0x00100000a08, 'MediaTrackPrevious': 0x00100000a09, 'MicrophoneToggle': 0x00100000e06, 'MicrophoneVolumeDown': 0x00100000e07, 'MicrophoneVolumeMute': 0x00100000e09, 'MicrophoneVolumeUp': 0x00100000e08, 'ModeChange': 0x0010000070b, 'NavigateIn': 0x00100000d56, 'NavigateNext': 0x00100000d57, 'NavigateOut': 0x00100000d58, 'NavigatePrevious': 0x00100000d59, 'New': 0x00100000a0a, 'NextCandidate': 0x0010000070c, 'NextFavoriteChannel': 0x00100000d33, 'NextUserProfile': 0x00100000d34, 'NonConvert': 0x0010000070d, 'Notification': 0x00100001009, 'NumLock': 0x0010000010a, 'OnDemand': 0x00100000d35, 'Open': 0x00100000a0b, 'PageDown': 0x00100000307, 'PageUp': 0x00100000308, 'Pairing': 0x00100000d5a, 'Paste': 0x00100000408, 'Pause': 0x00100000509, 'PinPDown': 0x00100000d36, 'PinPMove': 0x00100000d37, 'PinPToggle': 0x00100000d38, 'PinPUp': 0x00100000d39, 'Play': 0x0010000050a, 'PlaySpeedDown': 0x00100000d3a, 'PlaySpeedReset': 0x00100000d3b, 'PlaySpeedUp': 0x00100000d3c, 'Power': 0x00100000606, 'PowerOff': 0x00100000607, 'PreviousCandidate': 0x0010000070e, 'Print': 0x00100000a0c, 'PrintScreen': 0x00100000608, 'Process': 0x0010000070f, 'Props': 0x0010000050b, 'RandomToggle': 0x00100000d3d, 'RcLowBattery': 0x00100000d3e, 'RecordSpeedNext': 0x00100000d3f, 'Redo': 0x00100000409, 'RfBypass': 0x00100000d40, 'Romaji': 0x0010000071b, 'STBInput': 0x00100000d45, 'STBPower': 0x00100000d46, 'Save': 0x00100000a0d, 'ScanChannelsToggle': 0x00100000d41, 'ScreenModeNext': 0x00100000d42, 'ScrollLock': 0x0010000010c, 'Select': 0x0010000050c, 'Settings': 0x00100000d43, 'ShiftLevel5': 0x00100000111, 'SingleCandidate': 0x00100000710, 'Soft1': 0x00100000901, 'Soft2': 0x00100000902, 'Soft3': 0x00100000903, 'Soft4': 0x00100000904, 'Soft5': 0x00100000905, 'Soft6': 0x00100000906, 'Soft7': 0x00100000907, 'Soft8': 0x00100000908, 'SpeechCorrectionList': 0x00100000f01, 'SpeechInputToggle': 0x00100000f02, 'SpellCheck': 0x00100000a0e, 'SplitScreenToggle': 0x00100000d44, 'Standby': 0x0010000060a, 'Subtitle': 0x00100000d47, 'Super': 0x0010000010e, 'Symbol': 0x0010000010f, 'SymbolLock': 0x00100000110, 'TV': 0x00100000d49, 'TV3DMode': 0x00100001101, 'TVAntennaCable': 0x00100001102, 'TVAudioDescription': 0x00100001103, 'TVAudioDescriptionMixDown': 0x00100001104, 'TVAudioDescriptionMixUp': 0x00100001105, 'TVContentsMenu': 0x00100001106, 'TVDataService': 0x00100001107, 'TVInput': 0x00100000d4a, 'TVInputComponent1': 0x00100001108, 'TVInputComponent2': 0x00100001109, 'TVInputComposite1': 0x0010000110a, 'TVInputComposite2': 0x0010000110b, 'TVInputHDMI1': 0x0010000110c, 'TVInputHDMI2': 0x0010000110d, 'TVInputHDMI3': 0x0010000110e, 'TVInputHDMI4': 0x0010000110f, 'TVInputVGA1': 0x00100001110, 'TVMediaContext': 0x00100001111, 'TVNetwork': 0x00100001112, 'TVNumberEntry': 0x00100001113, 'TVPower': 0x00100000d4b, 'TVRadioService': 0x00100001114, 'TVSatellite': 0x00100001115, 'TVSatelliteBS': 0x00100001116, 'TVSatelliteCS': 0x00100001117, 'TVSatelliteToggle': 0x00100001118, 'TVTerrestrialAnalog': 0x00100001119, 'TVTerrestrialDigital': 0x0010000111a, 'TVTimer': 0x0010000111b, 'Tab': 0x00100000009, 'Teletext': 0x00100000d48, 'Undo': 0x0010000040a, 'Unidentified': 0x00100000001, 'VideoModeNext': 0x00100000d4c, 'VoiceDial': 0x0010000100b, 'WakeUp': 0x0010000060b, 'Wink': 0x00100000d4d, 'Zenkaku': 0x0010000071c, 'ZenkakuHankaku': 0x0010000071d, 'ZoomIn': 0x0010000050d, 'ZoomOut': 0x0010000050e, 'ZoomToggle': 0x00100000d4e, }; /// Maps Web KeyboardEvent codes to the matching PhysicalKeyboardKey USB HID code. const Map<String, int> kWebToPhysicalKey = <String, int>{ 'Abort': 0x0007009b, // abort 'Again': 0x00070079, // again 'AltLeft': 0x000700e2, // altLeft 'AltRight': 0x000700e6, // altRight 'ArrowDown': 0x00070051, // arrowDown 'ArrowLeft': 0x00070050, // arrowLeft 'ArrowRight': 0x0007004f, // arrowRight 'ArrowUp': 0x00070052, // arrowUp 'AudioVolumeDown': 0x00070081, // audioVolumeDown 'AudioVolumeMute': 0x0007007f, // audioVolumeMute 'AudioVolumeUp': 0x00070080, // audioVolumeUp 'Backquote': 0x00070035, // backquote 'Backslash': 0x00070031, // backslash 'Backspace': 0x0007002a, // backspace 'BracketLeft': 0x0007002f, // bracketLeft 'BracketRight': 0x00070030, // bracketRight 'BrightnessDown': 0x000c0070, // brightnessDown 'BrightnessUp': 0x000c006f, // brightnessUp 'BrowserBack': 0x000c0224, // browserBack 'BrowserFavorites': 0x000c022a, // browserFavorites 'BrowserForward': 0x000c0225, // browserForward 'BrowserHome': 0x000c0223, // browserHome 'BrowserRefresh': 0x000c0227, // browserRefresh 'BrowserSearch': 0x000c0221, // browserSearch 'BrowserStop': 0x000c0226, // browserStop 'CapsLock': 0x00070039, // capsLock 'Comma': 0x00070036, // comma 'ContextMenu': 0x00070065, // contextMenu 'ControlLeft': 0x000700e0, // controlLeft 'ControlRight': 0x000700e4, // controlRight 'Convert': 0x0007008a, // convert 'Copy': 0x0007007c, // copy 'Cut': 0x0007007b, // cut 'Delete': 0x0007004c, // delete 'Digit0': 0x00070027, // digit0 'Digit1': 0x0007001e, // digit1 'Digit2': 0x0007001f, // digit2 'Digit3': 0x00070020, // digit3 'Digit4': 0x00070021, // digit4 'Digit5': 0x00070022, // digit5 'Digit6': 0x00070023, // digit6 'Digit7': 0x00070024, // digit7 'Digit8': 0x00070025, // digit8 'Digit9': 0x00070026, // digit9 'DisplayToggleIntExt': 0x000100b5, // displayToggleIntExt 'Eject': 0x000c00b8, // eject 'End': 0x0007004d, // end 'Enter': 0x00070028, // enter 'Equal': 0x0007002e, // equal 'Esc': 0x00070029, // escape 'Escape': 0x00070029, // escape 'F1': 0x0007003a, // f1 'F10': 0x00070043, // f10 'F11': 0x00070044, // f11 'F12': 0x00070045, // f12 'F13': 0x00070068, // f13 'F14': 0x00070069, // f14 'F15': 0x0007006a, // f15 'F16': 0x0007006b, // f16 'F17': 0x0007006c, // f17 'F18': 0x0007006d, // f18 'F19': 0x0007006e, // f19 'F2': 0x0007003b, // f2 'F20': 0x0007006f, // f20 'F21': 0x00070070, // f21 'F22': 0x00070071, // f22 'F23': 0x00070072, // f23 'F24': 0x00070073, // f24 'F3': 0x0007003c, // f3 'F4': 0x0007003d, // f4 'F5': 0x0007003e, // f5 'F6': 0x0007003f, // f6 'F7': 0x00070040, // f7 'F8': 0x00070041, // f8 'F9': 0x00070042, // f9 'Find': 0x0007007e, // find 'Fn': 0x00000012, // fn 'FnLock': 0x00000013, // fnLock 'GameButton1': 0x0005ff01, // gameButton1 'GameButton10': 0x0005ff0a, // gameButton10 'GameButton11': 0x0005ff0b, // gameButton11 'GameButton12': 0x0005ff0c, // gameButton12 'GameButton13': 0x0005ff0d, // gameButton13 'GameButton14': 0x0005ff0e, // gameButton14 'GameButton15': 0x0005ff0f, // gameButton15 'GameButton16': 0x0005ff10, // gameButton16 'GameButton2': 0x0005ff02, // gameButton2 'GameButton3': 0x0005ff03, // gameButton3 'GameButton4': 0x0005ff04, // gameButton4 'GameButton5': 0x0005ff05, // gameButton5 'GameButton6': 0x0005ff06, // gameButton6 'GameButton7': 0x0005ff07, // gameButton7 'GameButton8': 0x0005ff08, // gameButton8 'GameButton9': 0x0005ff09, // gameButton9 'GameButtonA': 0x0005ff11, // gameButtonA 'GameButtonB': 0x0005ff12, // gameButtonB 'GameButtonC': 0x0005ff13, // gameButtonC 'GameButtonLeft1': 0x0005ff14, // gameButtonLeft1 'GameButtonLeft2': 0x0005ff15, // gameButtonLeft2 'GameButtonMode': 0x0005ff16, // gameButtonMode 'GameButtonRight1': 0x0005ff17, // gameButtonRight1 'GameButtonRight2': 0x0005ff18, // gameButtonRight2 'GameButtonSelect': 0x0005ff19, // gameButtonSelect 'GameButtonStart': 0x0005ff1a, // gameButtonStart 'GameButtonThumbLeft': 0x0005ff1b, // gameButtonThumbLeft 'GameButtonThumbRight': 0x0005ff1c, // gameButtonThumbRight 'GameButtonX': 0x0005ff1d, // gameButtonX 'GameButtonY': 0x0005ff1e, // gameButtonY 'GameButtonZ': 0x0005ff1f, // gameButtonZ 'Help': 0x00070075, // help 'Home': 0x0007004a, // home 'Hyper': 0x00000010, // hyper 'Insert': 0x00070049, // insert 'IntlBackslash': 0x00070064, // intlBackslash 'IntlRo': 0x00070087, // intlRo 'IntlYen': 0x00070089, // intlYen 'KanaMode': 0x00070088, // kanaMode 'KeyA': 0x00070004, // keyA 'KeyB': 0x00070005, // keyB 'KeyC': 0x00070006, // keyC 'KeyD': 0x00070007, // keyD 'KeyE': 0x00070008, // keyE 'KeyF': 0x00070009, // keyF 'KeyG': 0x0007000a, // keyG 'KeyH': 0x0007000b, // keyH 'KeyI': 0x0007000c, // keyI 'KeyJ': 0x0007000d, // keyJ 'KeyK': 0x0007000e, // keyK 'KeyL': 0x0007000f, // keyL 'KeyM': 0x00070010, // keyM 'KeyN': 0x00070011, // keyN 'KeyO': 0x00070012, // keyO 'KeyP': 0x00070013, // keyP 'KeyQ': 0x00070014, // keyQ 'KeyR': 0x00070015, // keyR 'KeyS': 0x00070016, // keyS 'KeyT': 0x00070017, // keyT 'KeyU': 0x00070018, // keyU 'KeyV': 0x00070019, // keyV 'KeyW': 0x0007001a, // keyW 'KeyX': 0x0007001b, // keyX 'KeyY': 0x0007001c, // keyY 'KeyZ': 0x0007001d, // keyZ 'KeyboardLayoutSelect': 0x000c029d, // keyboardLayoutSelect 'Lang1': 0x00070090, // lang1 'Lang2': 0x00070091, // lang2 'Lang3': 0x00070092, // lang3 'Lang4': 0x00070093, // lang4 'Lang5': 0x00070094, // lang5 'LaunchApp1': 0x000c0194, // launchApp1 'LaunchApp2': 0x000c0192, // launchApp2 'LaunchAssistant': 0x000c01cb, // launchAssistant 'LaunchControlPanel': 0x000c019f, // launchControlPanel 'LaunchMail': 0x000c018a, // launchMail 'LaunchScreenSaver': 0x000c01b1, // launchScreenSaver 'MailForward': 0x000c028b, // mailForward 'MailReply': 0x000c0289, // mailReply 'MailSend': 0x000c028c, // mailSend 'MediaFastForward': 0x000c00b3, // mediaFastForward 'MediaPause': 0x000c00b1, // mediaPause 'MediaPlay': 0x000c00b0, // mediaPlay 'MediaPlayPause': 0x000c00cd, // mediaPlayPause 'MediaRecord': 0x000c00b2, // mediaRecord 'MediaRewind': 0x000c00b4, // mediaRewind 'MediaSelect': 0x000c0183, // mediaSelect 'MediaStop': 0x000c00b7, // mediaStop 'MediaTrackNext': 0x000c00b5, // mediaTrackNext 'MediaTrackPrevious': 0x000c00b6, // mediaTrackPrevious 'MetaLeft': 0x000700e3, // metaLeft 'MetaRight': 0x000700e7, // metaRight 'MicrophoneMuteToggle': 0x00000018, // microphoneMuteToggle 'Minus': 0x0007002d, // minus 'NonConvert': 0x0007008b, // nonConvert 'NumLock': 0x00070053, // numLock 'Numpad0': 0x00070062, // numpad0 'Numpad1': 0x00070059, // numpad1 'Numpad2': 0x0007005a, // numpad2 'Numpad3': 0x0007005b, // numpad3 'Numpad4': 0x0007005c, // numpad4 'Numpad5': 0x0007005d, // numpad5 'Numpad6': 0x0007005e, // numpad6 'Numpad7': 0x0007005f, // numpad7 'Numpad8': 0x00070060, // numpad8 'Numpad9': 0x00070061, // numpad9 'NumpadAdd': 0x00070057, // numpadAdd 'NumpadBackspace': 0x000700bb, // numpadBackspace 'NumpadClear': 0x000700d8, // numpadClear 'NumpadClearEntry': 0x000700d9, // numpadClearEntry 'NumpadComma': 0x00070085, // numpadComma 'NumpadDecimal': 0x00070063, // numpadDecimal 'NumpadDivide': 0x00070054, // numpadDivide 'NumpadEnter': 0x00070058, // numpadEnter 'NumpadEqual': 0x00070067, // numpadEqual 'NumpadMemoryAdd': 0x000700d3, // numpadMemoryAdd 'NumpadMemoryClear': 0x000700d2, // numpadMemoryClear 'NumpadMemoryRecall': 0x000700d1, // numpadMemoryRecall 'NumpadMemoryStore': 0x000700d0, // numpadMemoryStore 'NumpadMemorySubtract': 0x000700d4, // numpadMemorySubtract 'NumpadMultiply': 0x00070055, // numpadMultiply 'NumpadParenLeft': 0x000700b6, // numpadParenLeft 'NumpadParenRight': 0x000700b7, // numpadParenRight 'NumpadSubtract': 0x00070056, // numpadSubtract 'Open': 0x00070074, // open 'PageDown': 0x0007004e, // pageDown 'PageUp': 0x0007004b, // pageUp 'Paste': 0x0007007d, // paste 'Pause': 0x00070048, // pause 'Period': 0x00070037, // period 'Power': 0x00070066, // power 'PrintScreen': 0x00070046, // printScreen 'PrivacyScreenToggle': 0x00000017, // privacyScreenToggle 'Props': 0x000700a3, // props 'Quote': 0x00070034, // quote 'Resume': 0x00000015, // resume 'ScrollLock': 0x00070047, // scrollLock 'Select': 0x00070077, // select 'SelectTask': 0x000c01a2, // selectTask 'Semicolon': 0x00070033, // semicolon 'ShiftLeft': 0x000700e1, // shiftLeft 'ShiftRight': 0x000700e5, // shiftRight 'ShowAllWindows': 0x000c029f, // showAllWindows 'Slash': 0x00070038, // slash 'Sleep': 0x00010082, // sleep 'Space': 0x0007002c, // space 'Super': 0x00000011, // superKey 'Suspend': 0x00000014, // suspend 'Tab': 0x0007002b, // tab 'Turbo': 0x00000016, // turbo 'Undo': 0x0007007a, // undo 'WakeUp': 0x00010083, // wakeUp 'ZoomToggle': 0x000c0232, // zoomToggle }; /// Maps Web KeyboardEvent keys to Flutter logical IDs that depend on locations. /// /// `KeyboardEvent.location` is defined as: /// /// * 0: Standard /// * 1: Left /// * 2: Right /// * 3: Numpad const Map<String, List<int?>> kWebLogicalLocationMap = <String, List<int?>>{ '*': <int?>[0x0000000002a, null, null, 0x0020000022a], // asterisk, null, null, numpadMultiply '+': <int?>[0x0000000002b, null, null, 0x0020000022b], // add, null, null, numpadAdd '-': <int?>[0x0000000002d, null, null, 0x0020000022d], // minus, null, null, numpadSubtract '.': <int?>[0x0000000002e, null, null, 0x0020000022e], // period, null, null, numpadDecimal '/': <int?>[0x0000000002f, null, null, 0x0020000022f], // slash, null, null, numpadDivide '0': <int?>[0x00000000030, null, null, 0x00200000230], // digit0, null, null, numpad0 '1': <int?>[0x00000000031, null, null, 0x00200000231], // digit1, null, null, numpad1 '2': <int?>[0x00000000032, null, null, 0x00200000232], // digit2, null, null, numpad2 '3': <int?>[0x00000000033, null, null, 0x00200000233], // digit3, null, null, numpad3 '4': <int?>[0x00000000034, null, null, 0x00200000234], // digit4, null, null, numpad4 '5': <int?>[0x00000000035, null, null, 0x00200000235], // digit5, null, null, numpad5 '6': <int?>[0x00000000036, null, null, 0x00200000236], // digit6, null, null, numpad6 '7': <int?>[0x00000000037, null, null, 0x00200000237], // digit7, null, null, numpad7 '8': <int?>[0x00000000038, null, null, 0x00200000238], // digit8, null, null, numpad8 '9': <int?>[0x00000000039, null, null, 0x00200000239], // digit9, null, null, numpad9 'Alt': <int?>[0x00200000104, 0x00200000104, 0x00200000105, null], // altLeft, altLeft, altRight, null 'AltGraph': <int?>[0x00100000103, null, 0x00100000103, null], // altGraph, null, altGraph, null 'ArrowDown': <int?>[0x00100000301, null, null, 0x00200000232], // arrowDown, null, null, numpad2 'ArrowLeft': <int?>[0x00100000302, null, null, 0x00200000234], // arrowLeft, null, null, numpad4 'ArrowRight': <int?>[0x00100000303, null, null, 0x00200000236], // arrowRight, null, null, numpad6 'ArrowUp': <int?>[0x00100000304, null, null, 0x00200000238], // arrowUp, null, null, numpad8 'Clear': <int?>[0x00100000401, null, null, 0x00200000235], // clear, null, null, numpad5 'Control': <int?>[0x00200000100, 0x00200000100, 0x00200000101, null], // controlLeft, controlLeft, controlRight, null 'Delete': <int?>[0x0010000007f, null, null, 0x0020000022e], // delete, null, null, numpadDecimal 'End': <int?>[0x00100000305, null, null, 0x00200000231], // end, null, null, numpad1 'Enter': <int?>[0x0010000000d, null, null, 0x0020000020d], // enter, null, null, numpadEnter 'Home': <int?>[0x00100000306, null, null, 0x00200000237], // home, null, null, numpad7 'Insert': <int?>[0x00100000407, null, null, 0x00200000230], // insert, null, null, numpad0 'Meta': <int?>[0x00200000106, 0x00200000106, 0x00200000107, null], // metaLeft, metaLeft, metaRight, null 'PageDown': <int?>[0x00100000307, null, null, 0x00200000233], // pageDown, null, null, numpad3 'PageUp': <int?>[0x00100000308, null, null, 0x00200000239], // pageUp, null, null, numpad9 'Shift': <int?>[0x00200000102, 0x00200000102, 0x00200000103, null], // shiftLeft, shiftLeft, shiftRight, null };
engine/lib/web_ui/lib/src/engine/key_map.g.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/key_map.g.dart", "repo_id": "engine", "token_count": 9768 }
308
// Copyright 2013 The Flutter 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 'dart:typed_data'; import '../dom.dart'; import '../platform_dispatcher.dart'; import '../services.dart'; import '../util.dart'; import 'content_manager.dart'; import 'slots.dart'; /// The signature for a callback for a Platform Message. From the `ui` package. /// Copied here so there's no circular dependencies. typedef _PlatformMessageResponseCallback = void Function(ByteData? data); /// A function that handle a newly created [DomElement] with the contents of a /// platform view with a unique [int] id. typedef PlatformViewContentHandler = void Function(DomElement); /// This class handles incoming framework messages to create/dispose Platform Views. /// /// (The instance of this class is connected to the `flutter/platform_views` /// Platform Channel in the [EnginePlatformDispatcher] class.) /// /// It uses a [PlatformViewManager] to handle the CRUD of the DOM of Platform Views. /// This `contentManager` is shared across the engine, to perform /// all operations related to platform views (registration, rendering, etc...), /// regardless of the rendering backend. /// /// Platform views are injected into the DOM when needed by the correct instance /// of the active renderer. /// /// The rendering and compositing of Platform Views can create the other "half" of a /// Platform View: the `slot`, through the [createPlatformViewSlot] method. /// /// When a Platform View is disposed of, it is removed from the cache (and DOM) /// directly by the `contentManager`. The canvaskit rendering backend needs to do /// some extra cleanup of its internal state, but it can do it automatically. See /// [HtmlViewEmbedder.disposeViews]. class PlatformViewMessageHandler { PlatformViewMessageHandler({ required PlatformViewManager contentManager, }) : _contentManager = contentManager; static const String channelName = 'flutter/platform_views'; /// The shared instance of PlatformViewMessageHandler. /// /// Unless configured differently, this connects to the shared instance of the /// [PlatformViewManager]. static PlatformViewMessageHandler instance = PlatformViewMessageHandler( contentManager: PlatformViewManager.instance, ); final MethodCodec _codec = const StandardMethodCodec(); final PlatformViewManager _contentManager; /// Handle a `create` Platform View message. /// /// This will attempt to render the `contents` of a Platform View, if its /// `viewType` has been registered previously. /// /// (See [PlatformViewManager.registerFactory] for more details.) /// /// If all goes well, this function will `callback` with an empty success envelope. /// In case of error, this will `callback` with an error envelope describing the error. /// /// The `callback` signals when the contents of a given [platformViewId] have /// been rendered. They're now accessible through `platformViewRegistry.getViewById` /// from `dart:ui_web`. **(Not the DOM!)** void _createPlatformView( _PlatformMessageResponseCallback callback, { required int platformViewId, required String platformViewType, required Object? params, }) { if (!_contentManager.knowsViewType(platformViewType)) { callback(_codec.encodeErrorEnvelope( code: 'unregistered_view_type', message: 'A HtmlElementView widget is trying to create a platform view ' 'with an unregistered type: <$platformViewType>.', details: 'If you are the author of the PlatformView, make sure ' '`registerViewFactory` is invoked.', )); return; } if (_contentManager.knowsViewId(platformViewId)) { callback(_codec.encodeErrorEnvelope( code: 'recreating_view', message: 'trying to create an already created view', details: 'view id: $platformViewId', )); return; } _contentManager.renderContent( platformViewType, platformViewId, params, ); callback(_codec.encodeSuccessEnvelope(null)); } /// Handle a `dispose` Platform View message. /// /// This will clear the cached information that the framework has about a given /// `platformViewId`, through the [_contentManager]. /// /// Once that's done, the dispose call is delegated to the [_disposeHandler] /// function, so the active rendering backend can dispose of whatever resources /// it needed to get ahold of. /// /// This function should always `callback` with an empty success envelope. void _disposePlatformView( _PlatformMessageResponseCallback callback, { required int platformViewId, }) { // The contentManager removes the slot and the contents from its internal // cache, and the DOM. _contentManager.clearPlatformView(platformViewId); callback(_codec.encodeSuccessEnvelope(null)); } /// Handles legacy PlatformViewCalls that don't contain a Flutter View ID. /// /// This is transitional code to support the old platform view channel. As /// soon as the framework code is updated to send the Flutter View ID, this /// method can be removed. void handlePlatformViewCall( String method, dynamic arguments, _PlatformMessageResponseCallback callback, ) { switch (method) { case 'create': arguments as Map<dynamic, dynamic>; _createPlatformView( callback, platformViewId: arguments.readInt('id'), platformViewType: arguments.readString('viewType'), params: arguments['params'], ); return; // TODO(web): Send `arguments` as a Map for `dispose` too! case 'dispose': _disposePlatformView(callback, platformViewId: arguments as int); return; } callback(null); } }
engine/lib/web_ui/lib/src/engine/platform_views/message_handler.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/platform_views/message_handler.dart", "repo_id": "engine", "token_count": 1739 }
309
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(yjbanov): TalkBack on Android incorrectly reads state changes for radio // buttons. When checking a radio button it reads // "Checked, not checked". This is likely due to another radio // button automatically becoming unchecked. VoiceOver reads it // correctly. It is possible we can fix this by using // "radiogroup" and "aria-owns". This may require a change in the // framework. Currently the framework does not report the // grouping of radio buttons. import 'package:ui/ui.dart' as ui; import 'label_and_value.dart'; import 'semantics.dart'; /// The specific type of checkable control. enum _CheckableKind { /// A checkbox. An element, which has [ui.SemanticsFlag.hasCheckedState] set /// and does not have [ui.SemanticsFlag.isInMutuallyExclusiveGroup] or /// [ui.SemanticsFlag.hasToggledState] state, is marked as a checkbox. checkbox, /// A radio button, defined by [ui.SemanticsFlag.isInMutuallyExclusiveGroup]. radio, /// A switch, defined by [ui.SemanticsFlag.hasToggledState]. toggle, } _CheckableKind _checkableKindFromSemanticsFlag( SemanticsObject semanticsObject) { if (semanticsObject.hasFlag(ui.SemanticsFlag.isInMutuallyExclusiveGroup)) { return _CheckableKind.radio; } else if (semanticsObject.hasFlag(ui.SemanticsFlag.hasToggledState)) { return _CheckableKind.toggle; } else { return _CheckableKind.checkbox; } } /// Renders semantics objects that have checkable (on/off) states. /// /// Three objects which are implemented by this class are checkboxes, radio /// buttons and switches. /// /// See also [ui.SemanticsFlag.hasCheckedState], [ui.SemanticsFlag.isChecked], /// [ui.SemanticsFlag.isInMutuallyExclusiveGroup], [ui.SemanticsFlag.isToggled], /// [ui.SemanticsFlag.hasToggledState] class Checkable extends PrimaryRoleManager { Checkable(SemanticsObject semanticsObject) : _kind = _checkableKindFromSemanticsFlag(semanticsObject), super.withBasics( PrimaryRole.checkable, semanticsObject, labelRepresentation: LeafLabelRepresentation.ariaLabel, ) { addTappable(); } final _CheckableKind _kind; @override void update() { super.update(); if (semanticsObject.isFlagsDirty) { switch (_kind) { case _CheckableKind.checkbox: setAriaRole('checkbox'); case _CheckableKind.radio: setAriaRole('radio'); case _CheckableKind.toggle: setAriaRole('switch'); } /// Adding disabled and aria-disabled attribute to notify the assistive /// technologies of disabled elements. _updateDisabledAttribute(); setAttribute( 'aria-checked', (semanticsObject.hasFlag(ui.SemanticsFlag.isChecked) || semanticsObject.hasFlag(ui.SemanticsFlag.isToggled)) ? 'true' : 'false', ); } } @override void dispose() { super.dispose(); _removeDisabledAttribute(); } void _updateDisabledAttribute() { if (semanticsObject.enabledState() == EnabledState.disabled) { setAttribute('aria-disabled', 'true'); setAttribute('disabled', 'true'); } else { _removeDisabledAttribute(); } } void _removeDisabledAttribute() { removeAttribute('aria-disabled'); removeAttribute('disabled'); } @override bool focusAsRouteDefault() => focusable?.focusAsRouteDefault() ?? false; }
engine/lib/web_ui/lib/src/engine/semantics/checkable.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/semantics/checkable.dart", "repo_id": "engine", "token_count": 1335 }
310
// Copyright 2013 The Flutter 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 'dart:typed_data'; import 'package:meta/meta.dart'; /// A message encoding/decoding mechanism. /// /// Both operations throw an exception, if conversion fails. Such situations /// should be treated as programming errors. /// /// See also: /// /// * [BasicMessageChannel], which use [MessageCodec]s for communication /// between Flutter and platform plugins. abstract class MessageCodec<T> { /// Encodes the specified [message] in binary. /// /// Returns null if the message is null. ByteData? encodeMessage(T message); /// Decodes the specified [message] from binary. /// /// Returns null if the message is null. T decodeMessage(ByteData message); } /// An command object representing the invocation of a named method. @immutable class MethodCall { /// Creates a [MethodCall] representing the invocation of [method] with the /// specified [arguments]. const MethodCall(this.method, [this.arguments]); /// The name of the method to be called. final String method; /// The arguments for the method. /// /// Must be a valid value for the [MethodCodec] used. final dynamic arguments; @override String toString() => '$runtimeType($method, $arguments)'; } /// A codec for method calls and enveloped results. /// /// All operations throw an exception, if conversion fails. /// /// See also: /// /// * [MethodChannel], which use [MethodCodec]s for communication /// between Flutter and platform plugins. /// * [EventChannel], which use [MethodCodec]s for communication /// between Flutter and platform plugins. abstract class MethodCodec { /// Encodes the specified [methodCall] into binary. ByteData? encodeMethodCall(MethodCall methodCall); /// Decodes the specified [methodCall] from binary. MethodCall decodeMethodCall(ByteData? methodCall); /// Decodes the specified result [envelope] from binary. /// /// Throws [PlatformException], if [envelope] represents an error, otherwise /// returns the enveloped result. dynamic decodeEnvelope(ByteData envelope); /// Encodes a successful [result] into a binary envelope. ByteData? encodeSuccessEnvelope(dynamic result); /// Encodes an error result into a binary envelope. /// /// The specified error [code], human-readable error [message], and error /// [details] correspond to the fields of [PlatformException]. ByteData? encodeErrorEnvelope( {required String code, String? message, dynamic details}); } /// Thrown to indicate that a platform interaction failed in the platform /// plugin. /// /// See also: /// /// * [MethodCodec], which throws a [PlatformException], if a received result /// envelope represents an error. /// * [MethodChannel.invokeMethod], which completes the returned future /// with a [PlatformException], if invoking the platform plugin method /// results in an error envelope. /// * [EventChannel.receiveBroadcastStream], which emits /// [PlatformException]s as error events, whenever an event received from the /// platform plugin is wrapped in an error envelope. class PlatformException implements Exception { /// Creates a [PlatformException] with the specified error [code] and optional /// [message], and with the optional error [details] which must be a valid /// value for the [MethodCodec] involved in the interaction. PlatformException({ required this.code, this.message, this.details, }); /// An error code. final String code; /// A human-readable error message, possibly null. final String? message; /// Error details, possibly null. final dynamic details; @override String toString() => 'PlatformException($code, $message, $details)'; } /// Thrown to indicate that a platform interaction failed to find a handling /// plugin. /// /// See also: /// /// * [MethodChannel.invokeMethod], which completes the returned future /// with a [MissingPluginException], if no plugin handler for the method call /// was found. /// * [OptionalMethodChannel.invokeMethod], which completes the returned future /// with null, if no plugin handler for the method call was found. class MissingPluginException implements Exception { /// Creates a [MissingPluginException] with an optional human-readable /// error message. MissingPluginException([this.message]); /// A human-readable error message, possibly null. final String? message; @override String toString() => 'MissingPluginException($message)'; }
engine/lib/web_ui/lib/src/engine/services/message_codec.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/services/message_codec.dart", "repo_id": "engine", "token_count": 1199 }
311
// Copyright 2013 The Flutter 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 'dart:collection'; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; import 'package:ui/ui.dart' as ui; class SkwasmPathMetrics extends IterableBase<ui.PathMetric> implements ui.PathMetrics { SkwasmPathMetrics({required this.path, required this.forceClosed}); SkwasmPath path; bool forceClosed; @override late Iterator<ui.PathMetric> iterator = SkwasmPathMetricIterator(path, forceClosed); } class SkwasmPathMetricIterator extends SkwasmObjectWrapper<RawContourMeasureIter> implements Iterator<ui.PathMetric> { SkwasmPathMetricIterator(SkwasmPath path, bool forceClosed) : super(contourMeasureIterCreate(path.handle, forceClosed, 1.0), _registry); static final SkwasmFinalizationRegistry<RawContourMeasureIter> _registry = SkwasmFinalizationRegistry<RawContourMeasureIter>(contourMeasureIterDispose); SkwasmPathMetric? _current; int _nextIndex = 0; @override ui.PathMetric get current { if (_current == null) { throw RangeError( 'PathMetricIterator is not pointing to a PathMetric. This can happen in two situations:\n' '- The iteration has not started yet. If so, call "moveNext" to start iteration.\n' '- The iterator ran out of elements. If so, check that "moveNext" returns true prior to calling "current".'); } return _current!; } @override bool moveNext() { final ContourMeasureHandle measureHandle = contourMeasureIterNext(handle); if (measureHandle == nullptr) { _current = null; return false; } else { _current = SkwasmPathMetric(measureHandle, _nextIndex); _nextIndex++; return true; } } } class SkwasmPathMetric extends SkwasmObjectWrapper<RawContourMeasure> implements ui.PathMetric { SkwasmPathMetric(ContourMeasureHandle handle, this.contourIndex) : super(handle, _registry); static final SkwasmFinalizationRegistry<RawContourMeasure> _registry = SkwasmFinalizationRegistry<RawContourMeasure>(contourMeasureDispose); @override final int contourIndex; @override ui.Path extractPath(double start, double end, {bool startWithMoveTo = true}) { return SkwasmPath.fromHandle( contourMeasureGetSegment(handle, start, end, startWithMoveTo)); } @override ui.Tangent? getTangentForOffset(double distance) { return withStackScope((StackScope scope) { final Pointer<Float> outPosition = scope.allocFloatArray(4); final Pointer<Float> outTangent = Pointer<Float>.fromAddress(outPosition.address + sizeOf<Float>() * 2); final bool result = contourMeasureGetPosTan(handle, distance, outPosition, outTangent); assert(result); return ui.Tangent( ui.Offset(outPosition[0], outPosition[1]), ui.Offset(outTangent[0], outTangent[1]) ); }); } @override bool get isClosed => contourMeasureIsClosed(handle); @override double get length => contourMeasureLength(handle); }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/path_metrics.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/path_metrics.dart", "repo_id": "engine", "token_count": 1099 }
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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:ffi'; import 'package:ui/src/engine/skwasm/skwasm_impl.dart'; final class RawVertices extends Opaque {} typedef VerticesHandle = Pointer<RawVertices>; @Native<VerticesHandle Function( Int vertexMode, Int vertexCount, RawPointArray positions, RawPointArray textureCoordinates, RawColorArray colors, Int indexCount, Pointer<Uint16> indices, )>(symbol: 'vertices_create', isLeaf: true) external VerticesHandle verticesCreate( int vertexMode, int vertexCount, RawPointArray positions, RawPointArray textureCoordinates, RawColorArray colors, int indexCount, Pointer<Uint16> indices, ); @Native<Void Function(VerticesHandle)>(symbol: 'vertices_dispose', isLeaf: true) external void verticesDispose(VerticesHandle handle);
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_vertices.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_vertices.dart", "repo_id": "engine", "token_count": 309 }
313
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(yjbanov): this does not need to be in the production sources. // https://github.com/flutter/flutter/issues/100394 import 'dart:async'; import 'package:ui/ui.dart' as ui; import 'package:ui/ui_web/src/ui_web.dart' as ui_web; const bool _debugLogHistoryActions = false; class TestHistoryEntry { const TestHistoryEntry(this.state, this.title, this.url); final dynamic state; final String? title; final String url; @override String toString() { return '$runtimeType(state:$state, title:"$title", url:"$url")'; } } /// This URL strategy mimics the browser's history as closely as possible /// while doing it all in memory with no interaction with the browser. /// /// It keeps a list of history entries and event listeners in memory and /// manipulates them in order to achieve the desired functionality. class TestUrlStrategy implements ui_web.UrlStrategy { /// Creates a instance of [TestUrlStrategy] with an empty string as the /// path. factory TestUrlStrategy() => TestUrlStrategy.fromEntry(const TestHistoryEntry(null, null, '')); /// Creates an instance of [TestUrlStrategy] and populates it with a list /// that has [initialEntry] as the only item. TestUrlStrategy.fromEntry(TestHistoryEntry initialEntry) : _currentEntryIndex = 0, history = <TestHistoryEntry>[initialEntry]; @override String getPath() => currentEntry.url; @override dynamic getState() => currentEntry.state; int _currentEntryIndex; int get currentEntryIndex => _currentEntryIndex; final List<TestHistoryEntry> history; TestHistoryEntry get currentEntry { assert(withinAppHistory); return history[_currentEntryIndex]; } set currentEntry(TestHistoryEntry entry) { assert(withinAppHistory); history[_currentEntryIndex] = entry; } /// Whether we are still within the history of the Flutter Web app. This /// remains true until we go back in history beyond the entry where the app /// started. bool get withinAppHistory => _currentEntryIndex >= 0; @override void pushState(dynamic state, String title, String url) { assert(withinAppHistory); _currentEntryIndex++; // When pushing a new state, we need to remove all entries that exist after // the current entry. // // If the user goes A -> B -> C -> D, then goes back to B and pushes a new // entry called E, we should end up with: A -> B -> E in the history list. history.removeRange(_currentEntryIndex, history.length); history.add(TestHistoryEntry(state, title, url)); if (_debugLogHistoryActions) { print('$runtimeType.pushState(...) -> $this'); } } @override void replaceState(dynamic state, String title, String? url) { assert(withinAppHistory); if (url == null || url == '') { url = currentEntry.url; } currentEntry = TestHistoryEntry(state, title, url); if (_debugLogHistoryActions) { print('$runtimeType.replaceState(...) -> $this'); } } /// This simulates the case where a user types in a url manually. It causes /// a new state to be pushed, and all event listeners will be invoked. Future<void> simulateUserTypingUrl(String url) { assert(withinAppHistory); return _nextEventLoop(() { pushState(null, '', url); _firePopStateEvent(); }); } @override Future<void> go(int count) { assert(withinAppHistory); // Browsers don't move in history immediately. They do it at the next // event loop. So let's simulate that. return _nextEventLoop(() { _currentEntryIndex = _currentEntryIndex + count; if (withinAppHistory) { _firePopStateEvent(); } if (_debugLogHistoryActions) { print('$runtimeType.back() -> $this'); } }); } final List<ui_web.PopStateListener> listeners = <ui_web.PopStateListener>[]; @override ui.VoidCallback addPopStateListener(ui_web.PopStateListener fn) { listeners.add(fn); return () { // Schedule a micro task here to avoid removing the listener during // iteration in [_firePopStateEvent]. scheduleMicrotask(() => listeners.remove(fn)); }; } /// Simulates the scheduling of a new event loop by creating a delayed future. /// Details explained here: https://webdev.dartlang.org/articles/performance/event-loop Future<void> _nextEventLoop(ui.VoidCallback callback) { return Future<void>.delayed(Duration.zero).then((_) => callback()); } /// Invokes all the attached event listeners in order of /// attaching. This method should be called asynchronously to make it behave /// like a real browser. void _firePopStateEvent() { assert(withinAppHistory); for (int i = 0; i < listeners.length; i++) { listeners[i](currentEntry.state); } if (_debugLogHistoryActions) { print('$runtimeType: fired popstate with state ${currentEntry.state}'); } } @override String prepareExternalUrl(String internalUrl) => internalUrl; @override String toString() { final List<String> lines = <String>[]; for (int i = 0; i < history.length; i++) { final TestHistoryEntry entry = history[i]; lines.add(_currentEntryIndex == i ? '* $entry' : ' $entry'); } return '$runtimeType: [\n${lines.join('\n')}\n]'; } }
engine/lib/web_ui/lib/src/engine/test_embedding.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/test_embedding.dart", "repo_id": "engine", "token_count": 1773 }
314
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Maps AutofillHints from the framework to the autofill hints that is used for /// browsers. /// See: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/autofill.dart /// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete class BrowserAutofillHints { BrowserAutofillHints._() : _flutterToEngineMap = <String, String>{ 'birthday': 'bday', 'birthdayDay': 'bday-day', 'birthdayMonth': 'bday-month', 'birthdayYear': 'bday-year', 'countryCode': 'country', 'countryName': 'country-name', 'creditCardExpirationDate': 'cc-exp', 'creditCardExpirationMonth': 'cc-exp-month', 'creditCardExpirationYear': 'cc-exp-year', 'creditCardFamilyName': 'cc-family-name', 'creditCardGivenName': 'cc-given-name', 'creditCardMiddleName': 'cc-additional-name', 'creditCardName': 'cc-name', 'creditCardNumber': 'cc-number', 'creditCardSecurityCode': 'cc-csc', 'creditCardType': 'cc-type', 'email': 'email', 'familyName': 'family-name', 'fullStreetAddress': 'street-address', 'gender': 'sex', 'givenName': 'given-name', 'impp': 'impp', 'jobTitle': 'organization-title', 'language': 'language', 'middleName': 'additional-name', 'name': 'name', 'namePrefix': 'honorific-prefix', 'nameSuffix': 'honorific-suffix', 'newPassword': 'new-password', 'nickname': 'nickname', 'oneTimeCode': 'one-time-code', 'organizationName': 'organization', 'password': 'current-password', 'photo': 'photo', 'postalCode': 'postal-code', 'streetAddressLevel1': 'address-level1', 'streetAddressLevel2': 'address-level2', 'streetAddressLevel3': 'address-level3', 'streetAddressLevel4': 'address-level4', 'streetAddressLine1': 'address-line1', 'streetAddressLine2': 'address-line2', 'streetAddressLine3': 'address-line3', 'telephoneNumber': 'tel', 'telephoneNumberAreaCode': 'tel-area-code', 'telephoneNumberCountryCode': 'tel-country-code', 'telephoneNumberExtension': 'tel-extension', 'telephoneNumberLocal': 'tel-local', 'telephoneNumberLocalPrefix': 'tel-local-prefix', 'telephoneNumberLocalSuffix': 'tel-local-suffix', 'telephoneNumberNational': 'tel-national', 'transactionAmount': 'transaction-amount', 'transactionCurrency': 'transaction-currency', 'url': 'url', 'username': 'username', }; static final BrowserAutofillHints _singletonInstance = BrowserAutofillHints._(); /// The [BrowserAutofillHints] singleton. static BrowserAutofillHints get instance => _singletonInstance; final Map<String, String> _flutterToEngineMap; /// Converts the Flutter AutofillHint to the autofill hint value used by the /// browsers. /// See: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/autofill.dart /// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete String flutterToEngine(String flutterAutofillHint) { // Use the hints as it is. return _flutterToEngineMap[flutterAutofillHint] ?? flutterAutofillHint; } }
engine/lib/web_ui/lib/src/engine/text_editing/autofill_hint.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/text_editing/autofill_hint.dart", "repo_id": "engine", "token_count": 1530 }
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. import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/util.dart' show setElementStyle; import '../hot_restart_cache_handler.dart' show registerElementForCleanup; import 'embedding_strategy.dart'; /// An [EmbeddingStrategy] that takes over the whole web page. /// /// This strategy takes over the <body> element, modifies the viewport meta-tag, /// and ensures that the root Flutter view covers the whole screen. class FullPageEmbeddingStrategy implements EmbeddingStrategy { FullPageEmbeddingStrategy() { hostElement.setAttribute('flt-embedding', 'full-page'); _applyViewportMeta(); _setHostStyles(); } @override final DomElement hostElement = domDocument.body!; @override DomEventTarget get globalEventTarget => domWindow; @override void attachViewRoot(DomElement rootElement) { /// Tweaks style so the rootElement works well with the hostElement. rootElement.style ..position = 'absolute' ..top = '0' ..right = '0' ..bottom = '0' ..left = '0'; hostElement.append(rootElement); registerElementForCleanup(rootElement); } // Sets the global styles for a flutter app. void _setHostStyles() { setElementStyle(hostElement, 'position', 'fixed'); setElementStyle(hostElement, 'top', '0'); setElementStyle(hostElement, 'right', '0'); setElementStyle(hostElement, 'bottom', '0'); setElementStyle(hostElement, 'left', '0'); setElementStyle(hostElement, 'overflow', 'hidden'); setElementStyle(hostElement, 'padding', '0'); setElementStyle(hostElement, 'margin', '0'); setElementStyle(hostElement, 'user-select', 'none'); setElementStyle(hostElement, '-webkit-user-select', 'none'); // This is required to prevent the browser from doing any native touch // handling. If this is not done, the browser doesn't report 'pointermove' // events properly. setElementStyle(hostElement, 'touch-action', 'none'); } // Sets a meta viewport tag appropriate for Flutter Web in full screen. void _applyViewportMeta() { for (final DomElement viewportMeta in domDocument.head!.querySelectorAll('meta[name="viewport"]')) { assert(() { // Filter out the meta tag that the engine placed on the page. This is // to avoid UI flicker during hot restart. Hot restart will clean up the // old meta tag synchronously with the first post-restart frame. if (!viewportMeta.hasAttribute('flt-viewport')) { print( 'WARNING: found an existing <meta name="viewport"> tag. Flutter ' 'Web uses its own viewport configuration for better compatibility ' 'with Flutter. This tag will be replaced.', ); } return true; }()); viewportMeta.remove(); } // The meta viewport is always removed by the for method above, so we don't // need to do anything else here, other than create it again. final DomHTMLMetaElement viewportMeta = createDomHTMLMetaElement() ..setAttribute('flt-viewport', '') ..name = 'viewport' ..content = 'width=device-width, initial-scale=1.0, ' 'maximum-scale=1.0, user-scalable=no'; domDocument.head!.append(viewportMeta); registerElementForCleanup(viewportMeta); } }
engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart/0
{ "file_path": "engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart", "repo_id": "engine", "token_count": 1180 }
316
// Copyright 2013 The Flutter 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 'dart:async'; import 'package:meta/meta.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import '../testing.dart'; import 'platform_location.dart'; UrlStrategy _realDefaultUrlStrategy = debugEmulateFlutterTesterEnvironment ? TestUrlStrategy.fromEntry(const TestHistoryEntry('default', null, '/')) : const HashUrlStrategy(); UrlStrategy get _defaultUrlStrategy => debugDefaultUrlStrategyOverride ?? _realDefaultUrlStrategy; /// Overrides the default URL strategy. /// /// Setting this to null allows the real default URL strategy to be used. /// /// This is intended to be used for testing and debugging only. @visibleForTesting UrlStrategy? debugDefaultUrlStrategyOverride; /// Whether a custom URL strategy has been set or not. // // It is valid to set [_customUrlStrategy] to null, so we can't use a null // check to determine whether it was set or not. We need an extra boolean. bool isCustomUrlStrategySet = false; /// Whether a custom URL strategy can be set or not. /// /// This is used to prevent setting a custom URL strategy for a second time or /// after the app has already started running. bool _customUrlStrategyCanBeSet = true; /// A custom URL strategy set by the app before running. UrlStrategy? _customUrlStrategy; /// Returns the present [UrlStrategy] for handling the browser URL. /// /// Returns null when the browser integration has been manually disabled. UrlStrategy? get urlStrategy => isCustomUrlStrategySet ? _customUrlStrategy : _defaultUrlStrategy; /// Sets a custom URL strategy instead of the default one. /// /// Passing null disables browser history integration altogether. /// /// This setter can only be called once. Subsequent calls will throw an error /// in debug mode. set urlStrategy(UrlStrategy? strategy) { assert( _customUrlStrategyCanBeSet, 'Cannot set URL strategy a second time or after the app has been initialized.', ); preventCustomUrlStrategy(); isCustomUrlStrategySet = true; _customUrlStrategy = strategy; } /// From this point on, prevents setting a custom URL strategy. void preventCustomUrlStrategy() { _customUrlStrategyCanBeSet = false; } /// Resets everything to do with custom URL strategy. /// /// This should only be used in tests to reset things back after each test. void debugResetCustomUrlStrategy() { isCustomUrlStrategySet = false; _customUrlStrategyCanBeSet = true; _customUrlStrategy = null; } /// Callback that receives the new state of the browser history entry. typedef PopStateListener = void Function(Object? state); /// Represents and reads route state from the browser's URL. /// /// By default, the [HashUrlStrategy] subclass is used if the app doesn't /// specify one. abstract class UrlStrategy { /// Adds a listener to the `popstate` event and returns a function that, when /// invoked, removes the listener. ui.VoidCallback addPopStateListener(PopStateListener fn); /// Returns the active path in the browser. String getPath(); /// The state of the current browser history entry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/state Object? getState(); /// Given a path that's internal to the app, create the external url that /// will be used in the browser. String prepareExternalUrl(String internalUrl); /// Push a new history entry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState void pushState(Object? state, String title, String url); /// Replace the currently active history entry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState void replaceState(Object? state, String title, String url); /// Moves forwards or backwards through the history stack. /// /// A negative [count] value causes a backward move in the history stack. And /// a positive [count] value causs a forward move. /// /// Examples: /// /// * `go(-2)` moves back 2 steps in history. /// * `go(3)` moves forward 3 steps in hisotry. /// /// See: https://developer.mozilla.org/en-US/docs/Web/API/History/go Future<void> go(int count); } /// This is an implementation of [UrlStrategy] that uses the browser URL's /// [hash fragments](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) /// to represent its state. /// /// In order to use this [UrlStrategy] for an app, it needs to be set like this: /// /// ```dart /// import 'package:flutter_web_plugins/flutter_web_plugins.dart'; /// /// // Somewhere before calling `runApp()` do: /// setUrlStrategy(const HashUrlStrategy()); /// ``` class HashUrlStrategy implements UrlStrategy { /// Creates an instance of [HashUrlStrategy]. /// /// The [PlatformLocation] parameter is useful for testing to mock out browser /// interactions. const HashUrlStrategy( [this._platformLocation = const BrowserPlatformLocation()]); final PlatformLocation _platformLocation; @override ui.VoidCallback addPopStateListener(PopStateListener fn) { void wrappedFn(Object event) { // `fn` expects `event.state`, not a `DomEvent`. fn((event as DomPopStateEvent).state); } _platformLocation.addPopStateListener(wrappedFn); return () => _platformLocation.removePopStateListener(wrappedFn); } @override String getPath() { // the hash value is always prefixed with a `#` // and if it is empty then it will stay empty final String path = _platformLocation.hash ?? ''; assert(path.isEmpty || path.startsWith('#')); // We don't want to return an empty string as a path. Instead we default to "/". if (path.isEmpty || path == '#') { return '/'; } // At this point, we know [path] starts with "#" and isn't empty. return path.substring(1); } @override Object? getState() => _platformLocation.state; @override String prepareExternalUrl(String internalUrl) { // It's convention that if the hash path is empty, we omit the `#`; however, // if the empty URL is pushed it won't replace any existing fragment. So // when the hash path is empty, we still return the location's path and // query. final String hash; if (internalUrl.isEmpty || internalUrl == '/') { // Let's not add the hash at all when the app is in the home page. That // way, the URL of the home page is cleaner. // // See: https://github.com/flutter/flutter/issues/127608 hash = ''; } else { hash = '#$internalUrl'; } return '${_platformLocation.pathname}${_platformLocation.search}$hash'; } @override void pushState(Object? state, String title, String url) { _platformLocation.pushState(state, title, prepareExternalUrl(url)); } @override void replaceState(Object? state, String title, String url) { _platformLocation.replaceState(state, title, prepareExternalUrl(url)); } @override Future<void> go(int count) { _platformLocation.go(count); return _waitForPopState(); } /// Waits until the next popstate event is fired. /// /// This is useful, for example, to wait until the browser has handled the /// `history.back` transition. Future<void> _waitForPopState() { final Completer<void> completer = Completer<void>(); late ui.VoidCallback unsubscribe; unsubscribe = addPopStateListener((_) { unsubscribe(); completer.complete(); }); return completer.future; } }
engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart/0
{ "file_path": "engine/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart", "repo_id": "engine", "token_count": 2302 }
317
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "export.h" #include "helpers.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkImageFilter.h" #include "third_party/skia/include/core/SkMaskFilter.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkShader.h" using namespace Skwasm; SKWASM_EXPORT SkPaint* paint_create() { auto paint = new SkPaint(); // Antialias defaults to true in flutter. paint->setAntiAlias(true); return paint; } SKWASM_EXPORT void paint_dispose(SkPaint* paint) { delete paint; } SKWASM_EXPORT void paint_setBlendMode(SkPaint* paint, SkBlendMode mode) { paint->setBlendMode(mode); } // No getter for blend mode, as it's non trivial. Cache on the dart side. SKWASM_EXPORT void paint_setStyle(SkPaint* paint, SkPaint::Style style) { paint->setStyle(style); } SKWASM_EXPORT SkPaint::Style paint_getStyle(SkPaint* paint) { return paint->getStyle(); } SKWASM_EXPORT void paint_setStrokeWidth(SkPaint* paint, SkScalar width) { paint->setStrokeWidth(width); } SKWASM_EXPORT SkScalar paint_getStrokeWidth(SkPaint* paint) { return paint->getStrokeWidth(); } SKWASM_EXPORT void paint_setStrokeCap(SkPaint* paint, SkPaint::Cap cap) { paint->setStrokeCap(cap); } SKWASM_EXPORT SkPaint::Cap paint_getStrokeCap(SkPaint* paint) { return paint->getStrokeCap(); } SKWASM_EXPORT void paint_setStrokeJoin(SkPaint* paint, SkPaint::Join join) { paint->setStrokeJoin(join); } SKWASM_EXPORT SkPaint::Join paint_getStrokeJoin(SkPaint* paint) { return paint->getStrokeJoin(); } SKWASM_EXPORT void paint_setAntiAlias(SkPaint* paint, bool antiAlias) { paint->setAntiAlias(antiAlias); } SKWASM_EXPORT bool paint_getAntiAlias(SkPaint* paint) { return paint->isAntiAlias(); } SKWASM_EXPORT void paint_setColorInt(SkPaint* paint, SkColor colorInt) { paint->setColor(colorInt); } SKWASM_EXPORT SkColor paint_getColorInt(SkPaint* paint) { return paint->getColor(); } SKWASM_EXPORT void paint_setMiterLimit(SkPaint* paint, SkScalar miterLimit) { paint->setStrokeMiter(miterLimit); } SKWASM_EXPORT SkScalar paint_getMiterLImit(SkPaint* paint) { return paint->getStrokeMiter(); } SKWASM_EXPORT void paint_setShader(SkPaint* paint, SkShader* shader) { paint->setShader(sk_ref_sp<SkShader>(shader)); } SKWASM_EXPORT void paint_setImageFilter(SkPaint* paint, SkImageFilter* filter) { paint->setImageFilter(sk_ref_sp<SkImageFilter>(filter)); } SKWASM_EXPORT void paint_setColorFilter(SkPaint* paint, SkColorFilter* filter) { paint->setColorFilter(sk_ref_sp<SkColorFilter>(filter)); } SKWASM_EXPORT void paint_setMaskFilter(SkPaint* paint, SkMaskFilter* filter) { paint->setMaskFilter(sk_ref_sp<SkMaskFilter>(filter)); }
engine/lib/web_ui/skwasm/paint.cpp/0
{ "file_path": "engine/lib/web_ui/skwasm/paint.cpp", "repo_id": "engine", "token_count": 1106 }
318
............................................................................... # Flutter Web Engine Test Suites The flutter engine unit tests can be run with a number of different configuration options that affect both compile time and run time. The permutations of these options are specified in the `felt_config.yaml` file that is colocated with this README. Here is an overview of the way the test suite configurations are structured: ## `compile-configs` Specifies how the tests should be compiled. Each compile config specifies the following: * `name` - The name of the compile configuration. * `compiler` - What compiler is used to compile the tests. Currently we support `dart2js` and `dart2wasm` as values. * `renderer` - Which renderer to use when compiling the tests. Currently we support `html`, `canvaskit`, and `skwasm`. ## `test-sets` A group of files that contain unit tests. Each test set specifies the following: * `name` - The name of the test set. * `directory` - The name of the directory under `flutter/lib/web_ui/test` that contains all the test files. ## `test-bundles` Specifies a group of tests and a compile configuration of those tests. The output of the test bundles appears in `flutter/lib/web_ui/build/test_bundles/<name>` where `<name>` is replaced by the name of the bundle. Each test bundle may be used by multiple test suites. Each test bundle specifies the following: * `name` - The name of the test bundle. * `test-set` - The name of the test set that contains the tests to be compiled. * `compile-config` - The name of the compile configuration to use. ## `run-configs` Specifies the test environment that should be provided to a unit test. Each run config specifies the following: * `name` - Name of the run configuration. * `browser` - The browser with which to run the tests. Valid values for this are `chrome`, `firefox`, `safari` or `edge`. * `canvaskit-variant` - An optionally supplied argument that forces the tests to use a particular variant of CanvasKit, either `full` or `chromium`. If none is specified, the engine will select the variant based on its normal selection logic. ## `test-suites` This is a fully specified run of a group of unit tests. They specify the following: * `name` - Name of the test suite. * `test-bundle` - Which compiled test bundle to use when running the suite. * `run-config` - Which run configuration to use when runnin the tests. * `artifact-deps` - Which gn/ninja build artifacts are needed to run the suite. Valid values are `canvaskit`, `canvaskit_chromium` or `skwasm`.
engine/lib/web_ui/test/README.md/0
{ "file_path": "engine/lib/web_ui/test/README.md", "repo_id": "engine", "token_count": 722 }
319
// Copyright 2013 The Flutter 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 'package:js/js_util.dart' as js_util; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../../common/test_initialization.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { group('initializeEngineServices', () { test('does not mock module loaders', () async { // Initialize CanvasKit... await bootstrapAndRunApp(); // CanvasKitInit should be defined... expect( js_util.hasProperty(domWindow, 'CanvasKitInit'), isTrue, reason: 'CanvasKitInit should be defined on Window', ); // window.exports and window.module should be undefined! expect( js_util.hasProperty(domWindow, 'exports'), isFalse, reason: '`window.exports` should not be defined.', ); expect( js_util.hasProperty(domWindow, 'module'), isFalse, reason: '`window.module` should not be defined.', ); }); }); }
engine/lib/web_ui/test/canvaskit/initialization/does_not_mock_module_exports_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/initialization/does_not_mock_module_exports_test.dart", "repo_id": "engine", "token_count": 453 }
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. import 'dart:math' as math; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); void testMain() { group('ShaderMask', () { setUpCanvasKitTest(withImplicitView: true); test('Renders sweep gradient with color blend', () async { final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0, 0); // Draw a red circle and apply it to the scene. final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( const ui.Offset(425, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle); final CkGradientSweep shader = CkGradientSweep( const ui.Offset(250, 125), const <ui.Color>[ ui.Color(0xFF4285F4), ui.Color(0xFF34A853), ui.Color(0xFFFBBC05), ui.Color(0xFFEA4335), ui.Color(0xFF4285F4), ], const <double>[ 0.0, 0.25, 0.5, 0.75, 1.0, ], ui.TileMode.clamp, -(math.pi / 2), math.pi * 2 - (math.pi / 2), null); final ui.Path clipPath = ui.Path() ..addOval(const ui.Rect.fromLTWH(25, 75, 100, 100)); builder.pushClipPath(clipPath); // Apply a shader mask. builder.pushShaderMask(shader, const ui.Rect.fromLTRB(0, 0, 200, 250), ui.BlendMode.color); // Draw another red circle and apply it to the scene. // This one should be grey since we have the color filter. final CkPictureRecorder recorder2 = CkPictureRecorder(); final CkCanvas canvas2 = recorder2.beginRecording(region); canvas2.drawRect(const ui.Rect.fromLTWH(25, 75, 100, 100), CkPaint()..color = const ui.Color.fromARGB(255, 0, 255, 0), ); final CkPicture sweepCircle = recorder2.endRecording(); builder.addPicture(ui.Offset.zero, sweepCircle); await matchSceneGolden( 'canvaskit_shadermask_linear.png', builder.build(), region: region, ); }); /// Regression test for https://github.com/flutter/flutter/issues/78959 test('Renders sweep gradient with color blend translated', () async { final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0, 0); // Draw a red circle and apply it to the scene. final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawCircle( const ui.Offset(425, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle); final CkGradientSweep shader = CkGradientSweep( const ui.Offset(250, 125), const <ui.Color>[ ui.Color(0xFF4285F4), ui.Color(0xFF34A853), ui.Color(0xFFFBBC05), ui.Color(0xFFEA4335), ui.Color(0xFF4285F4), ], const <double>[ 0.0, 0.25, 0.5, 0.75, 1.0, ], ui.TileMode.clamp, -(math.pi / 2), math.pi * 2 - (math.pi / 2), null); final ui.Path clipPath = ui.Path() ..addOval(const ui.Rect.fromLTWH(25, 75, 100, 100)); builder.pushClipPath(clipPath); // Apply a shader mask. builder.pushShaderMask(shader, const ui.Rect.fromLTRB(50, 50, 200, 250), ui.BlendMode.color); // Draw another red circle and apply it to the scene. // This one should be grey since we have the color filter. final CkPictureRecorder recorder2 = CkPictureRecorder(); final CkCanvas canvas2 = recorder2.beginRecording(region); canvas2.drawRect(const ui.Rect.fromLTWH(25, 75, 100, 100), CkPaint()..color = const ui.Color.fromARGB(255, 0, 255, 0), ); final CkPicture sweepCircle = recorder2.endRecording(); builder.addPicture(ui.Offset.zero, sweepCircle); await matchSceneGolden( 'canvaskit_shadermask_linear_translated.png', builder.build(), region: region, ); }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520 }, skip: isSafari || isFirefox); }
engine/lib/web_ui/test/canvaskit/shader_mask_golden_test.dart/0
{ "file_path": "engine/lib/web_ui/test/canvaskit/shader_mask_golden_test.dart", "repo_id": "engine", "token_count": 2263 }
321